Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 186df6fb53 feat(app): show only the Enable tools switch in setup
Setup is for getting started, so the Orchestration step shows a plain
Enable tools switch next to skills and the CLI. Tool groups stay in
Settings > Tools & prompts. Setup writes only the main switch, so the
groups a host already saved are never touched.
2026-11-28 17:32:07 +01:00
Mohamed Boudra d71f79570c fix(server): keep wire schemas out of the configuration entry point
tools-config.ts imported the default tool groups from protocol/messages,
which pulled every wire schema into @getpaseo/server/configuration. The
group constants now live in the Zod-free protocol/tool-groups module, and
messages re-exports them.

The WebSocket server read the config store behind a guard that only
existed for incomplete test stubs. The store is a required dependency, so
the guard is gone and the stubs provide get().
2026-11-28 17:32:07 +01:00
Mohamed Boudra 9e7e43c9ad fix(app): keep the host's tool groups when setup is shown again
The Orchestration step started its tool groups from the defaults and wrote
all four on Continue, so a host with Browser on or Schedules off lost those
choices when the user opened setup again. The groups sit in a collapsed row,
so the user never saw the switches. Setup now shows the host's groups and
writes only the groups the user changed.

The compact-layout setup test assumed the host starts with tools off; it now
turns them off first, since tools are on by default.
2026-11-28 17:32:07 +01:00
Mohamed Boudra 7e9f159b8a feat(server,app): group agent tools under one Enable tools setting
Replace the separate "Enable Paseo tools" and "Browser tools" settings with
one `daemon.tools` configuration: an `enabled` switch plus per-group switches
for orchestration, schedules, PR watching, and browser. Every built-in tool
now declares its group, scope, and daemon permission in one registry, so
native providers and the loopback MCP endpoint filter the same catalog.

Tools are on by default for hosts that never set the legacy injection flag.
Hosts that set `daemon.mcp.injectIntoAgents: false` keep tools off. Legacy
`daemon.mcp.*` and `daemon.browserTools.enabled` are still read when
`daemon.tools` is absent; those shims are tagged COMPAT.

Voice mode now requires tools. When tools are off it refuses with reasonCode
"tools_disabled" and the voice settings page offers a one-click Enable tools
action. Dictation is unaffected.
2026-11-28 17:32:06 +01:00
Mohamed Boudra 6916ceee47 test: fix the Claude listing heap test and the hero opening-scene race (#11204)
The Claude listing heap test capped its child at 96 MB, but most of
that budget went to loading the modules. Since prompt attachments
import the file-upload module, agent.ts also loads the protocol message
schemas, about 50 MB more. The 14 MB listing then ran out of heap on
runs where GC ran late. The test now measures what the imports retain
in a first child, then caps the listing child at that plus 64 MiB. That
is still below the 128 MiB transcript, so loading a whole history still
runs out of heap.

The opening-scene tests advanced the paused page clock once, right
after the scroll. The scene starts a few page tasks later
(IntersectionObserver, then a React render and effect). When the clock
advance ran first, the scene started on a paused clock and the request
never appeared. The tests now advance the clock in 1 s steps until the
request shows.

CI also uploads the website Playwright results when that step fails,
so the next stall has a trace.
2026-11-28 22:40:58 +07:00
Mohamed Boudra 635df88fa6 fix(ci): stop painting main commits red when packaging runs are superseded (#11200)
* fix(ci): let Docker and Desktop Packages runs on main finish

Each merge cancelled the packaging runs still going for the previous main commit, and the CANCELLED checks painted that commit red. #11192 fixed this for CI only.

* test(terminal): give slow Windows output time to reach the buffer

The test allowed 10s for 3000 console writes. Passing Windows CI runs take 0.7s to 9.5s, so a loaded runner crossed the limit. The suite allows 30s per test.
2026-11-28 21:54:26 +07:00
552690e45c fix(claude): settle advisor_tool_result blocks and redact encrypted payloads (#11202)
Co-authored-by: Lucas Vale Queiroz <142512124+LucasValeQueiroz@users.noreply.github.com>
Co-authored-by: SirisZheng <70536096+SirisZheng@users.noreply.github.com>
2026-11-28 14:42:41 +00:00
Mohamed Boudra 9815d68f3b Redesign model selection across desktop, phones, and provider settings (#11186)
* feat(providers): choose which models pickers show first

Provider settings now let you check the models pickers should list first,
with Reset and Undo. Claude's previous releases are marked legacy so
pickers can fold them; the default model is never legacy.

shownModels is overlaid on the provider snapshot at publish time instead of
living in the provider definition's configuration. Anything in that
configuration rebuilds the client and rediscovers the catalog when it
changes, which a checkbox toggle must not do. The catalog is never trimmed,
so search still finds every model.

The settings list keeps its order while you check boxes and re-sorts only
on search, reload, reset or undo, so rows never move under the pointer.
Gated on server_info.features.providerShownModels.

* feat(app): browse models in a two-pane desktop picker

On wide layouts the model picker shows a rail of Profiles and providers
beside the open provider's models. Each provider lists its chosen models
first and folds the rest under "Older models" or "All models". Search
covers every provider and profile at once, ranks shown models ahead of
folded ones, and tags folded matches. Arrow keys move between the rail
and the list, and Escape clears a query before it closes the picker.

The rail is kept on any surface that offers profiles, even with none
yet, so a one-provider host can still reach profile creation. Surfaces
without profiles and with one provider get a single 360px pane. Compact
layouts keep the existing sheet.

* feat(app): set up agents from one drawer on phones

The compact composer opened a second sheet on top of the first for the model
and each control. Phones now get one "Agent settings" drawer whose pages swap
in place: Home inlines thinking and speed pills, switches, and Mode as a radio
list (bypass modes in the warning colour); Model stacks providers as cards with
the open one in a fixed 220px box, so the others stay reachable below it, and
search sits in the thumb zone; Profiles lists saved profiles. Escape clears the
search, then returns Home, then closes. The standalone selector reuses the
Model page. Wide and desktop layouts are unchanged.

The Model page shows an empty state when the host lists no providers, which is
also the state before the first provider snapshot; the shared picker otherwise
falls back to its profiles rail and the page threw.

Themed padding sits on wrapper Views, not contentContainerStyle: the sheet
scrollers drop a themed contentContainerStyle on web.

* fix(app): finish the model picker redesign on phones and in search

- Cycle modes with the keyboard on phones again. The shortcut lived in the
  Mode control, which on phones only mounts while the settings drawer is
  open; the composer's controls now own it on every layout.
- Scroll a folded selected model into view when the phone Model page
  reopens. The fold opened, but the list stayed at the top.
- Rank search results by match strength before shown-vs-folded. Putting
  every shown row first let loose letter-order matches on uncurated
  providers bury exact matches on folded models, such as "Opus 4.6".
  Shown models still win ties.
- Drop ModelBrowser options and sheet scrolling that no caller uses, and
  let SettingsCard shrink instead of the phone list copying its style.

* feat(app): polish mobile model drawer, thinking slider, and desktop focus

- Use a pencil icon button for provider model customization instead of a text label.
- Restore composer focus after picking a model on desktop in workspace drafts and New Workspace, which previously omitted onDropdownClose on DraftAgentControls.
- Move Profiles out of the phone Home card into the Model accordion as the first collapsible category with unified profile + model search, and let every accordion section collapse.
- Render ordered thinking effort and token-budget ranges on phones as a switch-style stepped capsule slider with step dots, and restore the provider icon beside the selected model name plus control icons on inline sections.

* fix(app): fix Android bottom search dock height and update E2E picker helpers

- Give SheetSearchDock flexDirection: "row" and relax SearchField's input height from 20 to minHeight: 20. Inside a column container, SearchField's flex: 1 collapsed vertically on Android and clipped text at the bottom of the Model drawer.
- Update E2E helpers for the redesigned picker: selectPluginModel picks directly from the two-pane rail without clicking Back; applyProfileFromPicker opens the Profiles rail entry first; selectModel clears search on first Escape before closing on second; codex-speed interacts with compact Speed pills inline on Home and verifies the section header icon highlight.
2026-11-28 21:23:34 +07:00
Mohamed Boudra 59377767c7 fix(server): auto-deny unexpected permission prompts in unattended Hub runs (#11179) 2026-11-28 20:53:10 +07:00
Mohamed Boudra 67612b36f3 fix(nix): restore daemon server export in Nix trace and run Nix smoke on PRs (#11193)
* fix(nix): trace runtime edges with dynamic import and verify Nix on PRs

Bundling @getpaseo/cli in #11155 added an esbuild banner that aliases
createRequire as __paseoCliCreateRequire. @vercel/nft only follows
injected require() calls in ESM when createRequire is imported unaliased,
so scripts/trace-daemon.mjs silently dropped @getpaseo/server's exports.js
and exited 0 while the Nix daemon smoke failed at startup.

Inject runtime dependency edges with dynamic import() so nft follows them
in ESM regardless of createRequire aliasing and in CJS without changing
the parsed module type. Assert after tracing that every declared runtime
dependency target and its importer edge are present in nft's file list
before expanding additionalInputs, and run the Linux Nix build and daemon
smoke on pull requests touching Nix, CLI, server, or daemon packaging
inputs.

* fix(nix): include desktop and is-main-module in Nix PR path filter

scripts/trace-daemon.mjs imports scripts/is-main-module.mjs and the
Linux Nix build job also builds .#desktop with PASEO_TRACE_DESKTOP=1.
Include both paths in nix.yml pull_request.paths so changes to either
exercise the Nix build and trace checks before merge.
2026-11-28 20:53:05 +07:00
Mohamed Boudra 01227a73a4 fix(ci): stop painting interrupted main runs red and run CLI tests on server changes (#11192)
* fix(ci): finish main runs and run CLI tests on daemon changes

Cancelling a main run mid-flight left CANCELLED checks that painted the
commit red. Server PRs skipped cli-tests, which drive a real daemon, so two
server regressions first failed on main.

* test(plugin): let the ACP crash be reported before replay ends

The fake agent exits 20 ms after its last history chunk, and the provider
ended replay after 100 ms of silence. When Windows reported the exit later
than that, the open succeeded and the test never saw request.failed.
2026-11-28 20:50:29 +07:00
Kogeki 12a6f07939 fix(app): prevent React #185 update loops in web chat virtualizer (#11138) 2026-11-28 13:42:45 +00:00
paseo-bot[bot] 34d38a82d2 test(server): keep ACP replay open until shutdown in the reopen shutdown test (#11182)
The fake agent streams a history chunk every 20 ms, but the provider ended
replay after 100 ms without one. A runner stall longer than that ended
replay before the daemon stopped, so the reopen finished and the timeline
request resolved instead of being rejected. A 1 s quiet period keeps the
test on the path it checks: shutdown while replay is still streaming.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 12:54:40 +00:00
paseo-bot[bot]and3ae3ae d71d9b37c6 fix(opencode): add the Default thinking option for v2 models (#11184)
The v2 thinking picker listed only a model's explicit variants, so a user who
picked one could not go back to the model's base behaviour. List Default first,
as the v1 adapter does, and send no `variant` when it is selected.

Closes #7225

Co-authored-by: 3ae3ae <ogyshjsm@naver.com>
2026-11-28 12:42:51 +00:00
lukeandRoundRedDot eae885fba4 fix(app): hold back a closing code fence while it is still being typed (#7006)
While a reply streams, the last line of an open code block can hold one or
two backticks of the fence that will close it. Painted, they are a line of
code that disappears a moment later.

The reveal now withholds that line while the turn streams until it closes
the block or turns out to be code. Finished turns paint everything.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-28 12:12:54 +00:00
Mohamed Boudra 6ec8941943 fix(server): report a delegated agent's turn ends as compact tool calls until it settles (#11175)
* refactor(server): let the daemon decide whether an agent message is a tool call or a message

Lifecycle notices (finished, errored, needs permission, closed, still working) now reach
clients as ordinary plain-text tool calls such as "Agent finished · Child". Only peer
send_agent_prompt messages keep the agentMessage sender so they still render as a
"Sent by" bubble. No protocol fields were added.

Delivered prompts carry a trailing <paseo-message .../> marker instead of a leading
<paseo-system> envelope, so the body (including a slash command) stays at character 0
and is no longer XML-escaped. Plain human messages get no marker unless they share a
turn with agent messages or contain marker syntax. Legacy envelopes and legacy
agentMessage notification rows keep rendering (COMPAT tagged).

* fix(server): keep a delivered message's sender when a provider trims the replayed prompt

Claude history replay trims each user prompt, so a body that started with whitespace came
back shorter than the marker's length and replayed as raw text. Drop the body's leading
whitespace before writing the marker.

* fix(server): stop waking the parent when a delegated child ends its turn but is still working

#10864 told the caller "ended its turn but is still working" whenever a child's turn ended
with work pending, and "is still working" after 24 hours of following. The caller could not
act on either notice; it only woke up to wait again. The watch now follows such a child
silently and reports once: finished when it settles, or errored, permission, and closed as
they happen. After 24 hours it reports finished with the child's last reply, so a task that
never ends cannot hold the caller forever.

The still-working event and its agent_still_working tool are gone. Transcripts with #10864's
event="message" notices replay as messages from the child, as clients showed them then.

* fix(server): report every turn end and keep following until the child settles

A child that ends its turn while it still has pending work (a background task such as
`npm run dev`, queued messages, or its own delegated agents) now reports `finished` to its
caller at once. The notice names the pending work and says the caller will hear again. The
subscription keeps following the child: each later turn end reports again, and the child
settling with nothing pending, with or without another turn, sends the final `finished`.
The 24-hour follow limit sends a final `finished` with the child's last reply.

Every notice is a plain `agent_finished` tool call. There is no still-working event.

The observation's initial wait no longer repeats a turn end the stream already reported,
which would have sent the first turn end twice.
2026-11-28 19:01:24 +07:00
paseo-bot[bot]andtieo dbeb181f03 fix(server): keep concurrent agent reloads from failing (#8369)
* fix(server): share concurrent agent refresh results

Keep a refresh in flight until provider history has been hydrated so concurrent
requests receive the same reload outcome across connections.

* fix(server): keep concurrent refreshes within their daemon

Hold reload and history hydration together across client connections, and scope
pending work to the agent manager that owns it. Exercise the real daemon with a
slow-history provider, separate managers, shared failures and subsequent retries.

Co-authored-by: tieo <65707274+tieo@users.noreply.github.com>

* fix(server): capture reload reply before publishing updates

* test(server): run concurrent refresh coverage in CI

* fix(server): preserve each refresh caller workspace recovery

---------

Co-authored-by: tieo <65707274+tieo@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 11:42:40 +00:00
paseo-bot[bot]andChristoph Leiter b261d207c2 fix(server): reuse provider images across daemon restarts (#7895)
* fix(server): reuse provider images across daemon restarts

Co-authored-by: Christoph Leiter <christoph@leiter.io>

* test(server): isolate provider image fixtures from the daemon home

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Christoph Leiter <christoph@leiter.io>
2026-11-28 10:42:44 +00:00
Mohamed Boudra 9933a302bf feat(server,client): support activeTurnBehavior "queue" without sourceAgentId (#11169)
* feat(server,client): support activeTurnBehavior queue without sourceAgentId

Plugins and human UI surfaces previously had to pass steer or interrupt when sending a prompt without sourceAgentId, which could interrupt in-flight tool calls. Non-agent senders can now pass activeTurnBehavior: "queue" to wait behind a running turn and deliver as a normal user prompt once the turn ends, or start immediately when the agent is idle.

- Allow optional source in AgentMessageDelivery; non-agent queued messages skip the 2-second agent coalescing window when idle, stay unwrapped when dispatched alone, and use kind="user-message" envelopes when sharing a provider prompt with other messages.
- Route non-agent queue requests through Session's message queue with prepareAgentMessage, MessageReceipts deduplication, and clearPendingPermissions: false.
- Advertise features.nonAgentMessageQueue and gate non-agent queue in DaemonClient.activeTurnBehaviorForHost with COMPAT(nonAgentMessageQueue).

* docs: document non-agent activeTurnBehavior queue support

* chore: tag nonAgentMessageQueue COMPAT comments with v0.18.2

* test(cli): update terminal-worker upgrade test for protocol version 7

Commit d9497fb1e (#11163) bumped TERMINAL_WORKER_PROTOCOL_VERSION from 6 to 7 with a v6 draining adapter, leaving protocols 0-5 obsolete. Update 46-daemon-terminal-worker-upgrade.test.ts to match protocol version 7 so cli-tests shard 1 passes.
2026-11-28 17:24:28 +07:00
Mohamed Boudra af8601d060 fix(app): wire plugin host client into plugin Markdown for local images (#11171) 2026-11-28 17:24:22 +07:00
Mohamed BoudraandZayooo 82415b7c15 feat(usage): live Claude and Codex usage telemetry and poll schedule fix (#11170)
* feat(usage): push live Claude and Codex usage telemetry and preserve poll schedule

Stream Claude rate_limit_event and Codex account/rateLimits/updated observations
into cached discovered account reports, push status.usage_report_changed updates
to subscribed clients, preserve the 5-minute poll schedule across sidebar
toggles, and retry failed usage fetches with exponential backoff from 30s.

Closes #11115
Co-authored-by: Zayooo <mrcold135@gmail.com>

* fix(usage): preserve poll schedule on push and schedule trailing post-turn refetch

---------

Co-authored-by: Zayooo <mrcold135@gmail.com>
2026-11-28 17:24:12 +07:00
Mohamed Boudra 1f2a88e58a fix(usage): stop showing wrong local account for Claude and Codex wrappers and env tokens (#11154)
When Claude or Codex runs through a wrapper command (such as TeamClaude or a per-profile proxy wrapper) or an explicit login environment token (CLAUDE_CODE_OAUTH_TOKEN, ANTHROPIC_API_KEY, ANTHROPIC_AUTH_TOKEN, CODEX_API_KEY, CODEX_ACCESS_TOKEN), Paseo previously fell back to reading local ~/.claude / macOS Keychain or ~/.codex/auth.json from disk and showed another account's quota card or a rejected-login error.

- Add buildProviderUsageLaunch and expose resolved launch metadata from ClaudeAgentClient/ClaudeAgentSession, CodexAppServerAgentClient/CodexAppServerAgentSession, and ProviderSnapshotManager.listProviderEnvironments.
- Allow built-in claude and codex usage sources to declare provider so PluginService attaches resolved launch metadata on global discovery.
- Suppress local ~/.claude / Keychain and ~/.codex/auth.json fallback across global discovery, configured-provider host discovery (selectProviderUsageEnv), and agent session discovery when launched via a wrapper command, login token override, or foreign endpoint/cloud backend.
- Preserve plain OPENAI_API_KEY without OPENAI_BASE_URL for Codex (matching Codex load_auth precedence), legitimate custom CLAUDE_CONFIG_DIR / CODEX_HOME profiles, custom paths to the default claude / codex binary, and independent OpenCode/Pi/OMP harness routes.

Closes #3228
2026-11-28 16:53:13 +07:00
af4bfad1e2 fix(plugins): treat Node type declarations as host types in the type walk (#8618)
Dependency declarations that `import "node"` (e.g. utif2) pulled @types/node
into the install-time type walk, which failed on node: specifiers newer than
the host Node (node:stream/iter on Node 24) or, with @types/node absent,
on the unresolved "node" import. Map bare "node" in declarations to
@types/node and treat any node: specifier as a builtin.

Co-authored-by: Gabriele Magno <gabrigmm@gmail.com>
Co-authored-by: Gabriele Magno <36011800+nkwib@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 09:43:55 +00:00
Mohamed Boudra 4011199370 feat(mcp,plugin): expose workspace metadata updates via MCP and plugin snapshots (#11166)
* feat(mcp,plugin): expose workspace metadata updates via MCP and plugin snapshots

* fix(app,server): persist workspace metadata in replica cache and normalize null keys on create
2026-11-28 16:26:05 +07:00
paseo-bot[bot]andAndrew McFague a6054adb97 Show completed Pi background subagents after collecting their results (#11168)
* fix(pi): finish tintinweb subagents collected with get_subagent_result

@tintinweb/pi-subagents returns get_subagent_result as plain text with no
details, and reading a result cancels the completion notification. The
adapter only read details.status, so a background child collected this way
stayed running, and history replay after a restart rebuilt it as running.

Read the status from the result's "Agent: <id> / Type: ... | Status: <status>"
header, and look the child up by the header's id, because agent_id can be
the agent's name instead of its id.

* fix(pi): match tintinweb results to the spawn or resume that produced them

A resumed agent gets a new Agent call and its own row, but results were
matched by agent id to whichever call was latest. A completion notification
built before a resume, or a get_subagent_result that started before one,
could mark the resumed run finished while it was still running.

Notifications now go to the call named in their <tool-use-id>, and a
follow-up goes to the attempt that was latest when it started. A
notification without details is read from its <task-notification> blocks.

* fix(pi): finish tintinweb rows for scheduled spawns

An `Agent` call with `schedule` registers a job and returns only text, with
no `details` and no agent id. The adapter added a running row for the call
and never sent a final status, so every scheduled spawn stayed running.

When a completed `Agent` call with `schedule` has no `details`, the row now
ends `completed` if the text reports the registered job (`Scheduled "<name>"
(id: <id>, type: <type>)`), and `failed` for the extension's refusals, such
as scheduling being disabled.

* fix(pi): match name-based follow-ups to the attempt they started on

get_subagent_result accepts a handle such as `explore` as well as an
agent id. The adapter only saved a target for follow-ups that used an
id, so a follow-up by name fell back to the agent's latest call. If the
agent was resumed before the result arrived, the old result marked the
resumed run finished.

Record each agent's spawn and resume calls in order, and note how many
calls existed when a follow-up started. The result header supplies the
agent id, and the follow-up resolves to that agent's latest call from
before it started, whether it named the agent by id or by handle.

* fix(pi): keep collected subagent results on the right run

History replay visits every call in an assistant message before processing their results. Record attempt order as the calls start and attach the native ID when it arrives, so a collected result can finish the child it belongs to. Keep scheduled job registration outside the scope of this fix.

Co-authored-by: Andrew McFague <144809+amcfague@users.noreply.github.com>

---------

Co-authored-by: Andrew McFague <144809+amcfague@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-28 09:12:54 +00:00
Mohamed BoudraandThePharmer 6fc22514ed fix(claude): show Claude progress updates without repeating blocks (#11160)
Reconcile streamed Claude content blocks per block index instead of
against the whole message, preventing duplicate final thinking/text
blocks in multi-block messages (#6463). Buffer thinking deltas until
each block's completed snapshot arrives so blocks marked in
`narration_block_indexes` render as assistant text (for example before
AskUserQuestion) rather than inside Thinking (#6199), while flushing
any unfinished thinking on message stop or terminal turn events with
their explicit turnId preserved.

Co-authored-by: ThePharmer <metastallion@gmail.com>
2026-11-28 15:59:44 +07:00
Mohamed Boudra ea1f2ffab5 fix(server): order Pi and OMP streamed content blocks by contentIndex (#11159)
Pi and OMP tag streamed assistant deltas with contentIndex and can emit deltas for an earlier block after a later block starts. Forwarding deltas in raw arrival order split thinking blocks and cut answer text mid-word or mid-code-fence during live streaming.

Share a MessageContentStream helper across PiRpcAgentSession and OmpAgentSession that holds later indexed text/thinking blocks behind active earlier blocks until block end, flushes buffered content on message boundaries and on turn abort/interrupt/error paths, and avoids blocking on non-streamed or toolCall entries.
2026-11-28 15:59:27 +07:00
Mohamed BoudraandGlen Stampoultzis d9497fb1e4 fix(terminal): report active light/dark palette for OSC, COLORFGBG, and live DEC 2031 theme switches (#11163)
Send the active terminal defaultColors at creation time and sync live palette
updates from the focused viewer through active-viewer ownership (mirroring
terminal-size-ownership). Derive COLORFGBG at PTY spawn unless already set in
env, keep the daemon as the single OSC 10/11/12 responder, track DEC mode 2031
(CSI ? 2031 h/l + DECRQM) and DSR 996/997 reports on live light/dark polarity
switches, and bump TERMINAL_WORKER_PROTOCOL_VERSION from 6 to 7 with a v6
draining adapter.

Closes #2795
Supersedes #4345

Co-authored-by: Glen Stampoultzis <gstamp@gmail.com>
2026-11-28 15:59:18 +07:00
Mohamed BoudraandJustinJoshi 8c18b1558b fix(app): ignore Android system Bold text adjustment to prevent clipping (#11162)
Android 12+ system "Bold text" sets Configuration.fontWeightAdjustment (+300).
TextView applies that weight increase at draw time to text without an explicit
fontWeight or fontFamily, while React Native 0.86.3's TextLayoutManager measures
the text unbolded. The wider drawn glyphs overflow the measured box and clip
trailing words, characters, and lines app-wide (#4057, #10152, #10850).

Add an Android Expo config plugin that overrides MainActivity.attachBaseContext
to zero fontWeightAdjustment on an empty sparse Configuration(), so measurement
and drawing agree while unrelated configuration fields (uiMode, densityDpi,
orientation, screenWidthDp, fontScale, locales) continue updating across
onConfigurationChanged and compose cleanly with PaseoDisplayMetrics (#9995).

Paseo's own bold styles (Markdown **bold**, headings, bold labels) remain bold.

Co-authored-by: JustinJoshi <JustinJoshi@proton.me>
2026-11-28 15:55:59 +07:00
truelecter 2c2393f0ad fix(app): count native touches and typing as presence (#8070) 2026-11-28 08:43:29 +00:00
Mohamed Boudra f786001454 fix(acp): wait for cancel settlement and retire hung ACP subprocesses (#11152)
* fix(acp): wait for cancel settlement and retire hung ACP subprocesses

* fix(acp): keep 2s post-interrupt settlement timeout and unify stale-session reload
2026-11-28 15:04:34 +07:00
Mohamed BoudraandDaniel Stieglmayr 43aaf62c7d fix: prevent workspace update storms on reconnect and batch client directory commits (#11145)
* fix: prevent workspace update storms and batch client directory commits

Fixes three compounding causes of reconnect stalls, 60s RPC timeouts, and
client freezes/ANRs on hosts with many workspaces (especially sharing a Git
checkout):

1. Seed sequenced workspace subscriptions in Session from the full, untagged,
   visibility-filtered descriptor set instead of syncSeq-tagged or partial
   changes-mode response entries, eliminating redundant workspace_update
   re-emits and preserving includeBackground filtering and git observation.
2. Retain a bounded LRU (2,000 entries) of last-known WorkspaceGitService
   snapshots past the 90s warm release grace, serving retained snapshots
   stale-while-revalidate on non-forced getSnapshot reads while revalidating
   in the background Git lane and staying silent when Git state is unchanged.
3. Coalesce overlapping workspace update flushes per subscription and pace
   multi-workspace workspace_update bursts one drained frame at a time so
   interactive RPC replies are never head-of-line blocked on the transport.
4. Batch incoming workspace_update frames per animation frame/tick in
   DirectorySync and WorkspaceDirectoryReplica so a 200-workspace burst
   produces one mergeWorkspaces store commit and one checkpoint write.

Closes #5530
Refs #9487, #7760

Co-authored-by: Daniel Stieglmayr <theunlimited64@gmail.com>

* fix(server): decouple paced workspace burst queue from flush and bootstrap

---------

Co-authored-by: Daniel Stieglmayr <theunlimited64@gmail.com>
2026-11-28 15:03:54 +07:00
Mohamed BoudraandOleg Puchkov bf23004852 fix(desktop): isolate browser webview focus during agent automation (#11158)
* fix(desktop): isolate browser webview focus during agent automation

Prevent Electron browser guests from stealing keyboard focus from the
chat composer while an agent drives parked or visible split-pane tabs:

- Gate BrowserPane's webview focus/mousedown promoter so non-presented
  panes and agent-guarded presses never call onFocusPane, webview.focus,
  or paseo:browser:focus; mark parked 1x1 surfaces inert with tabindex=-1.
- Focus browser_type and browser_keypress targets via DOM element.focus
  plus caret-to-end positioning instead of CDP mousePressed.
- Bracket CDP pointer presses (browser_click, browser_drag) with a
  ref-counted host focus guard (including IME composition protection,
  50ms late-focus recheck, and Emulation.setFocusEmulationEnabled(true)).

Closes #4679
Supersedes #10603

Co-authored-by: Oleg Puchkov <puchkoff@gmail.com>

* fix(desktop): verify DOM focus in browser_type and require host focus guard in ipc

---------

Co-authored-by: Oleg Puchkov <puchkoff@gmail.com>
2026-11-28 15:03:44 +07:00
Mohamed BoudraandQichang Zheng 3680a4a185 fix(usage): discover configured custom provider accounts with strict source scoping (#11149)
* fix(usage): discover configured custom provider accounts with strict source scoping and locator env allowlist

Host Usage listings previously scanned only the daemon's default login stores,
leaving custom Claude and Codex providers configured with their own
CLAUDE_CONFIG_DIR, CLAUDE_SECURESTORAGE_CONFIG_DIR, or CODEX_HOME invisible in
Usage until one of their agents was opened.

Host Usage now discovers enabled providers that configure usage-locator
environment variables, while enforcing two strict security boundaries:
- Provider-matched dispatch: each configured provider scope is sent ONLY to
  usage sources whose declared `providers` list includes that provider's base
  provider ID (never broadcast to unrelated or third-party usage plugins).
- Explicit locator env allowlist: only non-secret config-directory /
  credential-store locator environment variables (including
  CLAUDE_CONFIG_DIR, CLAUDE_SECURESTORAGE_CONFIG_DIR, CODEX_HOME,
  OPENCODE_CONFIG_DIR, XDG_CONFIG_HOME, XDG_DATA_HOME, HOME, etc.) cross into
  usage discovery. Raw auth tokens, API keys, and arbitrary custom env vars
  are stripped, and foreign-endpoint providers are excluded daemon-side.

Also adds CLAUDE_SECURESTORAGE_CONFIG_DIR support to Claude Keychain route
derivation and preserves cached usage, recovery history, sidebar summary, and
source-toggle behavior across provider renames.

Closes #3589

Co-authored-by: Qichang Zheng <qichang.zheng2000@gmail.com>

* refactor(usage): keep provider env allowlist filtering solely inside UsageSourceRegistry

* fix(usage): allow OPENCODE_DB in host usage discovery locator env allowlist

---------

Co-authored-by: Qichang Zheng <qichang.zheng2000@gmail.com>
2026-11-28 15:01:48 +07:00
Mohamed Boudra 9808fd4198 perf(cli): cut CLI startup overhead with lean client, lazy dispatch, and esbuild bundling (#11155)
* perf(cli): cut CLI startup overhead with lean client, lazy dispatch, and esbuild bundling

- Add lean protocol codec and @getpaseo/client/node/lean entry that skip ws-outbound.aot.js and full Zod message schemas, and dynamically import @getpaseo/relay only for pairing-offer/E2EE targets
- Replace eager command imports in packages/cli/src/cli.ts with a static command manifest + lazy dynamic imports, remove duplicate createCli() in run.ts, and lazy-load yaml/chalk in output rendering
- Extract zero-Zod PID, home, and credential helpers to @getpaseo/server/daemon-files
- Bundle @getpaseo/cli with esbuild code splitting (--splitting --format=esm --minify) and update scripts/trace-daemon.mjs
- Fast-path complete agent UUIDs in resolveAgentEntry() via fetchAgent() without paginating archived agents

* fix(client): generate zero-Zod schema defaults for lean protocol codec

- Generate message-defaults.ts from Zod protocol schemas inside generate-validation-aot.mjs (50 outbound + 11 inbound tables, agent snapshot defaults, legacy transform fallbacks, and hello.rejected reasons)
- Apply generated defaults in leanProtocolCodec so older daemons get the same defaulted fields as strictProtocolCodec without loading Zod or ws-outbound.aot.js
- Add strict-vs-lean parity tests across legacy outbound, inbound, and status payloads
- Deduplicate sync/async CLI renderer dispatch between render.ts and render-async.ts
- Switch startup-boundary runtime hook test to module.registerHooks + synchronous stderr flush and it.skipIf for missing dist

* fix(protocol): support prefault and reject unlisted non-pure schemas in defaults generator

- Support Zod .prefault() nodes directly in message-defaults.ts (e.g., pull_request_timeline_response with omitted payload)
- Fail generate:validators loudly if any new .catch() or .transform()/.preprocess() schema is added without a lean rule or explicit legacy allowlist entry
- Add pull_request_timeline_response omitted-payload parity test to lean.test.ts
2026-11-28 15:01:34 +07:00
Mohamed Boudra 5d4793ddc1 Let plugins expose local HTTP services at public URLs through tunnel providers (#11036)
* feat(plugins): add tunnel provider plugins with cloudflared and tailscale funnel built-ins

Plugins can now register a tunnel provider that turns a local HTTP host:port
into a public HTTPS URL. The daemon's TunnelManager owns exposures and their
lifecycle, so a provider only reports state through report() and stops when
its signal aborts. Exposures close when the owning plugin stops, reloads, is
disabled, or crashes, and when the daemon shuts down.

This is the shared primitive that later work uses to expose MCP servers and
workspace services. Clients gate on server_info.features.tunnelProviders.

* fix(plugins): keep tunnel exposures from reporting wrong URLs or outliving Paseo

- cloudflared: the quick-tunnel URL pattern matched api.trycloudflare.com in
  provisioning errors, so an offline open reported ready with the API endpoint.
- tailscale-funnel: `funnel --bg` stored the Funnel in tailscaled, so a crashed
  plugin or daemon left the target public with no owner. Run the Funnel in the
  foreground instead; tailscaled drops it when the CLI exits.
- tailscale-funnel: a failed `funnel status` counted as "no ports in use" and
  could replace and later remove the user's own handler. Fail the open instead.
- Add the Chinese translation of the tunnel providers reference section.

* fix(plugins): ship cloudflared with quick tunnels only

A named Cloudflare tunnel routes through ingress set in the Cloudflare
dashboard, so its URL never served the exposure target. Two exposures for
different targets both reported ready at the same URL. Named tunnels return
later with per-target routing.

Also mark the tunnel-provider example as requiring 0.18.0-beta.1, like the
notifications example, so the example build test loads it.

* fix(plugins): detect missing tunnel CLIs and run tunnel tests on Windows

On Windows a bare name that is not on PATH runs through cmd.exe, which exits
9009 instead of failing the spawn with ENOENT. The providers reported a
missing tailscale as "not running". Treat exit 9009 as not installed.

The fake CLIs were shebang scripts, which Windows does not run, and the
tests relied on SIGTERM handlers that a Windows force kill skips. The fakes
now get a .cmd launcher on Windows, and the tests check that the fake
process is gone instead of a handler side effect.

* test(plugins): replace the Windows Path variable in tunnel CLI tests

Windows keeps the original case of environment names, usually `Path`.
Spreading process.env and setting `PATH` left the real search path beside
the override, so the missing-CLI tests could still find or query a real CLI.
The missing-CLI tests now assert the exact "not installed" status.

* test(plugin): parse shared declarations once in SDK boundary type checks

Each typeErrors() call built a fresh program and parsed the SDK, library,
and dependency declarations again. On a slow Windows runner one check took
over the 5 s test timeout. The checks now share the parsed configuration
and declaration files, so each one parses only its snippet. The file runs
in about a quarter of the time locally.

* fix(plugins): launch tunnel CLIs without a shell so a missing CLI reads as not installed

On Windows a bare name that is not on PATH ran through cmd.exe, which exits
with a generic code and a localized "not recognized" message. The providers
then reported a missing tailscale or cloudflared as "not running" or "failed
to query". Without a shell the spawn fails with ENOENT on every platform.
Both CLIs ship as executables; a .cmd set as a full binary path still runs
through cmd.exe. This replaces the exit-code 9009 check, which cmd.exe does
not return as the process exit code.
2026-11-28 14:36:10 +07:00
cb5bcb5a60 feat(app): act on files from chat links, file tabs, and a filterable Files tree (#11073)
Shared workspace file actions across file tabs, compact file sheets, chat/Markdown links, Files tree, and Changes pane, plus desktop open-in-default-app, explicit Reveal in Files, workspace-wide Files sidebar filter, shared 16px tree indent guides, and Android link long-press selection fix.

Refs #10699

Co-authored-by: YASICJUNWOO <99794552+YASICJUNWOO@users.noreply.github.com>
Co-authored-by: apple-ouyang <45086632+apple-ouyang@users.noreply.github.com>
Co-authored-by: iqshen <24309546+iqshen@users.noreply.github.com>
Co-authored-by: Ctrl-Creeper <190502953+Ctrl-Creeper@users.noreply.github.com>
Co-authored-by: softyoda <13988751+softyoda@users.noreply.github.com>
2026-11-28 14:34:54 +07:00
73fab19166 fix(usage): discover Cursor credentials across macOS, Windows, and Linux (#11148)
Cursor 3.27+ encrypts `cursorAuth/accessToken` in `state.vscdb` with a
`cursor-safe-storage:v1:` Electron safeStorage prefix, so sending that
value as a bearer token caused Usage to fail with HTTP 401. At the same
time, discovery missed the macOS Keychain (`cursor-access-token` /
`cursor-user`), macOS `~/.cursor/auth.json`, and Windows
`%APPDATA%\Cursor\auth.json`, and stopped at the first candidate instead
of letting the usage registry fall back after a 401.

- Skip `cursor-safe-storage:` values across every token store and reader
  so ciphertext is never sent as a bearer token.
- Add macOS Keychain (`cursor-access-token` / `cursor-user`) and
  `~/.cursor/auth.json` discovery to both global and session lookup.
- Add Windows `%APPDATA%\Cursor\auth.json` discovery to global lookup.
- Return all unique usable credentials in priority order so
  `UsageSourceRegistry.fetchWithFallback` tries the next candidate when
  an earlier credential is rejected.

Co-authored-by: jasonhnd <3293256+jasonhnd@users.noreply.github.com>
Co-authored-by: Kevin <kevin.pierrot@gmail.com>
Co-authored-by: Sian Lerk Lau <kiawin@gmail.com>
Co-authored-by: ChicorSun <125846596+ChicorSun@users.noreply.github.com>
Co-authored-by: Karl Bitz <kb@wardbitz.com>
2026-11-28 14:27:30 +07:00
Mohamed BoudraandJiayang Wu 4842f7e24d fix(usage): support OpenCode v2 usageSession, OpenCode session scopes, and Codex opencode.db logins (#11153)
* fix(usage): support OpenCode v2 usageSession, session scopes, and Codex opencode.db logins

- Implement usageSession() on OpenCodeV2Session with provider "opencode",
  authoritative model tracking (info.model falling back to config.model),
  effective provider + launch harness environment, and a stable sessionKey.
- Read active and migrated OpenAI OAuth logins from OpenCode v2's opencode.db
  in codex-usage-source (honoring absolute/relative OPENCODE_DB, active=1 or
  migrated active IS NULL, falling back to v1 auth.json, and normalizing
  provider to "opencode").
- Add OpenCode session-scope discovery to built-in usage sources OpenCode
  serves (opencode-go, minimax, zai, kimi, grok, copilot, openrouter-host).

Co-authored-by: Jiayang Wu <651475459@qq.com>

* fix(usage): keep Copilot/Kimi default visibility hints and deduplicate session discovery helpers

---------

Co-authored-by: Jiayang Wu <651475459@qq.com>
2026-11-28 14:22:19 +07:00
Mohamed Boudra ada93c7a1a Upload image attachments via file.upload.request instead of inlining base64 (#11137)
* feat(app,server): upload image attachments via file.upload.request

Previously, sending images inlined base64 payloads directly inside
send_agent_message_request and create_agent_request JSON messages,
causing phone photos to exceed relay message limits (#2668) and
multi-photo batches on Android to overflow OkHttp's 16 MiB outbound
WebSocket queue and close with code 1001 (#11117).

- Upload attached images sequentially via DaemonClient.uploadFile
  (file.upload.request + 128 KiB FileChunk frames) across all composer,
  queued send, draft creation, new workspace, and workspace setup paths.
- Pace DaemonClient.uploadFile on unpaced transports (supportsDrain=false)
  with a 1 MiB correlated ping/pong flush barrier so single >16 MiB files
  cannot overflow OkHttp's outbound queue, and start the 60s RPC response
  deadline only after FileEnd so slow uplinks do not time out mid-stream.
- Resolve uploadedImages on the daemon into native { type: "image" }
  provider content blocks after enforcing canonical realpath containment
  inside join(paseoHome, "uploads"), and project UploadedImage metadata
  onto user_message timeline items so thumbnails and lightbox previews
  persist across reloads and devices.
- Preserve full resolution and quality for JPEG/PNG images (picker
  quality: 1, no downscaling for already-supported formats) while keeping
  HEIC/HEIF conversion to resized JPEG for provider vision compatibility.

* test(server): canonicalize temp paseoHome path in prompt-attachments test

* refactor(protocol,app,server): carry uploaded images as uploaded_file attachments with role="image"

Replace the separate top-level `uploadedImages` wire field with an
optional `role: "image"` hint on `UploadedFileAttachmentSchema` inside
the existing `attachments` array.

- On current daemons, `resolveAgentPrompt` partitions `uploaded_file`
  entries with `role: "image"` out of `attachments`, validates canonical
  `realpath` containment in `$PASEO_HOME/uploads`, resolves them into
  native `{ type: "image", data, mimeType }` provider vision blocks, and
  projects `user_message.images` thumbnails.
- On older daemons (v0.1.91-v0.18.1), Zod strips only the unknown
  optional `role` field and preserves the valid `uploaded_file`
  attachment (`type`, `id`, `fileName`, `mimeType`, `size`, `path`), so
  an auto-updated mobile or web app never silently drops photos against
  an older host.
- Plain `Upload file` attachments (without `role: "image"`) remain
  unchanged (`Uploaded file: ... Path: ...`).
- Also reverts the unrelated conditional-spread refactor in
  `DaemonClient.createLegacyAgent`.
2026-11-28 13:51:56 +07:00
Mohamed Boudra e05d39bdde fix(server): serve agent endpoints on loopback and bypass HTTP proxies (#11144)
Local agent subprocesses expect an HTTP loopback URL for Paseo's built-in
MCP server (/mcp/agents) and terminal activity hooks (/api/terminal-activity).
Previously, bootstrap derived both URLs directly from the primary listener,
so Unix-socket and named-pipe daemons returned null (silently omitting MCP
and terminal activity) and non-loopback TCP listeners handed agents a
non-loopback address that fails loopback validation and proxy bypass. In
addition, providers spawned under a user's HTTP_PROXY routed local 127.0.0.1
MCP requests through the proxy and failed with HTTP 502 / handshake errors.

Introduce a daemon-owned loopback agent endpoint that reuses the primary
listener when it is already loopback-reachable TCP and otherwise binds a
dedicated 127.0.0.1:0 HTTP server exposing only /mcp/agents and
/api/terminal-activity with loopback remote-address, Host-header, and bearer
auth checks. Merge 127.0.0.1, localhost, and ::1 into NO_PROXY (and no_proxy
when set) in the shared provider launch environment without clobbering user
entries.
2026-11-28 13:51:48 +07:00
5e568571ba fix(app): fix Android terminal typing, Backspace, CJK/Latin IMEs, and hardware Enter (#11146)
* fix(app): replace hidden Android terminal TextInput with native input view

Android's hidden React Native TextInput splits every IME edit into two
unsynchronized JS events (onChangeText and onKeyPress), hides Android's
active composing span, omits deleteSurroundingTextInCodePoints, and leaves
multiline newline residue after Enter. Those boundary flaws caused doubled
first/initial characters, locked or dropped Backspace, swallowed Latin
candidates in mixed CJK/English keyboards, broken Korean Hangul after
Enter, and duplicate hardware Enter presses.

Replace the hidden Android TextInput with a dedicated 1x1 native Android
PaseoTerminalInputView backed by a custom BaseInputConnection
(TerminalInputConnection) and onKeyDown handler in paseo-terminal. The
native input connection coalesces batch edits, diffs against real Android
composing spans, clears its private Editable after commit/finish, handles
all three Backspace paths, emits a single CR on Enter, and sets
EditorInfo flags directly without ReactFindViewUtil patching.

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
Co-authored-by: Lennart Schoch <lennart@usebounce.com>
Co-authored-by: Jason <jaeysin@gmail.com>

* fix(app): expose composing state via ComposingTextOwner and deduplicate terminal input types

React Native's BaseViewManager.setTestId overwrites the unkeyed View.tag
with the string testID, which would hide PaseoTerminalInputView's active
IME composing span from PaseoHardwareKeyboardModule.

Introduce ComposingTextOwner in paseo-hardware-keyboard and implement it
on PaseoTerminalInputView so hardware arrow routing reads composing state
without touching View.tag. Also re-export shared terminal input types
from terminal-input.types.ts in terminal-input.native.tsx and drop its
unreachable Android hardware-keyboard effect.

---------

Co-authored-by: Ouyang Xingyuan <galaxyroaming@qq.com>
Co-authored-by: Lennart Schoch <lennart@usebounce.com>
Co-authored-by: Jason <jaeysin@gmail.com>
2026-11-28 13:51:06 +07:00
paseo-bot[bot]andClaude Opus 5.5 3b5cf28cae fix(terminal): force-kill the program on Windows when killAndWait times out (#11147)
On Windows, node-pty's kill closes the pseudoconsole and kills the
console's processes only after a forked helper reports them. The force
step of killAndWait repeated that same soft kill. The terminal worker
exits right after killAndWait during shutdown, so on a slow machine the
helper's kill never ran and the program outlived its worker. This made
"Restart and close terminals" leave the program running and flaked the
terminal-worker-lifecycle Windows test.

The force step now kills the program's process tree with tree-kill.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 06:50:54 +00:00
Mohamed Boudra feb0d74ab5 chore(website): update Hoplite's sponsor tagline (#11150)
The new tagline is the sponsor's own wording and is much longer. With two
long captions the footer sponsors band pushed "Become a sponsor" onto its
own row in the docs column (max-w-prose, about 700px), so the footer
placement uses narrower captions and a smaller column gap.
2026-11-28 13:47:42 +07:00
cd5b713a1b fix(app): keep terminal text in the code font when an interface font is set (#11099)
The interface font rule applies to every element outside a `data-pmono`
surface. The terminal root had no marker, so xterm's DOM renderer rows took
the interface font while the cell grid was measured with the code font.

Fixes #6903

Co-authored-by: sh0nuff <sh0nuff@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 06:42:58 +00:00
Mohamed Boudra fef4530e4a fix(codex): inject MCP servers as per-server config overrides (#11142)
Codex combines process-level -c overrides and thread/start request config
overrides sequentially in build_cli_overrides_layer. Sending a whole-table
mcp_servers object (including an empty {}) replaces the entire mcp_servers
table built from earlier -c mcp_servers.* flags, wiping out alias-configured
MCP servers.

Emit dotted mcp_servers.<name> keys (and omit MCP keys entirely when empty)
so Paseo-injected MCP servers and tool-policy preapprovals merge alongside
alias -c overrides and config.toml servers. Fall back to a single whole-table
mcp_servers only when a server name contains a dot, which Codex's
path.split('.') override parser cannot represent as one segment.
2026-11-28 13:23:54 +07:00
d77356210e fix(server): close Claude launch race, pre-init idle lock, and unbounded metadata generation (#11143)
Close three verified provider child-process leaks (Part of #4450):

1. Single-flight Claude query launch (`ensureQuery`): concurrent callers
   (such as the app and plugins both requesting commands on resume) now
   share one in-flight `queryStart` promise instead of spawning duplicate
   `claude` processes and overwriting `this.childProcess`. A restart
   requested mid-launch retires the stale query and relaunches once, a
   pre-launch restart mark is consumed when launch options are copied,
   and `queryStarting` is always cleared in `finally`.

2. Pre-init prompt withdrawal (`ClaudeRuntimeSafety`): track `initSeen`
   separately from `turnSeen` so withdrawing every unstarted prompt before
   `system/init` clears `turnSeen` and allows idle collection to stop the
   runtime, while preserving the hold when a turn had already started or
   announced `init`.

3. Bounded structured metadata generation (`generateStructuredAgentResponse`):
   enforce a 300s default deadline across retries and share one deadline
   across `generateStructuredAgentResponseWithFallback`, so stalled
   internal metadata agents always reach `finally` and call `closeAgent`.

Co-authored-by: Desmond Leong <desmond@returning.ai>
Co-authored-by: Nicholas Salgueiro <nickmaglowsch3@gmail.com>
2026-11-28 13:23:40 +07:00
630 changed files with 56525 additions and 13894 deletions
+6 -2
View File
@@ -1,6 +1,6 @@
# Pull-request checks are routed by the behavior they prove. Package consumers
# do not inherit their dependencies' test suites; main and manual runs execute
# every contract regardless of these paths.
# do not inherit their dependencies' test suites, except where noted below; main
# and manual runs execute every contract regardless of these paths.
routing:
- ".github/ci-paths.yml"
@@ -87,5 +87,9 @@ browser:
relay:
- "packages/relay/**"
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
# plugins included, so daemon changes run it too.
cli:
- "packages/cli/**"
- "packages/server/**"
- "plugins/**"
+18 -5
View File
@@ -8,13 +8,14 @@ on:
merge_group:
workflow_dispatch:
# A newer push to the same ref cancels the run still in progress, main included.
# A full run costs about 200 runner-minutes against the org's 20 concurrent
# jobs, and a superseded main run only answers a question the newer commit
# answers again.
# A newer push cancels the run still in progress on every ref except main,
# because a full run costs about 200 runner-minutes against the org's 20
# concurrent jobs. A main run finishes: cancelling it mid-flight leaves CANCELLED
# checks that paint the commit red. Each ref has one run in progress and one
# pending, so a newer push replaces a pending main run before it starts any job.
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
env:
# CI does not use the CUDA execution provider, and the onnxruntime-node
@@ -174,6 +175,9 @@ jobs:
- name: Verify dependency patch recovery
run: node --test scripts/postinstall-patches.test.mjs
- name: Verify daemon runtime trace contract
run: node --test scripts/trace-daemon.test.mjs
- name: Build server stack
run: npm run build:server
@@ -213,6 +217,15 @@ jobs:
- name: Verify website mockups
run: npm run test:e2e --workspace=@getpaseo/website
- name: Upload website test artifacts
uses: actions/upload-artifact@v4
if: failure()
with:
name: website-playwright-results
path: packages/website/test-results/
if-no-files-found: ignore
retention-days: 7
- name: Verify public package contents
run: |
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
+3 -1
View File
@@ -13,9 +13,11 @@ on:
- ".github/workflows/desktop-packages.yml"
workflow_dispatch:
# A main run finishes. A run cancelled mid-flight leaves CANCELLED checks that
# paint the commit red.
concurrency:
group: desktop-packages-${{ github.ref }}
cancel-in-progress: true
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
permissions:
contents: read
+3 -1
View File
@@ -28,9 +28,11 @@ on:
- "false"
- "true"
# main, tag and publish runs finish. A run cancelled mid-flight leaves CANCELLED
# checks that paint a main commit red.
concurrency:
group: docker-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.publish == 'true' && format('publish-{0}', inputs.paseo_version || github.run_id) || github.ref }}
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
env:
REGISTRY: ghcr.io
+30
View File
@@ -3,8 +3,37 @@ name: Nix
on:
push:
branches: [main]
# Prove the real Nix package and daemon smoke before merge when Nix, CLI,
# server, or daemon packaging inputs change.
pull_request:
paths:
- "nix/**"
- "flake.nix"
- "flake.lock"
- "package.json"
- "package-lock.json"
- "packages/protocol/**"
- "packages/client/**"
- "packages/highlight/**"
- "packages/plugin/**"
- "packages/server/**"
- "packages/relay/**"
- "packages/cli/**"
- "packages/desktop/**"
- "plugins/**"
- "skills/**"
- "scripts/trace-daemon.mjs"
- "scripts/is-main-module.mjs"
- "scripts/build-daemon-web-ui.mjs"
- "scripts/update-nix.sh"
- "scripts/fix-lockfile.mjs"
- ".github/workflows/nix.yml"
workflow_dispatch:
concurrency:
group: nix-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
permissions:
contents: read
@@ -102,6 +131,7 @@ jobs:
run: nix build .#desktop -o result-desktop
build-desktop-darwin:
if: ${{ github.event_name != 'pull_request' }}
runs-on: macos-latest
steps:
- uses: actions/checkout@v4
+1
View File
@@ -86,6 +86,7 @@ packages/server/src/server/fixtures/dictation/dictation-debug-largest.wav
packages/server/src/server/fixtures/dictation/dictation-debug-largest.transcript.txt
packages/protocol/src/generated/validation/*.aot.ts
packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts
packages/protocol/src/generated/validation/message-defaults.ts
packages/protocol/codegen/generated/
/artifacts
+1 -1
View File
@@ -58,7 +58,7 @@
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo のスポンサーになる</a></td>
</tr>
+1 -1
View File
@@ -52,7 +52,7 @@
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo 스폰서 되기</a></td>
</tr>
+1 -1
View File
@@ -57,7 +57,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="56"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
</tr>
+1 -1
View File
@@ -58,7 +58,7 @@
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/zh-CN/sponsor">成为 Paseo 赞助商</a></td>
</tr>
+22 -15
View File
@@ -154,17 +154,17 @@ Users can also detach an existing subagent from the subagents track. Detach is d
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
An agent sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. `steer` and `interrupt` mean what they mean for a person. A person's send has no `queue`. Each kind of prompt is released this way:
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
- **`queue`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries. Finish notifications and change-request updates always queue.
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages. Finish notifications and change-request updates always queue.
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
- **A person's prompt** (app, CLI, top-level MCP) is dispatched directly with its existing steer or interrupt behavior and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) is dispatched directly and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`.
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`. A new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
A command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and a `steer` or `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text.
@@ -198,17 +198,24 @@ outstanding intent. A crash after successful dispatch but before removal commits
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. When the child ends its turn with work that will start its
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
the subscription keeps following the child. That work is a running turn, queued messages, a pending
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
recurring crons, change-request watches, and other daemon background items never count: they are
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
is stored before the notice is sent, so restarts resume following without repeating it, and following
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
report their first turn end as `finished`.
A turn end is not always a settled child. A child can end its turn with work that will start its next
turn by itself: a running turn, queued messages, a pending provider wake-up
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
crons, change-request watches, and other daemon background items never count: they are external
triggers, not work the caller is waiting for.
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
subscription follows the child: each later turn end reports `finished` again, and the child settling
with nothing pending sends a final `finished` and removes the subscription, even when the work
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
the child's last reply and the subscription ends. Remote children and providers without the probe
report their first turn end as a settled `finished`.
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
+7 -4
View File
@@ -209,7 +209,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
listen: "127.0.0.1:6767",
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
mcp: { enabled: boolean, injectIntoAgents: boolean },
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
appendSystemPrompt: string, // appended to supported provider system/developer prompts
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
@@ -311,12 +312,14 @@ Each entry may include a Paseo-tool policy:
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for
agents that can access the host through a shell.
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
+3 -4
View File
@@ -205,10 +205,9 @@ docker build \
.
```
The Docker workflow builds the image on pull requests and on `main` as a
non-publishing check. Stable `vX.Y.Z` tag pushes publish
`ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`. Beta tags
publish only the exact prerelease tag, such as
The Docker workflow builds the image on `main` as a non-publishing check.
Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and
`ghcr.io/getpaseo/paseo:latest`. Beta tags publish only the exact prerelease tag, such as
`ghcr.io/getpaseo/paseo:0.1.102-beta.1`, and do not update `latest`.
To replace a Docker image in place without rebuilding desktop, APK, or EAS
+1 -3
View File
@@ -72,9 +72,7 @@ hashes, never prompts, environment values, or credentials.
Before messaging an archived workspace, call `workspace.recovery.inspect.request`, then
`workspace.recovery.restore.request` and await success. The native message handler unarchives the
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so
`activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn
when that provider cannot steer. The daemon rejects `queue` on a direct send.
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so `activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn when that provider cannot steer, and `activeTurnBehavior: "queue"` waits for the running turn to end when the host advertises `server_info.features.nonAgentMessageQueue`.
Execution completion and arrival-specific output authority remain Hub responsibilities.
The older `hub.execution.*` RPCs remain accepted for existing clients. Their execution ownership
+3 -3
View File
@@ -95,9 +95,9 @@ A focused terminal excludes that binding. The source leaves terminal Escape alon
terminal Escape/Ctrl forwarding is a separate feature.
Terminal arrows never pass through the shortcut pipeline. The Android hardware
module claims them while the terminal's hidden input (`nativeID`) owns the focus.
`TextInput.onKeyPress` only sees IME keys, and an arrow that falls through moves
the hidden caret and desyncs the next text change, so the pipeline cannot own them.
module claims them while the terminal's native input (`nativeID`) owns the focus,
so Android DPAD focus search cannot move focus away from the terminal view, while
leaving active IME composition spans untouched for candidate navigation.
## Keys shared with text editing
+2
View File
@@ -12,6 +12,8 @@ Every block is separated by one gap, `density.blockGap`: 12 on compact layouts,
Workspace file links use the shared file-link resolver. The workspace supplies its client, root and open-file action once; chat can supply the agent's more specific context. URLs use the same link press path. Recognized inline-code paths stay tappable. The library callback carries the tapped occurrence’s syntax context. Preserve it when opening files: explicit Markdown links decode URL escapes, while recognized inline-code paths preserve literal percent characters and use suffix lookup. Identical URL strings in different occurrences must stay distinct. Explicit absolute workspace links receive a relative hover title; existing authored titles remain intact. Inside a workspace, forge references such as `#12` and `owner/repo#12` are recognized in prose (not code) and open the workspace forge; the reference pattern comes before path recognition so `group/project#12` is not read as a path. See [forge providers](forge-providers.md#gotchas).
Right-click on web and long press on native open one link menu per rendered part (`components/markdown/link-menu`), not one per link: a menu root cannot sit inside a paragraph without producing invalid markup on web. The native long-press event carries only the URL, with no position and no syntax context. The menu takes the position from the touch that started the press, and treats a URL that is no `](destination)` in the source as recognized text.
Pass `external` for author-controlled Markdown from outside the host, such as a plugin README. It follows the registry's overview contract in `packages/protocol/src/plugin-overview.ts`, which the website also uses: only absolute https links and images work, and any other destination renders as its label or alt text. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only https. None of the workspace recognition above applies, so `Node.js` is prose, not a file. The lines of a paragraph join, as they do on the README's forge.
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[![Retrigger](badge.svg)](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (fixed in the fork).
+2
View File
@@ -63,6 +63,8 @@ An arbitrary Activity launch with data extras does not exercise Expo's FCM path.
Foreground pushes remain in Notification Center without a banner or sound.
This preserves notifications sent with stale presence information.
Native clients have no DOM events, so presence comes from `@/hooks/native-user-activity`: touches on the root `GestureHandlerRootView` and edits in the native `EditingTextInput` refresh `lastActivityAt`. Touches inside a native `Modal` open a separate window and do not reach the root.
## Startup and verification
Wait for the root navigator, host registry, remembered selection, and startup
+7
View File
@@ -103,6 +103,13 @@ The `worktree-include` built-in copies gitignored files selected by
[`.worktreeinclude`](../public-docs/worktrees.md#copy-local-files-with-worktreeinclude)
before setup and agents, through `worktree.create.after`.
The `cloudflared-tunnel` and `tailscale-funnel` built-ins register tunnel providers through
`server.registerTunnelProvider()`. Both start without installed binaries or credentials and report
availability through `status()`. `cloudflared-tunnel` runs quick tunnels only, with `--url` set to
the exposure target. Named Cloudflare tunnels are not supported: the Cloudflare dashboard sets
their routing, so their URL does not serve the exposure target. `tailscale-funnel` runs `tailscale funnel` in the foreground: with
`--bg`, tailscaled keeps the Funnel public after a crash with no owner.
Desktop packaging ships the entire built-in plugin directory as an external resource,
including declarations. The external esbuild compiler cannot read Electron's `app.asar`
filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation.
+1 -1
View File
@@ -21,7 +21,7 @@ The protocol package owns generation.
- `packages/protocol/src/validation/ws-outbound-envelope.ts` defines the tag-only envelope schema and exposes the session message schemas that get their own validators.
- `packages/protocol/scripts/generate-validation-aot.mjs` writes the zod-aot discovery entry and the runtime schema metadata, runs the exact-pinned compiler, and applies the small local compiler patches before generation. It also emits the `type` → validator map the boundary dispatches through.
- `packages/protocol/scripts/watch-validation-aot.mjs` reruns generation while editing protocol sources.
- `packages/protocol/codegen/generated/ws-outbound.compile.ts`, `packages/protocol/src/generated/validation/ws-outbound.aot.ts`, and `packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts` are generated and gitignored. The metadata module lets generated code reach schema fallback/default values.
- `packages/protocol/codegen/generated/ws-outbound.compile.ts`, `packages/protocol/src/generated/validation/ws-outbound.aot.ts`, `packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts`, and `packages/protocol/src/generated/validation/message-defaults.ts` are generated and gitignored. The metadata module lets generated code reach schema fallback/default values, and `message-defaults.ts` lets zero-Zod clients (`packages/protocol/src/validation/message-defaults.ts`) apply every schema `.default()` without loading Zod or `ws-outbound.aot.ts`.
Generation runs from protocol-owned lifecycle hooks: `prebuild`, `pretypecheck`, `pretest`, and `watch`. Installs do not run generation: published packages consume protocol from prebuilt `dist`, and local build/typecheck/test flows generate the source file at the point it is actually needed.
+4 -3
View File
@@ -118,8 +118,9 @@ An explicit user instruction can select another base.
`chore(release): cut <version>` without a tag.
5. Push the release branch (`git push -u origin HEAD`). Pushing any `release/**` branch triggers
`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.
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
each other and a newer merge replaces the pending one.
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, push the tag first with `npm run release:push` so remote builds start right away.
@@ -278,7 +279,7 @@ The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Relea
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (a running check finishes, and a newer merge replaces the pending one). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
The production relay is the Elixir service in [getpaseo/paseo-relay](https://github.com/getpaseo/paseo-relay), with its own deployment process. Paseo releases and pushes to this repository do not deploy it. The Cloudflare relay code and workflow in this repository are legacy and are not used in production.
+1 -1
View File
@@ -200,7 +200,7 @@ Test suites in this repo are heavy. Running them in bulk freezes the machine, es
## Pull-request test routing
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. The CLI E2E tests are the exception: they drive a real daemon, so changes to the server or built-in plugins run them too. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
Required matrix legs are declared as statically named jobs. Their shared steps use YAML anchors, while job-level `if` conditions let GitHub report an unaffected leg as genuinely skipped without allocating a runner or losing the exact required-check name.
+24 -8
View File
@@ -330,19 +330,35 @@ that starts or accepts them. Received messages retain sender attribution, while
notifications remain visible events. Collapse, timing and locally mounted history share
these boundaries.
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
Agent-message markup belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
removed senders must remain understandable without a live directory lookup.
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
presentation (`protocol/paseo-tool-presentation`) owns its heading and expanded details, next to the
labels for every Paseo MCP tool. The daemon
must not construct UI labels or prepend sender labels to the semantic message body. The existing
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
Each delivered message keeps its text first and ends with a `<paseo-message … length="N"/>` marker.
Text at character 0 stays the sender's, so a provider still reads a slash command there, and bodies
are never escaped. `length` bounds the text before the marker, so marker syntax inside a body cannot
split it, and a batch splits back into rows by reading markers from the end. A person's prompt gets a
marker only when it shares a provider turn with other deliveries or contains `<paseo-message` or
`<paseo-system`. Transcripts written before markers open with a `<paseo-system>` envelope; the
projection still reads those (`COMPAT(leadingPaseoSystemEnvelope)`).
The daemon decides whether a delivery is a message or a tool call, and clients render what it sends:
- A person's text is a `user_message`.
- A peer message is an `agent_message` tool call whose `agentMessage` carries sender and text. The
wire has no sender on `user_message`, so clients present it as a "Sent by" bubble.
- Lifecycle notifications (`agent_finished`, `agent_errored`, `agent_needs_permission`,
`agent_closed`), schedule fires (`heartbeat`), and change-request updates
are plain tool calls. `plain_text` detail carries the sender in `label`, the body in `text`, and
the icon. Clients render the heading from the tool name, so no notification event reaches them.
`isTimelineTurnTrigger` (`packages/protocol/src/timeline-turn.ts`) lists the delivered tool names that
start a turn. Add a name there when the daemon projects a new delivery. Rows that older daemons stored
with notification `agentMessage` metadata are rewritten to the plain call at presentation
(`COMPAT(agentNotificationMetadata)`). Stream reduction and disk-cache serialization preserve the
payload without rendering it.
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
+8 -2
View File
@@ -47,8 +47,14 @@
"ignore": ["android/**", "ios/**", ".expo/**", "dist/**", "scripts/reset-project.js"]
},
"packages/cli": {
"entry": ["src/index.ts", "bin/paseo", "src/**/*.test.{ts,tsx}", "tests/**/*.{ts,tsx}"],
"project": ["src/**/*.{ts,tsx}", "tests/**/*.{ts,tsx}"]
"entry": [
"src/index.ts",
"bin/paseo",
"scripts/**/*.mjs",
"src/**/*.test.{ts,tsx}",
"tests/**/*.{ts,tsx}"
],
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.mjs", "tests/**/*.{ts,tsx}"]
},
"packages/relay": {
"entry": ["src/index.ts", "src/e2ee.ts", "src/cloudflare-adapter.ts", "src/**/*.test.ts"],
+2
View File
@@ -2,6 +2,7 @@ const fs = require("node:fs");
const path = require("node:path");
const pkg = require("./package.json");
const withAndroidAsyncStorageSize = require("./plugins/with-android-async-storage-size");
const withAndroidIgnoreBoldText = require("./plugins/with-android-ignore-bold-text");
const withAndroidOptionalCamera = require("./plugins/with-android-optional-camera");
const withAndroidProfileable = require("./plugins/with-android-profileable");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
@@ -148,6 +149,7 @@ export default {
withPasteInput,
withAndroidScroll,
withAndroidDisplayMetrics,
withAndroidIgnoreBoldText,
[withAndroidAsyncStorageSize, 64],
...buildProfile.cameraPlugins,
withAndroidOptionalCamera,
+89
View File
@@ -112,3 +112,92 @@ describe("hardware keyboard scene integration", () => {
expect(configureHardwareKeyboardAppDelegate(configured)).toBe(configured);
});
});
// Android Bold text bolds unstyled text at draw time after React Native measured it
// unbolded, which clips trailing words (#4057, #10152, #10850). The activity must opt out
// with a sparse Configuration() so other configuration fields still update live.
describe("Android Bold text opt-out", () => {
const {
configureIgnoreBoldTextMainActivity,
} = require("./plugins/with-android-ignore-bold-text.js");
const {
configureDisplayMetricsActivity,
} = require("./modules/paseo-display-metrics/app.plugin.js");
const mainActivity = [
"package sh.paseo",
"import expo.modules.splashscreen.SplashScreenManager",
"",
"import android.os.Build",
"import android.os.Bundle",
"",
"import com.facebook.react.ReactActivity",
"",
"class MainActivity : ReactActivity() {",
" override fun onCreate(savedInstanceState: Bundle?) {",
" super.onCreate(null)",
" }",
"}",
"",
].join("\n");
it("zeroes fontWeightAdjustment on a sparse Configuration before attaching and is idempotent", () => {
const configured = configureIgnoreBoldTextMainActivity(mainActivity);
expect(configured).toMatch(/^import android\.content\.Context$/m);
expect(configured).toMatch(/^import android\.content\.res\.Configuration$/m);
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
expect(configured).toContain("val override = Configuration()");
expect(configured).not.toContain("Configuration(configuration)");
expect(configured).toContain("override.fontWeightAdjustment = 0");
expect(configured).toContain(
"super.attachBaseContext(newBase.createConfigurationContext(override))",
);
expect(configured.indexOf("attachBaseContext")).toBeLessThan(configured.indexOf("onCreate"));
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
});
it("composes cleanly with withAndroidDisplayMetrics in both plugin orders", () => {
const displayFirst = configureIgnoreBoldTextMainActivity(
configureDisplayMetricsActivity(mainActivity),
);
const boldFirst = configureDisplayMetricsActivity(
configureIgnoreBoldTextMainActivity(mainActivity),
);
for (const configured of [displayFirst, boldFirst]) {
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
expect(configured).toContain("val override = Configuration()");
expect(configured).toContain("override.fontWeightAdjustment = 0");
expect(configured).toContain("override fun onContentChanged()");
expect(configured).toContain(
"override fun onConfigurationChanged(newConfig: android.content.res.Configuration)",
);
expect(configured).toContain(
"sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)",
);
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
expect(configureDisplayMetricsActivity(configured)).toBe(configured);
}
});
it("fails the prebuild when the MainActivity template changes shape", () => {
expect(() => configureIgnoreBoldTextMainActivity("package sh.paseo\n")).toThrow(
/MainActivity class declaration/,
);
});
it("fails the prebuild rather than duplicate an existing attachBaseContext override", () => {
const withExistingOverride = mainActivity.replace(
"override fun onCreate",
"override fun attachBaseContext(newBase: Context) { super.attachBaseContext(newBase) }\n\n override fun onCreate",
);
expect(() => configureIgnoreBoldTextMainActivity(withExistingOverride)).toThrow(
/existing attachBaseContext override/,
);
});
it("is registered in the app config", async () => {
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
// Expo records function plugins by name.
expect(exp.plugins).toContain("withAndroidIgnoreBoldText");
}, 30_000);
});
@@ -6,16 +6,15 @@ import {
expectComposerDoesNotName,
expectAgentProfilesEmptyPrompt,
expectHostAgentProfiles,
expectProfileEditTooltip,
expectComposerMode,
expectCreateProfileFromModelRow,
expectComposerModel,
expectModelRowProfileActionBesideRow,
expectModelRowSelected,
expectProfileEditIsPencilOnly,
expectProfileReachableByScrolling,
expectProfileSearchResult,
expectProfileVisibleForProvider,
expectPickerProfile,
expectProfilesEditLink,
fillAgentProfileName,
openEditProfileFromModelRow,
openModelPicker,
@@ -86,17 +85,19 @@ test.describe("Agent profiles in the model picker", () => {
await expectComposerMode(page, "Load test");
});
await test.step("the sole provider opens directly", async () => {
await test.step("the picker opens on the agent's provider with Profiles beside it", async () => {
await openModelPicker(page);
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
await expect(page.getByTestId("sheet-header-back")).toHaveCount(0);
await expect(page.locator('[data-testid^="model-provider-"]')).toHaveCount(0);
await expectProfileVisibleForProvider(page, {
await expect(page.getByTestId("model-search-input").first()).toBeFocused();
await expect(page.getByTestId("model-provider-mock")).toHaveAttribute(
"data-active",
"true",
);
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
await expectPickerProfile(page, {
name: PROFILE.name,
summary: PROFILE_SUMMARY,
});
await expectProfileEditIsPencilOnly(page);
await expectProfileEditTooltip(page);
await expectProfilesEditLink(page);
});
await test.step("applying it writes its model and mode into the composer", async () => {
@@ -115,14 +116,13 @@ test.describe("Agent profiles in the model picker", () => {
await expectComposerDoesNotName(page, PROFILE.name);
});
await test.step("reopening returns directly to the provider models", async () => {
await test.step("reopening returns to the provider models with the new model checked", async () => {
await openModelPicker(page);
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
await expectProfileVisibleForProvider(page, {
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
await expectPickerProfile(page, {
name: PROFILE.name,
summary: PROFILE_SUMMARY,
});
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
await closeModelPicker(page);
});
} finally {
@@ -0,0 +1,559 @@
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import {
beginTextReveal,
retargetTextReveal,
visibleRevealedText,
} from "../../src/agent-stream/text-reveal";
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: Object.fromEntries(
[
"claude",
"codex",
"copilot",
"opencode",
"pi",
"omp",
"antigravity",
"hoplite",
"muse",
].map((id) => [id, { enabled: false }]),
),
},
},
});
interface ClosingFenceFrameSample {
text: string;
codeBlockHeights: number[];
codeBlockTexts: string[];
messageHeights: number[];
partialFenceLines: string[];
}
interface ClosingFenceFrameReport {
finished: boolean;
samples: ClosingFenceFrameSample[];
}
async function sampleClosingFenceFrames(page: Page): Promise<ClosingFenceFrameReport> {
return await page.evaluate(async () => {
const samples: ClosingFenceFrameSample[] = [];
let finished = false;
await new Promise<void>((resolve) => {
const tick = () => {
const messages = Array.from(
document.querySelectorAll<HTMLElement>('[data-testid="assistant-message"]'),
);
const text = messages.map((message) => message.textContent ?? "").join("");
const sample: ClosingFenceFrameSample = {
text,
codeBlockHeights: [],
codeBlockTexts: [],
messageHeights: messages.map((message) =>
Math.round(message.getBoundingClientRect().height),
),
partialFenceLines: [],
};
for (const message of messages) {
for (const block of message.querySelectorAll<HTMLElement>(
'pre, [data-paseo-markdown-tag="pre"]',
)) {
const code = block.querySelector<HTMLElement>('code, [data-paseo-markdown-tag="code"]');
const codeText = code?.textContent ?? block.textContent ?? "";
sample.codeBlockTexts.push(codeText.trimEnd());
// Opening fence prefixes render as prose; closing artifacts live inside code blocks.
for (const line of codeText.split(/\r?\n/)) {
if (/^\s*`{1,2}\s*$/.test(line)) sample.partialFenceLines.push(line);
}
sample.codeBlockHeights.push(Math.round(block.getBoundingClientRect().height));
}
}
samples.push(sample);
finished = text.includes("Both blocks are closed.");
if (finished) {
resolve();
return;
}
requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
});
return { finished, samples };
});
}
const FIRST_PAUSE_TEXT = "Here is the first snippet:const answer = 42;\nconsole.log(answer);";
const SECOND_PAUSE_TEXT = `${FIRST_PAUSE_TEXT}And a second one:echo done`;
for (const { label, html } of [
{ label: "semantic", html: "<pre><code>const answer = 42;\n`\n``</code></pre>" },
{
label: "annotated",
html: '<div data-paseo-markdown-tag="pre"><span data-paseo-markdown-tag="code">const answer = 42;\n`\n``</span><button>Copy</button></div>',
},
{
label: "annotated semantic",
html: '<pre data-paseo-markdown-tag="pre"><code data-paseo-markdown-tag="code">const answer = 42;\n`\n``</code></pre>',
},
]) {
test(`samples ${label} code block DOM without duplicate blocks or controls`, async ({ page }) => {
await page.setContent(
`<div data-testid="assistant-message">${html}<p>Both blocks are closed.</p></div>`,
);
const report = await sampleClosingFenceFrames(page);
const sample = report.samples.at(-1)!;
expect(report.finished).toBe(true);
expect(sample.codeBlockTexts).toEqual(["const answer = 42;\n`\n``"]);
expect(sample.partialFenceLines).toEqual(["`", "``"]);
expect(sample.codeBlockHeights).toHaveLength(1);
expect(sample.codeBlockHeights[0]).toBeGreaterThan(0);
});
}
function closingFencePauseSamples(
samples: readonly ClosingFenceFrameSample[],
pauseText: string,
): ClosingFenceFrameSample[] {
return samples.filter((sample) => sample.text === pauseText);
}
function expectStableGeometry(
samples: readonly ClosingFenceFrameSample[],
expectedCodeBlockTexts: readonly string[],
): void {
expect(samples.length, "the paused text state should be sampled").toBeGreaterThan(0);
expect(
samples.every(
(sample) => JSON.stringify(sample.codeBlockTexts) === JSON.stringify(expectedCodeBlockTexts),
),
"the sampled code should contain only the authored lines",
).toBe(true);
const geometries = new Set(
samples.map((sample) => JSON.stringify([sample.messageHeights, sample.codeBlockHeights])),
);
expect(
geometries.size,
"message and code block geometry should stay fixed during the pause",
).toBe(1);
}
/**
* A closing fence that is still being typed must not be painted as code.
*
* The mock reply closes each code block in two arrivals: one backtick, a pause,
* then the other two. Painted, that first backtick is a line of code that
* vanishes when the fence completes, so the block grows and shrinks and every
* row below it moves twice. Each pause is sampled and its text geometry checked.
*/
test("does not paint a closing fence while it is still being typed", async ({ page }, testInfo) => {
test.setTimeout(90_000);
const agent = await seedMockAgentWorkspace({
repoPrefix: "closing-fence-",
title: "Closing fence",
model: "e2e-fast-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const reportPromise = sampleClosingFenceFrames(page);
await agent.client.sendAgentMessage(
agent.agentId,
"Stream a code block with a split closing fence.",
);
const report = await reportPromise;
await testInfo.attach("closing-fence-frames", {
body: JSON.stringify(report, null, 2),
contentType: "application/json",
});
expect(report.finished, "the reply should finish streaming").toBe(true);
expect(
report.samples.flatMap((sample) => sample.partialFenceLines),
"no frame, including transitions outside the pause windows, may show a partial fence inside code",
).toEqual([]);
const firstPauseSamples = closingFencePauseSamples(report.samples, FIRST_PAUSE_TEXT);
const secondPauseSamples = closingFencePauseSamples(report.samples, SECOND_PAUSE_TEXT);
expectStableGeometry(firstPauseSamples, ["const answer = 42;\nconsole.log(answer);"]);
expectStableGeometry(secondPauseSamples, [
"const answer = 42;\nconsole.log(answer);",
"echo done",
]);
expect(secondPauseSamples[0]?.codeBlockHeights[0]).toBe(
firstPauseSamples[0]?.codeBlockHeights[0],
);
} finally {
await agent.cleanup();
}
});
test("excludes each revealed character of the next paragraph from both pauses", () => {
for (const [pauseText, paragraph] of [
[FIRST_PAUSE_TEXT, "And a second one:"],
[SECOND_PAUSE_TEXT, "Both blocks are closed."],
]) {
const state = retargetTextReveal(beginTextReveal(pauseText), pauseText + paragraph);
const samples = Array.from({ length: paragraph.length + 1 }, (_, index) => ({
text: visibleRevealedText({ ...state, revealed: pauseText.length + index }),
codeBlockHeights: [],
codeBlockTexts: [],
messageHeights: [index],
partialFenceLines: [],
}));
expect(closingFencePauseSamples(samples, pauseText)).toEqual([samples[0]]);
}
});
for (const { label, markdown, expectedCode, expectedPartialFenceLines } of [
{
label: "opening prefixes in prose",
markdown: "And a second one:\n\n`\n\n``\n\nBoth blocks are closed.",
expectedCode: [],
expectedPartialFenceLines: [],
},
{
label: "partial fences inside rendered code",
markdown: "```ts\nconst answer = 42;\n`\n``\n```\n\nBoth blocks are closed.",
expectedCode: ["const answer = 42;\n`\n``"],
expectedPartialFenceLines: ["`", "``"],
},
]) {
test(`samples ${label} in the correct container`, async ({ page }, testInfo) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "fence-sample-container-",
title: "Fence sample container",
featureValues: { mockAssistantResponse: markdown },
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const reportPromise = sampleClosingFenceFrames(page);
await agent.client.sendAgentMessage(agent.agentId, "Show the fence sampling fixture.");
const report = await reportPromise;
await testInfo.attach("fence-container-frames", {
body: JSON.stringify(report, null, 2),
contentType: "application/json",
});
expect(report.finished).toBe(true);
const messageText = await page.getByTestId("assistant-message").innerText();
const messageLines = messageText.split(/\r?\n/);
const messageFenceLines = messageLines.filter((line) => /^\s*`{1,2}\s*$/.test(line));
expect(messageFenceLines).toEqual(["`", "``"]);
const finalSample = report.samples.at(-1);
expect(finalSample?.codeBlockTexts).toEqual(expectedCode);
expect(finalSample?.partialFenceLines).toEqual(expectedPartialFenceLines);
} finally {
await agent.cleanup();
}
});
}
test("shows the complete reasoning after a streamed turn finishes", async ({ page }, testInfo) => {
test.setTimeout(90_000);
await page.setViewportSize({ width: 1280, height: 900 });
await page.addInitScript(() => {
localStorage.setItem(
"@paseo:app-settings",
JSON.stringify({ toolCallDetailLevel: "detailed", autoExpandReasoning: true }),
);
});
const reasoning =
"Need to find the scroll container, the layout effect that watches for new messages, and any gesture handler that might fight with programmatic scrolling. Probably a ref on the FlatList plus a near-bottom threshold.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "finished-reasoning-",
title: "Finished reasoning",
model: "ten-second-stream",
});
const historyClient = await connectDaemonClient<
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
>({ clientIdPrefix: "finished-reasoning-history" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await agent.client.sendAgentMessage(
agent.agentId,
"Stream briefly to check finished reasoning.",
);
await agent.client.waitForFinish(agent.agentId, 30_000);
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
const thoughts = history.entries
.map((entry) => entry.item)
.filter((item) => item.type === "reasoning");
await testInfo.attach("canonical-reasoning", {
body: JSON.stringify(thoughts, null, 2),
contentType: "application/json",
});
expect(thoughts[0]?.text).toBe(reasoning);
const expectedCounts = new Map<string, number>();
for (const thought of thoughts)
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
const rendered = page.getByText(reasoning, { exact: true });
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
await expect(rendered.first()).toBeVisible();
await testInfo.attach("finished-reasoning", {
body: await page.screenshot(),
contentType: "image/png",
});
await page.reload();
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
await expect(rendered.first()).toBeVisible();
} catch (error) {
await testInfo.attach("reasoning-before-cleanup", {
body: await page.screenshot(),
contentType: "image/png",
});
throw error;
} finally {
await historyClient.close();
await agent.cleanup();
}
});
test("records equal-input long-reply rendering metrics", async ({ page }, testInfo) => {
test.setTimeout(120_000);
await page.setViewportSize({ width: 1280, height: 900 });
const markdown =
Array.from({ length: 15 }, (_, index) =>
[
"### Block " + index,
"",
"\x60\x60\x60ts",
...Array.from(
{ length: 12 },
(_value, line) => "const value_" + index + "_" + line + " = " + (index * 12 + line) + ";",
),
"\x60\x60\x60",
"",
].join("\n"),
).join("\n") + "\nEqual-input stream complete.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "equal-input-long-reply-",
title: "Equal-input long reply",
featureValues: {
mockStreamingAssistantResponse: markdown,
mockStreamingAssistantIntervalMs: 5,
},
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const session = await page.context().newCDPSession(page);
await session.send("Performance.enable");
const before = await session.send("Performance.getMetrics");
const sampler = await page.evaluateHandle(() => {
const state = {
frames: [] as number[],
longTasks: [] as number[],
running: true,
last: performance.now(),
};
const observer = new PerformanceObserver((list) => {
state.longTasks.push(...list.getEntries().map((entry) => entry.duration));
});
observer.observe({ type: "longtask", buffered: false });
const tick = (now: number) => {
state.frames.push(now - state.last);
state.last = now;
if (state.running) requestAnimationFrame(tick);
};
requestAnimationFrame(tick);
return { state, observer };
});
await agent.client.sendAgentMessage(agent.agentId, "Render the fixed fifteen-block fixture.");
await agent.client.waitForFinish(agent.agentId, 60_000);
const message = page.getByTestId("assistant-message").last();
await expect(message).toContainText("Equal-input stream complete.", { timeout: 30_000 });
const blocks = message.locator('pre, [data-paseo-markdown-tag="pre"]');
await expect(blocks).toHaveCount(15);
for (let index = 0; index < 15; index++) {
await expect(blocks.nth(index)).toContainText(
"const value_" + index + "_11 = " + (index * 12 + 11) + ";",
);
}
const samples = await sampler.evaluate(({ state, observer }) => {
state.running = false;
state.longTasks.push(...observer.takeRecords().map((entry) => entry.duration));
observer.disconnect();
return state;
});
const after = await session.send("Performance.getMetrics");
const frames = [...samples.frames].sort((a, b) => a - b);
await testInfo.attach("equal-input-rendering", {
body: JSON.stringify(
{
markdown,
viewport: page.viewportSize(),
intervalMs: 5,
frameCount: frames.length,
frameP95Ms: frames[Math.floor(frames.length * 0.95)],
maxFrameMs: frames.at(-1),
longTasksMs: samples.longTasks,
before: before.metrics,
after: after.metrics,
},
null,
2,
),
contentType: "application/json",
});
await sampler.dispose();
await session.detach();
} finally {
await agent.cleanup();
}
});
test("manually expands complete reasoning after leaving output following", async ({
page,
}, testInfo) => {
test.setTimeout(90_000);
await page.setViewportSize({ width: 1280, height: 900 });
await page.addInitScript(() => {
localStorage.setItem(
"@paseo:app-settings",
JSON.stringify({ chatDisplay: "full", autoExpandReasoning: false }),
);
});
const agent = await seedMockAgentWorkspace({
repoPrefix: "manual-finished-reasoning-",
title: "Manual finished reasoning",
model: "ten-second-stream",
});
const historyClient = await connectDaemonClient<
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
>({ clientIdPrefix: "manual-finished-reasoning-history" });
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await agent.client.sendAgentMessage(
agent.agentId,
"Stream briefly to check finished reasoning.",
);
const finished = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finished.status).toBe("idle");
await testInfo.attach("manual-completed-turn", {
body: JSON.stringify(finished),
contentType: "application/json",
});
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
const thoughts = history.entries
.map((entry) => entry.item)
.filter((item) => item.type === "reasoning");
expect(thoughts.length).toBeGreaterThan(0);
expect(thoughts.every((thought) => thought.text.length > 0)).toBe(true);
const expectedCounts = new Map<string, number>();
for (const thought of thoughts)
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
await testInfo.attach("manual-canonical-reasoning", {
body: JSON.stringify(thoughts, null, 2),
contentType: "application/json",
});
const pointerCapture = await page.evaluateHandle(() => {
const events: {
type: string;
timestamp: number;
tag: string;
label: string;
scrollTop: number | null;
}[] = [];
const observe = (event: Event) => {
const target = event.target;
if (!(target instanceof HTMLElement)) return;
const scroll = document.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
events.push({
type: event.type,
timestamp: event.timeStamp,
tag: target.tagName,
label: target.textContent?.slice(0, 80) ?? "",
scrollTop: scroll?.scrollTop ?? null,
});
};
for (const type of ["pointerdown", "pointerup", "wheel"])
document.addEventListener(type, observe, true);
return {
events,
stop: () => {
for (const type of ["pointerdown", "pointerup", "wheel"])
document.removeEventListener(type, observe, true);
},
};
});
const badges = page.getByTestId("tool-call-badge").filter({ hasText: "Thinking" });
await expect(badges).toHaveCount(thoughts.length);
// Locator scrolling alone leaves output-following armed, so pointer-down can
// snap the feed to its tail before pointer-up reaches the Thinking control.
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
for (let index = 0; index < thoughts.length; index++) {
await badges
.nth(index)
.getByRole("button", { name: "Thinking", exact: true })
.first()
.click();
await expect(
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
).toBeVisible();
}
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
const first = badges.first();
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
await expect(first.getByText(thoughts[0].text, { exact: true })).not.toBeVisible();
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
await expect(first.getByText(thoughts[0].text, { exact: true })).toBeVisible();
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
await testInfo.attach("manual-expanded-reasoning", {
body: await page.screenshot(),
contentType: "image/png",
});
const pointerEvents = await pointerCapture.evaluate(({ events, stop }) => {
stop();
return events;
});
await pointerCapture.dispose();
await testInfo.attach("manual-pointer-events", {
body: JSON.stringify(pointerEvents, null, 2),
contentType: "application/json",
});
await page.reload();
await expect(badges).toHaveCount(thoughts.length);
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
for (let index = 0; index < thoughts.length; index++) {
await badges
.nth(index)
.getByRole("button", { name: "Thinking", exact: true })
.first()
.click();
await expect(
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
).toBeVisible();
}
for (const [text, count] of expectedCounts)
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
} catch (error) {
await testInfo.attach("manual-before-cleanup", {
body: await page.screenshot(),
contentType: "image/png",
});
throw error;
} finally {
await historyClient.close();
await agent.cleanup();
}
});
@@ -84,17 +84,14 @@ async function openModelSelector(page: Page) {
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 10_000 });
}
async function dismissStackedModelPickerWithBackdrop(page: Page) {
await page
.getByTestId("agent-controls-settings-list")
.getByRole("button", { name: /Select model/ })
.click();
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport();
await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24);
// In CI, Gorhom retains the dismissed sheet below the viewport.
// Dismissal is complete when it leaves the displayed surface.
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
async function openModelPage(page: Page) {
await page.getByTestId("agent-controls-model").click();
await expect(page.getByTestId("mobile-model-page")).toBeVisible();
await expect(page.getByTestId("agent-controls-settings-list")).toHaveCount(0);
}
async function returnHomeWithBack(page: Page) {
await page.getByTestId("sheet-header-back").click();
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
}
@@ -113,7 +110,7 @@ async function openAndCloseModelSelectorTwice(page: Page) {
}
test.describe("mobile bottom sheet reopen", () => {
test("sheets reopen and model search returns to configuration", async ({ page }) => {
test("sheets reopen and a model pick returns to Home", async ({ page }) => {
const session = await openMockAgentAtMobileBreakpoint(page);
try {
await test.step("tab switcher opens, closes, and reopens", async () => {
@@ -124,24 +121,28 @@ test.describe("mobile bottom sheet reopen", () => {
await openAndCloseModelSelectorTwice(page);
});
await test.step("model search returns to configuration", async () => {
await test.step("the Model page swaps in place and Back returns to Home", async () => {
await openModelSelector(page);
const sheet = page.getByTestId("agent-controls-model-sheet");
await openModelPage(page);
await returnHomeWithBack(page);
await expect(sheet).toBeVisible();
});
await dismissStackedModelPickerWithBackdrop(page);
await page.getByTestId("model-search-all-input").click();
await test.step("a model found by search returns to Home with that model", async () => {
await openModelPage(page);
const search = page.getByTestId("model-search-all-input");
await expect(search).not.toBeFocused();
await search.click();
await search.fill("Ten second");
const model = page.getByRole("button", { name: /^Ten second stream/ });
await expect(model).toBeVisible({
timeout: 10_000,
});
await expect(model).toBeVisible({ timeout: 10_000 });
await model.click();
await expect(sheet).toBeVisible();
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream");
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
});
} finally {
await session.cleanup();
@@ -1042,7 +1042,7 @@ test("changes context menu recursively collapses descendant folders", async ({ p
nestedLabel.boundingBox(),
]);
if (!rootBounds || !nestedBounds) throw new Error("Changes tree rows have no bounds");
expect(nestedBounds.x - rootBounds.x).toBe(12);
expect(nestedBounds.x - rootBounds.x).toBe(16);
await tree.getByTestId("diff-folder-src-toggle").click({ button: "right" });
await page.getByTestId("diff-folder-src-collapse-folder").click();
+25 -1
View File
@@ -30,7 +30,14 @@ test.use({
const ACTIVE_SPEED_COLOR = "rgb(251, 191, 36)";
const NORMAL_SPEED_COLOR = "rgb(113, 113, 122)";
const COMPACT_SPEED_CONTROL = "agent-feature-service_tier";
const COMPACT_SPEED_SECTION = `${COMPACT_SPEED_CONTROL}-section`;
async function openSpeedSelector(page: Page): Promise<void> {
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
if (await compactSection.isVisible().catch(() => false)) {
return;
}
const speed = page.getByRole("button", { name: /^(Select speed|Speed: .+)$/ });
const features = page.getByRole("button", { name: "Open agent features", exact: true });
const modelSettings = page.getByRole("button", { name: /^Select model \(/ });
@@ -39,7 +46,12 @@ async function openSpeedSelector(page: Page): Promise<void> {
});
if (!(await speed.isVisible())) {
if (await features.isVisible()) await features.click();
else await modelSettings.click();
else {
await modelSettings.click();
await expect(compactSection).toBeVisible({ timeout: 30_000 });
await expect(compactSection.getByText("Normal", { exact: true })).toBeVisible();
return;
}
}
await expect(speed).toBeVisible({ timeout: 30_000 });
await speed.click();
@@ -47,6 +59,13 @@ async function openSpeedSelector(page: Page): Promise<void> {
}
async function selectSpeed(page: Page, label: string): Promise<void> {
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
if (await compactSection.isVisible().catch(() => false)) {
const pill = compactSection.getByRole("button", { name: label, exact: true });
await pill.click();
await expect(pill).toHaveAttribute("aria-selected", "true");
return;
}
await page.getByRole("button", { name: label, exact: true }).last().click();
const toolbarTrigger = page.getByRole("button", { name: `Speed: ${label}`, exact: true });
const sheetTrigger = page.getByRole("button", { name: "Select speed", exact: true });
@@ -56,6 +75,11 @@ async function selectSpeed(page: Page, label: string): Promise<void> {
}
async function expectSpeedIconColor(page: Page, color: string): Promise<void> {
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
if (await compactSection.isVisible().catch(() => false)) {
await expect(compactSection.locator("svg").first()).toHaveCSS("stroke", color);
return;
}
const trigger = page
.getByRole("button", { name: /^(Speed: .+|Select speed)$/ })
.filter({ visible: true });
@@ -3,6 +3,7 @@ import path from "node:path";
import { expect, test } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSubagentRowGone,
@@ -29,6 +30,89 @@ import {
const FILE_LINK = "linked.ts:3";
test("compact offers file actions from a link and from the file sheet", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await seedMockAgentWorkspace({
repoPrefix: "compact-file-actions-",
title: "File actions",
initialPrompt: promptMentioning(FILE_LINK),
});
try {
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
const fileLink = page.getByText(FILE_LINK, { exact: true });
await expect(fileLink).toBeVisible({ timeout: 15_000 });
// Native opens the same sheet from a long press.
await fileLink.click({ button: "right" });
const linkMenu = page.getByTestId("markdown-link-menu-content");
await expect(linkMenu.getByRole("menuitem")).toHaveText([
"Open file",
"Reveal in Files",
"Download",
"Copy path",
"Copy relative path",
]);
await linkMenu.getByRole("menuitem", { name: "Open file" }).click();
await expect(sheet(page, "linked.ts")).toBeVisible();
await page.getByTestId("sheet-file-menu-trigger").click();
const sheetMenu = page.getByTestId("sheet-file-menu-content");
await expect(sheetMenu.getByRole("menuitem")).toHaveText([
"Reveal in Files",
"Download",
"Copy path",
"Copy relative path",
]);
await expect(sheetMenu.getByRole("menuitem").last()).toBeInViewport({ ratio: 1 });
await page.screenshot({
path: test.info().outputPath("compact-file-sheet-menu.png"),
animations: "disabled",
});
await sheetMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
await expectNoSheetOpen(page);
await expect(
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
).toContainText("linked.ts");
await page.screenshot({
path: test.info().outputPath("compact-reveal-in-files.png"),
animations: "disabled",
});
} finally {
await workspace.cleanup();
}
});
test("a narrow desktop window keeps the desktop actions in the file sheet menu", async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await seedMockAgentWorkspace({
repoPrefix: "narrow-desktop-file-actions-",
title: "File actions",
initialPrompt: promptMentioning(FILE_LINK),
});
try {
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
await installLocalDesktopHost(page, workspace.cwd, { fileManager: "Dolphin" });
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await page.getByText(FILE_LINK, { exact: true }).click();
await expect(sheet(page, "linked.ts")).toBeVisible({ timeout: 15_000 });
await page.getByTestId("sheet-file-menu-trigger").click();
await expect(page.getByTestId("sheet-file-menu-content").getByRole("menuitem")).toHaveText([
"Reveal in Files",
"Reveal in Dolphin",
"Open in default app",
"Download",
"Copy path",
"Copy relative path",
]);
} finally {
await workspace.cleanup();
}
});
test("compact opens files and subagents in a sheet, leaving the tabs for agents", async ({
page,
}) => {
@@ -387,7 +387,10 @@ test.describe("Composer model and effort shortcuts", () => {
const effortLabel = page.getByTestId("combined-model-selector-thinking-label");
await expect(effortLabel).toHaveText("Medium");
await toggleModelPickerFromComposer(page);
await expectModelPickerClosesFromSearch(page);
const drawerModelRow = page.getByTestId("agent-controls-model");
await expect(drawerModelRow).toBeVisible();
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
await expect(drawerModelRow).toBeHidden();
await cycleComposerEffort(page);
await expect(effortLabel).toHaveText("High");
});
@@ -0,0 +1,143 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import {
expectExplorerEntryHidden,
expectExplorerEntryVisible,
expandFolder,
expectFileTabOpen,
openFileExplorer,
} from "../support/helpers/file-explorer";
import { gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
let workspace: SeededWorkspace;
test.beforeEach(async () => {
workspace = await seedWorkspace({ repoPrefix: "file-explorer-filter-" });
await mkdir(path.join(workspace.repoPath, "data/nested"), { recursive: true });
await writeFile(path.join(workspace.repoPath, "data/nested/report.csv"), "name,total\n");
await mkdir(path.join(workspace.repoPath, "docs"), { recursive: true });
await writeFile(path.join(workspace.repoPath, "docs/guide.md"), "# Guide\n");
});
test.afterEach(async () => {
await workspace?.cleanup();
});
function filterInput(page: Page) {
return page.getByTestId("files-filter-input");
}
function matches(page: Page) {
return page.locator('[data-testid^="file-filter-row-"][aria-selected]');
}
function match(page: Page, name: string) {
return matches(page).filter({ hasText: name });
}
test("finds files in collapsed folders and acts on them", async ({ page }) => {
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
await expandFolder(page, "docs");
await expectExplorerEntryVisible(page, "guide.md");
await filterInput(page).fill("report");
await expect(matches(page)).toHaveCount(1);
await expect(match(page, "report.csv")).toContainText("data/nested");
// Draggable onto the chat, like a tree row.
await expect(match(page, "report.csv").locator('[draggable="true"]')).toHaveCount(1);
await match(page, "report.csv").click({ button: "right" });
const menu = page.getByTestId(/file-filter-row-\d+-context-menu$/);
for (const name of [
"Reveal in Files",
"Copy path",
"Copy relative path",
"Download",
"Rename",
"Delete",
]) {
await expect(menu.getByRole("menuitem", { name, exact: true })).toBeVisible();
}
await expect(menu.getByRole("menuitem", { name: "New file", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(menu).toHaveCount(0);
await match(page, "report.csv").click();
await expectFileTabOpen(page, "data/nested/report.csv");
// Escape restores the tree with its expanded folders.
await filterInput(page).press("Escape");
await expect(filterInput(page)).toHaveValue("");
await expectExplorerEntryVisible(page, "guide.md");
await expectExplorerEntryHidden(page, "report.csv");
// So does the clear button.
await filterInput(page).fill("zzz-no-such-file");
await expect(page.getByText("No matching files", { exact: true })).toBeVisible();
await page.getByTestId("files-filter-clear").click();
await expect(filterInput(page)).toHaveValue("");
await expectExplorerEntryVisible(page, "guide.md");
// Revealing a match leaves the filter and selects the file in the tree.
await filterInput(page).fill("report");
await match(page, "report.csv").click({ button: "right" });
await page.getByRole("menuitem", { name: "Reveal in Files", exact: true }).click();
await expect(filterInput(page)).toHaveValue("");
await expect(
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
).toContainText("report.csv");
});
/** The directory listings the app asks the host for, by path. */
function recordDirectoryListings(page: Page): string[] {
const listed: string[] = [];
page.on("websocket", (socket) => {
socket.on("framesent", ({ payload }) => {
if (typeof payload !== "string") return;
const { message } = JSON.parse(payload);
if (message?.type === "file_explorer_request" && message.mode === "list") {
listed.push(message.path);
}
});
});
return listed;
}
test("opens a matching folder in the tree", async ({ page }) => {
const listed = recordDirectoryListings(page);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
await filterInput(page).fill("nested");
await match(page, "nested").first().click();
await expect(filterInput(page)).toHaveValue("");
await expectExplorerEntryVisible(page, "report.csv");
await expect(
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
).toContainText("nested");
// One walk down to the folder: its collapsed parent is listed once.
expect(listed.filter((directory) => directory === "data")).toEqual(["data"]);
});
test("renames and deletes a match without leaving the filter", async ({ page }) => {
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
await filterInput(page).fill("guide");
await match(page, "guide.md").click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
const nameInput = page.getByTestId("file-explorer-name-input");
await nameInput.fill("guide-v2.md");
await nameInput.press("Enter");
await expect(match(page, "guide-v2.md")).toBeVisible();
page.once("dialog", (dialog) => void dialog.accept());
await match(page, "guide-v2.md").click({ button: "right" });
await page.getByRole("menuitem", { name: "Delete", exact: true }).click();
await expect(page.getByText("No matching files", { exact: true })).toBeVisible();
});
@@ -0,0 +1,135 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import { commandCenterSection, openCommandCenter } from "../support/helpers/command-center";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const REPLY = [
"Read [the report](data/report.csv), the [settings](.config/nested/file-55.json),",
"the [data folder](data) or the [website](https://example.test/docs).",
"Nothing is at gone.md.",
].join(" ");
async function seedLinkedFiles() {
const agent = await seedMockAgentWorkspace({
repoPrefix: "file-link-menu-",
title: "File link actions",
initialPrompt: "Show the links",
featureValues: { mockAssistantResponse: REPLY },
});
await mkdir(path.join(agent.cwd, "data"), { recursive: true });
await writeFile(path.join(agent.cwd, "data/report.csv"), "name,total\nalpha,1\n");
await mkdir(path.join(agent.cwd, ".config/nested"), { recursive: true });
// Enough siblings that the target row starts outside the tree's viewport.
await Promise.all(
Array.from({ length: 60 }, (_, index) =>
writeFile(
path.join(agent.cwd, `.config/nested/file-${String(index).padStart(2, "0")}.json`),
"{}\n",
),
),
);
await agent.client.waitForFinish(agent.agentId, 30_000);
return agent;
}
function replyLink(page: Page, name: string) {
return page.getByTestId("assistant-message").getByRole("link", { name, exact: true });
}
function linkMenu(page: Page) {
return page.getByTestId("markdown-link-menu");
}
function selectedTreeRow(page: Page) {
return page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]');
}
async function expectMenuItems(page: Page, names: string[]) {
await expect(linkMenu(page).getByRole("menuitem")).toHaveText(names);
}
async function dismissMenu(page: Page) {
await page.keyboard.press("Escape");
await expect(linkMenu(page)).toHaveCount(0);
}
async function screenshot(page: Page, name: string) {
await page.screenshot({
path: test.info().outputPath(`${name}.png`),
animations: "disabled",
});
}
test("links in chat and file tabs offer file actions and reveal the file in Files", async ({
page,
}, testInfo) => {
testInfo.setTimeout(180_000);
const agent = await seedLinkedFiles();
try {
await page.addInitScript(() => {
localStorage.setItem(
"panel-state",
JSON.stringify({ state: { explorerShowHiddenFiles: false }, version: 0 }),
);
});
await openAgentRoute(page, agent);
await replyLink(page, "the report").click({ button: "right" });
await expectMenuItems(page, [
"Open file",
"Open to the side",
"Reveal in Files",
"Download",
"Copy path",
"Copy relative path",
]);
await screenshot(page, "chat-file-link-menu");
await dismissMenu(page);
await replyLink(page, "data folder").click({ button: "right" });
await expectMenuItems(page, ["Reveal in Files", "Copy path", "Copy relative path"]);
await dismissMenu(page);
await replyLink(page, "website").click({ button: "right" });
await expectMenuItems(page, ["Open in default browser", "Copy link"]);
await screenshot(page, "chat-web-link-menu");
await dismissMenu(page);
// A bare name is looked up while the menu is open; acting on one that matches nothing says so.
await replyLink(page, "gone.md").click({ button: "right" });
await linkMenu(page).getByRole("menuitem", { name: "Download" }).click();
await expect(page.getByTestId("assistant-file-link-not-found-toast")).toContainText("gone.md");
await replyLink(page, "the report").click({ button: "right" });
await linkMenu(page).getByRole("menuitem", { name: "Reveal in Files" }).click();
await expect(selectedTreeRow(page)).toContainText("report.csv");
await expect(replyLink(page, "the report")).toBeVisible();
await screenshot(page, "reveal-in-files-from-chat-link");
// A hidden folder, a freshly expanded tree and a row far below the fold.
await replyLink(page, "settings").click();
const fileTab = page.getByTestId("workspace-tab-file_.config/nested/file-55.json").first();
await expect(fileTab).toBeVisible();
await fileTab.click({ button: "right" });
const tabMenu = page.getByTestId("workspace-tab-context-file_.config/nested/file-55.json");
await expect(tabMenu.getByRole("menuitem", { name: "Reveal in Files" })).toBeVisible();
await expect(tabMenu.getByRole("menuitem", { name: "Copy relative path" })).toBeVisible();
await screenshot(page, "file-tab-menu");
await tabMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
await expect(selectedTreeRow(page)).toContainText("file-55.json");
await expect(selectedTreeRow(page)).toBeInViewport();
await screenshot(page, "reveal-in-files-from-file-tab");
// The tree is already mounted and scrolled elsewhere. Command Center reveals the active tab.
await page.getByTestId("file-explorer-tree-scroll").hover();
await page.mouse.wheel(0, -100_000);
await expect(selectedTreeRow(page)).not.toBeInViewport();
const commandCenter = await openCommandCenter(page);
await commandCenter.getByTestId("command-center-input").fill("Reveal in Files");
await commandCenterSection(commandCenter, "Reveal in Files").click();
await expect(selectedTreeRow(page)).toBeInViewport();
} finally {
await agent.cleanup();
}
});
@@ -3,9 +3,11 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { test, expect, type Page } from "../support/fixtures";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import {
clearModelSearchWithEscape,
clickModelRowWhileProviderOpens,
closeModelPicker,
expectModelListScrollKeepsSearchFocused,
expectSearchProfilesAtTop,
expectModelSearchEmptyState,
expectModelPickerHeight,
expectModelPickerWidth,
@@ -19,7 +21,12 @@ import {
seedModelProvider,
expectSearchResultsVirtualized,
} from "../support/helpers/agent-profiles";
import { expectComposerVisible } from "../support/helpers/composer";
import {
blurComposerInput,
expectComposerFocused,
expectComposerVisible,
} from "../support/helpers/composer";
import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace";
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace } from "../support/helpers/seed-client";
@@ -56,9 +63,7 @@ const LARGE_CATALOG = {
};
test.describe("Cross-provider model search", () => {
test("one query over the picker root reaches every provider and names each result's provider", async ({
page,
}) => {
test("one query reaches every provider and names each result's provider", async ({ page }) => {
const provider = await seedModelProvider(STUDIO);
const profile = await seedAgentProfiles([ROOT_VIEW_PROFILE]);
const workspace = await seedWorkspace({ repoPrefix: "model-search-providers-" });
@@ -99,7 +104,7 @@ test.describe("Cross-provider model search", () => {
});
});
await test.step("results replace the pinned profiles", async () => {
await test.step("results replace the Profiles list", async () => {
await expectPinnedProfilesHidden(page);
});
@@ -108,6 +113,10 @@ test.describe("Cross-provider model search", () => {
await test.step("a query with no matches repeats the query back", async () => {
await searchAllModels(page, "zzz");
await expectModelSearchEmptyState(page, "zzz");
});
await test.step("Escape clears the query before it closes the picker", async () => {
await clearModelSearchWithEscape(page);
await closeModelPicker(page);
});
} finally {
@@ -135,16 +144,23 @@ test.describe("Cross-provider model search", () => {
const restingHeight = await readModelPickerHeight(page);
const restingWidth = await readModelPickerWidth(page);
await test.step("a broad query renders only the visible result window", async () => {
await test.step("a broad query renders only the visible result window and scrolls without leaving search", async () => {
await searchAllModels(page, "bulk model");
await expectSearchResultsVirtualized(page, {
provider: LARGE_CATALOG.id,
total: LARGE_CATALOG_SIZE,
});
await expectModelListScrollKeepsSearchFocused(page);
await expectModelPickerHeight(page, restingHeight);
await expectModelPickerWidth(page, restingWidth);
});
await test.step("a new query opens at the top, with the Profiles heading above the matching profile", async () => {
// "search" matches the profile's name and every bulk model's description.
await searchAllModels(page, "search");
await expectSearchProfilesAtTop(page, ROOT_VIEW_PROFILE.id);
});
await test.step("narrowing to one result does not resize the picker", async () => {
await searchAllModels(page, "bulk model 199");
await expectModelSearchResult(page, {
@@ -179,7 +195,7 @@ test.describe("Cross-provider model search", () => {
}
});
test("arrow keys navigate profiles, providers, models, and search results in the composer", async ({
test("arrow keys move between the rail, the model list, and search results in the composer", async ({
page,
}) => {
const provider = await seedModelProvider(STUDIO);
@@ -194,7 +210,7 @@ test.describe("Cross-provider model search", () => {
const workspace = await seedWorkspace({ repoPrefix: "model-picker-arrows-" });
try {
await test.step("open the composer model picker on the root view", async () => {
await test.step("open the composer model picker", async () => {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
@@ -204,32 +220,42 @@ test.describe("Cross-provider model search", () => {
const viewport = page.getByTestId("combobox-desktop-container");
const trigger = page.getByTestId("combined-model-selector").filter({ visible: true }).first();
const profileRow = viewport.getByTestId("model-profile-row-agent_profile_e2e_arrows");
const profilesRailRow = viewport.getByTestId("model-picker-rail-profiles");
const studioProviderRow = viewport.getByTestId(`model-provider-${STUDIO.id}`);
await test.step("move from profiles to providers, drill in with ArrowRight, and go back with ArrowLeft", async () => {
await expect(profileRow).toHaveAttribute("data-active", "true");
// Root view keeps aria-selected absent while keyboard-active uses data-active.
await expect(viewport.locator("[aria-selected]")).toHaveCount(0);
await test.step("ArrowLeft moves to the rail, ArrowDown opens each entry, ArrowRight enters its list", async () => {
await page.keyboard.press("ArrowLeft");
// The rail opens what it lands on, so ArrowUp from any provider reaches Profiles.
for (let step = 0; step < 10; step += 1) {
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowUp");
}
await expect(profilesRailRow).toHaveAttribute("data-active", "true");
await expect(profileRow).toBeVisible();
// Step down until Mock Studio is active (provider order can vary across environments).
// Step down until Mock Studio is open (provider order can vary across environments).
for (let step = 0; step < 10; step += 1) {
if ((await studioProviderRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowDown");
}
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("ArrowRight");
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toBeVisible();
await page.keyboard.press("ArrowRight");
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toHaveAttribute(
"data-active",
"true",
);
await page.keyboard.press("ArrowLeft");
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
await expect(
viewport.locator('[data-testid^="model-row-"][data-active="true"]'),
).toHaveCount(0);
});
await test.step("Enter drills into the active provider and ArrowDown + Enter selects a model", async () => {
await test.step("Enter moves from the rail into the list and ArrowDown + Enter selects a model", async () => {
await page.keyboard.press("Enter");
const deepRow = viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`);
await expect(deepRow).toBeVisible();
await expectModelListScrollKeepsSearchFocused(page);
for (let step = 0; step < 5; step += 1) {
if ((await deepRow.getAttribute("data-active")) === "true") break;
@@ -240,6 +266,7 @@ test.describe("Cross-provider model search", () => {
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Studio deep think");
await expectComposerFocused(page);
});
await test.step("typing filters results while arrow keys select across search matches", async () => {
@@ -258,6 +285,7 @@ test.describe("Cross-provider model search", () => {
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Ten second stream");
await expectComposerFocused(page);
});
await test.step("a press on a model row selects it while the provider list is still opening", async () => {
@@ -265,27 +293,42 @@ test.describe("Cross-provider model search", () => {
await clickModelRowWhileProviderOpens(page, {
provider: "mock",
modelLabel: "One minute stream",
otherProvider: STUDIO.id,
});
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("One minute stream");
await expectComposerFocused(page);
});
await test.step("Enter on the active profile row applies it", async () => {
await openModelPicker(page);
await page.keyboard.press("ArrowLeft");
for (let step = 0; step < 10; step += 1) {
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
await page.keyboard.press("ArrowUp");
}
await page.keyboard.press("ArrowRight");
await expect(profileRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await expect(viewport).toHaveCount(0);
await expect(trigger).toContainText("Ten second stream");
await expectComposerFocused(page);
});
await test.step("folded compact sheet also supports Enter on the active profile row", async () => {
await test.step("the compact drawer puts Profiles in the Model accordion and lets all groups collapse", async () => {
await page.setViewportSize({ width: 390, height: 800 });
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-profiles")).toHaveCount(0);
await page.getByTestId("agent-controls-model").click();
await expect(page.getByTestId("compact-model-list")).toBeVisible();
await page.locator('[data-testid^="model-provider-section-"]').first().click();
await expect(page.getByTestId("compact-model-list")).toHaveCount(0);
await page.getByTestId("model-picker-rail-profiles").click();
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
await expect(sheetProfileRow).toBeVisible();
await expect(sheetProfileRow).toHaveAttribute("data-active", "true");
await page.keyboard.press("Enter");
await sheetProfileRow.click();
await expect(sheetProfileRow).toHaveCount(0);
await expect(page.getByTestId("agent-controls-model-sheet")).not.toBeInViewport();
});
} finally {
await workspace.cleanup();
@@ -293,6 +336,43 @@ test.describe("Cross-provider model search", () => {
await provider.restore();
}
});
test("choosing a model restores composer focus in workspace drafts and New Workspace", async ({
page,
}) => {
const provider = await seedModelProvider(STUDIO);
const workspace = await seedWorkspace({ repoPrefix: "model-picker-focus-" });
try {
await test.step("clicking a model after blurring the workspace draft returns focus to the composer", async () => {
await gotoWorkspace(page, workspace.workspaceId);
await clickNewChat(page);
await expectComposerVisible(page);
await blurComposerInput(page);
await openModelPicker(page);
const viewport = page.getByTestId("combobox-desktop-container");
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`).click();
await expect(viewport).toHaveCount(0);
await expectComposerFocused(page);
});
await test.step("clicking a model on the New Workspace screen returns focus to the composer", async () => {
await openGlobalNewWorkspaceComposer(page);
await expectComposerVisible(page);
await blurComposerInput(page);
await openModelPicker(page);
const viewport = page.getByTestId("combobox-desktop-container");
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`).click();
await expect(viewport).toHaveCount(0);
await expectComposerFocused(page);
});
} finally {
await workspace.cleanup();
await provider.restore();
}
});
});
async function setRuntimeCatalog(client: DaemonClient, count: number, cwd: string) {
@@ -332,7 +412,6 @@ async function reloadSavedDraft(page: Page) {
}
async function expectOneCatalogChoice(page: Page, label: string) {
await openModelPicker(page);
await page.getByRole("button", { name: "Back", exact: true }).click();
await searchAllModels(page, label);
await expect(page.getByTestId("model-row-gemini-gemini-3.5-flash")).toHaveCount(1);
await closeModelPicker(page);
@@ -34,7 +34,6 @@ async function rememberModel(page: Page) {
async function expectRecoveredModelInPicker(page: Page) {
await openModelPicker(page);
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
await drillIntoProvider(page, PROVIDER);
await expect(
page.getByTestId("combobox-desktop-container").getByText(LABEL, { exact: true }),
+28 -1
View File
@@ -10,6 +10,7 @@ import {
finishSetup,
goToSetupStep,
hostGivesAgentsPaseoTools,
hostToolGroups,
openAppAsNewUser,
openRelayPairingFromSetup,
closeRelayPairing,
@@ -24,6 +25,7 @@ import {
recordFirstLaunch,
setupModal,
setupPrimaryButton,
setHostTools,
setupSheet,
showSetupAgainFromSettings,
skipSetup,
@@ -426,6 +428,30 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
}
});
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
const host = await startSetupHost("tool-groups");
try {
await setHostTools(host, { groups: { schedules: false, browser: true } });
await openAppAsNewUser(page, host);
await expectSetupStep(page, "Welcome to Paseo");
await goToSetupStep(page, "Orchestration");
await expectSetupStep(page, "Let agents use Paseo");
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
// Setup offers only the main switch; tool groups live in Settings.
await expect(
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
).toHaveCount(0);
await continueSetup(page);
await expectSetupStep(page, "Take your agents with you");
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
} finally {
await host.close();
}
});
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
const host = await startSetupHost("no-skills");
@@ -463,6 +489,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
try {
await setHostTools(host, { enabled: false });
await openAppAsNewUser(page, host);
await step("Welcome to Paseo");
await primary("Continue").click();
@@ -471,7 +498,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
await step("Add your projects");
await primary("Continue").click();
// The setup host starts with Paseo tools off; the switch starts on.
// The host has tools off; the setup switch still starts on.
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
await step("Let agents use Paseo");
await expect(paseoToolsSwitch(page)).toBeChecked();
@@ -13,11 +13,17 @@ import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
const PLUGIN_ID = "plugin-host-ui-e2e";
const TINY_PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
"base64",
);
const PLUGIN_SOURCE = `import { usePaseo } from "@getpaseo/plugin/client";
import { Icon, Modal, useToast, Markdown } from "@getpaseo/plugin/client/ui";
@@ -39,6 +45,7 @@ function ModalBody({ onSaved }) {
<Text>Plugin modal contexts ready</Text>
<Markdown>{"## Plugin report"}</Markdown>
<Markdown>{"Checks **passed**. [Documentation](https://paseo.sh/docs/plugins)"}</Markdown>
<Markdown>{"![Modal preview](" + SCREENSHOT_PATH + ")"}</Markdown>
<Markdown>{""}</Markdown>
<Pressable accessibilityRole="button" onPress={save}>
<Text>Save issue</Text>
@@ -56,6 +63,7 @@ function Surface({ playAudio }) {
const [open, setOpen] = useState(false);
return <View>
<Text>{audioStatus}</Text>
<Markdown>{"![Before](" + SCREENSHOT_PATH + ")\\n\\n![After](" + SCREENSHOT_FILE_URL + ")"}</Markdown>
<Pressable accessibilityRole="button" onPress={() => play(AUDIO_BASE64)}><Text>Play plugin audio</Text></Pressable>
<Pressable accessibilityRole="button" onPress={() => play("UklGRg==")}><Text>Play invalid audio</Text></Pressable>
<Pressable accessibilityRole="button" onPress={() => setOpen(true)}>
@@ -105,20 +113,39 @@ async function openPluginModal(page: Page): Promise<void> {
await page.getByRole("button", { name: "Open plugin modal", exact: true }).click();
}
async function expectPluginMarkdown(page: Page): Promise<void> {
await expect(page.getByRole("heading", { name: "Plugin report" })).toBeVisible();
await expect(page.getByText("Checks passed.", { exact: false })).toBeVisible();
await expect(page.getByRole("link", { name: "Documentation", exact: true })).toHaveAttribute(
async function expectLoadedMarkdownImage(scope: Page | Locator, alt: string): Promise<void> {
const image = scope.getByAltText(alt, { exact: true });
await expect(image).toBeVisible();
await expect
.poll(() =>
image.evaluate((node) => {
const img = node as HTMLImageElement;
return {
isBlob: img.src.startsWith("blob:"),
complete: img.complete,
naturalWidth: img.naturalWidth,
};
}),
)
.toEqual({ isBlob: true, complete: true, naturalWidth: 1 });
}
async function expectPluginMarkdown(scope: Page | Locator): Promise<void> {
await expect(scope.getByRole("heading", { name: "Plugin report" })).toBeVisible();
await expect(scope.getByText("Checks passed.", { exact: false })).toBeVisible();
await expect(scope.getByRole("link", { name: "Documentation", exact: true })).toHaveAttribute(
"href",
"https://paseo.sh/docs/plugins",
);
await expectLoadedMarkdownImage(scope, "Modal preview");
await expect(scope.getByText("Image unavailable")).toHaveCount(0);
}
async function expectCenteredPluginDialog(page: Page): Promise<void> {
const dialog = page.getByRole("dialog");
await expect(dialog.getByText("Edit plugin issue", { exact: true })).toBeVisible();
await expect(dialog.getByText("Plugin modal contexts ready", { exact: true })).toBeVisible();
await expectPluginMarkdown(page);
await expectPluginMarkdown(dialog);
}
async function closeCenteredPluginDialog(page: Page): Promise<void> {
@@ -147,10 +174,15 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
const beforePath = path.join(directory, "before.png");
const afterPath = path.join(directory, "after.png");
const afterFileUrl = pathToFileURL(afterPath).href;
await writeFile(beforePath, TINY_PNG);
await writeFile(afterPath, TINY_PNG);
const audio = await readFile(path.resolve(__dirname, "../../assets/audio/thinking-tone.wav"));
await writeFile(
path.join(directory, "index.client.tsx"),
`const AUDIO_BASE64 = ${JSON.stringify(audio.toString("base64"))};\n${PLUGIN_SOURCE}`,
`const AUDIO_BASE64 = ${JSON.stringify(audio.toString("base64"))};\nconst SCREENSHOT_PATH = ${JSON.stringify(beforePath)};\nconst SCREENSHOT_FILE_URL = ${JSON.stringify(afterFileUrl)};\n${PLUGIN_SOURCE}`,
);
try {
@@ -159,6 +191,12 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
await useNonCompactLayout(page);
await openHostUiPlugin(page);
await test.step("plugin screen Markdown renders local absolute and file:// PNG images inline", async () => {
await expectLoadedMarkdownImage(page, "Before");
await expectLoadedMarkdownImage(page, "After");
await expect(page.getByText("Image unavailable")).toHaveCount(0);
});
await test.step("plugin audio finishes, rejects corrupt files, and recovers", async () => {
await playPluginAudio(page, "Play plugin audio", "Audio finished");
await playPluginAudio(page, "Play invalid audio", "Audio rejected");
@@ -26,16 +26,14 @@ async function openProviderSettingsFromModelSelector(page: Page) {
const configuration = page.getByTestId("agent-controls-model-sheet");
await expect(configuration).toBeVisible({ timeout: 10_000 });
await page.getByTestId("agent-controls-model").click();
const modelBrowser = page.getByTestId("agent-controls-model-browser-sheet");
await expect(modelBrowser).toBeVisible({ timeout: 10_000 });
await expect(page.getByTestId("mobile-model-page")).toBeVisible({ timeout: 10_000 });
await page.getByRole("button", { name: /Open .* settings/ }).click();
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
}
async function expectModelBrowserVisible(page: Page) {
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeVisible({
async function expectModelPageVisible(page: Page) {
await expect(page.getByTestId("mobile-model-page")).toBeVisible({
timeout: 10_000,
});
await expect(page.getByRole("button", { name: /Open .* settings/ })).toBeVisible();
@@ -187,7 +185,7 @@ test.describe("provider settings overlay stack", () => {
}
});
test("provider settings and children close back through the model browser to configuration", async ({
test("provider settings and children close back to the Model page, then Back reaches Home", async ({
page,
}) => {
test.setTimeout(180_000);
@@ -199,17 +197,15 @@ test.describe("provider settings overlay stack", () => {
await exerciseProviderSettingsStack(page);
await closeSheetByHeaderButton(page, "provider-settings-sheet");
await expectModelBrowserVisible(page);
await expectModelPageVisible(page);
await page.getByRole("button", { name: /Open .* settings/ }).click();
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
await exerciseProviderSettingsStack(page);
await closeSheetByHeaderButton(page, "provider-settings-sheet");
await expectModelBrowserVisible(page);
await closeTopSheet(page);
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible({
timeout: 10_000,
});
await expectModelPageVisible(page);
await page.getByTestId("sheet-header-back").click();
await expect(page.getByTestId("mobile-model-page")).toHaveCount(0);
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
await closeTopSheet(page);
} finally {
@@ -226,8 +222,6 @@ async function openTimedOutProvider(page: Page, workspaceId: string, width: numb
await page.getByRole("button", { name: /Select model/ }).click();
if (width < 600) {
await page.getByTestId("agent-controls-model").click();
} else {
await page.getByRole("button", { name: "Back", exact: true }).click();
}
await page.getByTestId("model-provider-picker-timeout").click();
await expect(page.getByText(/Timed out refreshing Pi timeout/)).toBeVisible();
@@ -0,0 +1,51 @@
import { test, expect } from "../support/fixtures";
import { TerminalE2EHarness, withTerminalInApp } from "../support/helpers/terminal-dsl";
import { waitForTerminalContent } from "../support/helpers/terminal-perf";
const CODE_FONT = "monospace";
const INTERFACE_FONT = "serif";
test("terminal text keeps the code font when an interface font is set", async ({ page }) => {
// Without WebGL2 the terminal falls back to xterm's DOM renderer, whose rows are
// styled by CSS and so can inherit the interface font.
await page.addInitScript(() => {
const getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function (
this: HTMLCanvasElement,
type: string,
...rest: unknown[]
) {
if (type === "webgl2") return null;
return (getContext as (...args: unknown[]) => unknown).call(this, type, ...rest);
} as typeof getContext;
});
await page.addInitScript(
(fonts) => {
const saved = JSON.parse(localStorage.getItem("@paseo:app-settings") ?? "{}");
localStorage.setItem("@paseo:app-settings", JSON.stringify({ ...saved, ...fonts }));
},
{ monoFontFamily: CODE_FONT, uiFontFamily: INTERFACE_FONT },
);
const harness = await TerminalE2EHarness.create({ tempPrefix: "terminal-font-family-" });
try {
await withTerminalInApp(page, harness, { name: "font-family" }, async () => {
await harness.setupPrompt(page);
await harness
.terminalSurface(page)
.pressSequentially("clear; printf 'iiiiiiiiii\\nWWWWWWWWWW\\n'\n", { delay: 0 });
await waitForTerminalContent(page, (text) => text.includes("WWWWWWWWWW"), 10_000);
await harness
.terminalSurface(page)
.screenshot({ path: test.info().outputPath("terminal-font-family.png") });
const rowFont = await page
.locator(".xterm-rows")
.evaluate((rows) => getComputedStyle(rows).fontFamily);
expect(rowFont).toBe(CODE_FONT);
});
} finally {
await harness.cleanup();
}
});
@@ -4,7 +4,9 @@ import path from "node:path";
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { holdFileUploadResponse } from "../support/helpers/file-upload-gate";
import { clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
import { TerminalE2EHarness } from "../support/helpers/terminal-dsl";
import { getTerminalBufferText, waitForTerminalContent } from "../support/helpers/terminal-perf";
@@ -23,13 +25,134 @@ if (process.stdin.isTTY) {
process.stdin.resume();
process.stdin.on("data", (chunk) => {
captured = Buffer.concat([captured, chunk]);
if (captured.includes(Buffer.from("rgb:"))) {
finish();
}
});
setTimeout(finish, 700);
`;
const TERMINAL_PALETTE_PROBE_SCRIPT = `
process.stdin.setRawMode(true);
process.stdin.resume();
const mode = process.argv[2];
let buf = "";
const timer = setTimeout(() => {
process.stdout.write("PROBE_TIMEOUT:" + mode + ":" + buf.replace(/\\x1b/g, "ESC") + "\\n");
process.exit(2);
}, 5000);
if (mode === "osc") {
const code = process.argv[3];
process.stdin.on("data", (chunk) => {
buf += chunk.toString("binary");
const match = buf.match(new RegExp("\\\\x1b\\\\]" + code + ";rgb:[0-9a-f/]+\\\\x1b\\\\\\\\"));
if (!match) return;
clearTimeout(timer);
process.stdout.write("OSC_COLOR_OK:" + code + ":" + match[0].replace(/\\x1b/g, "ESC") + "\\n");
process.exit(0);
});
process.stdout.write("\\x1b]" + code + ";?\\x07");
} else if (mode === "dsr996") {
process.stdin.on("data", (chunk) => {
buf += chunk.toString("binary");
const match = buf.match(/\\x1b\\[\\?997;([12])n/);
if (!match) return;
clearTimeout(timer);
process.stdout.write("DSR996_OK:" + match[1] + "\\n");
process.exit(0);
});
process.stdout.write("\\x1b[?996n");
} else if (mode === "watch2031") {
clearTimeout(timer);
process.stdin.on("data", (chunk) => {
buf += chunk.toString("binary");
if (buf.includes("Q")) {
process.stdout.write("\\x1b[?2031lWATCH2031_DONE\\n");
process.exit(0);
}
let match;
while ((match = buf.match(/\\x1b\\[\\?997;([12])n/))) {
process.stdout.write("WATCH2031_EVENT:" + match[1] + "\\n");
buf = buf.slice(match.index + match[0].length);
}
});
process.stdout.write("\\x1b[?2031hWATCH2031_READY\\n");
}
`;
const TERMINAL_PALETTE_SCENARIOS = {
light: {
label: "Light",
colorFgBg: "0;15",
schemeCode: "2",
colors: {
10: "rgb:1a1a/1a1a/1e1e",
11: "rgb:ffff/ffff/ffff",
12: "rgb:1a1a/1a1a/1e1e",
},
},
dark: {
label: "Dark",
colorFgBg: "15;0",
schemeCode: "1",
colors: {
10: "rgb:fafa/fafa/fafa",
11: "rgb:1818/1b1b/1a1a",
12: "rgb:fafa/fafa/fafa",
},
},
} as const;
type TerminalPaletteScenario =
(typeof TERMINAL_PALETTE_SCENARIOS)[keyof typeof TERMINAL_PALETTE_SCENARIOS];
async function selectAppThemeInApp(
page: Page,
label: TerminalPaletteScenario["label"],
): Promise<void> {
await page.getByRole("button", { name: "Settings", exact: true }).click();
await expect(page.getByTestId("settings-sidebar")).toBeVisible();
await openSettingsSection(page, "appearance");
const themeRadio = page.getByRole("radio", { name: label, exact: true });
await themeRadio.click();
await expect(themeRadio).toBeChecked();
await clickSettingsBackToWorkspace(page);
}
function collectBrowserOsc11Replies(page: Page): string[] {
const replies: string[] = [];
page.on("websocket", (ws) => {
ws.on("framesent", ({ payload }) => {
const text = typeof payload === "string" ? payload : payload.toString("latin1");
if (text.includes("]11;rgb:")) {
replies.push(text);
}
});
});
return replies;
}
async function waitForCreatedTerminal(
harness: TerminalE2EHarness,
knownTerminalIds: Set<string>,
): Promise<string> {
let createdTerminalId: string | undefined;
await expect
.poll(
async () => {
const result = await harness.client.listTerminals(harness.tempRepo.path, undefined, {
workspaceId: harness.workspaceId,
});
createdTerminalId = result.terminals.find(
(terminal) => !knownTerminalIds.has(terminal.id),
)?.id;
return createdTerminalId;
},
{ timeout: 10_000 },
)
.toBeTruthy();
return createdTerminalId!;
}
// A TUI stand-in: turns on bracketed paste, reads every quoted path in each
// bracketed paste, and echoes typed lines, so the PTY output proves what reached
// the terminal and where the file was read from.
@@ -158,6 +281,10 @@ test.describe("Terminal protocol queries", () => {
test.beforeAll(async () => {
harness = await TerminalE2EHarness.create({ tempPrefix: "terminal-protocol-query-" });
await writeFile(path.join(harness.tempRepo.path, "osc11-capture.cjs"), OSC11_CAPTURE_SCRIPT);
await writeFile(
path.join(harness.tempRepo.path, "palette-probe.cjs"),
TERMINAL_PALETTE_PROBE_SCRIPT,
);
await writeFile(path.join(harness.tempRepo.path, "file-receiver.cjs"), FILE_RECEIVER_SCRIPT);
});
@@ -166,6 +293,8 @@ test.describe("Terminal protocol queries", () => {
});
test("does not send browser OSC 11 color-query replies back to the PTY", async ({ page }) => {
const browserOscReplies = collectBrowserOsc11Replies(page);
const terminalInstance = await harness.createTerminal({ name: "osc11-query" });
try {
await harness.openTerminal(page, { terminalId: terminalInstance.id });
@@ -178,14 +307,110 @@ test.describe("Terminal protocol queries", () => {
await page.waitForTimeout(500);
const text = await getTerminalBufferText(page);
const captureLine =
text.split("\n").find((line) => line.includes("PASEO_OSC11_CAPTURE:")) ?? "";
const capturedMatches = captureLine.match(/\]11;rgb:[0-9a-f/]+/g) ?? [];
expect(text).toContain("rgb:0b0b/0b0b/0b0b");
expect(text).not.toContain("rgb:ffff/ffff/ffff");
expect(capturedMatches).toHaveLength(1);
expect(browserOscReplies).toEqual([]);
const afterCapture = text.slice(text.indexOf("PASEO_OSC11_CAPTURE:") + captureLine.length);
expect(afterCapture).not.toContain("rgb:");
} finally {
await harness.killTerminal(terminalInstance.id);
}
});
test("reports Light and Dark palettes through OSC 10/11/12, COLORFGBG, DSR 996/997, and live DEC 2031 toggles", async ({
page,
}) => {
const createAppTerminal = async (): Promise<string> => {
const existing = await harness.client.listTerminals(harness.tempRepo.path, undefined, {
workspaceId: harness.workspaceId,
});
const knownIds = new Set(existing.terminals.map((entry) => entry.id));
await clickNewTerminal(page);
const terminalId = await waitForCreatedTerminal(harness, knownIds);
const surface = terminalSurface(page);
await expect(surface).toBeVisible({ timeout: 20_000 });
await surface.click();
const readyTag = `READY_${Date.now()}`;
await surface.pressSequentially(`echo ${readyTag}\n`, { delay: 0 });
await expectTerminalOutput(terminalId, readyTag);
return terminalId;
};
const runPaletteChecks = async (
terminalId: string,
scenario: TerminalPaletteScenario,
options: { checkColorFgBg: boolean },
): Promise<void> => {
const surface = terminalSurface(page);
await surface.click();
if (options.checkColorFgBg) {
await surface.pressSequentially('echo "CFGBG=$COLORFGBG"\n', { delay: 0 });
await expectTerminalOutput(terminalId, `CFGBG=${scenario.colorFgBg}`);
}
for (const code of [10, 11, 12] as const) {
await surface.pressSequentially(`${process.execPath} palette-probe.cjs osc ${code}\n`, {
delay: 0,
});
await expectTerminalOutput(
terminalId,
`OSC_COLOR_OK:${code}:ESC]${code};${scenario.colors[code]}ESC\\`,
);
}
await surface.pressSequentially(`${process.execPath} palette-probe.cjs dsr996\n`, {
delay: 0,
});
await expectTerminalOutput(terminalId, `DSR996_OK:${scenario.schemeCode}`);
};
// 1. Open workspace once, switch to Light in-app, and create a fresh Light terminal.
await gotoWorkspace(page, harness.workspaceId);
await selectAppThemeInApp(page, "Light");
const lightTerminalId = await createAppTerminal();
let darkTerminalId: string | null = null;
try {
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.light, {
checkColorFgBg: true,
});
// 2. Start DEC 2031 watcher in that running Light terminal, then toggle Light -> Dark -> Light.
await terminalSurface(page).pressSequentially(
`${process.execPath} palette-probe.cjs watch2031\n`,
{ delay: 0 },
);
await expectTerminalOutput(lightTerminalId, "WATCH2031_READY");
await selectAppThemeInApp(page, "Dark");
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:1");
await selectAppThemeInApp(page, "Light");
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:2");
// Stop watcher, toggle to Dark, and verify live OSC 10/11/12 + DSR 996 update on the same PTY.
await terminalSurface(page).click();
await terminalSurface(page).pressSequentially("Q", { delay: 0 });
await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE");
await selectAppThemeInApp(page, "Dark");
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
checkColorFgBg: false,
});
// 3. Fresh Dark terminal reports Dark OSC 10/11/12, COLORFGBG=15;0, and DSR 996 -> dark (1).
darkTerminalId = await createAppTerminal();
await runPaletteChecks(darkTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
checkColorFgBg: true,
});
} finally {
await harness.killTerminal(lightTerminalId);
if (darkTerminalId) {
await harness.killTerminal(darkTerminalId);
}
}
});
async function openFileReceiver(page: Page, name: string) {
const terminal = await harness.createTerminal({
name,
@@ -13,8 +13,12 @@ import { test, expect } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
test.use({
e2eInjectPaseoTools: true,
e2eDaemonConfig: {
version: 1,
agents: {
@@ -290,6 +294,89 @@ test("received messages show their sender and open that agent", async ({ page })
}
});
/** Calls a Paseo MCP tool as `callerAgentId`, the way that agent's provider would. */
async function callPaseoToolAs(
callerAgentId: string,
name: string,
args: Record<string, unknown>,
): Promise<Record<string, unknown>> {
const mcp = new Client({ name: "turn-collapse-e2e", version: "1" });
await mcp.connect(
new StreamableHTTPClientTransport(
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${callerAgentId}`),
),
);
try {
const response = await mcp.callTool({ name, arguments: args });
expect(response, name).not.toMatchObject({ isError: true });
return response.structuredContent as Record<string, unknown>;
} finally {
await mcp.close();
}
}
test("a delegated child reports each turn end as a compact tool call until its own delegate is done", async ({
page,
}, testInfo) => {
const frames: string[] = [];
page.on("websocket", (socket) => {
socket.on("framereceived", ({ payload }) => {
if (typeof payload === "string") frames.push(payload);
});
});
const childNoticeFrames = () => frames.filter((frame) => frame.includes('"label":"Child"'));
const parent = await seedMockAgentWorkspace({ repoPrefix: "child-notices-", title: "Lead" });
try {
await openAgentRoute(page, parent);
await expectComposerVisible(page);
const child = await callPaseoToolAs(parent.agentId, "create_agent", {
workspaceId: parent.workspaceId,
title: "Child",
provider: "mock/e2e-fast-stream",
settings: { modeId: "load-test" },
initialPrompt: "Delegate the slow part",
});
const childId = String(child.agentId);
// The child's own delegate outlives the child's first turn.
const grandchild = await callPaseoToolAs(childId, "create_agent", {
workspaceId: parent.workspaceId,
title: "Grandchild",
provider: "mock/ten-second-stream",
settings: { modeId: "load-test" },
initialPrompt: "Take your time",
});
const notices = page.getByRole("button", { name: /^Agent .*Child/ });
const finished = page.getByRole("button", { name: /^Agent finished.*Child/ });
// The child ended its turn while waiting on its delegate: the parent hears it now.
await expect(finished).toHaveCount(1, { timeout: 30_000 });
const delegate = await parent.client.waitForAgentUpsert(String(grandchild.agentId), () => true);
expect(delegate.status, "the delegate must still be running").toBe("running");
expect(
childNoticeFrames().some((frame) => frame.includes("It still has agents it is waiting on.")),
).toBe(true);
// The delegate reports to the child, and the child's settled turn reaches the parent.
await expect(finished).toHaveCount(2, { timeout: 60_000 });
await expect(notices).toHaveCount(2);
await expect(page.getByText(/still working/i)).toHaveCount(0);
await expect(page.getByText(/Sent by/)).toHaveCount(0);
await expect(page.getByText(/<agent-response>/)).toHaveCount(0);
await finished.last().scrollIntoViewIfNeeded();
await page.screenshot({ path: testInfo.outputPath("child-notices.png") });
// Notification events stay on the daemon: clients get only plain tool calls.
expect(frames.filter((frame) => frame.includes('"agentMessage"'))).toEqual([]);
expect(childNoticeFrames().some((frame) => frame.includes('"name":"agent_finished"'))).toBe(
true,
);
expect(childNoticeFrames().filter((frame) => /"name":"agent_(?!finished)/.test(frame))).toEqual(
[],
);
} finally {
await parent.cleanup();
}
});
test("long sender attribution stays on one line in compact chat", async ({ page }, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 });
await page.addInitScript(() =>
@@ -668,3 +668,186 @@ test("sidebar usage falls back to period shorthands before dropping all labels",
await dragSidebarTo(300);
await expectPinnedUsage(page, ["6%", "20%", "100%", "14%", "22%", "97%"]);
});
test("pushed status.usage_report_changed updates sidebar summary and open Usage modal without polling", async ({
page,
}) => {
const [claude] = claudeAndCodexReports();
const initialFetchedAt = new Date(Date.now() - 60_000).toISOString();
const usage = await installUsageReportsFixture(page, {
lists: [
() => [
{
...claude!,
fetchedAt: initialFetchedAt,
successfulAt: initialFetchedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 31 },
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 54 },
],
},
},
],
],
});
await page.setViewportSize(WIDE);
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk"]);
await usage.waitForUsageReportSubscription();
await openUsageFromItem(page);
const modal = usageModal(page);
await expect(modal.getByText("31% used")).toBeVisible();
const requestsBeforePush = usage.listRequests();
const updatedAt = new Date().toISOString();
usage.pushReportUpdate({
...claude!,
fetchedAt: updatedAt,
successfulAt: updatedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 64 },
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 54 },
],
},
});
await expectPinnedUsage(page, ["64% 5h", "54% wk"]);
await expect(modal.getByText("64% used")).toBeVisible();
expect(usage.listRequests()).toEqual(requestsBeforePush);
});
test("a pushed report for one source does not postpone the five-minute poll of other sources", async ({
page,
}) => {
const [claude, codex] = claudeAndCodexReports();
let codexUsedPct = 7;
let listFetchedAt = "2026-11-28T10:00:00.000Z";
const usage = await installUsageReportsFixture(page, {
lists: [
() => [
{
...claude!,
fetchedAt: listFetchedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 31 },
],
},
},
{
...codex!,
fetchedAt: listFetchedAt,
report: {
status: "available",
windows: [
{
id: "five_hour",
label: "Session",
shortLabel: "5h",
summary: true,
usedPct: codexUsedPct,
},
],
},
},
],
],
});
await page.clock.install();
await page.setViewportSize(WIDE);
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "7% 5h"]);
await usage.waitForUsageReportSubscription();
const initialRequests = usage.listRequests();
// Push a Claude update 2 minutes into the 5-minute poll window.
await page.clock.fastForward(2 * 60_000);
const pushedAt = "2026-11-28T10:02:00.000Z";
usage.pushReportUpdate({
...claude!,
fetchedAt: pushedAt,
successfulAt: pushedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 64 },
],
},
});
await expectPinnedUsage(page, ["64% 5h", "7% 5h"]);
expect(usage.listRequests()).toEqual(initialRequests);
// Only 3 minutes later (t = 5m from initial fetch), the scheduled poll still runs for Codex.
codexUsedPct = 19;
listFetchedAt = "2026-11-28T10:05:00.000Z";
await page.clock.fastForward(3 * 60_000);
await expectPinnedUsage(page, ["31% 5h", "19% 5h"]);
expect(usage.listRequests()).toHaveLength(initialRequests.length + 1);
});
test("hiding and showing the sidebar preserves the five-minute poll schedule and failed reports retry after one minute", async ({
page,
}) => {
const [claude] = claudeAndCodexReports();
let mode: "ok" | "error" = "ok";
let usedPct = 31;
const usage = await installUsageReportsFixture(page, {
lists: [
() => [
{
...claude!,
fetchedAt: new Date().toISOString(),
report:
mode === "error"
? { status: "error", error: "Temporary 503" }
: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct },
],
},
},
],
],
});
await page.clock.install();
await page.setViewportSize(WIDE);
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h"]);
const initialRequests = usage.listRequests();
// Hide and reopen the sidebar within the stale window: no extra fetch starts on remount,
// and the original 5-minute poll slot fires on time rather than restarting from zero.
await page.clock.fastForward(20_000);
await page.setViewportSize(COMPACT);
await expect(usageItem(page)).toHaveCount(0);
await page.clock.fastForward(15_000);
await openCompactSidebar(page);
await expectPinnedUsage(page, ["31% 5h"]);
expect(usage.listRequests()).toEqual(initialRequests);
usedPct = 44;
await page.clock.fastForward(4 * 60_000 + 25_000);
await expectPinnedUsage(page, ["44% 5h"]);
expect(usage.listRequests()).toHaveLength(initialRequests.length + 1);
// When a report enters error state, the app retries after 1 minute instead of waiting 5 minutes.
mode = "error";
await page.clock.fastForward(5 * 60_000);
const requestsAfterError = usage.listRequests();
expect(requestsAfterError).toHaveLength(initialRequests.length + 2);
mode = "ok";
usedPct = 58;
await page.clock.fastForward(60_000);
await expectPinnedUsage(page, ["58% 5h"]);
expect(usage.listRequests()).toHaveLength(requestsAfterError.length + 1);
});
@@ -31,7 +31,7 @@ function keyboardState() {
return {
shown: /^ mInputShown=true$/m.test(state),
// The native object identity survives layout/flag changes but not a remount.
input: view.match(/ReactEditText\{(\w+)/)?.[1] ?? null,
input: view.match(/PaseoTerminalInputView\{(\w+)/)?.[1] ?? null,
};
}
async function waitForKeyboard(shown) {
@@ -587,7 +587,12 @@ export async function openModelPicker(page: Page): Promise<void> {
await expect(pickerViewport(page)).toBeVisible({ timeout: 30_000 });
}
/** Escape clears a typed query first; the next Escape closes the picker. */
export async function closeModelPicker(page: Page): Promise<void> {
const search = pickerViewport(page).getByTestId("model-search-input");
if ((await search.count()) > 0 && (await search.inputValue()) !== "") {
await clearModelSearchWithEscape(page);
}
await page.keyboard.press("Escape");
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
}
@@ -598,70 +603,40 @@ export function profilePickerRow(page: Page, name: string): Locator {
.filter({ hasText: name });
}
/**
* Profiles are pinned above the provider list, so "pinned" is an ordering claim:
* the profile row's top edge sits above every provider row's.
*/
export async function expectProfilePinnedAboveProviders(
page: Page,
input: { name: string; summary: string },
): Promise<void> {
const viewport = pickerViewport(page);
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
const row = profilePickerRow(page, input.name);
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
const profileTop = await boxTop(row);
const providerRows = viewport.locator('[data-testid^="model-provider-"]');
await expect(providerRows.first()).toBeVisible();
const providerCount = await providerRows.count();
for (let index = 0; index < providerCount; index += 1) {
expect(profileTop).toBeLessThan(await boxTop(providerRows.nth(index)));
}
/** Desktop keeps profiles behind the rail's Profiles entry, beside the providers. */
export async function openPickerProfiles(page: Page): Promise<void> {
await pickerViewport(page).getByTestId("model-picker-rail-profiles").click();
}
export async function expectProfileVisibleForProvider(
export async function expectPickerProfile(
page: Page,
input: { name: string; summary: string },
): Promise<void> {
const viewport = pickerViewport(page);
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
await openPickerProfiles(page);
const row = profilePickerRow(page, input.name);
await expect(row).toBeVisible({ timeout: 30_000 });
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
}
export async function expectProfileEditIsPencilOnly(page: Page): Promise<void> {
const viewport = pickerViewport(page);
await expect(
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
).toBeVisible();
await expect(viewport.getByText("Edit", { exact: true })).toHaveCount(0);
}
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
const viewport = pickerViewport(page);
await expect(viewport.getByText("Profiles", { exact: true })).toHaveCount(0);
await expect(
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
).toHaveCount(0);
await expect(viewport.getByRole("button", { name: "Create profile", exact: true })).toBeVisible({
timeout: 30_000,
});
}
export async function expectProfileEditTooltip(page: Page): Promise<void> {
export async function expectProfilesEditLink(page: Page): Promise<void> {
const edit = pickerViewport(page).getByRole("button", {
name: "Edit agent profiles",
exact: true,
});
await edit.hover();
await expect(page.getByText("Edit agent profiles", { exact: true })).toBeVisible();
await expect(edit).toBeVisible();
await expect(edit).toHaveText("Edit");
}
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
await openPickerProfiles(page);
const viewport = pickerViewport(page);
await expect(viewport.locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
await expect(viewport.getByTestId("model-profiles-empty")).toBeVisible({ timeout: 30_000 });
}
export async function openAgentProfilesFromEmptyPrompt(page: Page): Promise<void> {
await pickerViewport(page).getByRole("button", { name: "Create profile", exact: true }).click();
await pickerViewport(page).getByTestId("model-profiles-empty").click();
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
}
@@ -709,25 +684,17 @@ export async function expectProfileReachableByScrolling(page: Page, name: string
}
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
await profilePickerRow(page, name).click();
const row = profilePickerRow(page, name);
if (!(await row.isVisible().catch(() => false))) {
const profilesRail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
if (await profilesRail.isVisible().catch(() => false)) {
await profilesRail.click();
}
}
await row.click();
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
}
/**
* Applying a profile materializes it and forgets it: nothing in the root view
* claims selection. Model rows do carry `aria-selected`, so a count of zero here
* is the absence of a checkmark, not the absence of the attribute everywhere.
*/
export async function expectNothingSelectedInPickerRoot(page: Page): Promise<void> {
await expect(pickerViewport(page).locator("[aria-selected]")).toHaveCount(0);
}
export async function expectAgentProfilesEditShortcut(page: Page): Promise<void> {
await expect(
pickerViewport(page).getByRole("button", { name: "Edit agent profiles", exact: true }),
).toBeVisible({ timeout: 30_000 });
}
export async function drillIntoProvider(page: Page, providerId: string): Promise<void> {
await pickerViewport(page).getByTestId(`model-provider-${providerId}`).click();
}
@@ -798,13 +765,13 @@ export async function selectModelRow(
*/
export async function clickModelRowWhileProviderOpens(
page: Page,
input: { provider: string; modelLabel: string },
input: { provider: string; modelLabel: string; otherProvider: string },
): Promise<void> {
const viewport = pickerViewport(page);
await drillIntoProvider(page, input.provider);
const rowBox = await viewport.getByText(input.modelLabel, { exact: true }).boundingBox();
if (!rowBox) throw new Error(`Model row ${input.modelLabel} has no box`);
await viewport.getByRole("button", { name: "Back", exact: true }).click();
await drillIntoProvider(page, input.otherProvider);
const cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 10 });
@@ -822,7 +789,7 @@ export async function clickModelRowWhileProviderOpens(
/** Scrolling a provider's model list with the wheel leaves typing and Enter in the search field. */
export async function expectModelListScrollKeepsSearchFocused(page: Page): Promise<void> {
const search = pickerViewport(page).getByTestId("model-search-input");
const list = pickerViewport(page).getByTestId("compact-model-list");
const list = pickerViewport(page).getByTestId("model-picker-model-list");
await expect(search).toBeFocused();
await list.hover();
await page.mouse.wheel(0, 200);
@@ -833,11 +800,18 @@ export async function expectModelListScrollKeepsSearchFocused(page: Page): Promi
// ─── Cross-provider model search ───────────────────────────────────────────
export async function searchAllModels(page: Page, query: string): Promise<void> {
const input = page.getByTestId("model-search-all-input");
const input = pickerViewport(page).getByTestId("model-search-input");
await expect(input).toBeVisible({ timeout: 30_000 });
await input.fill(query);
}
/** Search results open at the top, with the Profiles heading above the first matching profile. */
export async function expectSearchProfilesAtTop(page: Page, profileId: string): Promise<void> {
const list = pickerViewport(page).getByTestId("model-picker-model-list");
await expect(list.getByText("Profiles", { exact: true })).toBeInViewport({ ratio: 1 });
await expect(list.getByTestId(`model-profile-row-${profileId}`)).toBeInViewport({ ratio: 1 });
}
export async function expectModelSearchResult(
page: Page,
expected: { provider: string; modelId: string; providerLabel: string; modelLabel: string },
@@ -856,11 +830,19 @@ function escapeForRegex(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
/** Search results replace the whole root view, pinned profiles included. */
/** Search results replace both panes, the Profiles list included. */
export async function expectPinnedProfilesHidden(page: Page): Promise<void> {
await expect(pickerViewport(page).locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
}
export async function clearModelSearchWithEscape(page: Page): Promise<void> {
const search = pickerViewport(page).getByTestId("model-search-input");
await page.keyboard.press("Escape");
await expect(search).toHaveValue("");
await expect(search).toBeFocused();
await expect(pickerViewport(page)).toBeVisible();
}
export async function expectModelSearchEmptyState(page: Page, query: string): Promise<void> {
const empty = page.getByTestId("model-search-empty");
await expect(empty).toBeVisible({ timeout: 30_000 });
+6 -4
View File
@@ -362,8 +362,8 @@ export const selectModel = async (page: Page, model: string) => {
// Type to search/filter models
await searchInput.fill(normalizedModel);
const dialog = page.getByRole("dialog");
const exactOption = dialog
const viewport = page.getByTestId("combobox-desktop-container").or(page.getByRole("dialog"));
const exactOption = viewport
.getByText(new RegExp(`^${escapeRegex(normalizedModel)}$`, "i"))
.first();
const exactVisible = await exactOption.isVisible().catch(() => false);
@@ -375,8 +375,10 @@ export const selectModel = async (page: Page, model: string) => {
await searchInput.press("Enter");
}
// Wait for dropdown to close
if (await searchInput.isVisible().catch(() => false)) {
// Wait for dropdown to close; when a query has no match, the first Escape clears the query
// and the second closes the picker.
for (let attempt = 0; attempt < 2; attempt += 1) {
if (!(await searchInput.isVisible().catch(() => false))) break;
await page.keyboard.press("Escape").catch(() => undefined);
}
await expect(searchInput).not.toBeVisible({ timeout: 5000 });
@@ -3,15 +3,35 @@ import type { Page } from "@playwright/test";
// Poses as the desktop app running the e2e daemon as its own managed daemon, so
// `useIsLocalDaemon` reports the host as this machine. `directory` is where the
// desktop bridge claims dropped files live on disk.
export async function installLocalDesktopHost(page: Page, directory: string): Promise<void> {
export async function installLocalDesktopHost(
page: Page,
directory: string,
// `fileManager` adds the editor bridge: a file manager of that name, and the default-app opener.
{ fileManager = null }: { fileManager?: string | null } = {},
): Promise<void> {
const serverId = process.env.E2E_SERVER_ID;
if (!serverId) {
throw new Error("E2E_SERVER_ID is not set");
}
await page.addInitScript(
(localHost: { serverId: string; directory: string }) => {
(localHost: { serverId: string; directory: string; fileManager: string | null }) => {
const editor = localHost.fileManager
? {
listTargets: async () => [
{
id: "file-manager",
label: localHost.fileManager,
kind: "file-manager",
icon: { kind: "symbol", name: "folder" },
},
],
openTarget: async () => undefined,
openDefaultApp: async () => undefined,
}
: undefined;
(window as unknown as { paseoDesktop: unknown }).paseoDesktop = {
platform: "linux",
editor,
invoke: async (command: string) => {
if (command === "desktop_daemon_status") {
return {
@@ -33,6 +53,6 @@ export async function installLocalDesktopHost(page: Page, directory: string): Pr
webUtils: { getPathForFile: (file: File) => `${localHost.directory}/${file.name}` },
};
},
{ serverId, directory },
{ serverId, directory, fileManager },
);
}
@@ -17,7 +17,6 @@ export async function chooseModel(page: Page, provider: string, label: string) {
export async function reselectModel(page: Page, provider: string, label: string) {
await expectRememberedModel(page, label);
await openModelPicker(page);
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
await selectProviderModel(page, provider, label);
}
+36 -2
View File
@@ -4,6 +4,10 @@ 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 type {
MutableDaemonToolGroups,
MutableDaemonToolsConfigPatch,
} from "@getpaseo/protocol/messages";
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
import { connectDaemonClient } from "./daemon-client-loader";
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
@@ -138,7 +142,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
}
export function paseoToolsSwitch(scope: Page | Locator): Locator {
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
return scope.getByRole("switch", { name: "Enable tools", exact: true });
}
/** Whether the host gives its agents Paseo tools, read from the host itself. */
@@ -147,7 +151,37 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
const config = (await client.getDaemonConfig()).config;
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
} finally {
await client.close();
}
}
/** The host's saved tool groups, read from the host itself. */
export async function hostToolGroups(host: {
port: number;
}): Promise<MutableDaemonToolGroups | undefined> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
return (await client.getDaemonConfig()).config.tools?.groups;
} finally {
await client.close();
}
}
/** Saves tool settings on the host, the way Settings does. */
export async function setHostTools(
host: { port: number },
tools: MutableDaemonToolsConfigPatch,
): Promise<void> {
const client = await connectDaemonClient<
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
try {
await client.patchDaemonConfig({ tools });
} finally {
await client.close();
}
@@ -44,9 +44,8 @@ async function expectProviderIcon(surface: Locator, paths: string[]): Promise<vo
async function selectPluginModel(page: Page): Promise<void> {
await openModelPicker(page);
await page.getByRole("button", { name: "Back", exact: true }).click();
await page.getByText("Direct provider example", { exact: true }).click();
await page.getByText("Example 1", { exact: true }).click();
await page.getByTestId("model-provider-direct-example").click();
await page.getByTestId("model-row-direct-example-example-1").click();
await expect(page.getByRole("button", { name: MODEL_LABEL, exact: true })).toBeVisible();
}
@@ -1,5 +1,6 @@
import path from "node:path";
import { readFileSync } from "node:fs";
import type { TerminalDefaultColors } from "@getpaseo/protocol/messages";
import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity";
import { connectDaemonClient } from "./daemon-client-loader";
import { withProjectOwnership } from "./project-ownership";
@@ -94,7 +95,13 @@ export interface SeedDaemonClient {
cwd: string,
name?: string,
requestId?: string,
options?: { agentId?: string; command?: string; args?: string[]; workspaceId?: string },
options?: {
agentId?: string;
command?: string;
args?: string[];
workspaceId?: string;
defaultColors?: TerminalDefaultColors;
},
): Promise<{
terminal: { id: string; name: string; cwd: string; activity?: TerminalActivity | null } | null;
error: string | null;
+1 -1
View File
@@ -480,7 +480,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
const card = page.getByTestId("host-page-inject-mcp-card");
await expect(card).toBeVisible();
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
}
function idleAgentReleaseSwitch(page: Page) {
+9 -10
View File
@@ -463,16 +463,15 @@ export async function delegateFleetThroughMcp() {
direction: "tail",
limit: 100,
});
return timeline.entries
.flatMap(({ item }) =>
item.type === "tool_call" && item.agentMessage ? [item.agentMessage] : [],
)
.filter(
(message) =>
message.event === "finished" &&
message.sender.id === child.agentId &&
message.text.includes(`Server: ${child.serverId}`),
).length;
return timeline.entries.filter(
({ item }) =>
item.type === "tool_call" &&
item.name === "agent_finished" &&
item.detail.type === "plain_text" &&
item.detail.label === child.title &&
item.detail.text?.includes(child.agentId) &&
item.detail.text.includes(`Server: ${child.serverId}`),
).length;
})
.toBe(1);
},
@@ -1,4 +1,5 @@
import type { Page } from "@playwright/test";
import type { TerminalDefaultColors } from "@getpaseo/protocol/messages";
import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity";
import { createTempGitRepo } from "./workspace";
import { navigateToTerminal, setupDeterministicPrompt } from "./terminal-perf";
@@ -19,6 +20,7 @@ interface CreateTerminalInput {
name: string;
command?: string;
args?: string[];
defaultColors?: TerminalDefaultColors;
}
function sleep(ms: number): Promise<void> {
@@ -69,14 +71,11 @@ export class TerminalE2EHarness {
}
async createTerminal(input: CreateTerminalInput): Promise<TerminalInstance> {
const options =
input.command || input.args
? {
command: input.command,
args: input.args,
workspaceId: this.workspaceId,
}
: { workspaceId: this.workspaceId };
const options = {
...(input.command || input.args ? { command: input.command, args: input.args } : {}),
workspaceId: this.workspaceId,
...(input.defaultColors ? { defaultColors: input.defaultColors } : {}),
};
const result = await this.client.createTerminal(
this.tempRepo.path,
input.name,
@@ -11,6 +11,10 @@ export interface UsageListRequest {
export interface UsageReportsFixture {
listRequests(): UsageListRequest[];
waitForListRequests(count: number): Promise<void>;
/** Waits until the app holds an active `status.usage_report_changed` subscription. */
waitForUsageReportSubscription(): Promise<void>;
/** Pushes a `status.usage_report_changed` update to every active app subscription. */
pushReportUpdate(report: UsageReportEntry): void;
/** Runs `action`, then waits until the app has received the agent's next usage scope. */
untilUsageScopeChanges(agentId: string, action: () => Promise<unknown>): Promise<void>;
}
@@ -28,6 +32,8 @@ interface UsageReportsFixtureOptions {
*/
usageSupported?: boolean | (() => boolean);
usageSettingSupported?: boolean;
/** Overrides `server_info.features.usageReportUpdates` when set. */
usageReportUpdates?: boolean;
/** Released hosts expose provider.usage.list with no source icons. */
providerUsageListOnly?: boolean;
/** The host daemon's port; defaults to the E2E daemon. */
@@ -67,6 +73,7 @@ function withUsageSupportFeature(
enabled: boolean,
providerUsageListOnly: boolean,
usageSettingSupported: boolean,
usageReportUpdates?: boolean,
): string | null {
const envelope = parseJson(message) as {
type?: unknown;
@@ -93,6 +100,7 @@ function withUsageSupportFeature(
usageSetting: usageSettingSupported ? true : undefined,
usageSources: enabled && !providerUsageListOnly,
providerUsageList: enabled,
...(usageReportUpdates !== undefined ? { usageReportUpdates } : {}),
},
},
},
@@ -143,12 +151,37 @@ function createCounter() {
};
}
function trackUsageReportSubscriptionMessage(
request: Record<string, unknown> | null,
pendingUsageSubRequestIds: Set<string>,
usageReportSubscriptions: Map<string, { send: (payload: string) => void }>,
socketSubIds: Set<string>,
): void {
if (
request?.type === "session.events.set_subscription.request" &&
typeof request.requestId === "string" &&
Array.isArray(request.events) &&
request.events.includes("status.usage_report_changed")
) {
pendingUsageSubRequestIds.add(request.requestId);
}
if (
request?.type === "subscription.release.request" &&
typeof request.subscriptionId === "string"
) {
usageReportSubscriptions.delete(request.subscriptionId);
socketSubIds.delete(request.subscriptionId);
}
}
export async function installUsageReportsFixture(
page: Page,
options: UsageReportsFixtureOptions,
): Promise<UsageReportsFixture> {
const listRequests: UsageListRequest[] = [];
const listCounter = createCounter();
const usageReportSubscriptions = new Map<string, { send: (payload: string) => void }>();
const usageReportSubCounter = createCounter();
const usageScopes = new Map<string, string>();
const usageScopeChanges = new Map<string, ReturnType<typeof createCounter>>();
const usageScopeCounts = new Map<string, number>();
@@ -171,10 +204,23 @@ export async function installUsageReportsFixture(
options.port === undefined ? daemonWsRoutePattern() : wsRoutePatternForPort(`${options.port}`);
await page.routeWebSocket(route, (ws) => {
const server = ws.connectToServer();
const pendingUsageSubRequestIds = new Set<string>();
const socketSubIds = new Set<string>();
ws.onClose(() => {
for (const id of socketSubIds) usageReportSubscriptions.delete(id);
socketSubIds.clear();
});
ws.onMessage((message) => {
const request = getSessionMessage(message);
const requestId = request?.requestId;
trackUsageReportSubscriptionMessage(
request,
pendingUsageSubRequestIds,
usageReportSubscriptions,
socketSubIds,
);
if (request?.type === requestType && typeof requestId === "string") {
const listRequest: UsageListRequest = {
forceRefresh: request.forceRefresh === true,
@@ -262,6 +308,26 @@ export async function installUsageReportsFixture(
});
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const subPayload =
sessionMessage?.type === "session.events.set_subscription.response"
? (sessionMessage.payload as
| { requestId?: unknown; subscriptionId?: unknown }
| undefined)
: undefined;
if (
typeof subPayload?.requestId === "string" &&
pendingUsageSubRequestIds.delete(subPayload.requestId) &&
typeof subPayload.subscriptionId === "string"
) {
usageReportSubscriptions.set(subPayload.subscriptionId, {
send: (payload) => ws.send(payload),
});
socketSubIds.add(subPayload.subscriptionId);
ws.send(message);
usageReportSubCounter.increment();
return;
}
const serverInfo =
typeof message === "string"
? withUsageSupportFeature(
@@ -269,6 +335,7 @@ export async function installUsageReportsFixture(
isUsageSupported(),
providerUsageListOnly,
options.usageSettingSupported ?? true,
options.usageReportUpdates,
)
: null;
const scope = agentUsageScope(message);
@@ -287,6 +354,24 @@ export async function installUsageReportsFixture(
return {
listRequests: () => [...listRequests],
waitForListRequests: (count) => listCounter.waitFor(count),
waitForUsageReportSubscription: () => usageReportSubCounter.waitFor(1),
pushReportUpdate: (report) => {
for (const [subscriptionId, target] of usageReportSubscriptions) {
target.send(
JSON.stringify({
type: "session",
message: {
type: "status",
payload: {
status: "usage_report_changed",
subscriptionId,
report,
},
},
}),
);
}
},
untilUsageScopeChanges: async (agentId, action) => {
const next = (usageScopeCounts.get(agentId) ?? 0) + 1;
await action();
@@ -2,12 +2,16 @@ package sh.paseo.keyboard
import android.app.Activity
import android.content.Intent
import android.text.SpannableStringBuilder
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.BaseInputConnection
import android.widget.EditText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -57,6 +61,44 @@ class TerminalArrowTest {
}
}
@Test fun customTerminalViewExposesComposingStateToHardwareArrows() {
val host = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
activity = host
val editable = SpannableStringBuilder("한")
lateinit var view: View
instrumentation.runOnMainSync {
view = object : View(host), ComposingTextOwner {
init {
isFocusable = true
isFocusableInTouchMode = true
setTag(com.facebook.react.R.id.view_tag_native_id, "paseo-terminal-input")
// Mirrors React Native BaseViewManager.setTestId, which overwrites the unkeyed View tag.
setTag("terminal-native-input")
}
override fun isComposingText(): Boolean =
BaseInputConnection.getComposingSpanStart(editable) >= 0
}
host.setContentView(view)
view.requestFocus()
HardwareKeyboard.observe(host.window)
}
instrumentation.waitForIdleSync()
instrumentation.runOnMainSync {
assertSame(view, host.window.currentFocus)
// When not composing, hardware arrows are claimed for the terminal.
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)))
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)))
// While composing, hardware arrows must NOT be claimed so IME candidate navigation still works.
BaseInputConnection.setComposingSpans(editable)
assertFalse(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)))
assertFalse(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)))
}
}
private fun withInput(terminal: Boolean, check: (EditText, Activity) -> Unit) {
val host = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -115,11 +115,23 @@ internal object HardwareKeyboard {
}
}
/**
* Implemented by custom non-EditText editor views so window-level hardware key dispatch can
* detect active IME composition without depending on `View.getTag()` (which React Native's
* `BaseViewManager.setTestId` overwrites with the string `testID`).
*/
interface ComposingTextOwner {
fun isComposingText(): Boolean
}
private class KeyboardWindowCallback(private val window: Window, val previous: Window.Callback) : Window.Callback by previous {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val focus = window.currentFocus
val editable = (focus as? EditText)?.text
val composing = editable != null && BaseInputConnection.getComposingSpanStart(editable) >= 0
val composing = when (focus) {
is ComposingTextOwner -> focus.isComposingText()
is EditText -> focus.text != null && BaseInputConnection.getComposingSpanStart(focus.text) >= 0
else -> false
}
val terminalFocused = focus?.getTag(R.id.view_tag_native_id) == TERMINAL_INPUT_NATIVE_ID
return HardwareKeyboard.dispatcher.dispatch(
event,
@@ -18,6 +18,7 @@ android {
}
dependencies {
implementation project(":paseo-hardware-keyboard")
implementation "androidx.customview:customview:1.1.0"
implementation "com.facebook.react:react-android"
testImplementation "junit:junit:4.13.2"
@@ -0,0 +1,337 @@
package sh.paseo.terminal
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Exercises `TerminalInputConnection` and `PaseoTerminalInputView` against real Android
* `SpannableStringBuilder`, `BaseInputConnection`, `EditorInfo`, and `KeyEvent` instances.
*/
@RunWith(AndroidJUnit4::class)
class TerminalInputConnectionTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private class RecordedTerminal {
val chunks = mutableListOf<String>()
val keys = mutableListOf<TerminalKeyPayload>()
fun write(data: String) {
chunks.add(data)
}
fun key(payload: TerminalKeyPayload) {
keys.add(payload)
}
val rawStream: String
get() = chunks.joinToString("")
/** Applies `\x7f` rubouts onto a simulated terminal line buffer to verify visible text. */
fun applyToLine(initial: String = ""): String {
val codePoints = mutableListOf<Int>()
initial.codePoints().forEach { codePoints.add(it) }
rawStream.codePoints().forEach { cp ->
if (cp == 0x7f) {
if (codePoints.isNotEmpty()) codePoints.removeAt(codePoints.lastIndex)
} else {
codePoints.add(cp)
}
}
val sb = StringBuilder()
codePoints.forEach { sb.appendCodePoint(it) }
return sb.toString()
}
}
private fun withInputHarness(
block: (View, TerminalInputConnection, EditorInfo, RecordedTerminal) -> Unit,
) {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val terminal = RecordedTerminal()
val view = object : View(context) {
init {
isFocusable = true
isFocusableInTouchMode = true
}
}
val editorInfo = EditorInfo()
val connection = TerminalInputConnection(
targetView = view,
onInput = terminal::write,
onTerminalKey = terminal::key,
)
TerminalInputConnection.configureEditorInfo(editorInfo)
block(view, connection, editorInfo, terminal)
}
}
@Test
fun editorInfoDisablesSuggestionsFullscreenAndPersonalizedLearning() {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val editorInfo = EditorInfo()
val view = PaseoTerminalInputView.createForTest(context)
assertTrue("Terminal input view must declare itself as a text editor", view.onCheckIsTextEditor())
assertTrue("Terminal input view must be focusable", view.isFocusable && view.isFocusableInTouchMode)
val connection = view.onCreateInputConnection(editorInfo)
assertTrue("onCreateInputConnection must return TerminalInputConnection", connection is TerminalInputConnection)
assertEquals(
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS,
editorInfo.inputType,
)
assertEquals(EditorInfo.IME_ACTION_NONE, editorInfo.imeOptions and EditorInfo.IME_MASK_ACTION)
assertNotEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_FULLSCREEN)
assertNotEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING)
}
}
@Test
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
withInputHarness { _, ic, _, terminal ->
for (ch in listOf("a", "b", "c", "d")) {
ic.beginBatchEdit()
ic.commitText(ch, 1)
ic.endBatchEdit()
}
assertEquals("abcd", terminal.rawStream)
assertEquals("", ic.editable.toString())
// Coalesced setComposingText + finishComposingText inside one batch emits once.
ic.beginBatchEdit()
ic.setComposingText("ef", 1)
ic.finishComposingText()
ic.endBatchEdit()
assertEquals("abcdef", terminal.rawStream)
assertEquals("", ic.editable.toString())
}
}
@Test
fun backspaceWorksAcrossAllThreeImePaths() {
withInputHarness { _, ic, _, terminal ->
ic.commitText("abcd", 1)
assertEquals("abcd", terminal.applyToLine())
// Path 1: deleteSurroundingText (empty editable after commit)
ic.deleteSurroundingText(0, 0)
assertEquals("abcd", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("abc", terminal.applyToLine())
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
ic.setComposingText("😀", 1)
assertEquals("ab😀", terminal.applyToLine())
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 3: sendKeyEvent(KEYCODE_DEL) emits on ACTION_DOWN only, not ACTION_UP
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
assertEquals("a", terminal.applyToLine())
// Multi-char deleteSurroundingText on empty buffer
ic.commitText("xyz", 1)
ic.deleteSurroundingText(2, 0)
assertEquals("ax", terminal.applyToLine())
}
}
@Test
fun hangulCompositionSyllableMigrationBackspaceAndPostEnter() {
withInputHarness { _, ic, _, terminal ->
// ㅎ -> 하 -> 한
ic.setComposingText("ㅎ", 1)
ic.setComposingText("하", 1)
ic.setComposingText("한", 1)
assertEquals("한", terminal.applyToLine())
// Final consonant migration: 한 + ㅏ -> commit 하 + compose 나 in one batch
ic.beginBatchEdit()
ic.commitText("하", 1)
ic.setComposingText("나", 1)
ic.endBatchEdit()
assertEquals("하나", terminal.applyToLine())
// Continue composing second syllable: 나 -> 난
ic.setComposingText("난", 1)
assertEquals("하난", terminal.applyToLine())
// Backspace decomposes 난 -> 나 -> ㄴ -> "" (leaving 하) -> ""
ic.setComposingText("나", 1)
assertEquals("하나", terminal.applyToLine())
ic.setComposingText("ㄴ", 1)
assertEquals("하ㄴ", terminal.applyToLine())
ic.commitText("", 1)
assertEquals("하", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("", terminal.applyToLine())
// Submit via Enter, then immediately type 한글 with zero stale newline residue (#7164)
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
ic.setComposingText("ㅎ", 1)
ic.setComposingText("하", 1)
ic.setComposingText("한", 1)
ic.beginBatchEdit()
ic.commitText("한", 1)
ic.setComposingText("ㄱ", 1)
ic.endBatchEdit()
ic.setComposingText("그", 1)
ic.setComposingText("글", 1)
ic.finishComposingText()
assertEquals("\r한글", terminal.applyToLine())
}
}
@Test
fun pinyinCompositionAndMixedChineseThenLatinCandidate() {
withInputHarness { _, ic, _, terminal ->
// Pinyin reading: nihao -> ni hao -> 你好
ic.setComposingText("n", 1)
ic.setComposingText("ni", 1)
ic.setComposingText("nih", 1)
ic.setComposingText("niha", 1)
ic.setComposingText("ni hao", 1)
ic.beginBatchEdit()
ic.commitText("你好", 1)
ic.endBatchEdit()
assertEquals("你好", terminal.applyToLine())
// WeChat Keyboard #9121: immediately compose English and pick 2nd suggestion `hello`
ic.setComposingText("h", 1)
ic.setComposingText("he", 1)
ic.setComposingText("hel", 1)
ic.beginBatchEdit()
ic.commitText("hello", 1)
ic.endBatchEdit()
assertEquals("你好hello", terminal.applyToLine())
// Backspace right after Latin candidate deletes from terminal visibly
ic.deleteSurroundingText(1, 0)
assertEquals("你好hell", terminal.applyToLine())
}
}
@Test
fun latinCandidatesAutocorrectAndRepeatedClipboardCommit() {
withInputHarness { _, ic, _, terminal ->
// Candidate completion: hel -> hello
ic.setComposingText("hel", 1)
ic.commitText("hello", 1)
assertEquals("hello", terminal.applyToLine())
// Autocorrect replacement inside composing span: teh -> the
ic.setComposingText("teh", 1)
ic.commitText("the", 1)
assertEquals("hellothe", terminal.applyToLine())
// Repeated clipboard paste of identical text works because editable clears after commit
ic.commitText("echo ok", 1)
ic.commitText("echo ok", 1)
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
}
}
@Test
fun enterKeyAndEditorActionEmitSingleCarriageReturn() {
withInputHarness { _, ic, _, terminal ->
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
assertEquals("\r", terminal.rawStream)
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_NUMPAD_ENTER))
assertEquals("\r\r", terminal.rawStream)
ic.performEditorAction(EditorInfo.IME_ACTION_NONE)
assertEquals("\r\r\r", terminal.rawStream)
ic.commitText("\n", 1)
assertEquals("\r\r\r\r", terminal.rawStream)
}
}
@Test
fun physicalKeyboardKeysAndDeadKeyAccents() {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val terminal = RecordedTerminal()
val view = PaseoTerminalInputView.createForTest(
context = context,
onInput = terminal::write,
onTerminalKey = terminal::key,
)
view.onCreateInputConnection(EditorInfo())
// Enter & Numpad Enter: ACTION_DOWN + ACTION_UP -> single \r each
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_ENTER, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)))
assertTrue(view.onKeyUp(KeyEvent.KEYCODE_ENTER, KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER)))
assertTrue(view.onKeyUp(KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_NUMPAD_ENTER)))
assertEquals("\r\r", terminal.rawStream)
// Tab, Shift+Tab, Escape, Del
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, 0, KeyEvent.META_SHIFT_ON)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_ESCAPE, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ESCAPE)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_DEL, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f", terminal.rawStream)
// Ctrl+C and Alt+B
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_C, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_C, 0, KeyEvent.META_CTRL_ON)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_B, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_B, 0, KeyEvent.META_ALT_ON)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bb", terminal.rawStream)
// Printable key
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_A, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bba", terminal.rawStream)
// Dead key accent (acute + e -> é)
val deadAcuteEvent = object : KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E) {
override fun getUnicodeChar(metaState: Int): Int =
KeyCharacterMap.COMBINING_ACCENT or '\u00b4'.code
}
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_E, deadAcuteEvent))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_E, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bbaé", terminal.rawStream)
// Meta shortcuts pass through unhandled
assertFalse(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, 0, KeyEvent.META_META_ON)))
}
}
@Test
fun composingStateIsExposedOnViewForHardwareKeyboardModule() {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val view = PaseoTerminalInputView.createForTest(context)
// Mirrors React Native BaseViewManager.setTestId, which overwrites the unkeyed View tag.
view.setTag("terminal-native-input")
val ic = checkNotNull(view.onCreateInputConnection(EditorInfo()))
assertFalse(view.isComposingText())
ic.setComposingText("한", 1)
assertTrue(view.isComposingText())
ic.commitText("한", 1)
assertFalse(view.isComposingText())
}
}
}
@@ -1,69 +0,0 @@
package sh.paseo.terminal
import android.text.InputType
import android.view.inputmethod.EditorInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import com.facebook.react.bridge.BridgeReactContext
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.facebook.react.uimanager.ThemedReactContext
import com.facebook.react.views.textinput.ReactEditText
import com.facebook.react.views.textinput.ReactTextInputManager
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotEquals
import org.junit.Test
import org.junit.runner.RunWith
/**
* Builds React Native's own text input and applies `nativeID` through its view manager, which is
* how Fabric mounts the hidden terminal input. The app runs bridgeless, so the context is too.
*/
@RunWith(AndroidJUnit4::class)
class TerminalInputKeyboardTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
@Test fun terminalInputAsksTheKeyboardNotToLearnWhatIsTyped() {
onInput("paseo-terminal-input") { input, editorInfo ->
assertNotEquals(
"The keyboard must not learn passwords typed at a terminal prompt",
0,
editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING,
)
assertEquals(
"Suggestions stay off and the input stays multiline",
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE,
editorInfo.inputType and (InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE),
)
val connection = checkNotNull(input.onCreateInputConnection(EditorInfo()))
connection.setComposingText("su", 1)
connection.commitText("sudo ls", 1)
connection.deleteSurroundingText(1, 0)
assertEquals("sudo l", input.text.toString())
}
}
@Test fun otherInputsKeepPersonalizedLearning() {
onInput("message-composer") { _, editorInfo ->
assertEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING)
}
}
private fun onInput(nativeId: String, check: (ReactEditText, EditorInfo) -> Unit) {
TerminalInputKeyboard.install()
instrumentation.runOnMainSync {
val app = instrumentation.targetContext
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(app)
val react = object : BridgeReactContext(app) {
override fun isBridgeless() = true
}
val input = ReactEditText(ThemedReactContext(react, app, null, -1))
input.inputType = InputType.TYPE_CLASS_TEXT or
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
InputType.TYPE_TEXT_FLAG_MULTI_LINE
ReactTextInputManager().setNativeId(input, nativeId)
val editorInfo = EditorInfo()
input.onCreateInputConnection(editorInfo)
check(input, editorInfo)
}
}
}
@@ -0,0 +1,168 @@
package sh.paseo.terminal
import android.content.Context
import android.graphics.Rect
import android.text.SpannableStringBuilder
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputConnection
import android.view.inputmethod.InputMethodManager
import expo.modules.kotlin.viewevent.EventDispatcher
import sh.paseo.keyboard.ComposingTextOwner
/**
* Focusable 1x1 native Android text editor view that owns the terminal's [InputConnection] and
* physical keyboard [onKeyDown] delivery directly, bypassing React Native's `TextInput`.
*
* Implements [ComposingTextOwner] so `PaseoHardwareKeyboardModule` reads active IME composition
* reliably even after React Native's `BaseViewManager.setTestId` overwrites `View.getTag()`.
*/
class PaseoTerminalInputView(context: Context) : View(context), ComposingTextOwner {
private val onTerminalInput by EventDispatcher<Map<String, String>>()
private val onTerminalKey by EventDispatcher<Map<String, Any>>()
private val onFocusChange by EventDispatcher<Map<String, Boolean>>()
private val editable = SpannableStringBuilder()
private var inputSink: ((String) -> Unit)? = null
private var keySink: ((TerminalKeyPayload) -> Unit)? = null
private var focusSink: ((Boolean) -> Unit)? = null
private var inputConnection: TerminalInputConnection? = null
init {
isFocusable = true
isFocusableInTouchMode = true
importantForAutofill = IMPORTANT_FOR_AUTOFILL_NO
contentDescription = "Terminal input"
}
override fun isComposingText(): Boolean =
BaseInputConnection.getComposingSpanStart(editable) >= 0
override fun onCheckIsTextEditor(): Boolean = true
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
TerminalInputConnection.configureEditorInfo(outAttrs)
val connection = ensureInputConnection()
connection.resetState()
return connection
}
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (ensureInputConnection().handleKeyDown(keyCode, event)) {
return true
}
return super.onKeyDown(keyCode, event)
}
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
if (ensureInputConnection().handleKeyUp(keyCode, event)) {
return true
}
return super.onKeyUp(keyCode, event)
}
@Suppress("DEPRECATION")
override fun onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent): Boolean {
if (ensureInputConnection().handleKeyMultiple(event)) {
return true
}
return super.onKeyMultiple(keyCode, repeatCount, event)
}
override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
if (!gainFocus) {
inputConnection?.resetState()
}
val sink = focusSink
if (sink != null) {
sink(gainFocus)
} else {
onFocusChange(mapOf("focused" to gainFocus))
}
}
fun focusInput() {
showKeyboard()
}
fun showKeyboard() {
val show: () -> Unit = {
if (!hasFocus()) {
requestFocus()
}
val imm = context.getSystemService(InputMethodManager::class.java)
imm?.showSoftInput(this, 0)
}
if (hasFocus()) {
show()
} else {
requestFocus()
post(show)
}
}
fun blurInput() {
inputConnection?.resetState()
if (hasFocus()) {
clearFocus()
}
val imm = context.getSystemService(InputMethodManager::class.java)
imm?.hideSoftInputFromWindow(windowToken, 0)
}
private fun ensureInputConnection(): TerminalInputConnection {
val existing = inputConnection
if (existing != null) return existing
val created = TerminalInputConnection(
targetView = this,
sharedEditable = editable,
onInput = ::emitInput,
onTerminalKey = ::emitKey,
)
inputConnection = created
return created
}
private fun emitInput(data: String) {
val sink = inputSink
if (sink != null) {
sink(data)
} else {
onTerminalInput(mapOf("data" to data))
}
}
private fun emitKey(payload: TerminalKeyPayload) {
val sink = keySink
if (sink != null) {
sink(payload)
} else {
onTerminalKey(
mapOf(
"key" to payload.key,
"ctrl" to payload.ctrl,
"shift" to payload.shift,
"alt" to payload.alt,
"meta" to payload.meta,
),
)
}
}
companion object {
internal fun createForTest(
context: Context,
onInput: (String) -> Unit = {},
onTerminalKey: (TerminalKeyPayload) -> Unit = {},
onFocus: (Boolean) -> Unit = {},
): PaseoTerminalInputView =
PaseoTerminalInputView(context).apply {
inputSink = onInput
keySink = onTerminalKey
focusSink = onFocus
}
}
}
@@ -7,8 +7,6 @@ class PaseoTerminalModule : Module() {
override fun definition() = ModuleDefinition {
Name("PaseoTerminal")
OnCreate { TerminalInputKeyboard.install() }
View(PaseoTerminalView::class) {
Events("onCellMetrics")
@@ -22,5 +20,13 @@ class PaseoTerminalModule : Module() {
OnViewDidUpdateProps { view: PaseoTerminalView -> view.commit() }
}
View(PaseoTerminalInputView::class) {
Events("onTerminalInput", "onTerminalKey", "onFocusChange")
AsyncFunction("focusInput") { view: PaseoTerminalInputView -> view.focusInput() }
AsyncFunction("showKeyboard") { view: PaseoTerminalInputView -> view.showKeyboard() }
AsyncFunction("blurInput") { view: PaseoTerminalInputView -> view.blurInput() }
}
}
}
@@ -0,0 +1,501 @@
package sh.paseo.terminal
import android.text.Editable
import android.text.InputType
import android.text.Selection
import android.text.SpannableStringBuilder
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.BaseInputConnection
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
internal data class TerminalKeyPayload(
val key: String,
val ctrl: Boolean = false,
val shift: Boolean = false,
val alt: Boolean = false,
val meta: Boolean = false,
)
/**
* Single authoritative IME + key stream for the Android native terminal.
*
* Keeps a private [SpannableStringBuilder] so Android IMEs can compose Hangul, Pinyin, and Latin
* candidates normally, diffs the editable against what was last sent to the PTY once each batch
* edit settles, and clears the editable as soon as no composing span remains.
*/
internal class TerminalInputConnection(
private val targetView: View,
private val sharedEditable: SpannableStringBuilder = SpannableStringBuilder(),
private val onInput: (String) -> Unit,
private val onTerminalKey: (TerminalKeyPayload) -> Unit,
) : BaseInputConnection(targetView, true) {
private var batchEditDepth = 0
private var lastSentText = ""
private var pendingBackspaces = 0
private var deadAccent = 0
private var lastSelStart = 0
private var lastSelEnd = 0
private var lastCompStart = -1
private var lastCompEnd = -1
override fun getEditable(): Editable = sharedEditable
override fun beginBatchEdit(): Boolean {
batchEditDepth += 1
return super.beginBatchEdit()
}
override fun endBatchEdit(): Boolean {
val result = super.endBatchEdit()
if (batchEditDepth > 0) {
batchEditDepth -= 1
}
if (batchEditDepth == 0) {
flush()
}
return result
}
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
val result = super.setComposingText(text, newCursorPosition)
if (batchEditDepth == 0) flush()
return result
}
override fun setComposingRegion(start: Int, end: Int): Boolean {
val result = super.setComposingRegion(start, end)
if (batchEditDepth == 0) flush()
return result
}
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
val result = super.commitText(text, newCursorPosition)
if (batchEditDepth == 0) flush()
return result
}
override fun finishComposingText(): Boolean {
val result = super.finishComposingText()
if (batchEditDepth == 0) flush()
return result
}
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
if (beforeLength <= 0 && afterLength <= 0) return true
val lengthBefore = sharedEditable.length
val result = super.deleteSurroundingText(beforeLength, afterLength)
val deletedChars = maxOf(0, lengthBefore - sharedEditable.length)
var remaining = maxOf(0, beforeLength - deletedChars)
if (remaining > 0 && sharedEditable.isNotEmpty()) {
val toTrim = minOf(remaining, sharedEditable.length)
sharedEditable.delete(sharedEditable.length - toTrim, sharedEditable.length)
Selection.setSelection(sharedEditable, sharedEditable.length)
remaining -= toTrim
}
if (remaining > 0) {
pendingBackspaces += remaining
}
if (batchEditDepth == 0) flush()
return result
}
override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean {
if (beforeLength <= 0 && afterLength <= 0) return true
val codePointsBefore = Character.codePointCount(sharedEditable, 0, sharedEditable.length)
val result = super.deleteSurroundingTextInCodePoints(beforeLength, afterLength)
val codePointsAfter = Character.codePointCount(sharedEditable, 0, sharedEditable.length)
val deletedCodePoints = maxOf(0, codePointsBefore - codePointsAfter)
var remaining = maxOf(0, beforeLength - deletedCodePoints)
if (remaining > 0 && codePointsAfter > 0) {
val toTrim = minOf(remaining, codePointsAfter)
val trimStart = Character.offsetByCodePoints(sharedEditable, sharedEditable.length, -toTrim)
sharedEditable.delete(trimStart, sharedEditable.length)
Selection.setSelection(sharedEditable, sharedEditable.length)
remaining -= toTrim
}
if (remaining > 0) {
pendingBackspaces += remaining
}
if (batchEditDepth == 0) flush()
return result
}
override fun performEditorAction(editorAction: Int): Boolean {
submitEnter()
return true
}
override fun sendKeyEvent(event: KeyEvent): Boolean {
return when (event.action) {
KeyEvent.ACTION_DOWN -> handleKeyDown(event.keyCode, event)
KeyEvent.ACTION_UP -> isHandledKeyCode(event.keyCode, event)
@Suppress("DEPRECATION")
KeyEvent.ACTION_MULTIPLE -> handleKeyMultiple(event)
else -> false
}
}
override fun closeConnection() {
resetState()
super.closeConnection()
}
internal fun resetState() {
batchEditDepth = 0
pendingBackspaces = 0
deadAccent = 0
lastSentText = ""
clearEditableSilently()
lastSelStart = 0
lastSelEnd = 0
lastCompStart = -1
lastCompEnd = -1
}
internal fun handleKeyDown(keyCode: Int, event: KeyEvent): Boolean {
if (KeyEvent.isModifierKey(keyCode)) return false
if (event.isMetaPressed) return false
when (keyCode) {
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> {
submitEnter(altPressed = event.isAltPressed && !event.isCtrlPressed && !event.isShiftPressed)
return true
}
KeyEvent.KEYCODE_DEL -> {
handleDeleteKey(altPressed = event.isAltPressed && !event.isCtrlPressed)
return true
}
KeyEvent.KEYCODE_FORWARD_DEL -> {
deadAccent = 0
flushAndClear()
onInput("\u001b[3~")
return true
}
KeyEvent.KEYCODE_TAB -> {
deadAccent = 0
flushAndClear()
val sequence = when {
event.isShiftPressed && !event.isCtrlPressed && !event.isAltPressed -> "\u001b[Z"
event.isAltPressed && !event.isCtrlPressed -> "\u001b\t"
else -> "\t"
}
onInput(sequence)
return true
}
KeyEvent.KEYCODE_ESCAPE -> {
deadAccent = 0
flushAndClear()
onInput("\u001b")
return true
}
KeyEvent.KEYCODE_DPAD_UP,
KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT -> {
deadAccent = 0
val name = when (keyCode) {
KeyEvent.KEYCODE_DPAD_UP -> "ArrowUp"
KeyEvent.KEYCODE_DPAD_DOWN -> "ArrowDown"
KeyEvent.KEYCODE_DPAD_LEFT -> "ArrowLeft"
else -> "ArrowRight"
}
onTerminalKey(
TerminalKeyPayload(
key = name,
ctrl = event.isCtrlPressed,
shift = event.isShiftPressed,
alt = event.isAltPressed,
meta = event.isMetaPressed,
),
)
return true
}
}
if (event.isCtrlPressed) {
val ctrlSeq = encodeCtrlKey(keyCode, event) ?: return false
deadAccent = 0
flushAndClear()
onInput(if (event.isAltPressed) "\u001b$ctrlSeq" else ctrlSeq)
return true
}
if (event.isAltPressed) {
val withAlt = event.getUnicodeChar(event.metaState)
val withoutAlt = event.getUnicodeChar(event.metaState and KeyEvent.META_ALT_MASK.inv())
if (withAlt != 0 && withAlt != withoutAlt) {
return handleUnicodeChar(withAlt)
}
if (withoutAlt != 0 && (withoutAlt and KeyCharacterMap.COMBINING_ACCENT) == 0) {
deadAccent = 0
flushAndClear()
onInput("\u001b" + String(Character.toChars(withoutAlt)))
return true
}
return false
}
val unicodeChar = event.getUnicodeChar(event.metaState)
if (unicodeChar != 0) {
return handleUnicodeChar(unicodeChar)
}
return false
}
internal fun handleKeyUp(keyCode: Int, event: KeyEvent): Boolean =
isHandledKeyCode(keyCode, event)
@Suppress("DEPRECATION")
internal fun handleKeyMultiple(event: KeyEvent): Boolean {
val characters = event.characters ?: return false
if (characters.isEmpty()) return false
deadAccent = 0
flushAndClear()
onInput(normalizeLineEndings(characters))
return true
}
private fun isHandledKeyCode(keyCode: Int, event: KeyEvent): Boolean {
if (KeyEvent.isModifierKey(keyCode) || event.isMetaPressed) return false
return when (keyCode) {
KeyEvent.KEYCODE_ENTER,
KeyEvent.KEYCODE_NUMPAD_ENTER,
KeyEvent.KEYCODE_DEL,
KeyEvent.KEYCODE_FORWARD_DEL,
KeyEvent.KEYCODE_TAB,
KeyEvent.KEYCODE_ESCAPE,
KeyEvent.KEYCODE_DPAD_UP,
KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT,
KeyEvent.KEYCODE_DPAD_RIGHT -> true
else -> {
if (event.isCtrlPressed) return encodeCtrlKey(keyCode, event) != null
val plainMeta = event.metaState and KeyEvent.META_ALT_MASK.inv()
event.getUnicodeChar(event.metaState) != 0 ||
(event.isAltPressed && event.getUnicodeChar(plainMeta) != 0)
}
}
}
private fun handleUnicodeChar(unicodeChar: Int): Boolean {
if (unicodeChar and KeyCharacterMap.COMBINING_ACCENT != 0) {
deadAccent = unicodeChar and KeyCharacterMap.COMBINING_ACCENT_MASK
return true
}
var codePoint = unicodeChar
if (deadAccent != 0) {
val combined = KeyEvent.getDeadChar(deadAccent, codePoint)
val previousAccent = deadAccent
deadAccent = 0
if (combined != 0) {
codePoint = combined
} else {
flushAndClear()
val accentChar =
KeyEvent.getDeadChar(previousAccent, ' '.code).takeIf { it != 0 } ?: previousAccent
onInput(String(Character.toChars(accentChar)) + String(Character.toChars(codePoint)))
return true
}
}
flushAndClear()
onInput(String(Character.toChars(codePoint)))
return true
}
private fun handleDeleteKey(altPressed: Boolean) {
deadAccent = 0
if (altPressed) {
flushAndClear()
onInput("\u001b\u007f")
return
}
if (sharedEditable.isNotEmpty()) {
val end = sharedEditable.length
val prevCpStart = Character.offsetByCodePoints(sharedEditable, end, -1)
sharedEditable.delete(prevCpStart, end)
Selection.setSelection(sharedEditable, sharedEditable.length)
flush()
} else {
onInput("\u007f")
}
}
private fun submitEnter(altPressed: Boolean = false) {
deadAccent = 0
flushAndClear()
onInput(if (altPressed) "\u001b\r" else "\r")
}
private fun flush() {
val out = StringBuilder()
if (pendingBackspaces > 0) {
repeat(pendingBackspaces) { out.append('\u007f') }
pendingBackspaces = 0
}
val currentText = sharedEditable.toString()
val diff = computeDiff(lastSentText, currentText)
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
val compStart = getComposingSpanStart(sharedEditable)
val compEnd = getComposingSpanEnd(sharedEditable)
val isComposing = compStart >= 0 && compEnd > compStart
if (!isComposing) {
val hadText = sharedEditable.isNotEmpty()
if (hadText || compStart >= 0) {
clearEditableSilently()
}
lastSentText = ""
if (hadText) {
// The IME just advanced its cursor for the committed text; report the reset to 0, 0.
forceUpdateSelection(0, 0, -1, -1)
} else {
notifySelectionIfChanged(0, 0, -1, -1)
}
} else {
lastSentText = currentText
val selStart = maxOf(0, Selection.getSelectionStart(sharedEditable))
val selEnd = maxOf(0, Selection.getSelectionEnd(sharedEditable))
notifySelectionIfChanged(selStart, selEnd, compStart, compEnd)
}
if (out.isNotEmpty()) {
onInput(out.toString())
}
}
private fun flushAndClear() {
batchEditDepth = 0
val hadText = sharedEditable.isNotEmpty()
val out = StringBuilder()
if (pendingBackspaces > 0) {
repeat(pendingBackspaces) { out.append('\u007f') }
pendingBackspaces = 0
}
val currentText = sharedEditable.toString()
val diff = computeDiff(lastSentText, currentText)
if (diff.isNotEmpty()) {
out.append(normalizeLineEndings(diff))
}
if (hadText || getComposingSpanStart(sharedEditable) >= 0) {
clearEditableSilently()
}
lastSentText = ""
if (hadText || lastSelStart != 0 || lastSelEnd != 0 || lastCompStart != -1 || lastCompEnd != -1) {
forceUpdateSelection(0, 0, -1, -1)
}
if (out.isNotEmpty()) {
onInput(out.toString())
}
}
private fun clearEditableSilently() {
removeComposingSpans(sharedEditable)
sharedEditable.clear()
Selection.setSelection(sharedEditable, 0)
}
private fun notifySelectionIfChanged(selStart: Int, selEnd: Int, compStart: Int, compEnd: Int) {
if (
selStart == lastSelStart &&
selEnd == lastSelEnd &&
compStart == lastCompStart &&
compEnd == lastCompEnd
) {
return
}
forceUpdateSelection(selStart, selEnd, compStart, compEnd)
}
private fun forceUpdateSelection(selStart: Int, selEnd: Int, compStart: Int, compEnd: Int) {
lastSelStart = selStart
lastSelEnd = selEnd
lastCompStart = compStart
lastCompEnd = compEnd
val imm = targetView.context.getSystemService(InputMethodManager::class.java) ?: return
if (imm.isActive(targetView)) {
imm.updateSelection(targetView, selStart, selEnd, compStart, compEnd)
}
}
companion object {
internal fun configureEditorInfo(outAttrs: EditorInfo) {
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
outAttrs.imeOptions =
EditorInfo.IME_ACTION_NONE or
EditorInfo.IME_FLAG_NO_FULLSCREEN or
EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
outAttrs.initialSelStart = 0
outAttrs.initialSelEnd = 0
}
private fun normalizeLineEndings(text: String): String =
text.replace("\r\n", "\r").replace("\n", "\r")
private fun computeDiff(previous: String, next: String): String {
if (previous == next) return ""
val prevCps = previous.toCodePoints()
val nextCps = next.toCodePoints()
var common = 0
val limit = minOf(prevCps.size, nextCps.size)
while (common < limit && prevCps[common] == nextCps[common]) {
common += 1
}
val removed = prevCps.size - common
val out = StringBuilder(removed + (nextCps.size - common))
repeat(removed) { out.append('\u007f') }
for (i in common until nextCps.size) {
out.appendCodePoint(nextCps[i])
}
return out.toString()
}
private fun String.toCodePoints(): IntArray {
val count = codePointCount(0, length)
val result = IntArray(count)
var offset = 0
var index = 0
while (offset < length) {
val cp = codePointAt(offset)
result[index++] = cp
offset += Character.charCount(cp)
}
return result
}
private fun encodeCtrlKey(keyCode: Int, event: KeyEvent): String? {
val unctrlMeta =
event.metaState and
KeyEvent.META_CTRL_MASK.inv() and
KeyEvent.META_ALT_MASK.inv() and
KeyEvent.META_META_MASK.inv()
val unicode = event.getUnicodeChar(unctrlMeta)
val ch = when {
unicode != 0 -> unicode.toChar()
keyCode in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z ->
('a'.code + keyCode - KeyEvent.KEYCODE_A).toChar()
keyCode == KeyEvent.KEYCODE_SPACE -> ' '
else -> return null
}
val upper = ch.uppercaseChar()
return when {
upper in 'A'..'Z' -> (upper.code - 64).toChar().toString()
ch == ' ' || ch == '@' || ch == '2' -> "\u0000"
ch == '[' || ch == '3' -> "\u001b"
ch == '\\' || ch == '4' -> "\u001c"
ch == ']' || ch == '5' -> "\u001d"
ch == '^' || ch == '6' -> "\u001e"
ch == '_' || ch == '/' || ch == '7' -> "\u001f"
ch == '8' || ch == '?' -> "\u007f"
else -> null
}
}
}
}
@@ -1,32 +0,0 @@
package sh.paseo.terminal
import android.view.View
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import com.facebook.react.bridge.UiThreadUtil
import com.facebook.react.uimanager.util.ReactFindViewUtil
// Matched against the hidden terminal input's `nativeID`
// (TERMINAL_INPUT_NATIVE_ID in terminal-input.native.tsx).
private const val TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"
/**
* Keeps what is typed at a terminal prompt, such as a `sudo` password, out of the keyboard's
* learned words. React Native's TextInput has no prop for IME_FLAG_NO_PERSONALIZED_LEARNING, so the
* flag is added when the input receives its `nativeID`, before it can take focus.
*
* React Native replaces `imeOptions` when `returnKeyType` or `disableFullscreenUI` is set, so the
* terminal input sets neither.
*/
internal object TerminalInputKeyboard : ReactFindViewUtil.OnMultipleViewsFoundListener {
fun install() {
UiThreadUtil.runOnUiThread {
ReactFindViewUtil.addViewsListener(this, setOf(TERMINAL_INPUT_NATIVE_ID))
}
}
override fun onViewFound(view: View, nativeId: String) {
val input = view as? TextView ?: return
input.imeOptions = input.imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
}
}
@@ -0,0 +1,57 @@
import { requireNativeView } from "expo";
import { forwardRef, useCallback, type Ref } from "react";
import type { ViewProps } from "react-native";
import type {
PaseoTerminalInputKeyEvent,
PaseoTerminalInputViewHandle,
PaseoTerminalInputViewProps,
} from "./terminal-input-view";
export type {
PaseoTerminalInputKeyEvent,
PaseoTerminalInputViewHandle,
PaseoTerminalInputViewProps,
};
interface NativePaseoTerminalInputViewProps extends ViewProps {
ref?: Ref<PaseoTerminalInputViewHandle>;
onTerminalInput?: (event: { nativeEvent: { data: string } }) => void;
onTerminalKey?: (event: { nativeEvent: PaseoTerminalInputKeyEvent }) => void;
onFocusChange?: (event: { nativeEvent: { focused: boolean } }) => void;
}
const NativePaseoTerminalInputView = requireNativeView<NativePaseoTerminalInputViewProps>(
"PaseoTerminal",
"PaseoTerminalInputView",
);
export const PaseoTerminalInputView = forwardRef<
PaseoTerminalInputViewHandle,
PaseoTerminalInputViewProps
>(function PaseoTerminalInputView(
{ onTerminalInput, onTerminalKey, onFocusChange, ...props },
ref,
) {
const handleTerminalInput = useCallback(
(event: { nativeEvent: { data: string } }) => onTerminalInput?.(event.nativeEvent.data),
[onTerminalInput],
);
const handleTerminalKey = useCallback(
(event: { nativeEvent: PaseoTerminalInputKeyEvent }) => onTerminalKey?.(event.nativeEvent),
[onTerminalKey],
);
const handleFocusChange = useCallback(
(event: { nativeEvent: { focused: boolean } }) => onFocusChange?.(event.nativeEvent.focused),
[onFocusChange],
);
return (
<NativePaseoTerminalInputView
{...props}
ref={ref}
onTerminalInput={handleTerminalInput}
onTerminalKey={handleTerminalKey}
onFocusChange={handleFocusChange}
/>
);
});
@@ -0,0 +1,32 @@
import { forwardRef, type Ref } from "react";
import type { ViewProps } from "react-native";
export interface PaseoTerminalInputViewHandle {
focusInput: () => Promise<void>;
showKeyboard: () => Promise<void>;
blurInput: () => Promise<void>;
}
export interface PaseoTerminalInputKeyEvent {
key: string;
ctrl: boolean;
shift: boolean;
alt: boolean;
meta: boolean;
}
export interface PaseoTerminalInputViewProps extends ViewProps {
onTerminalInput?: (data: string) => void;
onTerminalKey?: (event: PaseoTerminalInputKeyEvent) => void;
onFocusChange?: (focused: boolean) => void;
}
export const PaseoTerminalInputView = forwardRef<
PaseoTerminalInputViewHandle,
PaseoTerminalInputViewProps
>(function PaseoTerminalInputView(
_props: PaseoTerminalInputViewProps,
_ref: Ref<PaseoTerminalInputViewHandle>,
) {
return null;
});
@@ -0,0 +1,70 @@
const { withMainActivity } = require("expo/config-plugins");
// Android 12+ "Bold text" sets Configuration.fontWeightAdjustment, and TextView
// applies it when drawing text that has no explicit fontWeight or fontFamily.
// React Native's TextLayoutManager measures that text without the adjustment, so
// the wider glyphs overflow the measured box and trailing words or lines are
// clipped (#4057, #10152, #10850).
//
// Override only fontWeightAdjustment on an empty sparse Configuration() so
// unrelated configuration fields (uiMode, densityDpi, orientation,
// screenWidthDp, fontScale, locales) keep flowing through onConfigurationChanged.
//
// Remove this plugin once upstream React Native's TextLayoutManager measures
// with Configuration.fontWeightAdjustment.
const IMPORTS = [
"android.content.Context",
"android.content.res.Configuration",
"android.os.Build",
];
const MARKER = "// paseo-ignore-bold-text";
const ATTACH_BASE_CONTEXT = ` ${MARKER}
override fun attachBaseContext(newBase: Context) {
val configuration = newBase.resources.configuration
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && configuration.fontWeightAdjustment != 0) {
val override = Configuration()
override.fontWeightAdjustment = 0
super.attachBaseContext(newBase.createConfigurationContext(override))
return
}
super.attachBaseContext(newBase)
}
`;
const CLASS_DECLARATION = /class MainActivity : ReactActivity\(\) \{\n/;
function configureIgnoreBoldTextMainActivity(source) {
if (source.includes(MARKER)) {
return source;
}
if (!CLASS_DECLARATION.test(source)) {
throw new Error("withAndroidIgnoreBoldText could not find the MainActivity class declaration");
}
if (/override fun attachBaseContext\(/.test(source)) {
throw new Error("withAndroidIgnoreBoldText found an existing attachBaseContext override");
}
let contents = source;
for (const name of IMPORTS) {
if (!contents.includes(`import ${name}\n`)) {
contents = contents.replace(/^package .*\n/m, (line) => `${line}import ${name}\n`);
}
}
return contents.replace(CLASS_DECLARATION, (line) => `${line}${ATTACH_BASE_CONTEXT}\n`);
}
function withAndroidIgnoreBoldText(config) {
return withMainActivity(config, (modConfig) => {
if (modConfig.modResults.language !== "kt") {
throw new Error("withAndroidIgnoreBoldText expects a Kotlin MainActivity");
}
modConfig.modResults.contents = configureIgnoreBoldTextMainActivity(
modConfig.modResults.contents,
);
return modConfig;
});
}
module.exports = withAndroidIgnoreBoldText;
module.exports.configureIgnoreBoldTextMainActivity = configureIgnoreBoldTextMainActivity;
@@ -783,6 +783,56 @@ it("presents received agent messages as attributed bubbles with the original tur
});
});
it("presents a finished notification as a compact tool call, not a received message", () => {
const call = toolCall("notice", "agent_finished");
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
call.payload.data.detail = {
type: "plain_text",
label: "Child",
text: "Agent child (Child) finished.",
icon: "bot",
};
const result = createStreamPresentation()({
...presentationOptions,
transform: undefined,
tail: [call],
head: [],
});
expect(result.tail).toEqual([call]);
});
// COMPAT(agentNotificationMetadata): rows from daemons that sent notification metadata.
it("presents a legacy notification as the plain tool call current daemons send", () => {
const call = toolCall("legacy", "agent_message");
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
call.turnId = "turn";
call.payload.data.detail = { type: "plain_text", text: "Done", icon: "bot" };
call.payload.data.agentMessage = {
event: "finished",
sender: { id: "child", title: "Child" },
text: "Done",
};
const result = createStreamPresentation()({
...presentationOptions,
transform: undefined,
tail: [call],
head: [],
});
expect(result.tail).toHaveLength(1);
const [presented] = result.tail;
if (presented?.kind !== "tool_call" || presented.payload.source !== "agent")
throw new Error("Expected agent tool");
expect(presented).toMatchObject({ id: call.id, turnId: "turn" });
expect(presented.payload.data).toEqual({
provider: "codex",
callId: "legacy",
name: "agent_finished",
status: "completed",
error: null,
detail: { type: "plain_text", label: "Child", text: "Done", icon: "bot" },
});
});
it("does not reopen the previous turn while a new run waits for its first row", () => {
const timestamp = new Date();
const tail: StreamItem[] = [
+24 -2
View File
@@ -9,7 +9,14 @@ import {
type ToolCallDetailLevel,
type ToolCallDetailProjection,
} from "@/tool-calls/detail-level/projection";
import type { StreamItem, UserMessageItem } from "@/types/stream";
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import { legacyAgentNotificationToolCall } from "@getpaseo/protocol/paseo-tool-presentation/index";
import {
isAgentToolCallItem,
type AgentToolCallItem,
type StreamItem,
type UserMessageItem,
} from "@/types/stream";
import { collapseTurns, type TurnCollapse } from "./turn-collapse/model";
import type { ReadingRowReplacements } from "./reading-anchor";
@@ -56,6 +63,7 @@ const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({
/** Source messages reach plugins before display projection. */
export function createStreamPresentation() {
const userMessageCache = new WeakMap<UserMessageItem, UserMessageItem>();
const legacyNotificationCache = new WeakMap<AgentToolCallItem, AgentToolCallItem>();
function presentUserMessage(item: UserMessageItem): UserMessageItem {
const cached = userMessageCache.get(item);
@@ -72,6 +80,19 @@ export function createStreamPresentation() {
return projected;
}
// COMPAT(agentNotificationMetadata): added in v0.18.1, remove after 2027-06-01.
function presentLegacyNotification(item: AgentToolCallItem, message: AgentMessage): StreamItem {
const cached = legacyNotificationCache.get(item);
if (cached) return cached;
const { agentMessage: _legacy, ...data } = item.payload.data;
const presented: AgentToolCallItem = {
...item,
payload: { source: "agent", data: { ...data, ...legacyAgentNotificationToolCall(message) } },
};
legacyNotificationCache.set(item, presented);
return presented;
}
let historySource: StreamItem[] | undefined;
let historyTransform: TimelineItemTransform | undefined;
let historyRows: StreamItem[] = [];
@@ -86,7 +107,7 @@ export function createStreamPresentation() {
let collapsed: TurnCollapse | undefined;
function presentRows(item: StreamItem): StreamItem[] {
if (item.kind === "tool_call" && item.payload.source === "agent") {
if (isAgentToolCallItem(item)) {
const message = item.payload.data.agentMessage;
if (message?.event === "message") {
return [
@@ -101,6 +122,7 @@ export function createStreamPresentation() {
},
];
}
if (message) return [presentLegacyNotification(item, message)];
}
return [item.kind === "user_message" ? presentUserMessage(item) : item];
}
@@ -22,10 +22,35 @@ function row(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "u
};
}
function assistantRow(
index: number,
height = ROW_HEIGHT,
): Extract<StreamItem, { kind: "assistant_message" }> {
return {
kind: "assistant_message",
id: `assistant-${index}`,
text: String(height),
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
};
}
function thoughtRow(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "thought" }> {
return {
kind: "thought",
id: `thought-${index}`,
text: String(height),
status: "ready",
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
};
}
const rowStyleByHeight = new Map<number, { height: number }>();
function renderRow(item: StreamItem) {
const height = item.kind === "user_message" ? Number(item.text) : ROW_HEIGHT;
const height =
item.kind === "user_message" || item.kind === "assistant_message" || item.kind === "thought"
? Number(item.text)
: ROW_HEIGHT;
let style = rowStyleByHeight.get(height);
if (!style) {
style = { height };
@@ -57,18 +82,30 @@ type OlderHistoryInput = Pick<
interface MountTimelineOptions {
olderHistory?: OlderHistoryInput;
isMobileBreakpoint?: boolean;
historyVirtualized?: StreamItem[];
viewportHeight?: number;
}
function mountTimeline(
historyMounted: StreamItem[],
{ olderHistory, isMobileBreakpoint = true }: MountTimelineOptions = {},
{
olderHistory,
isMobileBreakpoint = true,
historyVirtualized = [],
viewportHeight = VIEWPORT_HEIGHT,
}: MountTimelineOptions = {},
) {
host.style.height = `${viewportHeight}px`;
const strategy = createWebStreamStrategy({ isMobileBreakpoint });
const viewportRef = React.createRef<StreamViewportHandle>();
const input: StreamRenderInput = {
let currentInput: StreamRenderInput = {
agentId: "agent",
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
boundary: { hasVirtualizedHistory: false, hasMountedHistory: true, hasLiveHead: false },
segments: { historyVirtualized, historyMounted, liveHead: [] },
boundary: {
hasVirtualizedHistory: historyVirtualized.length > 0,
hasMountedHistory: historyMounted.length > 0,
hasLiveHead: false,
},
renderers: {
renderHistoryVirtualizedRow: renderRow,
renderHistoryMountedRow: renderRow,
@@ -91,8 +128,23 @@ function mountTimeline(
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
...olderHistory,
};
const render = (segments: Partial<StreamRenderInput["segments"]>) =>
root.render(strategy.render({ ...input, segments: { ...input.segments, ...segments } }));
const render = (
segments: Partial<StreamRenderInput["segments"]>,
overrides: Partial<Omit<StreamRenderInput, "segments">> = {},
) => {
const nextSegments = { ...currentInput.segments, ...segments };
currentInput = {
...currentInput,
...overrides,
segments: nextSegments,
boundary: {
hasVirtualizedHistory: nextSegments.historyVirtualized.length > 0,
hasMountedHistory: nextSegments.historyMounted.length > 0,
hasLiveHead: nextSegments.liveHead.length > 0,
},
};
root.render(strategy.render(currentInput));
};
act(() => render({}));
const scrollContainer = host.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
@@ -104,7 +156,10 @@ function mountTimeline(
};
return {
render: (segments: Partial<StreamRenderInput["segments"]>) => act(() => render(segments)),
render: (
segments: Partial<StreamRenderInput["segments"]>,
overrides?: Partial<Omit<StreamRenderInput, "segments">>,
) => act(() => render(segments, overrides)),
hold: (rowId: string, apply: () => void, triggerEdge: DisclosureTriggerEdge = "top") =>
act(() => viewportRef.current!.holdRow(rowId, apply, triggerEdge)),
rowTop: (id: string) =>
@@ -129,9 +184,9 @@ function mountTimeline(
scrollContainer.dispatchEvent(new Event("scroll"));
}),
// Resize observers and the hold's settle run on animation frames.
settle: () =>
settle: (frames = 4) =>
act(async () => {
for (let frame = 0; frame < 4; frame += 1) {
for (let frame = 0; frame < frames; frame += 1) {
await new Promise((resolve) => requestAnimationFrame(resolve));
}
}),
@@ -310,3 +365,148 @@ describe("web history start", () => {
expect(olderHistoryLoads).toBe(1);
});
});
describe("web virtualizer reconcile stability", () => {
it("settles without nested update loops when virtualized rows grow far past estimates above a mounted anchor", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(500 + index));
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
await timeline.settle();
timeline.scrollUp(200);
await timeline.settle();
const readingTop = timeline.rowTop("message-500");
const virtualized = Array.from({ length: 500 }, (_, index) => thoughtRow(index, 800));
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
await timeline.settle();
expect(timeline.rowTop("message-500")).toBe(readingTop);
expect(timeline.rowBottom("thought-499")).toBe(readingTop);
});
it("does not overflow React update depth via reconcileReadingPosition when growing virtualized rows reach the start on desktop", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(400 + index));
const timeline = mountTimeline(mounted, {
viewportHeight: 200,
isMobileBreakpoint: false,
});
await timeline.settle();
timeline.scrollUp(200);
await timeline.settle();
const readingTop = timeline.rowTop("message-400");
const virtualized = Array.from({ length: 170 }, (_, index) => thoughtRow(index, 800));
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
await timeline.settle();
expect(timeline.rowTop("message-400")).toBe(readingTop);
expect(timeline.rowBottom("thought-169")).toBe(readingTop);
});
it("does not runaway-loop when unmeasured virtualized rows shrink near the bottom of a long chat", async () => {
const virtualized = Array.from({ length: 2000 }, (_, index) => assistantRow(index, 20));
const mounted = Array.from({ length: 10 }, (_, index) => row(2000 + index, 40));
const timeline = mountTimeline(mounted, {
historyVirtualized: virtualized,
viewportHeight: 600,
});
await timeline.settle(10);
timeline.scrollUp(120);
await timeline.settle(10);
const readingTop = timeline.rowTop("message-2000");
timeline.render({}, { contentMaxWidth: 360 });
await timeline.settle(10);
expect(timeline.rowTop("message-2000")).toBe(readingTop);
expect(timeline.rowBottom("assistant-1999")).toBe(readingTop);
expect(timeline.rowTop("assistant-1990")).toBe(readingTop - 200);
});
it("keeps a mounted anchor near the bottom when prepended virtualized rows shrink below estimate", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(40 + index, 40));
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
await timeline.settle();
timeline.scrollUp(60);
await timeline.settle();
const readingTop = timeline.rowTop("message-44");
const virtualized = Array.from({ length: 40 }, (_, index) => assistantRow(index, 40));
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
await timeline.settle();
expect(timeline.rowTop("message-44")).toBe(readingTop);
expect(timeline.rowBottom("assistant-39")).toBe(timeline.rowTop("message-40"));
});
it("settles across frames without hitting React update depth limits for hundreds of tiny virtualized rows", async () => {
const mounted = Array.from({ length: 4 }, (_, index) => row(800 + index, 40));
const virtualized = Array.from({ length: 800 }, (_, index) => assistantRow(index, 2));
const timeline = mountTimeline(mounted, {
historyVirtualized: virtualized,
viewportHeight: 1200,
});
await timeline.settle(16);
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
const readingTop = timeline.rowTop("message-800");
timeline.hold("message-800", () => timeline.render({}, { contentMaxWidth: 360 }));
await timeline.settle(16);
expect(timeline.rowTop("message-800")).toBe(readingTop);
expect(timeline.rowBottom("assistant-799")).toBe(readingTop);
expect(timeline.rowTop("assistant-700")).toBe(readingTop - 200);
});
it("resumes following when a layout commit precedes the scroll event at the bottom", async () => {
const mounted = Array.from({ length: 10 }, (_, index) => row(index, 40));
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
await timeline.settle();
timeline.scrollUp(120);
await timeline.settle();
timeline.scrollTo(1000);
timeline.render({ historyMounted: [...mounted] });
await timeline.settle();
timeline.render({ liveHead: [row(10, 40)] });
await timeline.settle();
expect(timeline.distanceFromEnd()).toBe(0);
});
it("mounts the top of a newly virtualized block when all history fits in the viewport", async () => {
const timeline = mountTimeline([row(99, 40)], {
viewportHeight: 1200,
isMobileBreakpoint: false,
});
await timeline.settle();
timeline.render({
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
});
await timeline.settle();
expect(timeline.scrollTop()).toBe(0);
expect(timeline.rowTop("thought-0")).toBe(48);
expect(timeline.rowTop("message-99")).toBe(48 + 24 * 40);
});
it("mounts the top of a newly virtualized block when a mounted row shrinks in the same commit", async () => {
const timeline = mountTimeline([row(99, 1100)], {
viewportHeight: 1200,
isMobileBreakpoint: false,
});
await timeline.settle();
expect(timeline.scrollTop()).toBe(0);
timeline.render({
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
historyMounted: [row(99, 40)],
});
await timeline.settle();
expect(timeline.scrollTop()).toBe(0);
expect(timeline.rowTop("message-99")).toBe(1008);
expect(timeline.rowTop("thought-0")).toBe(48);
});
});
+344 -34
View File
@@ -57,8 +57,10 @@ const AUTO_SCROLL_RESUME_THRESHOLD_PX = 1;
const HISTORY_START_SETTLE_FRAMES = 2;
const HISTORY_START_SLOT_HEIGHT_PX = 32;
const CONTENT_PADDING_TOP_PX = 16;
const CONTENT_PADDING_BOTTOM_PX = 16;
const UPWARD_INPUT_EVIDENCE_TIMEOUT_MS = 100;
const VIRTUALIZER_SCROLL_MARGIN_PX = HISTORY_START_SLOT_HEIGHT_PX + CONTENT_PADDING_TOP_PX;
const MAX_SYNC_LAYOUT_PASSES = 16;
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedColorMapping = (theme: Theme) => ({
@@ -118,6 +120,127 @@ function isScrollContainerMeasurable(
return scrollContainer.clientHeight > 0 && scrollContainer.scrollHeight > 0;
}
function getUnclampedScrollTop(
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
lastKnownScrollTop: number,
): number {
if (!isScrollContainerMeasurable(scrollContainer)) {
return scrollContainer.scrollTop;
}
const maxScrollTop = Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight);
const isBrowserClamped =
maxScrollTop < lastKnownScrollTop - 0.5 &&
Math.abs(scrollContainer.scrollTop - maxScrollTop) <= 1;
return isBrowserClamped ? lastKnownScrollTop : scrollContainer.scrollTop;
}
interface MountedRowOffset {
topWithoutVirtual: number;
height: number;
mountedIndex: number;
}
interface MountedRowSnapshot {
firstRowId: string | null;
offsets: Map<string, MountedRowOffset>;
}
function findNonVirtualizedRowIndex(
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">,
rowId: string,
): number {
const mountedIndex = segments.historyMounted.findIndex((row) => row.id === rowId);
if (mountedIndex >= 0) {
return mountedIndex;
}
const liveHeadIndex = segments.liveHead.findIndex((row) => row.id === rowId);
return liveHeadIndex >= 0 ? segments.historyMounted.length + liveHeadIndex : -1;
}
interface CommittedLayoutMetrics {
hasCommittedFlowHeight: boolean;
virtualSpacerHeight: number;
nonVirtualFlowHeight: number;
nonVirtualRowCount: number;
}
interface ProjectRangeOffsetInput {
container: HTMLElement;
virtualizer: Virtualizer<HTMLElement, Element>;
followOutput: boolean;
isJumpSettling: boolean;
lastClampedBaselineScrollTop: number;
committedLayoutMetrics: CommittedLayoutMetrics;
anchorId: string | null;
anchorIndex: number;
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">;
mountedSnapshot: MountedRowSnapshot;
readingAnchor: ReturnType<typeof createReadingAnchor>;
readingRowReplacements: StreamRenderInput["readingRowReplacements"];
}
function projectRangeOffset(input: ProjectRangeOffsetInput): number {
const { container, virtualizer } = input;
if (input.isJumpSettling) {
return container.scrollTop;
}
const baseScrollTop = getUnclampedScrollTop(container, input.lastClampedBaselineScrollTop);
if (input.followOutput && isScrollContainerMeasurable(container)) {
const { committedLayoutMetrics } = input;
const currentNonVirtualRowCount =
input.segments.historyMounted.length + input.segments.liveHead.length;
if (
!committedLayoutMetrics.hasCommittedFlowHeight ||
currentNonVirtualRowCount < committedLayoutMetrics.nonVirtualRowCount
) {
return baseScrollTop;
}
const projectedFlowHeight =
committedLayoutMetrics.nonVirtualFlowHeight + virtualizer.getTotalSize();
return Math.max(0, projectedFlowHeight - container.clientHeight);
}
if (input.anchorIndex >= 0) {
const measurement = virtualizer.measurementsCache[input.anchorIndex];
if (!measurement) {
return baseScrollTop;
}
return input.readingAnchor.project(
baseScrollTop,
{
id: String(measurement.key),
top: measurement.start,
height: measurement.size,
},
input.readingRowReplacements,
);
}
if (!input.anchorId) {
return baseScrollTop;
}
const mountedAnchor = input.mountedSnapshot.offsets.get(input.anchorId);
if (!mountedAnchor) {
return baseScrollTop;
}
const currentMountedIndex = findNonVirtualizedRowIndex(input.segments, input.anchorId);
const currentFirstMountedId =
input.segments.historyMounted[0]?.id ?? input.segments.liveHead[0]?.id ?? null;
if (
currentMountedIndex !== mountedAnchor.mountedIndex ||
currentFirstMountedId !== input.mountedSnapshot.firstRowId
) {
return baseScrollTop;
}
return input.readingAnchor.project(
baseScrollTop,
{
id: input.anchorId,
top: mountedAnchor.topWithoutVirtual + virtualizer.getTotalSize(),
height: mountedAnchor.height,
},
input.readingRowReplacements,
);
}
function isEditableEventTarget(target: EventTarget | null): boolean {
if (!(target instanceof Element)) {
return false;
@@ -330,6 +453,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const isActive = useRetainedPanelActive();
const { t } = useTranslation();
const rowsHostRef = useRef<HTMLDivElement | null>(null);
const virtualSpacerRef = useRef<HTMLDivElement | null>(null);
const auxiliaryRef = useRef<HTMLDivElement | null>(null);
const isActiveRef = useRef(isActive);
const scrollContainerRef = useRef<HTMLElement | null>(null);
@@ -341,6 +465,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
contentRef.current = node;
}, []);
const [followOutput, setFollowOutputr] = useState(true);
const [rangeProjectionEpoch, setRangeProjectionEpoch] = useState(0);
const followOutputRef = useRef(followOutput);
const setFollowOutput = (value: boolean) => {
followOutputRef.current = value;
@@ -348,6 +473,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
return value;
};
const lastKnownScrollTopRef = useRef(0);
const lastClampedBaselineScrollTopRef = useRef(0);
const segmentsRef = useRef(segments);
segmentsRef.current = segments;
const isJumpSettlingRef = useRef<() => boolean>(() => false);
const mouseScrollGestureRef = useRef<
| { kind: "scrollbar"; pointerId: number }
| {
@@ -363,9 +492,23 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const lastTouchClientYRef = useRef<number | null>(null);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const pendingAutoScrollTimeoutRef = useRef<number | null>(null);
const deferredLayoutFrameRef = useRef<number | null>(null);
const lastProjectedRangeOffsetRef = useRef<number | null>(null);
const syncLayoutPassesRef = useRef(0);
const syncLayoutResetScheduledRef = useRef(false);
const historyStartReadyRef = useRef(false);
const readingAnchor = useMemo(createReadingAnchor, []);
const measuredRowHeights = useRef(new Map<string, { width: number; height: number }>());
const mountedRowSnapshotRef = useRef<MountedRowSnapshot>({
firstRowId: null,
offsets: new Map(),
});
const committedLayoutMetricsRef = useRef<CommittedLayoutMetrics>({
hasCommittedFlowHeight: false,
virtualSpacerHeight: 0,
nonVirtualFlowHeight: 0,
nonVirtualRowCount: 0,
});
const historyStartSettleSchedulerRef = useRef<HistoryStartSettleScheduler | null>(null);
const lastActiveFollowOutputLayoutRef = useRef<ActiveFollowOutputLayout | null>(null);
const lastObservedViewportGeometryRef = useRef<ObservedViewportGeometry | null>(null);
@@ -404,38 +547,50 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const rowVirtualizerRef = useRef<Virtualizer<HTMLElement, Element> | null>(null);
const rangeExtractor = useCallback(
(range: VirtualRange): number[] => {
const anchorIndex = segments.historyVirtualized.findIndex(
(row) => row.id === readingAnchor.getRowId(props.readingRowReplacements),
);
// Busts TanStack's getVirtualIndexes memo when a post-commit check detects a stale projection.
void rangeProjectionEpoch;
const anchorId = readingAnchor.getRowId(props.readingRowReplacements);
const anchorIndex = anchorId
? segments.historyVirtualized.findIndex((row) => row.id === anchorId)
: -1;
const container = scrollContainerRef.current;
// TanStack has computed the new measurements before calling the extractor.
// Select against the pending anchor correction, before mounting any rows at
// the stale pre-prepend offset. The DOM correction still belongs to commit.
const virtualizer = rowVirtualizerRef.current!;
const measurement = virtualizer.measurementsCache[anchorIndex];
const correctedOffset =
container && measurement
? readingAnchor.project(
container.scrollTop,
{
id: String(measurement.key),
top: measurement.start,
height: measurement.size,
},
props.readingRowReplacements,
)
: container?.scrollTop;
const virtualizerOffset = virtualizer.scrollOffset ?? 0;
const correctedOffset = container
? projectRangeOffset({
container,
virtualizer,
followOutput: followOutputRef.current,
isJumpSettling: isJumpSettlingRef.current(),
lastClampedBaselineScrollTop: lastClampedBaselineScrollTopRef.current,
committedLayoutMetrics: committedLayoutMetricsRef.current,
anchorId,
anchorIndex,
segments: segmentsRef.current,
mountedSnapshot: mountedRowSnapshotRef.current,
readingAnchor,
readingRowReplacements: props.readingRowReplacements,
})
: undefined;
let visibleRange = range;
let projectedRangeOffset: number | null = null;
if (
container &&
correctedOffset !== undefined &&
Math.abs(correctedOffset - container.scrollTop) > 0.5
Math.abs(correctedOffset - virtualizerOffset) > 0.5
) {
const first = virtualizer.getVirtualItemForOffset(correctedOffset);
const last = virtualizer.getVirtualItemForOffset(correctedOffset + container.clientHeight);
if (first && last)
const projectedOffset = Math.max(0, correctedOffset);
const first = virtualizer.getVirtualItemForOffset(projectedOffset);
const last = virtualizer.getVirtualItemForOffset(projectedOffset + container.clientHeight);
if (first && last) {
visibleRange = { ...range, startIndex: first.index, endIndex: last.index };
projectedRangeOffset = projectedOffset;
}
}
lastProjectedRangeOffsetRef.current = projectedRangeOffset;
return [
...new Set([
...defaultRangeExtractor(visibleRange),
@@ -444,7 +599,13 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
]),
].sort((left, right) => left - right);
},
[chatFindRowIndexes, readingAnchor, segments.historyVirtualized, props.readingRowReplacements],
[
chatFindRowIndexes,
rangeProjectionEpoch,
readingAnchor,
segments.historyVirtualized,
props.readingRowReplacements,
],
);
const virtualOffsetListener = useRef<((offset: number, scrolling: boolean) => void) | null>(null);
const observeVirtualOffset = useCallback<typeof observeElementOffset>((instance, onOffset) => {
@@ -563,8 +724,10 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
"[data-history-row-id][data-index]",
) ?? []) {
const index = Number(element.dataset.index);
const measurement = rowVirtualizer.measurementsCache[index];
if (!measurement) continue;
const height = measureVirtualElement(element, undefined, rowVirtualizer);
if (rowVirtualizer.measurementsCache[index]?.size === height) continue;
if (measurement.size === height) continue;
rowVirtualizer.resizeItem(index, height);
resized = true;
}
@@ -593,6 +756,22 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
);
useEffect(() => () => virtualRowObserver.disconnect(), [virtualRowObserver]);
const cancelDeferredLayoutPass = useCallback(() => {
const pendingFrame = deferredLayoutFrameRef.current;
if (pendingFrame !== null) {
deferredLayoutFrameRef.current = null;
window.cancelAnimationFrame(pendingFrame);
}
}, []);
useEffect(
() => () => {
cancelDeferredLayoutPass();
syncLayoutPassesRef.current = 0;
},
[cancelDeferredLayoutPass],
);
const cancelPendingStickToBottom = useCallback(() => {
const pendingFrame = pendingAutoScrollFrameRef.current;
if (pendingFrame !== null) {
@@ -638,11 +817,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
return;
}
cancelPendingStickToBottom();
cancelDeferredLayoutPass();
lastProjectedRangeOffsetRef.current = null;
syncLayoutPassesRef.current = 0;
historyStartSettleSchedulerRef.current?.cancel();
clearMouseScrollGesture();
clearUpwardInputEvidence();
lastTouchClientYRef.current = null;
}, [cancelPendingStickToBottom, clearMouseScrollGesture, clearUpwardInputEvidence, isActive]);
}, [
cancelDeferredLayoutPass,
cancelPendingStickToBottom,
clearMouseScrollGesture,
clearUpwardInputEvidence,
isActive,
]);
const scrollMessagesToBottom = useCallback(
(behavior: ScrollBehaviorLike = "auto") => {
@@ -659,6 +847,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
}
scrollElementToBottom(scrollContainer, behavior);
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
lastClampedBaselineScrollTopRef.current = scrollContainer.scrollTop;
syncNearBottom(scrollContainer, onNearBottomChange);
evaluateHistoryStart();
},
@@ -731,6 +920,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
setFollowOutput,
onNearBottomChange,
});
isJumpSettlingRef.current = isJumpSettling;
// Row tops in content coordinates, which survive scrolling.
const measureRows = useStableEvent(() => {
@@ -740,14 +930,89 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
const viewportTop = container.getBoundingClientRect().top;
const scrollTop = container.scrollTop;
const width = readContentWidth() ?? 0;
return Array.from(content.querySelectorAll<HTMLElement>("[data-history-row-id]"), (element) => {
const bounds = element.getBoundingClientRect();
const id = element.dataset.historyRowId!;
measuredRowHeights.current.set(id, { width, height: bounds.height });
return { id, top: bounds.top - viewportTop + scrollTop, height: bounds.height };
const virtualSpacerHeight = virtualSpacerRef.current?.getBoundingClientRect().height ?? 0;
const rowsHostHeight = rowsHostRef.current?.getBoundingClientRect().height ?? 0;
const auxiliaryHeight = auxiliaryRef.current?.getBoundingClientRect().height ?? 0;
const shouldTrackMountedOffsets = !followOutputRef.current;
const mountedOffsets = mountedRowSnapshotRef.current.offsets;
mountedOffsets.clear();
let firstRowId: string | null = null;
let mountedIndex = 0;
const rows = Array.from(
content.querySelectorAll<HTMLElement>("[data-history-row-id]"),
(element) => {
const bounds = element.getBoundingClientRect();
const id = element.dataset.historyRowId!;
const top = bounds.top - viewportTop + scrollTop;
measuredRowHeights.current.set(id, { width, height: bounds.height });
if (!element.hasAttribute("data-index")) {
if (shouldTrackMountedOffsets) {
if (firstRowId === null) {
firstRowId = id;
}
mountedOffsets.set(id, {
topWithoutVirtual: top - virtualSpacerHeight,
height: bounds.height,
mountedIndex,
});
}
mountedIndex += 1;
}
return { id, top, height: bounds.height };
},
);
mountedRowSnapshotRef.current.firstRowId = firstRowId;
committedLayoutMetricsRef.current = {
hasCommittedFlowHeight: true,
virtualSpacerHeight,
nonVirtualFlowHeight:
VIRTUALIZER_SCROLL_MARGIN_PX +
Math.max(0, rowsHostHeight - virtualSpacerHeight) +
auxiliaryHeight +
CONTENT_PADDING_BOTTOM_PX,
nonVirtualRowCount: mountedIndex,
};
return rows;
});
const scheduleDeferredLayoutPass = useStableEvent(() => {
if (deferredLayoutFrameRef.current !== null || !isActiveRef.current) {
return;
}
deferredLayoutFrameRef.current = window.requestAnimationFrame(() => {
deferredLayoutFrameRef.current = null;
syncLayoutPassesRef.current = 0;
if (!isActiveRef.current) {
return;
}
if (measureVirtualizedRows()) {
return;
}
reconcileReadingPosition();
if (followOutputRef.current && scrollContainerRef.current) {
reconcileProjectedRange(scrollContainerRef.current);
}
});
});
const reconcileProjectedRange = useStableEvent((container: HTMLElement): boolean => {
const projectedOffset = lastProjectedRangeOffsetRef.current;
if (projectedOffset === null) {
return false;
}
if (Math.abs(container.scrollTop - projectedOffset) <= 0.5) {
lastProjectedRangeOffsetRef.current = null;
return false;
}
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
scheduleDeferredLayoutPass();
return true;
}
lastProjectedRangeOffsetRef.current = null;
setRangeProjectionEpoch((value) => value + 1);
return true;
});
const reconcileReadingPosition = useStableEvent(() => {
const container = scrollContainerRef.current;
if (!isActiveRef.current || !container) return;
@@ -755,8 +1020,11 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
if (!rows) return;
const shouldAnchor = !followOutputRef.current && !isJumpSettling();
if (!shouldAnchor) readingAnchor.reset();
const anchorScrollTop = shouldAnchor
? getUnclampedScrollTop(container, lastClampedBaselineScrollTopRef.current)
: container.scrollTop;
const correctedTop = readingAnchor.reconcile(
container.scrollTop,
anchorScrollTop,
rows,
false,
props.readingRowReplacements,
@@ -768,9 +1036,20 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
if (Math.abs(correctedTop - container.scrollTop) > 0.5) {
container.scrollTop = correctedTop;
lastKnownScrollTopRef.current = container.scrollTop;
}
lastClampedBaselineScrollTopRef.current = container.scrollTop;
const virtualizerOffset = rowVirtualizer.scrollOffset ?? 0;
if (virtualOffsetListener.current && Math.abs(container.scrollTop - virtualizerOffset) > 0.5) {
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
scheduleDeferredLayoutPass();
return;
}
// The DOM scroll event arrives later. Fill the corrected virtual range in
// this layout so the reader does not get a frame containing only the pin.
virtualOffsetListener.current?.(container.scrollTop, false);
virtualOffsetListener.current(container.scrollTop, false);
}
if (reconcileProjectedRange(container)) {
return;
}
// A disclosure that closes back to the end of the list rejoins the output.
if (disclosurePendingRef.current) {
@@ -782,17 +1061,38 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
// Apply row positions and their scroll correction in the same paint, including
// the ordinary-to-virtualized handoff and measurements of newly mounted rows.
useLayoutEffect(() => {
if (!isActive) {
cancelDeferredLayoutPass();
lastProjectedRangeOffsetRef.current = null;
syncLayoutPassesRef.current = 0;
return;
}
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
scheduleDeferredLayoutPass();
return;
}
syncLayoutPassesRef.current += 1;
if (!syncLayoutResetScheduledRef.current) {
syncLayoutResetScheduledRef.current = true;
queueMicrotask(() => {
syncLayoutResetScheduledRef.current = false;
syncLayoutPassesRef.current = 0;
});
}
// Commit positions for every resized row before accepting reading geometry.
// Child layout can change during this commit, ahead of ResizeObserver delivery.
if (!isActive || measureVirtualizedRows()) return;
if (measureVirtualizedRows()) return;
cancelDeferredLayoutPass();
reconcileReadingPosition();
}, [
cancelDeferredLayoutPass,
contentWidth,
isActive,
segments,
virtualRows,
measureVirtualizedRows,
reconcileReadingPosition,
scheduleDeferredLayoutPass,
]);
const stopFollowingOutputFromUserIntent = useStableEvent(() => {
@@ -832,6 +1132,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
}
lastKnownScrollTopRef.current = currentScrollTop;
lastClampedBaselineScrollTopRef.current = currentScrollTop;
if (!followOutputRef.current && !isJumpSettling() && (scrolledUp || scrolledDown)) {
readingAnchor.scroll(currentScrollTop);
}
@@ -925,11 +1226,15 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
if (!followOutputRef.current || resumedUnchangedLayout) return;
cancelPendingStickToBottom();
scrollMessagesToBottom("auto");
if (scrollContainerRef.current) {
reconcileProjectedRange(scrollContainerRef.current);
}
}, [
activationKey,
cancelPendingStickToBottom,
isActive,
isActivationReady,
reconcileProjectedRange,
renderLiveAuxiliary,
scrollMessagesToBottom,
segments.historyMounted,
@@ -997,7 +1302,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
} else {
lastObservedViewportGeometryRef.current = nextGeometry;
}
reconcileReadingPosition();
if (deferredLayoutFrameRef.current === null) {
reconcileReadingPosition();
}
if (isHistoryStartSettling()) {
scheduleHistoryStartPrependSettle();
}
@@ -1208,6 +1515,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
setFollowOutput(false);
const row = measureRows()?.find((candidate) => candidate.id === rowId);
const scrollTop = scrollContainerRef.current?.scrollTop;
if (scrollTop !== undefined) {
lastClampedBaselineScrollTopRef.current = scrollTop;
}
if (row && scrollTop !== undefined) readingAnchor.pin(row, triggerEdge, scrollTop);
disclosurePendingRef.current = true;
apply();
@@ -1243,7 +1553,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
flexDirection: "column",
minHeight: "100%",
paddingTop: CONTENT_PADDING_TOP_PX,
paddingBottom: 16,
paddingBottom: CONTENT_PADDING_BOTTOM_PX,
paddingLeft,
paddingRight,
boxSizing: "border-box",
@@ -1375,7 +1685,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
<div ref={handleContentRef} style={contentContainerStyle}>
{historyStartSlot}
<div ref={rowsHostRef} style={streamRowsHostStyle}>
<div style={virtualRowsContainerStyle} />
<div ref={virtualSpacerRef} style={virtualRowsContainerStyle} />
{[
...virtualRows.map((virtualRow) => {
const item = segments.historyVirtualized[virtualRow.index];
@@ -12,6 +12,7 @@ import {
TEXT_REVEAL_FRAME_INTERVAL_MS,
TEXT_REVEAL_HORIZON_MS,
visibleRevealedText,
withholdPartialClosingFence,
} from "./text-reveal";
describe("computeRevealStep", () => {
@@ -275,3 +276,127 @@ describe("trailing fragments from arrival boundaries", () => {
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
});
});
describe("a closing fence still being typed", () => {
const code = "Intro\n\n```ts\nconst a = 1;\n";
it("holds back one or two backticks that can only become the closing fence", () => {
expect(withholdPartialClosingFence(`${code}\``)).toBe(code);
expect(withholdPartialClosingFence(`${code}\`\``)).toBe(code);
expect(withholdPartialClosingFence(`${code} \`\``)).toBe(code);
});
it.each([
{ char: "`", length: 3, whitespace: " " },
{ char: "`", length: 3, whitespace: "\t" },
{ char: "`", length: 4, whitespace: " " },
{ char: "`", length: 4, whitespace: "\t" },
{ char: "~", length: 3, whitespace: " " },
{ char: "~", length: 3, whitespace: "\t" },
{ char: "~", length: 5, whitespace: " " },
{ char: "~", length: 5, whitespace: "\t" },
])(
"paints real code after whitespace ends a $length $char run ($whitespace)",
({ char, length, whitespace }) => {
const prefix = `${char.repeat(length)}\ncode\n`;
const run = char.repeat(length - 1);
expect(withholdPartialClosingFence(prefix + run)).toBe(prefix);
const text = prefix + run + whitespace;
expect(withholdPartialClosingFence(text)).toBe(text);
expect(visibleRevealedText(beginTextReveal(text), { streaming: true })).toBe(text);
},
);
it("paints the fence once it closes the block", () => {
expect(withholdPartialClosingFence(`${code}\`\`\``)).toBe(`${code}\`\`\``);
expect(withholdPartialClosingFence(`${code}\`\`\`\n\nAfter`)).toBe(`${code}\`\`\`\n\nAfter`);
});
it("needs a run as long as the opener and of the same character", () => {
const long = "````md\nInside\n";
expect(withholdPartialClosingFence(`${long}\`\`\``)).toBe(long);
expect(withholdPartialClosingFence(`${long}\`\`\`\``)).toBe(`${long}\`\`\`\``);
const tilde = "~~~\ncode\n";
expect(withholdPartialClosingFence(`${tilde}~~`)).toBe(tilde);
expect(withholdPartialClosingFence(`${tilde}\``)).toBe(`${tilde}\``);
});
it.each([
{ lineEnding: "LF", newline: "\n", closer: "```" },
{ lineEnding: "CRLF", newline: "\r\n", closer: "```" },
{ lineEnding: "LF", newline: "\n", closer: "``` \t" },
{ lineEnding: "CRLF", newline: "\r\n", closer: "``` \t" },
])(
"recognizes completed closers before a tilde block with $lineEnding ($closer)",
({ newline, closer }) => {
const backtickBlock = ["Intro", "```ts", "const a = 1;", closer, ""].join(newline);
const tildeBlock = backtickBlock + ["~~~md", "code", ""].join(newline);
expect(withholdPartialClosingFence(tildeBlock + "~~")).toBe(tildeBlock);
expect(withholdPartialClosingFence(tildeBlock + "~~~")).toBe(tildeBlock + "~~~");
expect(withholdPartialClosingFence(tildeBlock + "~~ not a closer")).toBe(
tildeBlock + "~~ not a closer",
);
const closedTildeBlock = tildeBlock + "~~~" + newline;
expect(withholdPartialClosingFence(closedTildeBlock + "`")).toBe(closedTildeBlock + "`");
},
);
it.each([
{ marker: "-", fence: "```", newline: "\n" },
{ marker: "1.", fence: "~~~", newline: "\n" },
{ marker: "-", fence: "~~~", newline: "\r\n" },
{ marker: "1.", fence: "```", newline: "\r\n" },
])(
"keeps prose after a closed $marker list fence ($fence, $newline)",
({ marker, fence, newline }) => {
const indent = " ".repeat(marker.length + 1);
const closed = [`${marker} ${fence}`, `${indent}code`, `${indent}${fence}`, "", ""].join(
newline,
);
const prose = closed + fence[0];
expect(withholdPartialClosingFence(prose)).toBe(prose);
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
const open = [`${marker} ${fence}`, `${indent}code`, ""].join(newline);
expect(withholdPartialClosingFence(open + indent + fence[0])).toBe(open);
},
);
it("does not take an indented code block's fence for a top-level opener", () => {
const text = " code\n ```\n\n`";
expect(withholdPartialClosingFence(text)).toBe(text);
});
it("leaves backticks alone outside a code block", () => {
expect(withholdPartialClosingFence("Prose\n`")).toBe("Prose\n`");
const closed = "```\na\n```\n";
expect(withholdPartialClosingFence(`${closed}\``)).toBe(`${closed}\``);
expect(withholdPartialClosingFence("`` inline ``\n`")).toBe("`` inline ``\n`");
});
it("leaves a code line that only starts with backticks alone", () => {
expect(withholdPartialClosingFence(`${code}\`x`)).toBe(`${code}\`x`);
});
it("never paints a lone backtick line while a paced reveal crosses the closing fence", () => {
const full = `${code}\`\`\`\n\nAfter the block.`;
let state = retargetTextReveal(beginTextReveal(code), full);
const painted: string[] = [];
for (let frame = 0; frame < 120 && !isTextRevealSettled(state); frame += 1) {
state = advanceTextReveal(state, 16, 1_000);
painted.push(visibleRevealedText(state, { streaming: true }));
}
expect(painted.at(-1)).toBe(full);
for (const text of painted) {
expect(full.startsWith(text)).toBe(true);
expect(text.endsWith("\n`") || text.endsWith("\n``")).toBe(false);
}
});
it("holds the fence back when an arrival ends inside it, and paints it once the turn ends", () => {
const state = beginTextReveal(`${code}\``);
expect(visibleRevealedText(state, { streaming: true })).toBe(code);
expect(visibleRevealedText(state, { streaming: false })).toBe(`${code}\``);
});
});
+44 -2
View File
@@ -1,3 +1,5 @@
import { createMarkdownParser } from "@/utils/markdown-parser";
/**
* Paced reveal for streaming assistant text.
*
@@ -207,6 +209,41 @@ function trimIncompleteTrailingCluster(text: string): string {
return text;
}
// Only parse block context when the current line can still become a closer.
const UNFINISHED_FENCE_RUN = /^ {0,3}(`+|~+)$/;
const fenceParser = createMarkdownParser({ linkify: false }).disable("inline");
/**
* Hold back the closing fence of a code block while it is still being typed.
*
* Inside an open fence, a last line holding one or two backticks is code until
* the third one arrives and closes the block. Painted, it adds a line of code
* that vanishes a frame later, so the block grows and shrinks and every row
* below it shifts twice. A paced reveal hands out these prefixes one character
* at a time, and an arrival boundary can end on one too. The line waits until it
* either closes the block or turns out to be code.
*/
export function withholdPartialClosingFence(text: string): string {
const lineStart = text.lastIndexOf("\n") + 1;
if (lineStart === 0) return text;
const run = UNFINISHED_FENCE_RUN.exec(text.slice(lineStart))?.[1];
if (!run) return text;
// Source maps include container boundaries: a list closer must not become a
// new top-level opener, and a fence-looking line in indented code is not one.
const lastLine = text.split("\n").length - 1;
const open = fenceParser
.parse(text, {})
.findLast(
(token) =>
token.type === "fence" &&
token.map !== null &&
token.map[0] < lastLine &&
token.map[1] === lastLine + 1,
);
if (!open || open.markup[0] !== run[0] || run.length >= open.markup.length) return text;
return text.slice(0, lineStart);
}
/** Number of regional indicators at the end of `text`. A flag is a pair. */
function countTrailingRegionalIndicators(text: string): number {
let count = 0;
@@ -234,7 +271,12 @@ export function visibleRevealedText(
options?: { streaming?: boolean },
): string {
if (state.revealed >= state.target.length) {
return options?.streaming ? trimIncompleteTrailingCluster(state.target) : state.target;
return options?.streaming
? withholdPartialClosingFence(trimIncompleteTrailingCluster(state.target))
: state.target;
}
return state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed));
// More text is already here, so a partial fence at the cut is certainly unfinished.
return withholdPartialClosingFence(
state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed)),
);
}
@@ -162,11 +162,12 @@ describe("collapseTurns", () => {
create.payload.data.detail = { type: "unknown", input: { title: "Side fix" }, output: null };
const finished = shell("finished");
if (finished.payload.source !== "agent") throw new Error("Expected agent tool");
finished.payload.data.name = "agent_notification";
finished.payload.data.agentMessage = {
event: "finished",
sender: { id: "worker", title: "PR helper" },
finished.payload.data.name = "agent_finished";
finished.payload.data.detail = {
type: "plain_text",
label: "PR helper",
text: "Finished",
icon: "bot",
};
const items: StreamItem[] = [
user("u1"),
@@ -77,11 +77,8 @@ describe("canonical turn membership", () => {
delete trigger.turnId;
expect(continuesTurn(previous, trigger)).toBe(false);
trigger.payload.data.name = "agent_message";
trigger.payload.data.agentMessage = {
event: "finished",
sender: { id: "worker" },
text: "Done",
};
expect(continuesTurn(previous, trigger)).toBe(false);
trigger.payload.data.name = "agent_finished";
expect(continuesTurn(previous, trigger)).toBe(false);
});
+10 -2
View File
@@ -744,6 +744,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
<AssistantFileLinkResolverProvider
client={client}
serverId={resolvedServerId}
workspaceId={context.workspaceId}
workspaceRoot={workspaceRoot}
onOpenWorkspaceFile={handleInlinePathPress}
toast={toast}
@@ -766,7 +767,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
</AssistantFileLinkResolverProvider>
);
},
[agentId, client, handleInlinePathPress, resolvedServerId, toast, workspaceRoot],
[
agentId,
client,
context.workspaceId,
handleInlinePathPress,
resolvedServerId,
toast,
workspaceRoot,
],
);
const renderThoughtItem = useCallback(
@@ -818,7 +827,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
cwd={context.cwd}
serverId={resolvedServerId}
metadata={data.metadata}
agentMessage={data.agentMessage}
isLastInSequence={isLastInSequence}
onOpenFilePath={handleToolCallOpenFile}
standalone={options.standalone}
+6 -1
View File
@@ -108,6 +108,7 @@ import { useGlobalNewWorkspaceAction } from "@/hooks/use-global-new-workspace-ac
import { useLatchedBoolean } from "@/hooks/use-latched-boolean";
import { useFaviconStatus } from "@/hooks/use-favicon-status";
import { useKeyboardShortcuts } from "@/keyboard/use-shortcuts";
import { reportNativeUserActivity } from "@/hooks/native-user-activity";
import { KeyboardShiftProvider } from "@/keyboard/shift";
import { useCompactWebViewportZoomLock } from "@/hooks/use-compact-web-viewport-zoom-lock";
import { useOpenProject } from "@/hooks/use-open-project";
@@ -1026,7 +1027,11 @@ function RootProviders({ children }: { children: ReactNode }) {
function RootAppTree() {
return (
<GestureHandlerRootView style={flexStyle}>
<GestureHandlerRootView
style={flexStyle}
onTouchStart={reportNativeUserActivity}
onTouchEnd={reportNativeUserActivity}
>
<View style={layoutStyles.surfaceFill}>
<LucideProvider strokeWidth={ICON_STROKE_WIDTH}>
<AddHostProvider>
@@ -7,6 +7,7 @@ export const ASSISTANT_FILE_EXTENSIONS: ReadonlySet<string> = new Set([
"cpp",
"cs",
"css",
"csv",
"cts",
"cxx",
"env",
@@ -10,6 +10,11 @@ export {
type AssistantFileLinkResolverProviderProps,
} from "./provider";
export type { AssistantFileLinkSource } from "./resolver";
export { useAssistantFileLinkActions, useFileLink } from "./use-file-link";
export {
useAssistantFileLinkActions,
useFileLink,
type AssistantFileLinkInspection,
type AssistantFileLinkPath,
} from "./use-file-link";
export { createInlinePathOpener } from "./path-open";
@@ -169,6 +169,15 @@ describe("classifyAssistantFileLink", () => {
});
});
it("classifies a bare CSV filename as a workspace candidate", () => {
expect(
classifyAssistantFileLink("report.csv", { workspaceRoot: "/Users/test/project" }),
).toMatchObject({
kind: "ambiguousFileCandidate",
target: { path: "/Users/test/project/report.csv" },
});
});
it("does not classify normal bare domains as file candidates", () => {
expect(
classifyAssistantFileLink("google.com", {
@@ -49,6 +49,52 @@ export async function resolveInlinePathOpen(input: PathOpenInput): Promise<PathO
return { kind: "directory", directoryPath: input.file };
}
export type InlinePathDestination =
| { kind: "file"; location: WorkspaceFileLocation }
| { kind: "directory"; path: string }
| { kind: "outsideDirectory"; path: string };
/** What a path reference points at, as opening it would find it. */
export async function resolveInlinePathDestination(input: {
target: InlinePathTarget;
workspaceRoot: string;
client: {
listDirectory(root: string, path: string): Promise<unknown>;
getDirectorySuggestions: GetDirectorySuggestions;
} | null;
resolveRelativeFiles?: boolean;
}): Promise<InlinePathDestination | null> {
const { target, workspaceRoot, client } = input;
const normalized = normalizeInlinePathTarget(target.path, workspaceRoot);
if (!normalized) return null;
const destination = await resolveInlinePathOpen({
...normalized,
lineStart: target.lineStart,
workspaceRoot,
client,
});
if (destination.kind !== "file") {
return { kind: destination.kind, path: destination.directoryPath };
}
if (!normalized.file) return null;
const resolvedTarget =
input.resolveRelativeFiles && client
? await resolveMissingNestedRelativeFile({
target,
workspaceRoot,
getDirectorySuggestions: client.getDirectorySuggestions.bind(client),
})
: target;
const resolved = normalizeInlinePathTarget(resolvedTarget.path, workspaceRoot);
if (!resolved?.file) return null;
const location = normalizeWorkspaceFileLocation({
path: resolved.file,
lineStart: resolvedTarget.lineStart,
lineEnd: resolvedTarget.lineEnd,
});
return location ? { kind: "file", location } : null;
}
export function createInlinePathOpener(input: {
workspaceRoot: string;
client: {
@@ -64,37 +110,19 @@ export function createInlinePathOpener(input: {
return {
async open(target: InlinePathTarget, disposition: OpenFileDisposition) {
const ownGeneration = ++generation;
const normalized = normalizeInlinePathTarget(target.path, input.workspaceRoot);
if (!normalized) return;
const destination = await resolveInlinePathOpen({
...normalized,
lineStart: target.lineStart,
const destination = await resolveInlinePathDestination({
target,
workspaceRoot: input.workspaceRoot,
client: input.client,
resolveRelativeFiles: input.resolveRelativeFiles,
});
if (ownGeneration !== generation) return;
if (!destination || ownGeneration !== generation) return;
if (destination.kind === "directory") {
input.openDirectory(destination.directoryPath);
input.openDirectory(destination.path);
} else if (destination.kind === "outsideDirectory") {
input.openOutsideDirectory(destination.directoryPath);
} else if (normalized.file) {
const resolvedTarget =
input.resolveRelativeFiles && input.client
? await resolveMissingNestedRelativeFile({
target,
workspaceRoot: input.workspaceRoot,
getDirectorySuggestions: input.client.getDirectorySuggestions.bind(input.client),
})
: target;
if (ownGeneration !== generation) return;
const resolved = normalizeInlinePathTarget(resolvedTarget.path, input.workspaceRoot);
if (!resolved?.file) return;
const location = normalizeWorkspaceFileLocation({
path: resolved.file,
lineStart: resolvedTarget.lineStart,
lineEnd: resolvedTarget.lineEnd,
});
if (location) input.openFile(location, disposition);
input.openOutsideDirectory(destination.path);
} else {
input.openFile(destination.location, disposition);
}
},
cancel() {
@@ -16,11 +16,15 @@ import type { AssistantFileLinkContext, GetDirectorySuggestions } from "./resolv
export interface AssistantFileLinkDaemonClient {
readFile?: import("@getpaseo/client/internal/daemon-client").DaemonClient["readFile"];
getDirectorySuggestions: GetDirectorySuggestions;
/** Without it, a link to a folder is taken for a file. */
listDirectory?: (root: string, path: string) => Promise<unknown>;
}
export interface AssistantFileLinkResolverConfig {
client?: AssistantFileLinkDaemonClient | null;
serverId?: string;
/** The workspace the Markdown belongs to, for actions that change its panes. */
workspaceId?: string;
workspaceRoot?: string;
relativePathBase?: string;
onOpenWorkspaceFile?: (target: InlinePathTarget, disposition: OpenFileDisposition) => void;
@@ -55,6 +59,7 @@ export function useAssistantFileLinkEnvironmentBridge() {
export function AssistantFileLinkResolverProvider({
client,
serverId,
workspaceId,
workspaceRoot,
relativePathBase,
onOpenWorkspaceFile,
@@ -65,6 +70,7 @@ export function AssistantFileLinkResolverProvider({
const configRef = useRef<AssistantFileLinkResolverConfig>({
client,
serverId,
workspaceId,
workspaceRoot,
relativePathBase,
onOpenWorkspaceFile,
@@ -74,6 +80,7 @@ export function AssistantFileLinkResolverProvider({
configRef.current = {
client,
serverId,
workspaceId,
workspaceRoot,
relativePathBase,
onOpenWorkspaceFile,
@@ -9,7 +9,7 @@ import type { ToastApi } from "@/components/toast-host";
import type { InlinePathTarget } from "./parse";
import { AssistantFileLinkResolverProvider } from "./provider";
import type { DirectorySuggestionResult } from "./resolver";
import { useFileLink } from "./use-file-link";
import { useAssistantFileLinkActions, useFileLink } from "./use-file-link";
import type { OpenFileDisposition } from "@/workspace/file-open";
vi.mock("@/utils/open-external-url", () => ({
@@ -68,6 +68,7 @@ interface TestClient {
matchMode: "suffix";
limit: number;
}) => Promise<DirectorySuggestionResult>;
listDirectory?: (root: string, path: string) => Promise<unknown>;
}
function createQueryClient(): QueryClient {
@@ -347,4 +348,80 @@ describe("useFileLink", () => {
});
});
describe("inspecting a link before acting on it", () => {
afterEach(() => {
cleanup();
});
/** A workspace holding `docs/notes.md` and the folder `src/utils`. */
function inspectLinks(toast?: ToastApi) {
const client: TestClient = {
getDirectorySuggestions: async ({ query }) =>
resolvedSuggestions(query === "notes.md" ? [{ path: "docs/notes.md", kind: "file" }] : []),
listDirectory: async (_root, path) => {
if (path !== "src/utils") throw new Error("not a directory");
return {};
},
};
return renderHook(() => useAssistantFileLinkActions(), {
wrapper: createWrapper({ client, openedFiles: [], toast }),
}).result.current;
}
function pathInspection(inspection: ReturnType<ReturnType<typeof inspectLinks>["inspect"]>) {
if (inspection?.kind !== "path") throw new Error("Expected a path link");
return inspection;
}
it("reports a web link by its URL", () => {
const links = inspectLinks();
expect(links.inspect({ href: "https://example.test/doc" })).toEqual({
kind: "url",
url: "https://example.test/doc",
});
});
it("finds the file a bare name refers to without opening it", async () => {
const links = inspectLinks();
const report = pathInspection(
links.inspect({ href: "notes.md", text: "notes.md", markup: "linkify" }),
);
expect(report.written.kind).toBe("file");
await expect(report.lookup()).resolves.toEqual({ path: "docs/notes.md", kind: "file" });
});
it("tells a folder from a file by asking the host", async () => {
const links = inspectLinks();
await expect(pathInspection(links.inspect({ href: "src/utils" })).lookup()).resolves.toEqual({
path: "src/utils",
kind: "directory",
});
});
it("knows a trailing slash names a folder before asking", () => {
const links = inspectLinks();
expect(pathInspection(links.inspect({ href: "src/utils/" })).written.kind).toBe("directory");
});
it("says a name was not found only when asked to", async () => {
const toast = createToast();
const missing = pathInspection(
inspectLinks(toast).inspect({ href: "gone.md", text: "gone.md", markup: "linkify" }),
);
await expect(missing.lookup()).resolves.toBeNull();
expect(toast.show).not.toHaveBeenCalled();
missing.reportNotFound();
expect(toast.show).toHaveBeenCalledWith(expect.stringContaining("gone.md"), {
variant: "error",
testID: "assistant-file-link-not-found-toast",
});
});
});
const WorkspaceSwitchContext = React.createContext<(workspaceRoot: string) => void>(() => {});
@@ -6,7 +6,8 @@ import type { OpenFileDisposition } from "@/workspace/file-open";
import { shouldRouteWorkspaceUrlToProxiedBrowser } from "@/desktop/browser/proxy";
import { openExternalUrl } from "@/utils/open-external-url";
import { formatFileLinkTooltipPath } from "./tooltip-path";
import type { InlinePathTarget } from "./parse";
import { normalizeInlinePathTarget, type InlinePathTarget } from "./parse";
import { resolveInlinePathDestination } from "./path-open";
import {
useAssistantFileLinkResolverContext,
type AssistantFileLinkResolverContextValue,
@@ -31,8 +32,28 @@ export interface AssistantFileLinkActions {
open(source: AssistantFileLinkSource, disposition: OpenFileDisposition): void;
canOpen(source: AssistantFileLinkSource): boolean;
canResolveFile(source: AssistantFileLinkSource): boolean;
/** What a link names, for offering actions on it. Null when Paseo does nothing with it. */
inspect(source: AssistantFileLinkSource): AssistantFileLinkInspection | null;
}
export interface AssistantFileLinkPath {
/** Workspace-relative inside the workspace, absolute or `~/` outside it. */
path: string;
kind: "file" | "directory";
}
export type AssistantFileLinkInspection =
| { kind: "url"; url: string }
| {
kind: "path";
/** What the link says, before the host has been asked. */
written: AssistantFileLinkPath;
/** Where it actually leads, or null when nothing matches. */
lookup(): Promise<AssistantFileLinkPath | null>;
/** Tells the user `lookup` found nothing. */
reportNotFound(): void;
};
interface AssistantFileLinkLookupKey {
query: string;
path: string;
@@ -167,7 +188,116 @@ export function useAssistantFileLinkActions(): AssistantFileLinkActions {
[context.configRef],
);
return useMemo(() => ({ open, canOpen, canResolveFile }), [open, canOpen, canResolveFile]);
const queryClient = useQueryClient();
const { t } = useTranslation();
const inspect = useStableEvent((source: AssistantFileLinkSource) =>
inspectAssistantFileLink({
source,
context,
queryClient,
formatNoFileFoundMessage: (token) => t("common.errors.noFileFound", { token }),
}),
);
return useMemo(
() => ({ open, canOpen, canResolveFile, inspect }),
[open, canOpen, canResolveFile, inspect],
);
}
function inspectAssistantFileLink(input: {
source: AssistantFileLinkSource;
context: AssistantFileLinkResolverContextValue;
queryClient: ReturnType<typeof useQueryClient>;
formatNoFileFoundMessage: (token: string) => string;
}): AssistantFileLinkInspection | null {
const { serverId, workspaceRoot, relativePathBase, client } = input.context.configRef.current;
const resolution = classifyForResolution(input.source, { workspaceRoot, relativePathBase });
if (resolution.kind === "resolved" && resolution.value.kind !== "file") {
return resolution.value.kind === "external" ? { kind: "url", url: resolution.value.url } : null;
}
const target =
resolution.kind === "needsLookup"
? resolution.target
: (resolution.value as { kind: "file"; target: InlinePathTarget }).target;
const written = normalizeInlinePathTarget(target.path, workspaceRoot);
if (!written) return null;
const lookup = async (): Promise<AssistantFileLinkPath | null> => {
try {
const found =
resolution.kind === "needsLookup"
? await fetchLookup({
resolution,
serverId,
workspaceRoot,
context: input.context,
queryClient: input.queryClient,
})
: target;
const destination = await resolveInlinePathDestination({
target: found,
workspaceRoot: workspaceRoot ?? "",
resolveRelativeFiles: true,
client: client?.listDirectory
? {
listDirectory: client.listDirectory.bind(client),
getDirectorySuggestions: input.context.getDirectorySuggestions,
}
: null,
});
if (!destination) return null;
return destination.kind === "file"
? { path: destination.location.path, kind: "file" }
: { path: destination.path, kind: "directory" };
} catch {
return null;
}
};
return {
kind: "path",
// Parsing drops a trailing slash from the path; the link as written still has it.
written: {
path: written.file ?? written.directory,
kind: written.file && !target.raw.endsWith("/") ? "file" : "directory",
},
lookup,
reportNotFound: () => {
void dispatchUnresolvedError({
error: null,
noFileFoundMessage: input.formatNoFileFoundMessage(
resolution.kind === "needsLookup" ? resolution.token : target.raw,
),
capturedServerId: serverId,
capturedWorkspaceRoot: workspaceRoot,
context: input.context,
});
},
};
}
function fetchLookup(input: {
resolution: Extract<AssistantFileLinkResolution, { kind: "needsLookup" }>;
serverId?: string;
workspaceRoot?: string;
context: AssistantFileLinkResolverContextValue;
queryClient: ReturnType<typeof useQueryClient>;
}): Promise<InlinePathTarget> {
const { resolution, serverId, workspaceRoot } = input;
return input.queryClient.fetchQuery({
queryKey: assistantFileLinkQueryKey({ serverId, workspaceRoot, resolution }),
queryFn: () =>
fetchDaemonResolution({
ambiguousQuery: resolution.ambiguousQuery,
token: resolution.token,
target: resolution.target,
workspaceRoot,
getDirectorySuggestions: input.context.getDirectorySuggestions,
}),
retry: 0,
staleTime: Infinity,
});
}
function openAssistantFileLink(input: {
@@ -194,26 +324,14 @@ function openAssistantFileLink(input: {
return;
}
const capturedQueryKey = assistantFileLinkQueryKey({
serverId: capturedConfig.serverId,
workspaceRoot: capturedConfig.workspaceRoot,
resolution: capturedResolution,
});
const run = async () => {
try {
const target = await input.queryClient.fetchQuery({
queryKey: capturedQueryKey,
queryFn: () =>
fetchDaemonResolution({
ambiguousQuery: capturedResolution.ambiguousQuery,
token: capturedResolution.token,
target: capturedResolution.target,
workspaceRoot: capturedConfig.workspaceRoot,
getDirectorySuggestions: input.context.getDirectorySuggestions,
}),
retry: 0,
staleTime: Infinity,
const target = await fetchLookup({
resolution: capturedResolution,
serverId: capturedConfig.serverId,
workspaceRoot: capturedConfig.workspaceRoot,
context: input.context,
queryClient: input.queryClient,
});
await dispatchFileTarget({
target,
@@ -12,6 +12,7 @@ export interface AttachmentFileSystem {
writeBytes(uri: string, bytes: Uint8Array): Promise<void>;
copy(input: { from: string; to: string }): Promise<void>;
readAsBase64(uri: string): Promise<string>;
readBytes(uri: string): Promise<Uint8Array>;
delete(uri: string, options: { idempotent: boolean }): Promise<void>;
listDirectory(uri: string): Promise<string[]>;
}
@@ -44,6 +45,9 @@ export function createExpoAttachmentFileSystem(): AttachmentFileSystem {
encoding: FileSystem.EncodingType.Base64,
});
},
async readBytes(uri) {
return await new File(uri).bytes();
},
async delete(uri, options) {
await FileSystem.deleteAsync(uri, options);
},
@@ -166,6 +166,10 @@ export function createLocalFileAttachmentStore(params: {
return await fileSystem.readAsBase64(attachmentUri(attachment));
},
async readBytes({ attachment }): Promise<Uint8Array> {
return await fileSystem.readBytes(attachmentUri(attachment));
},
async resolvePreviewUrl({ attachment }): Promise<string> {
return await params.resolvePreviewUrl(attachment);
},
@@ -5,6 +5,7 @@ import {
encodeAttachmentsForSend,
garbageCollectAttachments,
persistAttachmentFromBytes,
uploadImageAttachments,
} from "./service";
function createAttachment(input: Partial<AttachmentMetadata> = {}): AttachmentMetadata {
@@ -42,6 +43,9 @@ function createRecordingStore(): AttachmentStore & {
async encodeBase64({ attachment }) {
return `${attachment.id}:base64`;
},
async readBytes({ attachment }) {
return new TextEncoder().encode(`${attachment.id}:bytes`);
},
async resolvePreviewUrl({ attachment }) {
return `blob:${attachment.id}`;
},
@@ -140,4 +144,80 @@ describe("attachment service", () => {
expect(garbageCollections).toEqual([["assistant-preview"]]);
});
it("uploads image attachments sequentially via uploadFile without inlining base64", async () => {
const store = createRecordingStore();
__setAttachmentStoreForTests(store);
const events: string[] = [];
const firstGate = (() => {
let release: () => void = () => {};
const promise = new Promise<void>((resolve) => {
release = resolve;
});
return { promise, release };
})();
const client = {
uploadFile: async (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => {
events.push(`start:${input.fileName}`);
if (input.fileName === "first.jpg") {
await firstGate.promise;
}
events.push(`end:${input.fileName}`);
return {
requestId: `req-${input.fileName}`,
file: {
type: "uploaded_file" as const,
id: `upload_${input.fileName}`,
fileName: input.fileName,
mimeType: input.mimeType,
size: input.bytes.byteLength,
path: `/home/user/.paseo/uploads/upload_${input.fileName}/${input.fileName}`,
},
error: null,
};
},
};
const uploadPromise = uploadImageAttachments({
client,
images: [
createAttachment({ id: "img-1", fileName: "first.jpg", mimeType: "image/jpeg" }),
createAttachment({ id: "img-2", fileName: "second.png", mimeType: "image/png" }),
],
});
await new Promise((resolve) => setTimeout(resolve, 0));
// Second photo must NOT start uploading until first photo's response has resolved.
expect(events).toEqual(["start:first.jpg"]);
firstGate.release();
const uploaded = await uploadPromise;
expect(events).toEqual([
"start:first.jpg",
"end:first.jpg",
"start:second.png",
"end:second.png",
]);
expect(uploaded).toEqual([
{
type: "uploaded_file",
id: "upload_first.jpg",
fileName: "first.jpg",
mimeType: "image/jpeg",
size: new TextEncoder().encode("img-1:bytes").byteLength,
path: "/home/user/.paseo/uploads/upload_first.jpg/first.jpg",
role: "image",
},
{
type: "uploaded_file",
id: "upload_second.png",
fileName: "second.png",
mimeType: "image/png",
size: new TextEncoder().encode("img-2:bytes").byteLength,
path: "/home/user/.paseo/uploads/upload_second.png/second.png",
role: "image",
},
]);
});
});
+72
View File
@@ -1,6 +1,9 @@
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
import { collectRetainedAttachmentIds } from "@/attachments/gc-retention";
import { getAttachmentStore } from "@/attachments/store";
import type { AttachmentMetadata, SaveAttachmentInput } from "@/attachments/types";
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
import { i18n } from "@/i18n/i18next";
const activePersistence = new Set<Promise<AttachmentMetadata>>();
const persistedDuringGarbageCollection = new Set<string>();
@@ -124,6 +127,75 @@ export async function encodeAttachmentsForSend(
return valid.length > 0 ? valid : undefined;
}
const DEFAULT_UPLOAD_EXTENSION_BY_MIME: Record<string, string> = {
"image/jpeg": ".jpg",
"image/jpg": ".jpg",
"image/png": ".png",
"image/gif": ".gif",
"image/webp": ".webp",
};
function resolveUploadedImageFileName(attachment: AttachmentMetadata): string {
const existing = attachment.fileName?.trim();
if (existing) {
return existing;
}
const ext = DEFAULT_UPLOAD_EXTENSION_BY_MIME[attachment.mimeType.toLowerCase()] ?? ".img";
return `${attachment.id}${ext}`;
}
export interface ImageUploadClient {
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
requestId: string;
file: UploadedFileAttachment | null;
error: string | null;
}>;
}
export async function readAttachmentBytes(attachment: AttachmentMetadata): Promise<Uint8Array> {
const store = await getAttachmentStore();
return await store.readBytes({ attachment });
}
/**
* Uploads persisted image attachments sequentially via `file.upload.request` so multi-photo
* batches drain cleanly between files instead of queueing concurrently on mobile sockets.
* Each uploaded image is marked with `role: "image"` inside `uploaded_file` so current daemons
* resolve it into a native vision block + timeline thumbnail, while older daemons (v0.1.91-v0.18.1)
* strip the unknown `role` field and still deliver the uploaded file path instead of dropping it.
*/
export async function uploadImageAttachments(input: {
client: ImageUploadClient;
images: readonly AttachmentMetadata[] | undefined;
}): Promise<UploadedFileAttachment[] | undefined> {
if (!input.images || input.images.length === 0) {
return undefined;
}
const uploaded: UploadedFileAttachment[] = [];
for (const attachment of input.images) {
const fileName = resolveUploadedImageFileName(attachment);
const bytes = await readAttachmentBytes(attachment);
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
}
const response = await input.client.uploadFile({
fileName,
mimeType: attachment.mimeType,
bytes,
});
if (response.error || !response.file) {
throw new Error(response.error ?? "Upload failed.");
}
uploaded.push({
...response.file,
role: "image",
});
}
return uploaded;
}
export async function resolveAttachmentPreviewUrl(attachment: AttachmentMetadata): Promise<string> {
const store = await getAttachmentStore();
return await store.resolvePreviewUrl({ attachment });
@@ -61,6 +61,13 @@ export function createTestAttachmentFileSystem(options?: {
}
return toBase64(bytes);
},
async readBytes(uri) {
const bytes = files.get(uri);
if (!bytes) {
throw new Error(`readBytes: file does not exist: ${uri}`);
}
return new Uint8Array(bytes);
},
async delete(uri, deleteOptions) {
if (!files.delete(uri) && !deleteOptions.idempotent) {
throw new Error(`delete: file does not exist: ${uri}`);
+1
View File
@@ -178,6 +178,7 @@ export interface AttachmentStore {
readonly storageType: AttachmentStorageType;
save(input: SaveAttachmentInput): Promise<AttachmentMetadata>;
encodeBase64(input: EncodeAttachmentInput): Promise<string>;
readBytes(input: EncodeAttachmentInput): Promise<Uint8Array>;
resolvePreviewUrl(input: ResolvePreviewUrlInput): Promise<string>;
releasePreviewUrl?(input: ReleasePreviewUrlInput): Promise<void>;
delete(input: DeleteAttachmentInput): Promise<void>;
@@ -0,0 +1,92 @@
// @vitest-environment jsdom
import { cleanup, renderHook, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { FileReadResult } from "@getpaseo/client/internal/daemon-client";
import { __setAttachmentStoreForTests } from "@/attachments/store";
import type { AttachmentStore } from "@/attachments/types";
import { useDaemonUploadedImage } from "./use-daemon-uploaded-image";
function createMemoryStore(): AttachmentStore {
const bytesById = new Map<string, Uint8Array>();
return {
storageType: "web-indexeddb",
async save(input) {
const id = input.id ?? "saved";
const bytes = input.source.kind === "bytes" ? input.source.bytes : new Uint8Array();
bytesById.set(id, bytes);
return {
id,
mimeType: input.mimeType ?? "image/png",
storageType: "web-indexeddb",
storageKey: id,
fileName: input.fileName ?? null,
byteSize: bytes.byteLength,
createdAt: 1,
};
},
async encodeBase64() {
return "";
},
async readBytes({ attachment }) {
return bytesById.get(attachment.id) ?? new Uint8Array();
},
async resolvePreviewUrl({ attachment }) {
return `blob:${attachment.id}`;
},
async delete() {},
async garbageCollect() {},
};
}
describe("useDaemonUploadedImage", () => {
beforeEach(() => {
__setAttachmentStoreForTests(createMemoryStore());
});
afterEach(() => {
cleanup();
__setAttachmentStoreForTests(null);
});
it("loads an uploaded image from the daemon via readFile and persists local AttachmentMetadata", async () => {
const readFile = vi.fn(
async (cwd: string, path: string): Promise<FileReadResult> => ({
kind: "image",
path,
mime: "image/jpeg",
size: 4,
modifiedAt: "2026-11-28T00:00:00.000Z",
bytes: new Uint8Array([0xff, 0xd8, 0xff, 0xd9]),
}),
);
const { result } = renderHook(() =>
useDaemonUploadedImage({
image: {
storageType: "daemon-upload",
id: "upload_reload_1",
fileName: "photo.jpg",
mimeType: "image/jpeg",
size: 4,
path: "/home/user/.paseo/uploads/upload_reload_1/photo.jpg",
},
client: { readFile },
serverId: "srv-1",
}),
);
await waitFor(() => {
expect(result.current).not.toBeNull();
});
expect(readFile).toHaveBeenCalledWith(
"/",
"/home/user/.paseo/uploads/upload_reload_1/photo.jpg",
);
expect(result.current).toMatchObject({
mimeType: "image/jpeg",
fileName: "photo.jpg",
byteSize: 4,
storageType: "web-indexeddb",
});
});
});
@@ -0,0 +1,83 @@
import { useEffect, useState } from "react";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { createAssistantImageAcquisitionCache } from "@/assistant-image/acquisition-cache";
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
import { persistAttachmentFromBytes } from "@/attachments/service";
import type { AttachmentMetadata } from "@/attachments/types";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import type { DaemonUploadedImageAttachment } from "@/types/stream";
const uploadedImageCache = createAssistantImageAcquisitionCache<AttachmentMetadata>({
capacity: 200,
onRetain: (attachment) => retainAttachmentForGarbageCollection(attachment.id),
});
function buildCacheKey(serverId: string | undefined, image: DaemonUploadedImageAttachment): string {
return [serverId ?? "local", image.id, image.path].join("\u0000");
}
function buildLocalAttachmentId(serverId: string | undefined, uploadId: string): string {
const safeServer = (serverId ?? "local").replace(/[^a-zA-Z0-9_-]/g, "_");
const safeUpload = uploadId.replace(/[^a-zA-Z0-9_-]/g, "_");
return `daemon-upload-${safeServer}-${safeUpload}`;
}
/**
* Loads a daemon-stored uploaded image through `client.readFile` (binary chunked stream),
* persists it into the local attachment store, and retains it in a bounded LRU cache so
* timeline reloads and cross-device views render thumbnails and lightbox previews cleanly.
*/
export function useDaemonUploadedImage(input: {
image: DaemonUploadedImageAttachment;
client?: Pick<DaemonClient, "readFile"> | null;
serverId?: string;
}): AttachmentMetadata | null {
const { image, client, serverId } = input;
const cacheKey = buildCacheKey(serverId, image);
const [resolved, setResolved] = useState<{ key: string; metadata: AttachmentMetadata } | null>(
null,
);
useEffect(() => {
if (!client) {
return;
}
const target = resolveFilePreviewReadTarget({ path: image.path });
if (!target) {
return;
}
let cancelled = false;
const retained = uploadedImageCache.acquireRetained(cacheKey, async () => {
const file = await client.readFile(target.cwd, target.path);
return await persistAttachmentFromBytes({
id: buildLocalAttachmentId(serverId, image.id),
bytes: file.bytes,
mimeType: image.mimeType || file.mime,
fileName: image.fileName,
});
});
void retained.promise
.then((metadata) => {
if (!cancelled) {
setResolved({ key: cacheKey, metadata });
}
return undefined;
})
.catch((error) => {
console.warn("[attachments] Failed to load uploaded user message image", {
id: image.id,
path: image.path,
error,
});
});
return () => {
cancelled = true;
retained.release();
};
}, [cacheKey, client, image.fileName, image.id, image.mimeType, image.path, serverId]);
return resolved?.key === cacheKey ? resolved.metadata : null;
}
@@ -165,6 +165,16 @@ export function createIndexedDbAttachmentStore(): AttachmentStore {
}
},
async readBytes({ attachment }): Promise<Uint8Array> {
const db = await openAttachmentDb();
try {
const blob = await loadBlob(db, attachment.storageKey);
return new Uint8Array(await blob.arrayBuffer());
} finally {
db.close();
}
},
async resolvePreviewUrl({ attachment }): Promise<string> {
const db = await openAttachmentDb();
try {
@@ -56,6 +56,7 @@ function source(gitActions: GitActions): {
copyAgentId: "Copy agent id",
copyTerminalId: "Copy terminal id",
copyFilePath: "Copy file path",
revealInFiles: "Reveal in Files",
closeTabsLeft: "Close tabs left",
closeTabsRight: "Close tabs right",
closeOtherTabs: "Close other tabs",
@@ -139,6 +140,21 @@ describe("workspace command center contributions", () => {
expect(fixture.dispatched).toEqual([]);
});
it("reveals the active file tab in Files", () => {
const fixture = source({ primary: null, secondary: [], menu: [] });
fixture.value.activeTabKind = "file";
fixture.value.activeTabIndex = 0;
fixture.value.activeTabCount = 1;
buildWorkspaceCommandCenterContributions(fixture.value)
.find((item) => item.id === "tab:reveal-in-files")
?.run();
expect(fixture.dispatched).toEqual([
{ id: "workspace.tab.reveal-in-files", scope: "workspace" },
]);
});
it("omits archive while the workspace cannot be archived", () => {
const fixture = source({ primary: null, secondary: [], menu: [] });
fixture.value.archiveWorkspace = null;
@@ -36,6 +36,7 @@ export interface WorkspaceCommandCenterLabels {
copyAgentId: string;
copyTerminalId: string;
copyFilePath: string;
revealInFiles: string;
closeTabsLeft: string;
closeTabsRight: string;
closeOtherTabs: string;
@@ -351,6 +352,14 @@ function buildActiveTabContributions(
icon: source.icons.copy,
action: { id: "workspace.tab.copy-file-path", scope: "workspace" },
}),
buildQueryAction(source, {
id: "tab:reveal-in-files",
rank: 37,
title: source.labels.revealInFiles,
keywords: ["tab", "file", "reveal", "files", "explorer"],
icon: source.icons.files,
action: { id: "workspace.tab.reveal-in-files", scope: "workspace" },
}),
);
}
if (source.activeTabIndex > 0) {
@@ -256,6 +256,7 @@ export function useWorkspaceCommandCenterActions(): void {
copyAgentId: t("workspace.tabs.menu.copyAgentId"),
copyTerminalId: t("workspace.tabs.menu.copyTerminalId"),
copyFilePath: t("workspace.tabs.menu.copyFilePath"),
revealInFiles: t("workspace.fileActions.revealInFiles"),
closeTabsLeft: t("workspace.tabs.menu.closeLeft"),
closeTabsRight: t("workspace.tabs.menu.closeRight"),
closeOtherTabs: t("workspace.tabs.menu.closeOthers"),
@@ -412,6 +412,29 @@ export function SheetHeaderIconButton({
);
}
/** The header's overflow trigger. Place it inside the `DropdownMenu` that holds its rows. */
export function SheetHeaderMenuButton({
icon,
label,
testID,
}: {
icon: LucideIcon;
/** The accessible name, also shown as the desktop tooltip. */
label: string;
testID?: string;
}) {
const compact = useIsCompactFormFactor();
return (
<ToolbarButton kind="menu" label={label} compact={compact} testID={testID}>
<ThemedHeaderGlyph
icon={icon}
size={iconButtonChromeGlyphSize("large", compact)}
uniProps={mutedIconColorMapping}
/>
</ToolbarButton>
);
}
function SheetHeaderBackButton({ back }: { back: SheetHeaderBack }) {
const { t } = useTranslation();
return (
@@ -601,8 +624,8 @@ export interface AdaptiveModalSheetProps {
/** Re-establishes caller-owned contexts inside the native or compact sheet portal. */
contextBridge?: ContextBridge | null;
/**
* Keys the body handles while the sheet is the top overlay, such as list navigation. Escape
* always closes the sheet. Return true from `onKeyDown` to claim the key.
* Keys the body handles while the sheet is the top overlay, such as list navigation. Return true
* from `onKeyDown` to claim the key. Escape closes the sheet unless the body lists it and claims it.
*/
keyboard?: SheetKeyboard;
}
@@ -760,12 +783,18 @@ export function AdaptiveModalSheet({
}
event.preventDefault();
event.stopPropagation();
// A body that lists Escape among its keys undoes its own step first, such as a page that
// returns to the one before it; Escape closes the sheet when the body has nothing to undo.
if (keyboard?.keys.includes("Escape") && keyboard.onKeyDown(event)) return true;
onClose();
return true;
},
[keyboard, onClose],
);
const overlayKeys = useMemo(() => ["Escape", ...(keyboard?.keys ?? [])], [keyboard?.keys]);
const overlayKeys = useMemo(
() => ["Escape", ...(keyboard?.keys ?? []).filter((key) => key !== "Escape")],
[keyboard?.keys],
);
const setOverlayScope = useOverlayRegistration({
keys: overlayKeys,
active: visible,
@@ -1,18 +1,26 @@
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { useCallback, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
import { Keyboard, Pressable, Text, View, type PressableStateCallbackType } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { StyleSheet } from "react-native-unistyles";
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
import { ModelBrowser, ModelProviderGlyph, useModelBrowser } from "@/components/model-browser";
import { resolveModelBrowserScrolling } from "@/components/model-browser-view";
import type { ComboboxProps } from "@/components/ui/combobox";
import {
AdaptiveModalSheet,
type SheetHeader,
type SheetKeyboard,
} from "@/components/adaptive-modal-sheet";
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
import {
MobileModelPageView,
SheetSearchDock,
useMobileModelPage,
} from "@/components/mobile-model-page";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { ICON_SIZE } from "@/styles/theme";
import {
TOOLBAR_GLYPH_SIZES,
toolbarContentSlot,
@@ -21,15 +29,9 @@ import {
import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle";
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
const DEFAULT_TRIGGER_DECORATION = { showCaret: true, tooltip: undefined };
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const foregroundMutedMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
function noop() {}
const SHEET_SNAP_POINTS = ["80%", "90%"];
const ESCAPE_KEYS = ["Escape"] as const;
interface CombinedModelSelectorProps {
providers: ProviderSelectorProvider[];
@@ -58,7 +60,6 @@ interface CombinedModelSelectorProps {
disabled?: boolean;
serverId?: string | null;
desktopPlacement?: ComboboxProps["desktopPlacement"];
desktopMinWidth?: number;
/**
* Render the custom trigger as a full-width form field: the outer Pressable
* becomes a transparent passthrough that stretches its child edge-to-edge and
@@ -75,7 +76,17 @@ interface CombinedModelSelectorProps {
};
}
export function CombinedModelSelector({
export function CombinedModelSelector(props: CombinedModelSelectorProps) {
const isCompact = useIsCompactFormFactor();
// One frame per form factor: a sheet that drills into providers, or a two-pane popover.
return isCompact ? (
<CompactCombinedModelSelector {...props} />
) : (
<DesktopCombinedModelSelector {...props} />
);
}
function DesktopCombinedModelSelector({
providers,
selectedProvider,
selectedModel,
@@ -95,60 +106,127 @@ export function CombinedModelSelector({
disabled = false,
serverId = null,
desktopPlacement,
desktopMinWidth,
triggerFill = false,
toolbar,
}: CombinedModelSelectorProps) {
const anchorRef = useRef<View>(null);
const [isOpen, setIsOpen] = useState(false);
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open) onOpen?.();
else onClose?.();
},
[onClose, onOpen],
);
const handleTriggerPress = useCallback(() => {
handleOpenChange(!isOpen);
}, [handleOpenChange, isOpen]);
const actions = useModelSelectorActions({
onOpenChange: handleOpenChange,
onSelect,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
});
useKeyboardToggle({
action: toggleAction,
disabled,
open: isOpen,
// The search field holds focus for as long as the popover is open.
searchFocused: isOpen,
onToggle: handleTriggerPress,
});
return (
<>
<ModelSelectorTrigger
anchorRef={anchorRef}
isOpen={isOpen}
disabled={disabled}
onPress={handleTriggerPress}
labels={labels}
selectedProvider={selectedProvider}
serverId={serverId}
renderTrigger={renderTrigger}
triggerFill={triggerFill}
toolbar={toolbar}
/>
<DesktopModelPicker
open={isOpen}
onOpenChange={handleOpenChange}
anchorRef={anchorRef}
desktopPlacement={desktopPlacement}
providers={providers}
selectedProvider={selectedProvider}
selectedModel={selectedModel}
profiles={profiles}
serverId={serverId}
onSelect={actions.handleSelect}
onApplyProfile={actions.handleApplyProfile}
onEditProfiles={onEditProfiles ? actions.handleEditProfiles : undefined}
onCreateProfile={onCreateProfile ? actions.handleCreateProfile : undefined}
onEditProfile={onEditProfile ? actions.handleEditProfile : undefined}
onRetryProvider={onRetryProvider}
isRetryingProvider={isRetryingProvider}
/>
</>
);
}
function CompactCombinedModelSelector({
providers,
selectedProvider,
selectedModel,
onSelect,
isLoading,
profiles = null,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
renderTrigger,
toggleAction,
onOpen,
onClose,
onRetryProvider,
isRetryingProvider = false,
disabled = false,
serverId = null,
triggerFill = false,
toolbar,
}: CombinedModelSelectorProps) {
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const modelBrowserScrolling = resolveModelBrowserScrolling({ isNative, isCompact });
const anchorRef = useRef<View>(null);
const [isOpen, setIsOpen] = useState(false);
const [isContentReady, setIsContentReady] = useState(isWeb);
const browser = useModelBrowser({
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
const page = useMobileModelPage({
providers,
profiles: profiles?.rows ?? null,
canCreateProfile: Boolean(onEditProfiles),
selectedProvider,
selectedModel,
isLoading,
profiles,
serverId,
});
const { prepareToOpen, reset } = browser;
const { reset, clearQuery } = page;
const handleOpenChange = useCallback(
(open: boolean) => {
setIsOpen(open);
if (open) {
prepareToOpen();
reset();
onOpen?.();
return;
}
reset();
Keyboard.dismiss();
onClose?.();
},
[onClose, onOpen, prepareToOpen, reset],
[onClose, onOpen, reset],
);
const handleSelect = useCallback(
(provider: string, modelId: string) => {
onSelect(provider, modelId);
handleOpenChange(false);
},
[handleOpenChange, onSelect],
);
useEffect(() => {
if (isWeb) return () => {};
if (!isOpen) {
setIsContentReady(false);
return () => {};
}
const frame = requestAnimationFrame(() => {
setIsContentReady(true);
});
return () => cancelAnimationFrame(frame);
}, [isOpen]);
const handleClose = useCallback(() => handleOpenChange(false), [handleOpenChange]);
const handleTriggerPress = useCallback(() => {
handleOpenChange(!isOpen);
}, [handleOpenChange, isOpen]);
@@ -157,10 +235,184 @@ export function CombinedModelSelector({
action: toggleAction,
disabled,
open: isOpen,
searchFocused: browser.isSearchFocused,
searchFocused: false,
onToggle: handleTriggerPress,
});
const actions = useModelSelectorActions({
onOpenChange: handleOpenChange,
onSelect,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
});
const pickerActions = useMemo<ModelPickerActions>(
() => ({
onSelect: actions.handleSelect,
onApplyProfile: actions.handleApplyProfile,
onEditProfiles: onEditProfiles ? actions.handleEditProfiles : undefined,
onCreateProfile: onCreateProfile ? actions.handleCreateProfile : undefined,
onEditProfile: onEditProfile ? actions.handleEditProfile : undefined,
onRetryProvider,
isRetryingProvider,
}),
[actions, isRetryingProvider, onCreateProfile, onEditProfile, onEditProfiles, onRetryProvider],
);
// Escape clears the search first, then closes the sheet.
const query = page.query;
const keyboard = useMemo<SheetKeyboard>(
() => ({
keys: ESCAPE_KEYS,
onKeyDown: (event) => {
if (event.key !== "Escape" || query.trim().length === 0) return false;
clearQuery();
return true;
},
}),
[clearQuery, query],
);
const header = useMemo<SheetHeader>(() => ({ title: t("modelSelector.selectModel") }), [t]);
const footer = useMemo(() => {
let placeholder = t("modelSelector.searchPlaceholder");
if (profiles && profiles.rows.length > 0) {
placeholder = t("modelSelector.searchModelsAndProfilesPlaceholder");
} else if (providers.length > 1) {
placeholder = t("modelSelector.searchAllPlaceholder");
}
return (
<SheetSearchDock
query={page.query}
searchKey={page.searchKey}
onChangeText={page.setQuery}
placeholder={placeholder}
testID="model-search-all-input"
/>
);
}, [page.query, page.searchKey, page.setQuery, profiles, providers.length, t]);
return (
<>
<ModelSelectorTrigger
anchorRef={anchorRef}
isOpen={isOpen}
disabled={disabled}
onPress={handleTriggerPress}
labels={labels}
selectedProvider={selectedProvider}
serverId={serverId}
renderTrigger={renderTrigger}
triggerFill={triggerFill}
toolbar={toolbar}
/>
<AdaptiveModalSheet
header={header}
visible={isOpen}
onClose={handleClose}
snapPoints={SHEET_SNAP_POINTS}
scrollable={false}
footer={footer}
keyboard={keyboard}
contentStyle={styles.sheetBody}
testID="model-selector-sheet"
>
<MobileModelPageView
page={page}
selectedProvider={selectedProvider}
selectedModel={selectedModel}
serverId={serverId}
profiles={profiles?.rows ?? null}
actions={pickerActions}
/>
</AdaptiveModalSheet>
</>
);
}
/**
* Every pick resolves the selector and closes it. A 1-tap `+` saves the profile, selects its model
* immediately, and closes the picker; useAgentProfileEditor surfaces a toast with Edit and Undo.
*/
function useModelSelectorActions({
onOpenChange,
onSelect,
onApplyProfile,
onEditProfiles,
onCreateProfile,
onEditProfile,
}: Pick<
CombinedModelSelectorProps,
"onSelect" | "onApplyProfile" | "onEditProfiles" | "onCreateProfile" | "onEditProfile"
> & { onOpenChange: (open: boolean) => void }) {
const handleSelect = useCallback(
(provider: string, modelId: string) => {
onSelect(provider, modelId);
onOpenChange(false);
},
[onOpenChange, onSelect],
);
const handleApplyProfile = useCallback(
(profileId: string) => {
onApplyProfile?.(profileId);
onOpenChange(false);
},
[onApplyProfile, onOpenChange],
);
const handleEditProfiles = useCallback(() => {
onOpenChange(false);
onEditProfiles?.();
}, [onEditProfiles, onOpenChange]);
const handleCreateProfile = useCallback(
(seed: AgentProfileSeed) => {
if (seed.modelId) {
onSelect(seed.provider, seed.modelId);
}
onOpenChange(false);
void onCreateProfile?.(seed);
},
[onCreateProfile, onOpenChange, onSelect],
);
const handleEditProfile = useCallback(
(profileId: string) => {
onOpenChange(false);
onEditProfile?.(profileId);
},
[onEditProfile, onOpenChange],
);
return {
handleSelect,
handleApplyProfile,
handleEditProfiles,
handleCreateProfile,
handleEditProfile,
};
}
function ModelSelectorTrigger({
anchorRef,
isOpen,
disabled,
onPress,
labels,
selectedProvider,
serverId,
renderTrigger,
triggerFill,
toolbar,
}: {
anchorRef: RefObject<View | null>;
isOpen: boolean;
disabled: boolean;
onPress: () => void;
labels: { selectedModelLabel: string; triggerLabel: string };
selectedProvider: string;
serverId: string | null;
renderTrigger: CombinedModelSelectorProps["renderTrigger"];
triggerFill: boolean;
toolbar: CombinedModelSelectorProps["toolbar"];
}) {
const { t } = useTranslation();
const triggerStyle = useCallback(
({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => {
if (triggerFill) {
@@ -181,145 +433,73 @@ export function CombinedModelSelector({
},
[disabled, isOpen, renderTrigger, triggerFill],
);
const handleApplyProfile = useCallback(
(profileId: string) => {
onApplyProfile?.(profileId);
handleOpenChange(false);
},
[handleOpenChange, onApplyProfile],
);
const handleEditProfiles = useCallback(() => {
handleOpenChange(false);
onEditProfiles?.();
}, [handleOpenChange, onEditProfiles]);
// 1-tap `+` saves the profile, selects the model immediately, and closes the picker;
// useAgentProfileEditor surfaces a toast with Edit and Undo actions.
const handleCreateProfile = useCallback(
(seed: AgentProfileSeed) => {
if (seed.modelId) {
onSelect(seed.provider, seed.modelId);
}
handleOpenChange(false);
void onCreateProfile?.(seed);
},
[handleOpenChange, onCreateProfile, onSelect],
);
const handleEditProfile = useCallback(
(profileId: string) => {
handleOpenChange(false);
onEditProfile?.(profileId);
},
[handleOpenChange, onEditProfile],
);
const selectorBody = isContentReady ? (
<ModelBrowser
state={browser}
onSelect={handleSelect}
onApplyProfile={handleApplyProfile}
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
onCreateProfile={onCreateProfile ? handleCreateProfile : undefined}
onEditProfile={onEditProfile ? handleEditProfile : undefined}
onRetryProvider={onRetryProvider}
isRetryingProvider={isRetryingProvider}
scrolling={modelBrowserScrolling}
/>
) : (
<View style={styles.sheetLoadingState}>
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
<Text style={styles.sheetLoadingText}>{t("modelSelector.loadingSelector")}</Text>
</View>
);
const accessibilityLabel = t("modelSelector.selectedModel", {
model: labels.selectedModelLabel,
});
const { showCaret, tooltip } = toolbar ?? DEFAULT_TRIGGER_DECORATION;
return (
<>
{renderTrigger ? (
<Pressable
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={handleTriggerPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={t("modelSelector.selectedModel", {
model: browser.selectedModelLabel,
})}
testID="combined-model-selector"
>
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
renderTrigger({
selectedModelLabel: browser.triggerLabel,
onPress: handleTriggerPress,
disabled,
isOpen,
hovered: Boolean(hovered),
pressed,
})
}
</Pressable>
) : (
<ComboboxTrigger
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={handleTriggerPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={t("modelSelector.selectedModel", {
model: browser.selectedModelLabel,
})}
testID="combined-model-selector"
chevron={showCaret === false ? null : undefined}
tooltip={tooltip}
>
{selectedProvider.trim().length > 0 ? (
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
<ModelProviderGlyph
provider={selectedProvider}
serverId={serverId}
size={toolbar?.glyph.size ?? ICON_SIZE.md}
strokeWidth={toolbar?.glyph.strokeWidth}
tone={toolbar?.glyph.tone}
/>
</View>
) : null}
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
{browser.triggerLabel}
</Text>
</ComboboxTrigger>
)}
<Combobox
options={EMPTY_COMBOBOX_OPTIONS}
value=""
onSelect={noop}
open={isOpen}
onOpenChange={handleOpenChange}
anchorRef={anchorRef}
desktopPlacement={desktopPlacement}
desktopMinWidth={desktopMinWidth}
desktopLockWidth
desktopFixedHeight={browser.desktopFixedHeight}
desktopChildrenScrollEnabled={false}
header={browser.header}
keyboard={browser.keyboard}
mobileChildrenScrollEnabled={!browser.isProviderView || !isNative}
mobileChildrenContentContainerStyle={styles.mobileBrowserContent}
if (renderTrigger) {
return (
<Pressable
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={onPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID="combined-model-selector"
>
{selectorBody}
</Combobox>
</>
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
renderTrigger({
selectedModelLabel: labels.triggerLabel,
onPress,
disabled,
isOpen,
hovered: Boolean(hovered),
pressed,
})
}
</Pressable>
);
}
return (
<ComboboxTrigger
ref={anchorRef}
collapsable={false}
disabled={disabled}
onPress={onPress}
style={triggerStyle}
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
testID="combined-model-selector"
chevron={showCaret === false ? null : undefined}
tooltip={tooltip}
>
{selectedProvider.trim().length > 0 ? (
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
<ModelProviderGlyph
provider={selectedProvider}
serverId={serverId}
size={toolbar?.glyph.size ?? ICON_SIZE.md}
strokeWidth={toolbar?.glyph.strokeWidth}
tone={toolbar?.glyph.tone}
/>
</View>
) : null}
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
{labels.triggerLabel}
</Text>
</ComboboxTrigger>
);
}
const styles = StyleSheet.create((theme) => ({
mobileBrowserContent: {
sheetBody: {
paddingHorizontal: 0,
paddingTop: 0,
paddingBottom: 0,
gap: 0,
},
trigger: {
minWidth: 0,
@@ -371,14 +551,4 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: "transparent",
borderRadius: 0,
},
sheetLoadingState: {
minHeight: 160,
justifyContent: "center",
alignItems: "center",
gap: theme.spacing[2],
},
sheetLoadingText: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
}));
@@ -11,6 +11,7 @@ import {
FolderMinus,
FolderOpen,
FolderPlus,
FolderTree,
MessageSquarePlus,
Pencil,
Trash2,
@@ -55,6 +56,8 @@ interface FileActionsContextMenuContentProps {
onOpenInEditor?: () => void;
editorTargetName?: string;
onOpenToSide?: () => void;
/** Only for a row listed outside the tree, such as a filter match. */
onRevealInFiles?: () => void;
onCopyPath?: () => void;
onCopyRelativePath?: () => void;
onReveal?: () => void;
@@ -82,6 +85,7 @@ export function FileActionsContextMenuContent({
onOpenInEditor,
editorTargetName,
onOpenToSide,
onRevealInFiles,
onCopyPath,
onCopyRelativePath,
onReveal,
@@ -157,6 +161,12 @@ export function FileActionsContextMenuContent({
label: t("workspace.fileActions.openToSide"),
icon: ArrowRightToLine,
}),
optionalFileAction(true, onRevealInFiles, {
key: "reveal-in-files",
group: "open",
label: t("workspace.fileActions.revealInFiles"),
icon: FolderTree,
}),
onCopyPath
? {
key: "copy-path",
@@ -265,6 +275,7 @@ export function FileActionsContextMenuContent({
onOpenToSide,
onRename,
onReveal,
onRevealInFiles,
onRevert,
revealTargetName,
t,
+335 -211
View File
@@ -12,6 +12,7 @@ import { useQuery } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import {
FlatList,
type LayoutChangeEvent,
ListRenderItemInfo,
Pressable,
Text,
@@ -26,11 +27,19 @@ import { EditingTextInput as TextInput } from "@/components/ui/text-input";
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isWeb } from "@/constants/platform";
import * as Clipboard from "expo-clipboard";
import { ChevronDown, Eye, EyeOff, FilePlus, FolderPlus, RotateCw } from "lucide-react-native";
import {
ChevronDown,
Eye,
EyeOff,
FilePlus,
Folder,
FolderPlus,
RotateCw,
} from "lucide-react-native";
import { MaterialFileIcon } from "@/components/material-file-icon";
import {
TreeChevron,
TreeIndentGuides,
treeRowPaddingLeft,
workspaceTreeRowStyles,
WORKSPACE_TREE_ICON_LABEL_GAP,
@@ -58,12 +67,17 @@ import type {
import { useSessionStore } from "@/stores/session-store";
import { FileActionsContextMenuContent } from "@/components/file-actions-menu";
import { ContextMenu, ContextMenuTrigger, useContextMenu } from "@/components/ui/context-menu";
import { useFileDownload } from "@/hooks/use-file-download";
import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
import { buildWorkspaceExplorerStateKey } from "@/hooks/use-file-explorer-actions";
import {
clearFileFilter,
FileFilterField,
FileFilterResults,
useFileFilterQuery,
useRefreshFileFilterResults,
type FileFilterMatch,
} from "@/file-explorer/filter";
import { usePanelStore, type ExpandedPathsUpdate, type SortOption } from "@/stores/panel-store";
import { buildAbsoluteExplorerPath } from "@/utils/explorer-paths";
import {
DIRECTORY_LISTING_INVALIDATED,
type DirectoryListingResult,
@@ -81,9 +95,10 @@ import {
import { useWorkspaceFileDragSource } from "@/attachments/use-workspace-file-drag-source";
import { confirmDialog } from "@/utils/confirm-dialog";
import { useToast } from "@/contexts/toast-context";
import { openDesktopTarget, useDesktopOpenTargets } from "@/workspace/desktop-open-targets";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import { useOpenDirectoryInEditor } from "@/workspace/open-in-editor/directory";
import { useWorkspaceFileActions } from "@/workspace/file-actions";
import { useScrollToRevealedEntry } from "@/file-explorer/use-scroll-to-revealed-entry";
const SORT_OPTIONS: { value: SortOption }[] = [
{ value: "name" },
@@ -92,6 +107,7 @@ const SORT_OPTIONS: { value: SortOption }[] = [
];
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
const ThemedFolder = withUnistyles(Folder);
const foregroundMutedColorMapping = (theme: Theme) => ({
color: theme.colors.foregroundMuted,
});
@@ -108,33 +124,64 @@ function DirectoryChevronIcon({ loading, expanded }: { loading: boolean; expande
return <TreeChevron expanded={expanded} />;
}
interface TreeRowItemProps {
/** What a row needs to know about its entry; tree entries and filter matches both have it. */
type ExplorerEntryRef = Pick<ExplorerEntry, "kind" | "name" | "path">;
/** What every row can do with its entry, whether the tree or the filter lists it. */
interface EntryRowActions {
onEntryPress: (entry: ExplorerEntryRef) => void;
onSelectEntry: (entry: ExplorerEntryRef) => void;
onCopyPath: (path: string) => void;
onCopyRelativePath: (path: string) => void;
onOpenInEditor?: (entry: ExplorerEntryRef) => void;
editorTargetName?: string;
onRevealEntry?: (entry: ExplorerEntryRef) => void;
revealTargetName?: string;
onDownloadEntry: (entry: ExplorerEntryRef) => void;
onAddToChat?: (path: string) => void;
onOpenFileToSide?: (path: string) => void;
onNewEntry?: (parentPath: string, kind: "file" | "directory") => void;
onRenameEntry?: (entry: ExplorerEntryRef) => void;
onDuplicateEntry?: (entry: ExplorerEntryRef) => void;
onDeleteEntry?: (entry: ExplorerEntryRef) => void;
}
interface TreeRowItemProps extends EntryRowActions {
serverId: string;
workspaceId?: string | null;
entry: ExplorerEntry;
entry: ExplorerEntryRef;
depth: number;
isExpanded: boolean;
isSelected: boolean;
loading: boolean;
onEntryPress: (entry: ExplorerEntry) => void;
onSelectEntry: (entry: ExplorerEntry) => void;
onCopyPath: (path: string) => void;
onCopyRelativePath: (path: string) => void;
onOpenInEditor?: (entry: ExplorerEntry) => void;
editorTargetName?: string;
onRevealEntry?: (entry: ExplorerEntry) => void;
revealTargetName?: string;
onDownloadEntry: (entry: ExplorerEntry) => void;
onAddToChat?: (path: string) => void;
onOpenFileToSide?: (path: string) => void;
onNewEntry?: (parentPath: string, kind: "file" | "directory") => void;
/** Set on a filter match, which names the folder it is in instead of sitting under it. */
parentDirectory?: string;
onRevealInFiles?: (path: string) => void;
onCollapseDirectory?: (path: string) => void;
onRenameEntry?: (entry: ExplorerEntry) => void;
onDuplicateEntry?: (entry: ExplorerEntry) => void;
onDeleteEntry?: (entry: ExplorerEntry) => void;
testID?: string;
}
function EntryIcon({
entry,
loading,
isExpanded,
isMatch,
}: {
entry: ExplorerEntryRef;
loading: boolean;
isExpanded: boolean;
isMatch: boolean;
}) {
if (entry.kind === "file") {
return <MaterialFileIcon fileName={entry.name} size={WORKSPACE_TREE_ICON_SIZE} />;
}
// A match does not expand in place, so it carries no disclosure chevron.
if (isMatch) {
return <ThemedFolder size={WORKSPACE_TREE_ICON_SIZE} uniProps={foregroundMutedColorMapping} />;
}
return <DirectoryChevronIcon loading={loading} expanded={isExpanded} />;
}
function sortTriggerStyle({
hovered,
pressed,
@@ -145,11 +192,16 @@ function sortTriggerStyle({
type ExplorerListRow =
| { type: "entry"; row: ExplorerTreeRow }
| { type: "draft"; parentPath: string; kind: "file" | "directory"; depth: number }
| { type: "rename"; entry: ExplorerEntry; depth: number };
| { type: "rename"; entry: ExplorerEntryRef; depth: number };
type ExplorerPendingEdit =
| { type: "create"; parentPath: string; kind: "file" | "directory" }
| { type: "rename"; entry: ExplorerEntry };
| { type: "rename"; entry: ExplorerEntryRef };
function listRowPath(row: ExplorerListRow): string | null {
if (row.type === "entry") return row.row.entry.path;
return row.type === "rename" ? row.entry.path : null;
}
function listRowKeyExtractor(row: ExplorerListRow) {
if (row.type === "entry") {
@@ -202,6 +254,7 @@ function EntryNameInputRow({
return (
<View style={[workspaceTreeRowStyles.row, { paddingLeft: treeRowPaddingLeft(depth) }]}>
<TreeIndentGuides depth={depth} />
<View style={styles.entryInfo}>
<View style={styles.entryIcon}>
{kind === "directory" ? (
@@ -242,6 +295,8 @@ function TreeRowItem({
isExpanded,
isSelected,
loading,
parentDirectory,
onRevealInFiles,
onEntryPress,
onSelectEntry,
onCopyPath,
@@ -264,6 +319,7 @@ function TreeRowItem({
const showNameHover = useCallback(() => setIsHovered(true), []);
const hideNameHover = useCallback(() => setIsHovered(false), []);
const isDirectory = entry.kind === "directory";
const isMatch = parentDirectory !== undefined;
const dragSourceRef = useWorkspaceFileDragSource({
enabled: !isDirectory,
serverId,
@@ -317,6 +373,10 @@ function TreeRowItem({
onAddToChat?.(entry.path);
}, [onAddToChat, entry.path]);
const handleRevealInFiles = useCallback(() => {
onRevealInFiles?.(entry.path);
}, [entry.path, onRevealInFiles]);
const handleOpenToSide = useCallback(() => {
onOpenFileToSide?.(entry.path);
}, [entry.path, onOpenFileToSide]);
@@ -358,17 +418,14 @@ function TreeRowItem({
aria-selected={isSelected}
testID={testID}
>
<TreeIndentGuides depth={depth} />
<View ref={dragSourceRef} style={styles.entryInfo}>
<View style={styles.entryIcon}>
{isDirectory ? (
<DirectoryChevronIcon loading={loading} expanded={isExpanded} />
) : (
<MaterialFileIcon fileName={entry.name} size={WORKSPACE_TREE_ICON_SIZE} />
)}
<EntryIcon entry={entry} loading={loading} isExpanded={isExpanded} isMatch={isMatch} />
</View>
<Text
style={[
styles.entryName,
isMatch ? styles.matchName : styles.entryName,
workspaceTreeRowStyles.name,
isHovered && workspaceTreeRowStyles.nameHovered,
]}
@@ -377,6 +434,11 @@ function TreeRowItem({
>
{entry.name}
</Text>
{parentDirectory ? (
<Text style={styles.matchDirectory} numberOfLines={1} ellipsizeMode="head">
{parentDirectory}
</Text>
) : null}
</View>
</ContextMenuTrigger>
<FileActionsContextMenuContent
@@ -390,6 +452,7 @@ function TreeRowItem({
onDownload={handleDownload}
onAddToChat={onAddToChat ? handleAddToChat : undefined}
onOpenToSide={!isDirectory && onOpenFileToSide ? handleOpenToSide : undefined}
onRevealInFiles={onRevealInFiles ? handleRevealInFiles : undefined}
onNewFile={onNewEntry ? handleNewFile : undefined}
onNewFolder={onNewEntry ? handleNewFolder : undefined}
onCollapseFolder={isDirectory && isExpanded ? handleCollapseDirectory : undefined}
@@ -439,6 +502,7 @@ export function FileExplorerPane({
);
const {
revealDirectory,
requestDirectoryListing,
invalidateDirectoryListings,
createEntry,
@@ -452,11 +516,11 @@ export function FileExplorerPane({
workspaceRoot: normalizedWorkspaceRoot,
});
const toast = useToast();
const isLocalDaemon = useIsLocalDaemon(serverId);
const { targets: desktopOpenTargets } = useDesktopOpenTargets({
isLocalExecution: isLocalDaemon,
const fileActions = useWorkspaceFileActions({
serverId,
workspaceId,
workspaceRoot: normalizedWorkspaceRoot,
});
const fileManagerTarget = desktopOpenTargets.find((target) => target.kind === "file-manager");
const projectId = useWorkspaceFields(
serverId,
workspaceId ?? null,
@@ -476,11 +540,8 @@ export function FileExplorerPane({
(state) => state.sessions[serverId]?.serverInfo?.features?.fsEntryDuplicate === true,
);
const [pendingEdit, setPendingEdit] = useState<ExplorerPendingEdit | null>(null);
const downloadFile = useFileDownload({
serverId,
workspaceId,
workspaceRoot: normalizedWorkspaceRoot,
});
const filterQuery = useFileFilterQuery(workspaceStateKey);
const refreshFilterResults = useRefreshFileFilterResults(serverId);
const sortOption = usePanelStore((state) => state.explorerSortOption);
const showHiddenFiles = usePanelStore((state) => state.explorerShowHiddenFiles);
const setSortOption = usePanelStore((state) => state.setExplorerSortOption);
@@ -534,7 +595,7 @@ export function FileExplorerPane({
]);
const handleToggleDirectory = useCallback(
(entry: ExplorerEntry) =>
(entry: ExplorerEntryRef) =>
toggleDirectory({
entry,
workspaceStateKey,
@@ -555,7 +616,7 @@ export function FileExplorerPane({
// Selection is intentionally separate from opening/expansion so future keyboard actions
// (for example, pressing R to rename) have one stable file-or-folder target.
const handleSelectEntry = useCallback(
(entry: ExplorerEntry) => {
(entry: ExplorerEntryRef) => {
if (hasWorkspaceScope) {
selectExplorerEntry(entry.path);
}
@@ -564,7 +625,7 @@ export function FileExplorerPane({
);
const handleOpenFile = useCallback(
(entry: ExplorerEntry) => {
(entry: ExplorerEntryRef) => {
if (!hasWorkspaceScope) {
return;
}
@@ -574,7 +635,7 @@ export function FileExplorerPane({
);
const handleEntryPress = useCallback(
(entry: ExplorerEntry) => {
(entry: ExplorerEntryRef) => {
handleSelectEntry(entry);
if (entry.kind === "directory") {
handleToggleDirectory(entry);
@@ -597,58 +658,37 @@ export function FileExplorerPane({
[setExpandedPathsForWorkspace, workspaceStateKey],
);
const handleCopyPath = useCallback(
async (path: string) => {
await Clipboard.setStringAsync(
buildAbsoluteExplorerPath({
workspaceRoot: normalizedWorkspaceRoot,
entryPath: path,
}),
);
},
[normalizedWorkspaceRoot],
);
const handleCopyRelativePath = useCallback(async (path: string) => {
await Clipboard.setStringAsync(path);
}, []);
const handleRevealEntry = useCallback(
async (entry: ExplorerEntry) => {
if (!fileManagerTarget) {
const handleMatchPress = useCallback(
async (entry: ExplorerEntryRef) => {
handleSelectEntry(entry);
if (entry.kind === "file") {
handleOpenFile(entry);
return;
}
try {
await openDesktopTarget({
editorId: fileManagerTarget.id,
workspacePath: normalizedWorkspaceRoot,
filePath: buildAbsoluteExplorerPath({
workspaceRoot: normalizedWorkspaceRoot,
entryPath: entry.path,
}),
});
} catch (cause) {
toast.error(
cause instanceof Error ? cause.message : t("workspace.fileExplorer.errors.revealFailed"),
);
}
// A folder has no tab to open: show it, expanded, in the tree.
await revealDirectory(entry.path, { select: true });
},
[fileManagerTarget, normalizedWorkspaceRoot, t, toast],
[handleOpenFile, handleSelectEntry, revealDirectory],
);
const handleRevealEntry = useCallback(
(entry: ExplorerEntryRef) => void fileActions.revealInFileManager(entry.path),
[fileActions],
);
const handleOpenDirectoryInEditor = useCallback(
(entry: ExplorerEntry) => openDirectoryInEditor?.open(entry.path),
(entry: ExplorerEntryRef) => openDirectoryInEditor?.open(entry.path),
[openDirectoryInEditor],
);
const handleDownloadEntry = useCallback(
(entry: ExplorerEntry) => {
(entry: ExplorerEntryRef) => {
if (entry.kind !== "file") {
return;
}
downloadFile({ fileName: entry.name, path: entry.path });
fileActions.download(entry.path);
},
[downloadFile],
[fileActions],
);
const handleNewEntry = useCallback(
@@ -656,6 +696,8 @@ export function FileExplorerPane({
if (!workspaceStateKey) {
return;
}
// The name is typed into a draft row in the tree.
clearFileFilter(workspaceStateKey);
if (parentPath !== ".") {
setExpandedPathsForWorkspace(workspaceStateKey, (currentPaths) =>
setExpandedDirectoryPath({
@@ -680,7 +722,7 @@ export function FileExplorerPane({
setPendingEdit(null);
}, []);
const handleRenameEntry = useCallback((entry: ExplorerEntry) => {
const handleRenameEntry = useCallback((entry: ExplorerEntryRef) => {
setPendingEdit({ type: "rename", entry });
}, []);
@@ -737,6 +779,7 @@ export function FileExplorerPane({
}
const renamedPath = payload.renamedPath;
void refreshFilterResults();
if (workspaceStateKey && entry.kind === "directory") {
const expandedRenamedPaths = Array.from(expandedPaths)
.filter((expandedPath) => isExplorerPathWithin(expandedPath, entry.path))
@@ -778,6 +821,7 @@ export function FileExplorerPane({
expandedPaths,
onOpenFile,
pendingEdit,
refreshFilterResults,
requestDirectoryListing,
renameEntry,
selectExplorerEntry,
@@ -790,7 +834,7 @@ export function FileExplorerPane({
);
const handleDuplicateEntry = useCallback(
async (entry: ExplorerEntry) => {
async (entry: ExplorerEntryRef) => {
try {
const payload = await duplicateEntry(entry.path);
if (!payload) {
@@ -801,15 +845,16 @@ export function FileExplorerPane({
return;
}
selectExplorerEntry(payload.duplicatedPath);
void refreshFilterResults();
} catch (cause) {
toast.error(cause instanceof Error ? cause.message : String(cause));
}
},
[duplicateEntry, selectExplorerEntry, t, toast],
[duplicateEntry, refreshFilterResults, selectExplorerEntry, t, toast],
);
const handleDeleteEntry = useCallback(
async (entry: ExplorerEntry) => {
async (entry: ExplorerEntryRef) => {
const confirmed = await confirmDialog({
title:
entry.kind === "directory"
@@ -835,11 +880,12 @@ export function FileExplorerPane({
if (selectedEntryPath === entry.path) {
selectExplorerEntry(null);
}
void refreshFilterResults();
} catch (cause) {
toast.error(cause instanceof Error ? cause.message : String(cause));
}
},
[deleteEntry, selectExplorerEntry, selectedEntryPath, t, toast],
[deleteEntry, refreshFilterResults, selectExplorerEntry, selectedEntryPath, t, toast],
);
const handleSortCycle = useCallback(() => {
@@ -906,7 +952,8 @@ export function FileExplorerPane({
const handleRefresh = useCallback(() => {
void refetchExplorer();
}, [refetchExplorer]);
void refreshFilterResults();
}, [refetchExplorer, refreshFilterResults]);
const sortLabels = useMemo(
() => ({
@@ -950,6 +997,13 @@ export function FileExplorerPane({
return rows;
}, [pendingEdit, treeRows]);
const revealScroll = useScrollToRevealedEntry({
stateKey: workspaceStateKey,
listRef: treeListRef,
rowPaths: useMemo(() => listRows.map(listRowPath), [listRows]),
onLayout: scrollbar.onLayout,
});
const showInitialLoading = resolveShowInitialLoading({
directories,
isExplorerLoading,
@@ -958,6 +1012,43 @@ export function FileExplorerPane({
const showBackFromError = Boolean(error && selectedEntryPath);
const errorRecoveryPath = useMemo(() => getErrorRecoveryPath(explorerState), [explorerState]);
const rowActions = useMemo<EntryRowActions>(
() => ({
onEntryPress: handleEntryPress,
onSelectEntry: handleSelectEntry,
onCopyPath: fileActions.copyPath,
onCopyRelativePath: fileActions.copyRelativePath,
onOpenInEditor: openDirectoryInEditor ? handleOpenDirectoryInEditor : undefined,
editorTargetName: openDirectoryInEditor?.targetName,
onRevealEntry: fileActions.revealTargetName ? handleRevealEntry : undefined,
revealTargetName: fileActions.revealTargetName ?? undefined,
onDownloadEntry: handleDownloadEntry,
onAddToChat,
onOpenFileToSide,
onNewEntry: fsEntryOpsEnabled ? handleNewEntry : undefined,
onRenameEntry: fsEntryOpsEnabled ? handleRenameEntry : undefined,
onDuplicateEntry: fsEntryDuplicateEnabled ? handleDuplicateEntry : undefined,
onDeleteEntry: fsEntryOpsEnabled ? handleDeleteEntry : undefined,
}),
[
fileActions,
fsEntryDuplicateEnabled,
fsEntryOpsEnabled,
handleDeleteEntry,
handleDownloadEntry,
handleDuplicateEntry,
handleEntryPress,
handleNewEntry,
handleOpenDirectoryInEditor,
handleRenameEntry,
handleRevealEntry,
handleSelectEntry,
onAddToChat,
onOpenFileToSide,
openDirectoryInEditor,
],
);
const renderTreeRow = useCallback(
(info: ListRenderItemInfo<ExplorerListRow>) => {
if (info.item.type === "draft") {
@@ -990,50 +1081,67 @@ export function FileExplorerPane({
expandedPaths={expandedPaths}
selectedEntryPath={selectedEntryPath}
isDirectoryLoading={isDirectoryLoading}
onEntryPress={handleEntryPress}
onSelectEntry={handleSelectEntry}
onCopyPath={handleCopyPath}
onCopyRelativePath={handleCopyRelativePath}
onOpenInEditor={openDirectoryInEditor ? handleOpenDirectoryInEditor : undefined}
editorTargetName={openDirectoryInEditor?.targetName}
onRevealEntry={fileManagerTarget ? handleRevealEntry : undefined}
revealTargetName={fileManagerTarget?.label}
onDownloadEntry={handleDownloadEntry}
onAddToChat={onAddToChat}
onOpenFileToSide={onOpenFileToSide}
onNewEntry={fsEntryOpsEnabled ? handleNewEntry : undefined}
actions={rowActions}
onCollapseDirectory={handleCollapseDirectory}
onRenameEntry={fsEntryOpsEnabled ? handleRenameEntry : undefined}
onDuplicateEntry={fsEntryDuplicateEnabled ? handleDuplicateEntry : undefined}
onDeleteEntry={fsEntryOpsEnabled ? handleDeleteEntry : undefined}
/>
);
},
[
expandedPaths,
fsEntryDuplicateEnabled,
fsEntryOpsEnabled,
handleCollapseDirectory,
handleCopyPath,
handleCopyRelativePath,
handleOpenDirectoryInEditor,
handleDeleteEntry,
handleDownloadEntry,
handleDraftCommit,
handleDuplicateEntry,
handleEditCancel,
handleEntryPress,
handleNewEntry,
handleRenameCommit,
handleRenameEntry,
handleRevealEntry,
handleSelectEntry,
isDirectoryLoading,
fileManagerTarget,
openDirectoryInEditor,
rowActions,
selectedEntryPath,
serverId,
workspaceId,
],
);
const matchActions = useMemo<EntryRowActions>(
// Creating inside a hit would put the draft row somewhere the user cannot see.
() => ({ ...rowActions, onEntryPress: handleMatchPress, onNewEntry: undefined }),
[handleMatchPress, rowActions],
);
const renderMatch = useCallback(
(match: FileFilterMatch, index: number) => {
if (pendingEdit?.type === "rename" && pendingEdit.entry.path === match.path) {
return (
<EntryNameInputRow
depth={0}
kind={match.kind}
initialName={match.name}
onCommit={handleRenameCommit}
onCancel={handleEditCancel}
/>
);
}
return (
<TreeRowItem
{...matchActions}
serverId={serverId}
workspaceId={workspaceId}
entry={match}
parentDirectory={match.directory}
onRevealInFiles={fileActions.revealInFiles}
depth={0}
isExpanded={false}
isSelected={selectedEntryPath === match.path}
loading={false}
testID={`file-filter-row-${index}`}
/>
);
},
[
fileActions,
handleEditCancel,
handleRenameCommit,
matchActions,
pendingEdit,
selectedEntryPath,
onAddToChat,
onOpenFileToSide,
serverId,
workspaceId,
],
@@ -1057,7 +1165,7 @@ export function FileExplorerPane({
});
}, [requestDirectoryListing]);
if (!hasWorkspaceScope) {
if (!workspaceStateKey || !hasWorkspaceScope) {
return (
<View style={styles.centerState}>
<Text style={styles.errorText}>{t("workspace.fileExplorer.states.unavailable")}</Text>
@@ -1075,6 +1183,11 @@ export function FileExplorerPane({
<FileExplorerPaneContent
error={error}
isCompact={isCompact}
serverId={serverId}
workspaceRoot={normalizedWorkspaceRoot}
filterStateKey={workspaceStateKey}
filterQuery={filterQuery}
renderMatch={renderMatch}
showInitialLoading={showInitialLoading}
showBackFromError={showBackFromError}
listRows={listRows}
@@ -1083,6 +1196,8 @@ export function FileExplorerPane({
isRefreshFetching={isRefreshFetching}
treeListRef={treeListRef}
scrollbar={scrollbar}
onListLayout={revealScroll.onLayout}
onScrollToIndexFailed={revealScroll.onScrollToIndexFailed}
renderTreeRow={renderTreeRow}
handleSortCycle={handleSortCycle}
handleToggleHiddenFiles={handleToggleHiddenFiles}
@@ -1149,6 +1264,12 @@ function RootCreationContextTarget({
interface FileExplorerPaneContentProps {
error: string | null;
isCompact: boolean;
serverId: string;
workspaceRoot: string;
filterStateKey: string;
/** While this is not empty, matches show in place of the tree. */
filterQuery: string;
renderMatch: (match: FileFilterMatch, index: number) => ReactElement;
showInitialLoading: boolean;
showBackFromError: boolean;
listRows: ExplorerListRow[];
@@ -1157,6 +1278,8 @@ interface FileExplorerPaneContentProps {
isRefreshFetching: boolean;
treeListRef: RefObject<FlatList<ExplorerListRow> | null>;
scrollbar: OverlayFlatListScrollbar;
onListLayout: (event: LayoutChangeEvent) => void;
onScrollToIndexFailed: (info: { index: number; averageItemLength: number }) => void;
renderTreeRow: (info: ListRenderItemInfo<ExplorerListRow>) => ReactElement;
handleSortCycle: () => void;
handleToggleHiddenFiles: () => void;
@@ -1172,6 +1295,11 @@ function FileExplorerPaneContent(props: FileExplorerPaneContentProps) {
const {
error,
isCompact,
serverId,
workspaceRoot,
filterStateKey,
filterQuery,
renderMatch,
showInitialLoading,
showBackFromError,
listRows,
@@ -1180,6 +1308,8 @@ function FileExplorerPaneContent(props: FileExplorerPaneContentProps) {
isRefreshFetching,
treeListRef,
scrollbar,
onListLayout,
onScrollToIndexFailed,
renderTreeRow,
handleSortCycle,
handleToggleHiddenFiles,
@@ -1328,46 +1458,67 @@ function FileExplorerPaneContent(props: FileExplorerPaneContentProps) {
</ToolbarButton>
</ToolbarControls>
</PaneContentToolbar>
<ContextMenu>
<RootCreationContextTarget enabled={Boolean(onNewEntryAtRoot)}>
{listRows.length === 0 ? (
<View style={styles.centerState}>
<Text style={styles.emptyText}>{emptyLabel}</Text>
</View>
) : (
<FlatList
ref={treeListRef}
style={styles.treeList}
data={listRows}
renderItem={renderTreeRow}
keyExtractor={listRowKeyExtractor}
testID="file-explorer-tree-scroll"
contentContainerStyle={styles.entriesContent}
onLayout={scrollbar.onLayout}
onScroll={scrollbar.onScroll}
onContentSizeChange={scrollbar.onContentSizeChange}
scrollEventThrottle={16}
showsVerticalScrollIndicator={!scrollbar.enabled}
initialNumToRender={24}
maxToRenderPerBatch={40}
windowSize={12}
<View {...{ onContextMenu: keepBrowserContextMenu }} style={styles.filterRow}>
<FileFilterField key={filterStateKey} stateKey={filterStateKey} />
</View>
{filterQuery ? (
<FileFilterResults
key={filterStateKey}
serverId={serverId}
workspaceRoot={workspaceRoot}
query={filterQuery}
showHiddenFiles={showHiddenFiles}
isCompact={isCompact}
renderMatch={renderMatch}
/>
) : (
<ContextMenu>
<RootCreationContextTarget enabled={Boolean(onNewEntryAtRoot)}>
{listRows.length === 0 ? (
<View style={styles.centerState}>
<Text style={styles.emptyText}>{emptyLabel}</Text>
</View>
) : (
<FlatList
ref={treeListRef}
style={styles.treeList}
data={listRows}
renderItem={renderTreeRow}
keyExtractor={listRowKeyExtractor}
testID="file-explorer-tree-scroll"
contentContainerStyle={styles.entriesContent}
onLayout={onListLayout}
onScrollToIndexFailed={onScrollToIndexFailed}
onScroll={scrollbar.onScroll}
onContentSizeChange={scrollbar.onContentSizeChange}
scrollEventThrottle={16}
showsVerticalScrollIndicator={!scrollbar.enabled}
initialNumToRender={24}
maxToRenderPerBatch={40}
windowSize={12}
/>
)}
{listRows.length > 0 ? scrollbar.overlay : null}
</RootCreationContextTarget>
{onNewEntryAtRoot ? (
<FileActionsContextMenuContent
fileKind="directory"
onNewFile={handleNewFileAtRoot}
onNewFolder={handleNewFolderAtRoot}
testIDPrefix="files-empty-area"
/>
)}
{listRows.length > 0 ? scrollbar.overlay : null}
</RootCreationContextTarget>
{onNewEntryAtRoot ? (
<FileActionsContextMenuContent
fileKind="directory"
onNewFile={handleNewFileAtRoot}
onNewFolder={handleNewFolderAtRoot}
testIDPrefix="files-empty-area"
/>
) : null}
</ContextMenu>
) : null}
</ContextMenu>
)}
</View>
);
}
// The pane suppresses the browser menu; the filter input wants it back for paste.
function keepBrowserContextMenu(event: { stopPropagation: () => void }) {
event.stopPropagation();
}
function deriveExplorerFields(state: AgentFileExplorerState | undefined) {
return {
directories:
@@ -1425,7 +1576,7 @@ function toggleDirectory({
requestDirectoryListing,
setExpandedPathsForWorkspace,
}: {
entry: ExplorerEntry;
entry: ExplorerEntryRef;
workspaceStateKey: string | null;
expandedPaths: Set<string>;
directories: Map<string, ExplorerDirectory>;
@@ -1462,22 +1613,8 @@ function TreeRowDispatcher({
expandedPaths,
selectedEntryPath,
isDirectoryLoading,
onEntryPress,
onSelectEntry,
onCopyPath,
onCopyRelativePath,
onOpenInEditor,
editorTargetName,
onRevealEntry,
revealTargetName,
onDownloadEntry,
onAddToChat,
onOpenFileToSide,
onNewEntry,
actions,
onCollapseDirectory,
onRenameEntry,
onDuplicateEntry,
onDeleteEntry,
}: {
serverId: string;
workspaceId?: string | null;
@@ -1486,55 +1623,23 @@ function TreeRowDispatcher({
expandedPaths: Set<string>;
selectedEntryPath: string | null;
isDirectoryLoading: (path: string) => boolean;
onEntryPress: (entry: ExplorerEntry) => void;
onSelectEntry: (entry: ExplorerEntry) => void;
onCopyPath: (path: string) => void | Promise<void>;
onCopyRelativePath: (path: string) => void | Promise<void>;
onOpenInEditor?: (entry: ExplorerEntry) => void;
editorTargetName?: string;
onRevealEntry?: (entry: ExplorerEntry) => void;
revealTargetName?: string;
onDownloadEntry: (entry: ExplorerEntry) => void;
onAddToChat?: (path: string) => void;
onOpenFileToSide?: (path: string) => void;
onNewEntry?: (parentPath: string, kind: "file" | "directory") => void;
onCollapseDirectory?: (path: string) => void;
onRenameEntry?: (entry: ExplorerEntry) => void;
onDuplicateEntry?: (entry: ExplorerEntry) => void;
onDeleteEntry?: (entry: ExplorerEntry) => void;
actions: EntryRowActions;
onCollapseDirectory: (path: string) => void;
}) {
const entry = row.entry;
const depth = row.depth;
const isDirectory = entry.kind === "directory";
const isExpanded = isDirectory && expandedPaths.has(entry.path);
const isSelected = selectedEntryPath === entry.path;
const loading = isDirectory && isDirectoryLoading(entry.path);
return (
<TreeRowItem
{...actions}
serverId={serverId}
workspaceId={workspaceId}
entry={entry}
depth={depth}
isExpanded={isExpanded}
isSelected={isSelected}
loading={loading}
onEntryPress={onEntryPress}
onSelectEntry={onSelectEntry}
onCopyPath={onCopyPath}
onCopyRelativePath={onCopyRelativePath}
onOpenInEditor={onOpenInEditor}
editorTargetName={editorTargetName}
onRevealEntry={onRevealEntry}
revealTargetName={revealTargetName}
onDownloadEntry={onDownloadEntry}
onAddToChat={onAddToChat}
onOpenFileToSide={onOpenFileToSide}
onNewEntry={onNewEntry}
depth={row.depth}
isExpanded={isDirectory && expandedPaths.has(entry.path)}
isSelected={selectedEntryPath === entry.path}
loading={isDirectory && isDirectoryLoading(entry.path)}
onCollapseDirectory={onCollapseDirectory}
onRenameEntry={onRenameEntry}
onDuplicateEntry={onDuplicateEntry}
onDeleteEntry={onDeleteEntry}
testID={`file-explorer-row-${index}`}
/>
);
@@ -1767,6 +1872,25 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
userSelect: "none",
},
matchName: {
flexShrink: 1,
minWidth: 0,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
userSelect: "none",
},
matchDirectory: {
flex: 1,
minWidth: 0,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
userSelect: "none",
},
filterRow: {
flexDirection: "row",
paddingHorizontal: theme.spacing[1.5],
paddingTop: theme.spacing[2],
},
draftInput: {
flex: 1,
color: theme.colors.foreground,

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