Compare commits

...
Author SHA1 Message Date
paseo-bot[bot] 423178804f Keep OpenCode reply paragraphs from running together (#11745)
* fix(opencode): keep reply paragraphs separate across text parts

OpenCode can put multiple text parts in one assistant message. Preserve their paragraph boundary when Paseo joins the streamed chunks or replays history.

* refactor(opencode): name timeline text arguments

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 13:12:52 +00:00
KiritoXD 5f3396fec0 Reject malformed label filters in agent listings (#11707) 2026-12-02 12:42:43 +00:00
Mohamed Boudra 45dfc2b98b Store durable agent message queues in paseo.db (#11740)
* refactor(server): store durable agent message queues in paseo.db

Move AgentMessageQueueStore persistence from per-recipient JSON files under $PASEO_HOME/agent-queues/ into a modular SchemaModule (agent_message_queues) in the existing SQLite daemon database (paseo.db).

Agent message queues have not shipped in a stable release yet, so switching before v0.19.0 avoids carrying permanent JSON-to-SQLite migration code and directory hygiene logic (corrupt/stray file handling). All queue transitions run inside synchronous DaemonDatabase transactions, preserving monotonic per-recipient sequence numbers, idempotency/conflict checks, depth caps, insertBeforeId ordering, urgency clearing, and lossless UTF-8/NUL/surrogate round-trips via JSON-encoded text columns.

* fix(server): JSON-encode queue ids, sessionMode, and fingerprint in SQLite

node:sqlite truncates raw TEXT columns at NUL bytes and replaces lone surrogates with U+FFFD, which could cause accepted messages with non-ASCII/surrogate messageIds to mismatch in markDispatching and stall in dispatching state. Store id, sessionMode, and fingerprint as JSON strings alongside text/payload columns and cover all lookup/mutation operations in the shared contract tests.
2026-12-02 19:14:27 +07:00
paseo-bot[bot] 6cee7dc10d fix(claude): keep goal acknowledgements after transcript import (#11733)
Claude records the goal acknowledgement as local command output. Replay that specific record so a restored conversation retains the same acknowledgement as the live turn.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 12:13:12 +00:00
Mohamed Boudra 5b2aa7e0ca fix(server): preserve session mode boundaries on direct sends and urgent queue releases (#11722)
* fix(server): preserve session mode boundaries on direct sends and urgent queue releases

Direct sends and urgent queue releases previously collected all queued messages up to the first provider switch and dispatched them as a single prompt under one session mode. A queued read-only or plan-mode message followed by a direct broader-permission prompt (or vice versa) was silently coalesced and executed under the wrong permission mode, and queued non-agent slash commands were wrapped into combined prompts.

Unify ordinary draining, urgent releases, and direct-send coalescing behind one shared dispatchGroups boundary rule covering provider switches, conflicting explicit session modes, and non-agent slash commands. When queued messages ahead of a direct send cannot share one dispatch, enqueue the direct prompt with urgency so the preceding boundary group runs first in FIFO order under its own mode and the direct prompt follows in a separate turn under its own mode.

* fix(server,app): persist urgency downgrades, preserve queue order, and defer receipts on queued direct sends

Address review findings on queued direct sends and split urgent releases:
- Defer MessageReceipts completion when sendDirect queues behind a boundary so receipts only complete via onDelivered.
- Persist clearUrgency on deferred groups before dispatching the first group so daemon restarts do not revive consumed interrupts.
- Support insertBeforeId in AgentMessageQueueStore and admit() so queued direct sends keep their slot ahead of queued provider switches and concurrent arrivals.
- Pass raw text and attachments from Session into DirectPrompt so delivery stays synchronous without re-parsing provider prompts or writing image files.
- Clear the optimistic composer timeline bubble in dispatchComposerAgentMessage when a direct send or switch returns deliveryStatus: queued.
- Remove new barrel re-exports from agent-messages/index.ts and await receipt.dispatched directly in delivery.test.ts.

* fix(server,app): dedupe retried queued direct sends, settle queued switch draft, and avoid eager image writes

Address follow-up review findings:
- Dedupe retried direct sends in sendDirect when direct.messageId is already queued in memory (with fingerprint conflict check) so retries return the existing queued receipt instead of duplicating or interrupting.
- Settle the staged provider switch draft via onProviderSwitchQueued in dispatchComposerAgentMessage when a direct switch returns deliveryStatus: queued.
- Only persist inline images via Session.queuedAttachments on direct sends when the recipient queue is non-empty, avoiding unused uploads on empty queues.
- Remove conditional assertion from delivery.test.ts using expectQueuedReceipt helper.

* fix(server): resolve inline direct-send attachments lazily inside queue save

Remove the racy Session.list(agentId) pre-check by passing a lazy resolveAttachments callback into DirectPrompt. Delivery admits the item into its exact in-memory slot synchronously and runs resolveAttachments inside item.saved only when the direct send actually queues behind a boundary, keeping both memory and store order aligned ahead of concurrent arrivals while writing zero files on immediate direct sends.

* fix(server): preserve live hold/withdraw state and store order across concurrent lazy saves

After awaiting lazy attachment resolution in save():
- Skip persisting if the message was withdrawn or rejected during the wait, and read current item.held and item.urgency rather than stale pre-await values.
- Insert before the first already-persisted successor in inbox.messages (tracked via item.persisted) so out-of-order upload completions still preserve admission order in the store.

* fix(server): close provider-switch, implicit-mode, and stray queue-file edge cases

- Respect direct providerSwitch boundaries in boundaryOfDirect()/canCoalesceDirect() so unheld messages or explicit-mode messages are not coalesced onto the target provider, while preserving Stop-held unset-mode queue carry-over.
- Treat any explicit sessionMode differing from an earlier group's mode (including undefined) as a dispatch boundary so later explicit-mode sends never retroactively promote earlier implicit-mode queued messages.
- Validate queue filename stems in createJsonAgentMessageQueueStore.listAll() before loading so stray .json files with invalid recipient ID stems are logged and ignored instead of aborting daemon startup.

* test(server): extract shared mode-boundary daemon E2E helper
2026-12-02 18:24:22 +07:00
Mohamed Boudra f576407576 fix(database): harden SQLite daemon storage defaults and statement caching (#11726)
* fix(database): harden SQLite daemon storage defaults and statement caching

Hardens the daemon SQLite layer before v0.19.0 creates paseo.db files in the wild:

- Enable PRAGMA auto_vacuum = INCREMENTAL on empty databases (page_count = 0) before creating page 1, so space reclamation never requires a blocking full VACUUM later.
- Bypass the prepared statement cache when bound string/binary parameters exceed 64 KiB (node:sqlite lacks clearBindings() and retains the last bound buffer in native memory), cap the cache with a 256-entry LRU, and evict statements on execution or iteration errors.
- Guard savepoint rollback with connection.isTransaction so SQLite auto-rollbacks (e.g. SQLITE_FULL/SQLITE_IOERR or ON CONFLICT ROLLBACK) preserve the original error instead of masking it with 'no such savepoint'.
- Probe schema_versions read-only before running mutating PRAGMAs so older daemons reject newer databases without altering page 1 or creating WAL sidecars, and pre-create missing database files atomically with O_CREAT|O_EXCL at 0o600 without opening existing inodes.
- Raise busy_timeout to 5000ms and set synchronous = NORMAL + checkpoint_fullfsync = ON on both the main connection and WalCheckpointer, set temp_store = MEMORY on main, keep a 10,000-page wal_autocheckpoint backstop while off-thread checkpointing is active, and skip WalCheckpointer if SQLite does not enter WAL mode.

* refactor(database): remove test-only accessors and harden lock test coordination

Addresses review feedback:
- Keep SqliteDaemonDatabase private with no test-only accessors and test statement cache bypass, saturation, and error eviction through the public DaemonDatabase interface.
- Keep the journal_mode === 'wal' decision in openDaemonDatabase without repeating it in checkpointOffThread.
- Extract named IterateInput and WalCheckpointerInput interfaces for multi-field parameter objects.
- Coordinate WalCheckpointer exclusive-lock contention deterministically using 0ms-timeout probe workers instead of fixed sleeps.
2026-12-02 18:10:25 +07:00
paseo-bot[bot] b2b05b599e fix(app): keep workspace sorting available when a host is offline (#11728)
The sidebar restores cached workspaces before their host sends its feature list. Keep the time sorts available until a host is known to lack support.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 10:42:45 +00:00
Mohamed Boudra 8fc8cb51b4 fix(server): validate schedule IDs in ScheduleStore (#11727)
Validate schedule IDs against [a-zA-Z0-9_-]+ and verify directory containment in ScheduleStore, and map InvalidScheduleIdError to PaseoToolInputError in the agent tool catalog.
2026-12-02 17:23:07 +07:00
TheCouchCommanderandjamescordrey-ops 18dc910689 fix(gitea): resolve bracketed IPv6 workspace remotes through Tea logins (#11692)
* fix(gitea): resolve bracketed IPv6 workspace remotes through Tea logins

* fix(gitea): canonicalize IPv6 literals when matching Tea logins

---------

Co-authored-by: jamescordrey-ops <jamescordrey-ops@users.noreply.github.com>
2026-12-02 10:18:52 +00:00
Mohamed Boudra 711188aadc fix(omp): handle lone checkbox labels and form edge cases in ask history (#11706)
* fix(omp): handle lone checkbox labels and form edge cases in ask history

* fix(omp): show Yes for checked lone checkbox asks in history
2026-12-02 16:59:56 +07:00
Mohamed Boudra d207bc5a57 feat(plugin): expose untrusted on lifecycle hooks and harden worktree-include copies (#11709)
* feat(plugin): expose untrusted on worktree and workspace lifecycle hooks

* fix(worktree-include): skip untrusted worktrees and harden destination copies

* fix(worktree-include): allow tracked destination symlinks and match realpath in test

Check only parent directory symlinks before git check-ignore so tracked leaf symlinks in the destination worktree are skipped instead of aborting creation, while ignored leaf symlinks still fail before copying. Also compare sourceCheckout with createRealpathAwarePathMatcher in paseo-worktree-service.test.ts to handle Windows short/long path and separator differences.
2026-12-02 16:59:06 +07:00
Mohamed Boudra f3213a2259 fix(daemon): harden WAL checkpointer fallback and propagate provider history read errors (#11711)
* fix(daemon): keep a failed WAL checkpoint fallback from crashing the daemon

When the WAL checkpointer worker ends on its own, the exit handler re-enabled SQLite's auto-checkpoint with no guard. A throw there (closed connection) was an uncaught exception that ended the daemon. It now logs a warning. A failing close() during a failed open also no longer replaces the DatabaseOpenError.

* fix(daemon): bound WAL checkpointer failures and propagate provider history errors

* fix(claude): reject waiting history readers when rewind rebind transcript load fails

* fix(claude): skip unparseable JSONL lines exceeding max string length during replay
2026-12-02 16:58:34 +07:00
paseo-bot[bot]andClaude Opus 5.5 370afb86c6 Keep a newer New workspace draft typed while creation finishes (#11720)
Since #11660, text typed on the web is published to the draft store after
the next paint. When workspace creation finished inside that frame, the
cleanup still saw the old draft version, cleared the draft as sent, and the
clear also dropped the unpublished text. Reopening New workspace showed an
empty composer. The cleanup now publishes pending text before it compares.

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-12-02 09:44:37 +00:00
paseo-bot[bot] 6caf7f6653 fix(app): attach files pasted into the web composer (#11718)
The browser paste listener handled raster images and skipped other clipboard files. Send browser files through the same composer upload path as picked and dropped files.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 09:42:50 +00:00
Mohamed Boudra f4a6d7841c refactor(markdown): decompose renderer capabilities and tighten local image path checks (#11699)
Split MarkdownRenderer's external flag into destinations, forgeShorthand, and softBreaks, and consolidate local image path parsing in @getpaseo/protocol/path-utils to validate local drive, POSIX, and in-workspace UNC paths while rejecting out-of-workspace UNC paths, malformed file URIs, and Win32 device namespace paths.
2026-12-02 14:56:55 +07:00
paseo-ai[bot] 4db5d454cd fix: update lockfile signatures and Nix hash [skip ci] 2026-12-02 07:47:52 +00:00
b34d4f5c3f fix(daemon): clamp oversized images before they enter agent history (#5119)
* fix(daemon): clamp oversized images before they enter agent history

An image over 2000px does not just fail the turn that carries it. Anthropic
rejects the whole conversation from then on, every retry replays the poisoned
history, and there is no in-app way to repair the session — the user has to
hand-edit the agent's JSONL. A 4864x2524 Retina screenshot is enough.

Clamp pixels and bytes in the daemon, on the three paths that assemble a
prompt's image blocks. That also covers callers no client-side fix can reach:
`paseo agent send`, plugins, schedules, and direct WebSocket clients. pi only
resizes what its own tools read; images arriving over RPC pass through, which
is why the pi provider is affected too.

The strategy and decoder are pi's: Photon (Rust compiled to WASM, 2MB, no
native binaries). After scaling to fit, PNG is tried before any JPEG quality,
and a further scale step is taken only when no encoding makes the byte
budget. What reaches this path is mostly UI and code screenshots, which PNG
keeps sharp and small and JPEG smears; photos fall through to JPEG on their
own. EXIF orientation is applied first so a downscaled phone photo is not
delivered sideways.

WASM is deliberate: the daemon ships to five platforms with
`npmRebuild: false`, and a codec resolved per-platform is a codec that
silently resolves to nothing wherever CI did not build it.

GIF and SVG pass through untouched, and every failure path returns the
original attachment. A bounded image beats an unbounded one; both beat a
dropped one.

Refs #4635. Revives the location #820 chose, with a codec that ships.

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

* fix(daemon): bound image work before decoding, refuse what cannot be clamped

Read the declared size out of the container header — PNG, JPEG, WebP, GIF,
BMP — before the decoder is handed anything. A decompression bomb states
gigapixels in a few kilobytes, so measuring an attachment by decoding it was
the wrong way round. Past 50MP declared, 64MB encoded, or 100 images in one
prompt, the attachment is refused before anything is allocated for it, and an
attachment already inside the provider's limits is no longer decoded at all.

Stop swallowing failures. A decoder that fails to load, or a codec that fails
on an oversized attachment, used to forward the original — silently reaching
the state #4635 is about. Both now raise a typed error that fails one send and
leaves the session usable. An attachment whose container cannot be read is
still forwarded when it is within budget: an unknown format is not a defect.

Take a single object parameter in both public functions, per the server guide,
and yield between attachments so one prompt cannot hold the event loop for its
whole batch.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* fix(daemon): apply the image ceilings to GIF and SVG too

A format that must not be re-encoded is still a format with limits. Both
returned before any size check, so an oversized or over-budget one reached
history untouched and every later turn replayed it — the state this guard
exists to prevent, through the one door left open. They are now measured
against the same ceilings, and one that is past them fails the send: there is
no clamped version to send instead, because flattening an animation or
rasterising a vector is a different image, not a smaller one.

Declare the TIFF readers as functions and take a single object parameter in
`applyExifOrientation` and the clamp helper, per the server guide.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* chore(deps): reduce the lockfile change to the photon entry

The previous lockfile was regenerated with a newer npm, which deduplicated the
nested vitest trees under cli, desktop and relay and dropped rollup's peer
flags. None of that belongs to this change. Restore main's lockfile and add
only @silvia-odwyer/photon-node and its server dependency edge.

* fix(daemon): tighten the image clamp's ordering and per-step cost

- Preprocess images before buildSessionConfig in agent creation. That step
  can create a worktree or workspace, and a refused attachment must not
  leave one behind.
- Decide "never re-encode" from the bytes as well as the MIME type. A GIF
  labelled image/png, or an animated WebP, was decoded and flattened to its
  first frame; both now get the passthrough rules.
- Take each scale step from the previous step's output instead of the full
  source, and stop encoding the bottom JPEG quality twice per step. A 50MP
  source was resampled again on every step.
- Fail send_agent_message_request with a warning when an attachment is
  refused, instead of routing client input through handleAgentRunError.

* fix(app,server): verify picked image headers and clamp uploaded images in resolveAgentPrompt

- Fix mobile pickedAssetSupportedFormat so explicit unsupported mimeType/fileName never falls back to a .jpeg URI (fixes Android RawImageExporter copying AVIF/HEIC into .jpeg) and sniff the first 12 header bytes on native.
- Wire daemon image clamping into resolveAgentPrompt so uploaded role='image' attachments and inline images share one daemon clamping boundary, and correct mismatched raster MIME labels from magic bytes.
- Validate uploaded image attachments before provisioning workspaces or worktrees.

* Address review feedback on uploaded image clamping and creation pre-resolution

* Tighten image preprocessing helpers and fix EXIF parser edge cases

* Restore named option interfaces on public image preprocessing exports

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-02 14:38:07 +07:00
lukeandRoundRedDot 7bfdbbad2c fix(omp): show the question and chosen option for HTML-form asks (#11697)
Since 18.18.3 OMP's ask tool takes one HTML form ({ html }) instead of a
questions array, and OMP 19 reports the result as details.answers
({ name, question, answer }) beside the text "User answers: { name: value }".
mapOmpAskDetail only read the older questions/results shape, so a
finished ask recorded the label "Question" and the raw "User answers"
JSON: the question and the option text the user chose were lost from
the timeline and from history.

Read details.answers into the same "question\nanswer" text the older
shape produced. When a result carries only the values, read them against
the parsed form so each value shows as its option's text. While the ask
waits, or after it is interrupted, the row is named by the form's first
question.

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-12-02 14:30:26 +07:00
Vivek KalyanandMohamed Boudra 98c98d1017 fix(usage): let Claude Enterprise monthly spend pin to the sidebar (#11514)
* fix(usage): summarize Claude Enterprise extra usage and clean plan badge

* fix(usage): distinguish Monthly spend label, quiet balance-only warning, and split conditional test

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-02 14:28:22 +07:00
Mohamed BoudraandVivek Kalyan e9ea31ef3b feat(usage): show Codex individual spend limit amounts as Spend credits (#11702)
Show Codex spend_control.individual_limit amounts as a Spend credits UsageBalance using existing primitives.

Co-authored-by: Vivek Kalyan <hello@vivekkalyan.com>
2026-12-02 14:27:29 +07:00
paseo-bot[bot] 5a6e6d1918 test(server): verify Claude permission decisions on the event feed (#11698)
The permission tests pass their file checks but fail when they look for an event on an unrequested agent stream. Observe the permission resolution feed so each test verifies the decision the daemon publishes.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 07:13:13 +00:00
Matt CowgerandMohamed Boudra acd119743b fix(plugins): add requirements.app to split daemon and app minimums (#11494)
* fix(plugins): add requirements.app to split daemon and app minimums

* fix(plugins): name the app in requirements.app failures and cover app-only reinstall

When requirements.app is the failing range, the message now reads
"requires Paseo app <range>. Your app is <version>." A registry test locks
that a requirements.app-only edit unloads the installed plugin.

* test(plugins): split requirements.app cases so no test branches on runtime

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-02 13:50:22 +07:00
paseo-bot[bot]andClaude Opus 5.5 a7bc7ac759 Wait for the reloaded app to report presence in the notification settings test (#11694)
After a reload, the test started the finished agent before the app had
connected and sent its first heartbeat. The daemon then had no present
client and sent no in-app notification, so the test saw zero
notifications.

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-12-02 06:43:19 +00:00
paseo-bot[bot] 9b82a65f3d fix(cli): show the active model in agent inspection and listings (#11693)
The provider reports a concrete model ID in runtime info. Preserve that ID when it matches the legacy default sentinel used in saved configurations.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 06:42:52 +00:00
Mohamed Boudra d131b54230 Fix Markdown collapse and layout shifts on plugin store navigation (#11691)
* fix(app): eliminate Markdown collapse and layout shifts on plugin store navigation

Opening a plugin in Settings -> Plugins previously painted several unstable frames before settling:

- On cold web sessions, the MD4C WASM parser only initialized after the first MarkdownRenderer mounted. Replacing OverviewSkeleton before the parser was ready collapsed the overview SettingsCard from 94px to a 34px empty box for 1-3 frames before expanding to the README.
- PluginPage tracked container width with a raw onLayout handler instead of useContainerWidthBelow, so narrow desktop windows (< 700px content width) painted a squeezed two-column first frame and hidden background stack screens recorded width 0 and flashed a stacked layout on Back navigation.
- Clicking a plugin row or card waited until navigation mounted to fetch the detail document, while showing a 94px stub skeleton, a fabricated Updates · 1 count, a mid-card Platforms insertion, and a premature Related plugins section that jumped down when the README arrived.

Expose preloadMarkdownParser and isMarkdownParserReady from react-native-enriched-markdown so the gallery warms WASM on mount and PluginPage holds one SettingsCard skeleton until both README data and the parser are ready. Prefetch plugin details on hover and press-in, compute the initial stacked threshold synchronously from window width while ignoring hidden zero-width measurements, size the overview skeleton to document proportions, defer the Updates count and Related plugins until detail resolves, and place Platforms after Updated.

* refactor(app): use named options and DSL helpers in plugin gallery navigation

* test(e2e): wait for registry detail response before clicking prefetched plugin
2026-12-02 13:39:43 +07:00
Matchy c75b718b2d fix(usage): prefer live Claude profile plan over credential snapshot (#11685)
Claude Code writes subscriptionType and rateLimitTier into
.credentials.json at sign-in and does not refresh them after a plan
change. Meanwhile GET /api/oauth/profile already returns live
organization.organization_type and organization.rate_limit_tier on the
account verification call.

Parse those fields from the profile response, resolve planLabel from the
live profile when present, and fall back atomically to the credential
snapshot only when the profile omits them so live and stale fields are
never mixed. Restrict rateLimitTier suffixes to multiplier tokens like
5x or 20x so default_claude_ai formats as "Pro" instead of "Pro ai".

Fixes #11668
2026-12-02 06:12:44 +00:00
Mohamed Boudra 3e2179cbc9 fix(copilot-usage-source): scope gh hosts.yml token lookup to github.com (#11689) 2026-12-02 13:02:44 +07:00
Mohamed Boudra 20755f5097 fix(server): restrict loopback alias origin check to canonical hosts (#11686) 2026-12-02 12:42:18 +07:00
Chirag Singhal 1fe9905fa3 fix: preserve rebound terminal routes on stale disposal (#10433) 2026-12-02 05:12:45 +00:00
Mohamed Boudra 211416b8eb feat(opencode): support conversation-only rewind on OpenCode v2 (#11675)
* feat(opencode): support Rewind conversation on OpenCode v2

OpenCode v2 stages a revert with files: false, which drops messages from the
target onward without restoring workspace files. Share one revert helper
between revertBoth (files: true) and the new revertConversation (files: false).

* refactor(opencode): pass single object parameter to OpenCodeV2Session.revert
2026-12-02 12:06:06 +07:00
Mohamed Boudra ab5e1d6fcb fix(app): wait for host connection before loading Files and related queries (#11679)
* fix(app): wait for host connection before loading Files and related queries

PR #11328 moved listWorkspaceExplorerDirectory out of useFileExplorerActions, removing the incidental client dependency that previously re-triggered FileExplorerPane initialization once the host finished connecting. Because FileExplorerPane had no connection gate, mounting while connecting wrote Host is not connected and stayed stuck after the host came online.

Gate FileExplorerPane and FileFilterResults on useHostRuntimeClient and useHostRuntimeConnectionStatus so they wait in a loading state while connecting and load automatically once online, and add useHostRuntimeIsConnected gates to the reconnect-vulnerable retry:false queries and observers (useAgentSkills, WorktreeSetupCalloutSource, add-project searches, useFileHandle/FilePane, ProviderSubagentPanel).

* refactor(app): let OwnedSubscription remain the sole reconnect owner in useFileHandle

subscribeFile already uses an OwnedSubscription that waits for connection and delivers fresh snapshots after reconnect. Keeping setObserving(observing) avoids duplicating reconnect ownership across two layers while still using useHostRuntimeClient.
2026-12-02 12:05:47 +07:00
paseo-bot[bot]andChirag Singhal 5029998013 fix: preserve workspace list connection diagnostics (#11676)
Co-authored-by: Chirag Singhal <76880977+chirag127@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 04:42:39 +00:00
Mohamed Boudra 2719695236 Brand plugin sponsor buttons and document funding waterfall (#11674)
* feat(plugins): brand sponsor buttons and document funding waterfall

Add shared funding platform normalization in @getpaseo/protocol and
render platform-branded Sponsor buttons with custom SVG marks across
the paseo.sh plugin sidebar and in-app plugin gallery (light and dark
themes). Document the four-tier funding collection waterfall in English
and Simplified Chinese publishing guides.

* fix(plugins): guard alias lookup, keep URL hash/port in dedup, assert theme colors
2026-12-02 11:23:51 +07:00
paseo-bot[bot] dc66f296da fix(app): confirm before discarding New Agent drafts (#11660)
Closing a New Agent tab dropped its only layout reference while leaving the draft active. Reuse the unsaved-changes prompt and finalize the draft after confirmation. Clear old active drafts once the saved layout identifies which ones still have tabs.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 03:43:15 +00:00
f7ceb13bd7 Create fork pull requests against the repository selected by gh (#11436)
* Create fork pull requests against the repository selected by gh

* Keep the origin fallback when GitHub CLI has no default remote

* Honor only an explicit GitHub CLI PR destination

* Resolve the current origin owner for fork pull requests

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 03:42:44 +00:00
paseo-bot[bot] fdec437e07 test(e2e): wait for the daemon to finish removing Hoplite (#11667)
Settings hides a provider's row as soon as Remove is confirmed, before
the daemon answers the config patch. The catalog test read the daemon
config once right after the row left, so it raced the in-flight patch
and saw hoplite still enabled. Poll the config and the providers
snapshot until the removal lands.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 03:40:13 +00:00
SuhailandMohamed Boudra 67b5da3544 fix(antigravity): omit relayed subagent tool calls from parent timeline (#11535)
* fix(antigravity): omit relayed subagent tool calls from parent timeline

* fix(acp): keep excluded tool calls out of message boundaries and turn state

Excluded tool calls (`AcpOptions.includeToolCall` returning false) are now
stored as `included: false` instead of dropped, so a later
`session/request_permission` that sends only the tool call ID still shows
the earlier input on its approval card. They no longer clear
`lastAssistantMessage`, so `turnEnd` still sees a silent executor error
that a relayed subagent call follows (#10885). They add no timeline row,
are not terminalized at turn end, and never keep the turn open. The
include decision is made once per call, on its first update.

Documents `includeToolCall` in the SDK and the provider guide, and adds
regression tests for the runtime and for Antigravity's relayed
`<uuid>:call_<id>` calls in Full access and Default modes.

Fixes #11541

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-02 10:26:25 +07:00
paseo-bot[bot]andChirag Singhal 197e84c337 fix: expose unconfirmed terminal cleanup in daemon status (#11658)
Co-authored-by: Chirag Singhal <76880977+chirag127@users.noreply.github.com>
2026-12-02 02:42:59 +00:00
Vivek Kalyan 4d9bc25a1d fix(usage): omit null Codex credit balances instead of coercing to zero (#11515) 2026-12-02 02:42:39 +00:00
paseo-bot[bot]andBrandon Elliott 910e65d8b2 fix(server): install registry plugins when npm omits lockfile URLs (#11656)
Managed plugin installs require a lockfile entry with a registry URL. Ask npm to emit that URL for the staged install so a user setting cannot remove it.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>
2026-12-02 01:42:36 +00:00
Mohamed Boudra 12e7f1fab1 Hide the keyboard by dragging the chat down on iOS or tapping empty space (#11625)
On iOS the chat list uses interactive keyboard dismissal: a drag that
reaches the keyboard pulls it down with the finger, and the composer
rides on its edge. The release-velocity flick still dismisses on both
platforms.

The chat list now keeps taps for the control under the finger. A link,
tool call, or copy button acts on the first tap instead of only closing
the keyboard. A tap on text or empty space still closes it.

On a new agent's empty draft, the panel wrappers no longer hide the dock
background from taps, so tapping empty space closes the keyboard there.

Closes #8775
2026-12-02 08:26:06 +07:00
paseo-bot[bot] bbdc3e326d fix(app): keep Import Session errors visible during Retry (#11654)
A retry clears the query error when the first request left no response. Cache the listing outcome so the provider row keeps its error until the new request settles.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-02 01:12:36 +00:00
SunicemanandShane Su bac45474de Include the tracked fork owner when polling a newly pushed workspace branch (#11441)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-12-02 00:42:47 +00:00
paseo-bot[bot]andClaude Opus 5.5 e928961472 Unmount a bottom sheet dismissed before its open animation starts (#11632)
* fix(app): dismiss a hidden bottom sheet that lands open after an interrupted open

The visibility tracker ignored an open detent when it had already moved to
closed. An open interrupted early reports -1, so an owner that hid the
sheet in that window left it closed in the tracker but open on screen.

* fix(app): unmount a bottom sheet dismissed before its open animation starts

Gorhom's BottomSheetModal sent a dismiss that arrived while the modal was
still INITIAL to BottomSheet.forceClose. The sheet still sat at its closed
position, so forceClose set isForcedClosing and animateToPosition returned
early: nothing cleared the flag, the mount animation was then skipped, and
the modal stayed mounted in DISMISSING with no onChange or onDismiss. Treat
INITIAL like CLOSED and unmount at once.

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

* fix(app): apply the INITIAL dismiss fix to Gorhom's src copy for native bundles

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

---------

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-12-02 00:00:59 +00:00
ralstonandpaseo-bot[bot] 83b80351f7 fix(server): stop probing provider snapshot targets whose workspace directory is gone (#11646)
* fix(server): stop probing provider snapshot targets whose workspace directory is gone

Background refreshes warmed every snapshot target ever seen, including archived workspaces whose worktrees were deleted. Each probe of a missing cwd ran into the provider's ready timeout while holding a slot in the per-provider discovery limiter, so a new agent's provider check queued behind them for minutes. Refreshes now drop targets whose directory no longer exists and warm only the rest.

Fixes #11643

* fix(server): keep targets with waiting reads and bound directory checks when pruning

A refresh no longer forgets a missing workspace target while a read is waiting on its probe, so the read gets its own result instead of a fresh loading target. Each directory check is capped at 1s and shared per cwd, so a stalled network or FUSE mount keeps its target without holding up every other workspace's refresh or stacking blocked stats.

* Inject the workspace directory check in snapshot tests

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 23:42:41 +00:00
paseo-bot[bot] 6eba86db2f Keep local plugin reloads fast from large package directories (#11653)
* fix(plugins): keep local plugin reloads independent of daemon cwd

esbuild inherited the daemon working directory and repeatedly read large ancestor directories during import resolution. Use the plugin root for the build and its metafile paths.

* Retry temporary worktree cleanup in the auto-archive test

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 23:12:43 +00:00
Junsandpaseo-bot[bot] f83c3bab70 Preserve Codex activity timestamps on reopen (#10760)
* Preserve Codex activity timestamps on reopen

* refactor(server): align reopen timestamp fix with server conventions

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 21:42:41 +00:00
Galaxy Roamingandpaseo-bot[bot] 535f3d36d0 fix(server): make concurrent archiveAgent calls idempotent (#10590)
* fix(server): make concurrent archiveAgent calls idempotent

* Share the outcome of overlapping agent archives

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 21:13:02 +00:00
paseo-bot[bot] 32fe3074a0 Retry Pi agent creation after an extension conflict is resolved (#11642)
* fix(server): retry failed provider catalogues when creating agents

A failed Pi extension probe could block agent creation after the user fixed the project. Let an explicit workspace lookup retry the failed discovery without starting extra probes on passive reads.

* Limit provider catalogue retries to named lookups

* Name the provider retry option

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 20:42:44 +00:00
SunicemanandShane Su 5b1ccba548 Probe the full Codex command for version-gated features (#11221)
Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
2026-12-01 20:12:42 +00:00
paseo-bot[bot] 6cffd3994d fix(app): keep image selections through Android Activity recreation (#7734)
Keep in-flight Expo activity-result callbacks in the live AppContext until the picker returns, then release the detached registration. Run the lifecycle regression tests with the Android module suite.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 18:42:48 +00:00
paseo-bot[bot] 4101519112 test(server): verify stale sockets expire after reconnect (#11622)
Session pongs go to the requesting socket, so the replacement cannot fill the original socket’s send queue with pings. Exercise lease expiry and verify that the replacement keeps working.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 17:13:15 +00:00
paseo-bot[bot]andLouis Deconinck da58a57998 Recover Stop for unresponsive Pi and OMP agents (#11618)
* fix(server): recover Stop for unresponsive Pi and OMP agents

Keep turn ownership until the provider acknowledges Stop or its process exits. Resume the saved session when the user sends the next prompt.

Co-authored-by: Louis Deconinck <LouisDeconinck@users.noreply.github.com>

* Fix Pi and OMP Stop follow-up behavior

Keep idle recovery distinct from user Stop and reload Pi before applying settings to a stopped session. Force-stop a timed-out provider tree while its tool processes are still discoverable. Wait for both processes to exit in the newer-worker Windows CI test.

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Louis Deconinck <LouisDeconinck@users.noreply.github.com>
2026-12-01 17:12:44 +00:00
paseo-bot[bot]andMarcel W. Wysocki f76fd024fb Resolve full agent UUIDs without scanning history (#11617)
* Resolve full agent IDs without paging through archived agents

* test(server): guard direct lookup of stored agent UUIDs

Exercise a single-agent fetch when the archived agent has no project record. Count full scans while using the real daemon storage.

Co-authored-by: Marcel W. Wysocki <maci.stgn@gmail.com>

---------

Co-authored-by: Marcel W. Wysocki <maci.stgn@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 16:42:50 +00:00
2f7e22e621 Release inactive workspace composers during repeated switches (#11613)
* fix(app): release inactive workspace decks and bound retention

* Keep workspace expiry on the live clock

Preserve the existing retention limits and cover expiry while switching workspaces in the compiled app.

Co-authored-by: Sergey S. Volkov <16340911+js2me@users.noreply.github.com>

---------

Co-authored-by: Сергей Волков <ser.volkov@vk.team>
Co-authored-by: Sergey Volkov <js2me@outlook.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Sergey S. Volkov <16340911+js2me@users.noreply.github.com>
2026-12-01 16:12:47 +00:00
paseo-bot[bot] 9592f88fdf Make OMP idle-deadline tests independent of runner speed (#11612)
The provider idle deadline compares Date.now() with the last provider
event. Two tests measured that silence with real delays, so a slow
Windows runner stretched a 50 ms delay past the 80 ms deadline and the
turn failed before the test retried. Freeze Date in those tests and
advance it explicitly.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 15:48:26 +00:00
paseo-bot[bot] 0d244c192a Keep finished Claude subagents completed after reopening (#11602)
* fix(claude): keep completed subagents after reopening

A stop inferred during restart could overwrite the saved completion for the same SendMessage resume. Preserve the completion when the transcript proves that the latest successful resume finished.

* Test the timeline toast with a delayed reply

* Name the replay and timeline test arguments

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-01 14:42:42 +00:00
263 changed files with 15082 additions and 1905 deletions
+2 -2
View File
@@ -178,9 +178,9 @@ the switch. Promoting the switch cuts the running turn once the target is known
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
the message and holds the queue; the reason is in the daemon log.
The queue is saved in `$PASEO_HOME/agent-queues/` ([data model](data-model.md#directory-layout)),
The queue is saved in `$PASEO_HOME/paseo.db` ([data model](data-model.md#agent-message-queues)),
and a message is saved before its receipt is sent. Inline images are first saved as uploads, so the
queue file holds references. An empty message is refused, and a recipient holds at most 100
queue holds references. An empty message is refused, and a recipient holds at most 100
messages.
A message is marked `dispatching` before the provider can receive it and removed when the provider
+9 -5
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo persists most stores as JSON files, and agent timelines and agent message queues in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -60,9 +60,6 @@ $PASEO_HOME/
│ └── {agentId}.json # One file per agent
├── schedules/
│ └── {scheduleId}.json # One file per schedule
├── agent-queues/
│ ├── {agentId}.json # Undelivered messages for one agent; removed when empty
│ └── {agentId}.json.corrupt.{ms} # Unreadable queue file, set aside at startup
├── projects/
│ ├── projects.json # Project registry
│ ├── workspaces.json # Workspace registry
@@ -188,7 +185,7 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
(`packages/server/src/server/database/`). Agent timelines and agent message queues live here. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
@@ -222,6 +219,13 @@ of a streamed assistant or reasoning message is stored as one chunk per source e
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
### Agent message queues
`AgentMessageQueueStore` stores undelivered per-recipient messages in `agent_message_queue_items`
and monotonic per-recipient sequence counters in `agent_message_queue_recipients`. Message text and
structured payloads are stored as JSON strings so NUL bytes and lone surrogates round-trip through
`node:sqlite`. See [agent-lifecycle.md](agent-lifecycle.md).
---
## 2. Daemon Configuration
+6 -2
View File
@@ -2,7 +2,7 @@
Use `MarkdownRenderer` for chat replies, file previews, plans, pull requests and changelog content. It uses `react-native-enriched-markdown` on iOS, Android and web. Keep source adaptation and renderer configuration in `components/markdown`; consumers supply Markdown and, when needed, its file location.
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Chat owns paced reveal, the web render cap, message identity and list measurement. A completed message renders as one document. While streaming, the renderer keeps closed blocks in head parts and updates a separate tail, then reunites the text on completion. See [Markdown parsing cost](agent-stream-performance.md#markdown-parsing-cost) for the boundary and pacing constraints.
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Call `preloadMarkdownParser()` ahead of navigation or gate a loading skeleton on `useMarkdownParserReady()` (`packages/app/src/components/markdown/parser-ready.ts`) so cold web mounts do not paint an empty interim container. Chat owns paced reveal, the web render cap, message identity and list measurement. A completed message renders as one document. While streaming, the renderer keeps closed blocks in head parts and updates a separate tail, then reunites the text on completion. See [Markdown parsing cost](agent-stream-performance.md#markdown-parsing-cost) for the boundary and pacing constraints.
## Block spacing
@@ -14,7 +14,11 @@ Workspace file links use the shared file-link resolver. The workspace supplies i
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.
Compose the renderer's capabilities per surface instead of bundling them under one flag:
- `destinations="https"` restricts links and images to absolute `https://` destinations following the registry's overview contract in `packages/protocol/src/plugin-overview.ts` (which the website also uses). Any other destination renders as its label or alt text, no host files are read via `client.readFile`, and workspace path recognition is off so `Node.js` stays prose. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only `https://`.
- `forgeShorthand` (default `true`) controls whether `#12` / `owner/repo#12` references resolve against the workspace's `ForgeShorthandProvider`. Pull request comments keep `destinations="https"` with `forgeShorthand` enabled; plugin READMEs and the changelog disable `forgeShorthand` so they never link to whichever workspace happens to be open.
- `softBreaks` (`"break"` default, `"join"` for READMEs and changelogs) controls whether single newlines inside a paragraph become hard breaks or join into one line as they do on a 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).
+1 -1
View File
@@ -1 +1 @@
sha256-04BfmBEaEZy3ohSi3Z8S3/a3xBsLKhls+8mcjJ0Y2/A=
sha256-x6E6SY98/8pUNLomlPzSNedZ+ZKJPzsQeS9L455i+n0=
+7
View File
@@ -12136,6 +12136,12 @@
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/@silvia-odwyer/photon-node": {
"version": "0.3.4",
"resolved": "https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz",
"integrity": "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==",
"license": "Apache-2.0"
},
"node_modules/@sinclair/typebox": {
"version": "0.27.10",
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.10.tgz",
@@ -40615,6 +40621,7 @@
"@modelcontextprotocol/server": "2.4.0",
"@opencode-ai/sdk": "1.14.46",
"@opencode/client": "2.0.10",
"@silvia-odwyer/photon-node": "^0.3.4",
"@xterm/addon-serialize": "0.14.0",
"@xterm/addon-unicode-graphemes": "0.5.0-beta.330",
"@xterm/headless": "6.1.0-beta.334",
@@ -125,10 +125,17 @@ for (const theme of ["light", "dark"] as const) {
await expect(
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
).toHaveCount(0);
expect((await client.getDaemonConfig()).config.providers?.hoplite).toBeUndefined();
expect(
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "hoplite"),
).toBe(false);
// The row leaves the list once Remove is confirmed, before the daemon answers.
await expect
.poll(async () => (await client.getDaemonConfig()).config.providers?.hoplite)
.toBeUndefined();
await expect
.poll(async () =>
(await client.getProvidersSnapshot()).entries.some(
(entry) => entry.provider === "hoplite",
),
)
.toBe(false);
await writeFile(
testInfo.outputPath(`hoplite-removed-${theme}.json`),
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
@@ -27,6 +27,7 @@ import {
restoreViewedTimelineWithHeldResponse,
restoreViewedTimelineWithLiveRowsFirst,
reopenWithFreshnessCheckUnanswered,
reopenWithTimelineTailUnanswered,
seedStreamingReplyAgent,
sendPromptWhileDisconnected,
stopStreamingReply,
@@ -180,7 +181,7 @@ test.describe("Agent timeline resume", () => {
}
});
test("cold opens and display-only cache reloads stay textless, steady, and free of Updating messages", async ({
test("cold opens and display-only cache reloads keep loading steady and reserve Updating messages for slow replies", async ({
page,
}) => {
test.setTimeout(120_000);
@@ -189,21 +190,21 @@ test.describe("Agent timeline resume", () => {
try {
await watchColdAndReloadLoadingSurfaces(page);
await test.step("cold open fetches one tail without flashing Updating messages", async () => {
await test.step("cold open fetches one tail without showing a premature toast", async () => {
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
await openAgentTimeline(page, agent);
await expectTimelinePromptVisible(page, agent.newestPrompt);
await expectCleanLoadingSurfaces(page, gate, requests);
});
await test.step("display-only cached reload settles quietly without Updating messages", async () => {
await test.step("display-only cached reload shows Updating messages until the overdue tail arrives", async () => {
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.firstOlderPagePrompt);
await waitForDisplayOnlyTimelineCache(page, agent);
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
await page.reload();
await reopenWithTimelineTailUnanswered({ page, gate, agentId: agent.agentId });
await expectTimelinePromptVisible(page, agent.newestPrompt);
await waitForResumeAnswer(gate, requests);
gate.releaseHeldTimelineResponses();
await expectCleanLoadingSurfaces(page, gate, requests);
});
} finally {
@@ -21,6 +21,7 @@ import {
expectAttachButtonDisabled,
fillComposerDraft,
dropFileOnComposer,
pasteFilesIntoComposer,
sendDraftToQueue,
expectQueuedMessageButton,
startRunningMockAgent,
@@ -152,7 +153,7 @@ test.describe("Composer attachments", () => {
// needed before this can be exercised end-to-end.
});
test("attaches, previews, and removes an image before dropping a file", async ({
test("attaches files from the menu, clipboard, and drag and drop", async ({
page,
withWorkspace,
}) => {
@@ -185,6 +186,19 @@ test.describe("Composer attachments", () => {
await expectComposerFocused(page);
});
await test.step("paste a Markdown file into the composer", async () => {
const file = {
name: "notes.md",
mimeType: "text/markdown",
buffer: Buffer.from("# Clipboard notes"),
};
const handled = await pasteFilesIntoComposer(page, [file]);
await expect(page.getByText(file.name, { exact: true })).toBeVisible();
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
expect(handled).toBe(true);
await expectComposerDraft(page, "");
});
await test.step("dropping an image focuses the composer", async () => {
await blurComposerInput(page);
await expectComposerNotFocused(page);
@@ -192,6 +206,15 @@ test.describe("Composer attachments", () => {
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expectComposerFocused(page);
});
await test.step("paste a file and an image together", async () => {
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
const file = { ...TEST_JSON, name: "clipboard.json" };
await pasteFilesIntoComposer(page, [file, TEST_IMAGE]);
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
await expectAttachmentPill(page, "composer-image-attachment-pill");
});
});
test("dropped JSON file renders as a file attachment in New Workspace", async ({ page }) => {
@@ -1,6 +1,9 @@
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
import { writeFile } from "node:fs/promises";
import path from "node:path";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { openFileFromExplorer } from "../support/helpers/file-explorer";
import { waitForWorkspaceInReplicaCache } from "../support/helpers/replica-cache-storage";
import { openSettingsSection, clickSettingsBackToWorkspace } from "../support/helpers/settings";
import { expect, test } from "../support/fixtures";
import {
@@ -547,3 +550,64 @@ test("keeps the comment shortcut in the editor beside an Explorer agent", async
await workspace.cleanup();
}
});
async function restoreHostConnection(gate: Awaited<ReturnType<typeof installDaemonWebSocketGate>>) {
gate.holdNextServerMessage("status");
gate.restore();
await gate.waitForHeldServerMessage("status");
gate.releaseHeldServerMessage("status");
}
test("loads Files and file filter automatically once the host connects after launch or disconnect", async ({
page,
withWorkspace,
}) => {
const gate = await installDaemonWebSocketGate(page);
const workspace = await withWorkspace();
await writeFile(path.join(workspace.repoPath, "startup-repro.txt"), "hello\n", "utf8");
await test.step("open Files on the workspace before reloading", async () => {
await workspace.navigateTo();
const explorer = await ensureExplorerSidebar(page);
await openFilesPanel(page);
await expect(
explorer
.getByTestId("file-explorer-tree-scroll")
.getByText("startup-repro.txt", { exact: true }),
).toBeVisible();
await waitForWorkspaceInReplicaCache(page, workspace.workspaceId);
});
await test.step("reload while the host is unreachable and recover automatically on connect", async () => {
await gate.drop();
await page.reload();
await gate.waitForBlockedConnection();
const explorer = explorerSidebar(page);
await expect(explorer).toBeVisible();
await restoreHostConnection(gate);
await expect(
explorer
.getByTestId("file-explorer-tree-scroll")
.getByText("startup-repro.txt", { exact: true }),
).toBeVisible();
await expect(explorer.getByText("Host is not connected", { exact: true })).toHaveCount(0);
});
await test.step("filter Files while disconnected and recover automatically on reconnect", async () => {
const explorer = explorerSidebar(page);
await gate.drop();
await gate.waitForBlockedConnection();
await explorer.getByPlaceholder("Search files").fill("startup-repro");
await restoreHostConnection(gate);
await expect(
explorer.getByTestId("file-filter-results").getByText("startup-repro.txt", { exact: true }),
).toBeVisible();
await expect(explorer.getByText("Host is not connected", { exact: true })).toHaveCount(0);
});
});
@@ -199,6 +199,39 @@ test("shows listing failure details beside healthy sessions and retries the fail
}
});
test("keeps a request timeout visible while retrying the provider", async ({ page }) => {
const gate = await installDaemonWebSocketGate(page);
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 1280, height: 844 });
await page.clock.install();
await test.step("the first listings time out before any response reaches the sheet", async () => {
gate.setServerMessageSuppressed("fetch_recent_provider_sessions_response", true);
await flow.openFromWorkspaceHeader();
await expect
.poll(() => gate.getClientRequestCount("fetch_recent_provider_sessions_request"))
.toBeGreaterThanOrEqual(2);
await page.clock.fastForward(101_000);
await flow.expectProviderError("Claude");
await flow.expectProviderRequestTimeout();
gate.setServerMessageSuppressed("fetch_recent_provider_sessions_response", false);
});
await test.step("Retry keeps the timeout visible until Claude replies", async () => {
gate.holdNextClientRequest("fetch_recent_provider_sessions_request");
await flow.startProviderRetry("claude");
await gate.waitForHeldClientRequest();
await flow.expectProviderRetryPending("claude");
await flow.expectProviderError("Claude");
await flow.expectProviderRequestTimeout();
gate.releaseHeldClientRequest();
await flow.expectProviderRecovered("Claude");
await flow.expectRows({ first: [scenario.importSessionId] });
await flow.expectProviderError("Broken ACP");
});
});
test("Import Session keeps listings tied to their host during a switch and a pending import", async ({
page,
}) => {
@@ -0,0 +1,83 @@
import { expect, test, type Page } from "../support/fixtures";
import { expectComposerDraft, fillComposerDraft } from "../support/helpers/composer";
import { gotoWorkspace } from "../support/helpers/launcher";
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
import { waitForDraftComposer } from "../support/helpers/command-center-agent-controls";
import { seedWorkspace } from "../support/helpers/seed-client";
const openText = "Keep this open New Agent draft";
const orphanText = "Unreachable draft from an earlier version";
const existingAgentText = "Keep this archived conversation draft";
async function openDraftTab(page: Page): Promise<void> {
await runWorkspaceActionFromCommandCenter(page, "New agent");
await waitForDraftComposer(page);
}
async function persistedDraftTexts(page: Page): Promise<string[]> {
return page.evaluate(() => {
const drafts = JSON.parse(localStorage.getItem("paseo-drafts") ?? "{}").state?.drafts ?? {};
return Object.values(drafts).map(
(record) => (record as { input: { text: string } }).input.text,
);
});
}
async function seedOrphanBeforeUpgrade(page: Page): Promise<void> {
await page.evaluate(
({ orphan, archived }) => {
const makeDraft = (text: string) => ({
input: { text, attachments: [] },
lifecycle: "active",
updatedAt: Date.now(),
version: 1,
});
const envelope = JSON.parse(localStorage.getItem("paseo-drafts") ?? "{}");
envelope.state.drafts["draft:old-server:previously-closed-tab"] = makeDraft(orphan);
envelope.state.drafts["agent:old-server:archived-agent"] = makeDraft(archived);
localStorage.setItem("paseo-drafts", JSON.stringify(envelope));
localStorage.removeItem("paseo:orphaned-workspace-drafts-swept");
const nonce = localStorage.getItem("@paseo:e2e-seed-nonce");
if (nonce) localStorage.setItem("@paseo:e2e-disable-default-seed-once", nonce);
},
{ orphan: orphanText, archived: existingAgentText },
);
}
async function closeDraftWithShortcut(page: Page, answer: "cancel" | "discard"): Promise<void> {
const prompt = page.waitForEvent("dialog");
const shortcut = page.keyboard.press("Alt+Shift+w");
const dialog = await prompt;
expect(dialog.message()).toContain("Unsaved changes");
if (answer === "cancel") await dialog.dismiss();
else await dialog.accept();
await shortcut;
}
test("keeps open New Agent drafts through upgrade and confirms before discarding them", async ({
page,
}) => {
const workspace = await seedWorkspace({ repoPrefix: "discard-new-agent-draft-" });
try {
await gotoWorkspace(page, workspace.workspaceId);
await openDraftTab(page);
await fillComposerDraft(page, openText);
await expect.poll(() => persistedDraftTexts(page)).toContain(openText);
await seedOrphanBeforeUpgrade(page);
await page.reload();
await expectComposerDraft(page, openText);
await expect.poll(() => persistedDraftTexts(page)).not.toContain(orphanText);
await expect.poll(() => persistedDraftTexts(page)).toContain(existingAgentText);
await closeDraftWithShortcut(page, "cancel");
await expectComposerDraft(page, openText);
await closeDraftWithShortcut(page, "discard");
await expect.poll(() => persistedDraftTexts(page)).not.toContain(openText);
await openDraftTab(page);
await expectComposerDraft(page, "");
} finally {
await workspace.cleanup();
}
});
@@ -11,6 +11,7 @@ import {
installBrowserNotificationRecorder,
openNotificationSettings,
readRecordedBrowserNotifications,
reloadAndWaitForDevicePresence,
setNotificationSwitch,
setPluginNotificationSwitch,
} from "../support/helpers/notification-settings";
@@ -107,7 +108,7 @@ test.describe("Settings → Notifications and OS notification filtering", () =>
await test.step("enabling Agent finished persists across page reload and allows finished notifications", async () => {
await setNotificationSwitch(page, "Agent finished", true);
await page.reload();
await reloadAndWaitForDevicePresence(page);
await expectNotificationSwitchState(page, "Agent finished", {
checked: true,
disabled: false,
@@ -137,7 +138,7 @@ test.describe("Settings → Notifications and OS notification filtering", () =>
).toBeVisible();
await expectNotificationSubControlsDisabled(page, true);
await page.reload();
await reloadAndWaitForDevicePresence(page);
await expectNotificationSwitchState(page, "Enable notifications", {
checked: false,
disabled: false,
@@ -2,6 +2,10 @@ import path from "node:path";
import { expect } from "../support/fixtures";
import {
test,
expectInstantPrefetchedRelatedOpen,
expectStableDesktopBackToListing,
expectStableUncachedListingOpen,
expectStackedFirstFrameOnNarrowDesktop,
expectStillBrowsing,
installFromPage,
installListingFromRow,
@@ -80,3 +84,89 @@ test("shows scorecard progressive disclosure, updates, custom links, and related
await page.screenshot({ path: path.join(captureDir, "live-app-mobile-scorecard.png") });
}
});
test("renders branded sponsor buttons for single and stacked platforms in light and dark themes", async ({
page,
directoryHost,
}) => {
const captureDir = process.env.PASEO_CAPTURE_DIR;
await page.setViewportSize({ width: 1280, height: 1000 });
await page.emulateMedia({ colorScheme: "dark" });
await openDirectory(page, directoryHost);
await openListingPage(page);
const singleGithub = page.getByTestId("funding-button-github");
await expect(singleGithub).toBeVisible();
await expect(singleGithub).toContainText("Sponsor on GitHub");
await expect(singleGithub).toHaveCSS("background-color", "rgba(219, 97, 162, 0.1)");
await expect(singleGithub).toHaveCSS("border-top-color", "rgba(219, 97, 162, 0.32)");
await expect(singleGithub.locator("svg")).toHaveAttribute("fill", "#ea7bb3");
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "app-gallery-single-dark.png") });
}
await page.emulateMedia({ colorScheme: "light" });
await expect(singleGithub).toBeVisible();
await expect(singleGithub).toHaveCSS("background-color", "rgba(191, 57, 137, 0.08)");
await expect(singleGithub).toHaveCSS("border-top-color", "rgba(191, 57, 137, 0.3)");
await expect(singleGithub.locator("svg")).toHaveAttribute("fill", "#bf3989");
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "app-gallery-single-light.png") });
}
await page.getByTestId("plugin-related-acme/pr-radar").click();
const platforms = [
["github", "Sponsor on GitHub"],
["kofi", "Support on Ko-fi"],
["buymeacoffee", "Buy Me a Coffee"],
["opencollective", "Sponsor on Open Collective"],
["patreon", "Support on Patreon"],
["polar", "Sponsor on Polar"],
["liberapay", "Donate on Liberapay"],
["paypal", "Donate via PayPal"],
["custom", "Sponsor"],
] as const;
for (const [platform, label] of platforms) {
const btn = page.getByTestId(`funding-button-${platform}`).filter({ visible: true });
await expect(btn).toBeVisible();
await expect(btn).toContainText(label);
}
const stackedKofi = page.getByTestId("funding-button-kofi").filter({ visible: true });
await expect(stackedKofi).toHaveCSS("background-color", "rgba(217, 67, 64, 0.08)");
await expect(stackedKofi.locator("svg")).toHaveAttribute("fill", "#d94340");
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "app-gallery-stacked-light.png") });
}
await page.emulateMedia({ colorScheme: "dark" });
for (const [platform] of platforms) {
await expect(
page.getByTestId(`funding-button-${platform}`).filter({ visible: true }),
).toBeVisible();
}
await expect(stackedKofi).toHaveCSS("background-color", "rgba(255, 94, 91, 0.1)");
await expect(stackedKofi.locator("svg")).toHaveAttribute("fill", "#ff7a78");
if (captureDir) {
await page.waitForTimeout(300);
await page.screenshot({ path: path.join(captureDir, "app-gallery-stacked-dark.png") });
}
});
test("opens plugin pages without empty markdown collapse, stacked back flash, or layout shift", async ({
page,
directoryHost,
}) => {
await page.setViewportSize({ width: 1280, height: 960 });
directoryHost.setDetailDelayMs(250);
await openDirectory(page, directoryHost);
await expectStableUncachedListingOpen(page);
await expectInstantPrefetchedRelatedOpen(page, directoryHost);
await expectStableDesktopBackToListing(page);
await expectStackedFirstFrameOnNarrowDesktop(page);
});
@@ -2,6 +2,8 @@ import path from "node:path";
import type { Page, TestInfo } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { addConnectedHostsAndReload } from "../support/helpers/hosts";
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
import {
closeMobileAgentSidebar,
expectMobileAgentSidebarHidden,
@@ -141,6 +143,7 @@ async function withPaseoOwnedWorktree(
async function readCachedRowIds(
page: Page,
rowKind: "workspace" | "checkpoint",
hostServerId = getServerId(),
): Promise<string[]> {
return page.evaluate(
async ({ serverId, kind }) => {
@@ -169,7 +172,7 @@ async function readCachedRowIds(
database.close();
}
},
{ serverId: getServerId(), kind: rowKind },
{ serverId: hostServerId, kind: rowKind },
);
}
@@ -317,7 +320,60 @@ async function expectRecoveredWorkspacesAfterReload(
});
}
async function expectTimeSortingAvailable(page: Page): Promise<void> {
await page.getByLabel("Display preferences", { exact: true }).click();
await page.getByRole("menuitem", { name: /^Sort/ }).click();
await expect(page.getByRole("menuitem", { name: "Created", exact: true })).toBeVisible();
await expect(page.getByRole("menuitem", { name: "Last prompt", exact: true })).toBeVisible();
await page.getByRole("menuitem", { name: "Created", exact: true }).click();
await page.getByLabel("Display preferences", { exact: true }).click();
await expect(page.getByRole("menuitem", { name: /^Sort/ })).toContainText("Created");
await page.keyboard.press("Escape");
}
async function cacheSecondaryHostWorkspace(page: Page, serverId: string, workspaceId: string) {
await expect(page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`)).toBeVisible();
await expect.poll(() => readCachedRowIds(page, "workspace", serverId)).toContain(workspaceId);
}
test.describe("Sidebar workspace list", () => {
test("keeps time sorting when a host's cached workspaces load offline", async ({ page }) => {
test.setTimeout(120_000);
const laptop = await startIsolatedHostDaemon("sidebar-sort-laptop");
try {
const other = await startIsolatedHostDaemon("sidebar-sort-other");
try {
const workspace = await seedWorkspace({
repoPrefix: "sidebar-sort-laptop-",
port: laptop.port,
});
try {
await gotoAppShell(page);
const hosts = [
{ ...laptop, label: "Laptop" },
{ ...other, label: "Other host" },
];
await test.step("cache the laptop workspace while its host is online", async () => {
await addConnectedHostsAndReload(page, hosts);
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
await expectTimeSortingAvailable(page);
});
await test.step("reopen the sidebar with the laptop offline", async () => {
await laptop.close();
await addConnectedHostsAndReload(page, hosts);
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
await expectTimeSortingAvailable(page);
});
} finally {
await workspace.cleanup();
}
} finally {
await other.close();
}
} finally {
await laptop.close();
}
});
test("recovers missing workspaces from a damaged legacy cache after reload", async ({
page,
}, testInfo) => {
@@ -3,12 +3,17 @@ import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../support/fixtures";
import { createIdleAgent } from "../support/helpers/archive-tab";
import { expectComposerVisible } from "../support/helpers/composer";
import { clickNewTerminal, terminalSurfaceLocator } from "../support/helpers/launcher";
import {
clickNewChat,
clickNewTerminal,
terminalSurfaceLocator,
} from "../support/helpers/launcher";
import { renameModalInput } from "../support/helpers/rename";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { clickSettingsBackToWorkspace, openCompactSettings } from "../support/helpers/settings";
import { openSettings } from "../support/helpers/app";
import { gotoAppShell, openSettings } from "../support/helpers/app";
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
import {
clickFirstTerminalTab,
@@ -35,8 +40,12 @@ async function expectSameRenderedNode(
);
}
function isRenderedNodeConnected(node: Awaited<ReturnType<typeof captureRenderedNode>>) {
return node.evaluate((candidate) => candidate.isConnected);
}
async function expectNodeConnected(node: Awaited<ReturnType<typeof captureRenderedNode>>) {
expect(await node.evaluate((candidate) => candidate.isConnected)).toBe(true);
expect(await isRenderedNodeConnected(node)).toBe(true);
}
async function getSettingsShortcut(page: Page) {
@@ -50,6 +59,34 @@ async function waitForWorkspaceRoute(page: Page, route: string) {
}
test.describe("Workspace pane mounting", () => {
test("inactive composers expire while switching between other workspaces", async ({
page,
withWorkspace,
}) => {
const first = await withWorkspace({ prefix: "deck-expiry-first-" });
const second = await withWorkspace({ prefix: "deck-expiry-second-" });
const third = await withWorkspace({ prefix: "deck-expiry-third-" });
const oneMinute = 60_000;
await page.clock.install();
await gotoAppShell(page);
await selectWorkspaceInSidebar(page, first.workspaceId);
await clickNewChat(page);
const composer = await captureRenderedNode(
page.getByTestId("message-input-root").filter({ visible: true }),
);
await selectWorkspaceInSidebar(page, second.workspaceId);
await expect(page).toHaveURL(buildHostWorkspaceRoute(getServerId(), second.workspaceId));
await page.clock.fastForward(9 * oneMinute);
await expectNodeConnected(composer);
await selectWorkspaceInSidebar(page, third.workspaceId);
await expect(page).toHaveURL(buildHostWorkspaceRoute(getServerId(), third.workspaceId));
await page.clock.fastForward(2 * oneMinute);
await expect.poll(() => isRenderedNodeConnected(composer)).toBe(false);
});
test("workspace navigation keeps the existing agent composer mounted", async ({ page }) => {
test.setTimeout(90_000);
// Keep both split panes wide enough for the tab-rail interactions below.
+40 -14
View File
@@ -178,24 +178,50 @@ export async function attachFileFromMenu(
await (await chooserPromise).setFiles(file);
}
export async function dropFileOnComposer(
page: Page,
file: { name: string; mimeType: string; buffer: Buffer },
): Promise<void> {
const dataTransfer = await page.evaluateHandle(
({ name, mimeType, base64 }) => {
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
const droppedFile = new File([bytes], name, { type: mimeType });
interface TransferFile {
name: string;
mimeType: string;
buffer: Buffer;
}
function createFileTransfer(page: Page, files: TransferFile[]) {
return page.evaluateHandle(
(entries) => {
const transfer = new DataTransfer();
transfer.items.add(droppedFile);
for (const { name, mimeType, base64 } of entries) {
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
transfer.items.add(new File([bytes], name, { type: mimeType }));
}
return transfer;
},
{
name: file.name,
mimeType: file.mimeType,
base64: file.buffer.toString("base64"),
},
files.map(({ name, mimeType, buffer }) => ({
name,
mimeType,
base64: buffer.toString("base64"),
})),
);
}
export async function pasteFilesIntoComposer(page: Page, files: TransferFile[]): Promise<boolean> {
const clipboardData = await createFileTransfer(page, files);
try {
const input = composerInput(page);
await input.focus();
return await input.evaluate((element, transfer) => {
const event = new ClipboardEvent("paste", {
clipboardData: transfer,
bubbles: true,
cancelable: true,
});
return !element.dispatchEvent(event);
}, clipboardData);
} finally {
await clipboardData.dispose();
}
}
export async function dropFileOnComposer(page: Page, file: TransferFile): Promise<void> {
const dataTransfer = await createFileTransfer(page, [file]);
const composerRoot = page.getByTestId("message-input-root").filter({ visible: true }).first();
await expect(composerRoot).toBeVisible({ timeout: 10_000 });
@@ -132,11 +132,31 @@ export class ImportSessionFlow {
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
await this.page.getByTestId(`import-session-retry-${provider}`).click();
await this.startProviderRetry(provider);
await expect(this.page.getByTestId(`import-session-retry-${provider}`)).toBeEnabled();
await this.expectProviderError(label);
await expect(this.page.getByRole("progressbar")).toHaveCount(0);
}
async startProviderRetry(provider: string) {
await this.page.getByTestId(`import-session-retry-${provider}`).click();
}
async expectProviderRetryPending(provider: string) {
await expect(this.page.getByTestId(`import-session-retry-${provider}`)).toBeDisabled();
}
async expectProviderRequestTimeout() {
await expect(
this.page
.getByText("No response to fetch_recent_provider_sessions_request after 100000ms", {
exact: true,
})
.first(),
).toBeVisible();
}
async expectProviderRecovered(label: string) {
await expect(
this.page.getByText(`Could not load ${label} sessions`, { exact: true }),
).toHaveCount(0);
}
async startImport(id: string) {
await this.revealSession(id);
await this.page.getByTestId(rowTestId(id)).click();
@@ -1,4 +1,4 @@
import { expect, type Page } from "@playwright/test";
import { expect, type Page, type WebSocket } from "@playwright/test";
import { openSettingsSection } from "./settings";
export interface RecordedBrowserNotification {
@@ -75,6 +75,32 @@ export async function installBrowserNotificationRecorder(page: Page): Promise<vo
});
}
/**
* Reloads the app and waits until it has told the daemon this device is present.
*
* The daemon shows an attention notification only on a client that has sent a
* heartbeat. Settings render from local storage before the reloaded app connects,
* so an agent that finishes right after the reload finds no present client and
* no notification is shown.
*/
export async function reloadAndWaitForDevicePresence(page: Page): Promise<void> {
let presenceReported = false;
const watchHeartbeats = (socket: WebSocket) => {
socket.on("framesent", (frame) => {
if (typeof frame.payload === "string" && frame.payload.includes('"client_heartbeat"')) {
presenceReported = true;
}
});
};
page.on("websocket", watchHeartbeats);
try {
await page.reload();
await expect.poll(() => presenceReported).toBe(true);
} finally {
page.off("websocket", watchHeartbeats);
}
}
export async function readRecordedBrowserNotifications(
page: Page,
): Promise<RecordedBrowserNotification[]> {
@@ -31,7 +31,14 @@ export const LISTING = {
overview: "Directory example keeps a checklist beside your agents.",
};
export const test = base.extend<{ directoryHost: { serverId: string; port: number } }>({
export const test = base.extend<{
directoryHost: {
serverId: string;
port: number;
setDetailDelayMs: (ms: number) => void;
waitForDetailServed: (listingId: string) => Promise<void>;
};
}>({
directoryHost: async ({ e2eWorker }, provide) => {
void e2eWorker;
const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-directory-"));
@@ -42,7 +49,12 @@ export const test = base.extend<{ directoryHost: { serverId: string; port: numbe
pluginRegistryUrl: registry.url,
});
try {
await provide({ serverId: host.serverId, port: host.port });
await provide({
serverId: host.serverId,
port: host.port,
setDetailDelayMs: registry.setDetailDelayMs,
waitForDetailServed: registry.waitForDetailServed,
});
} finally {
await host.dispose();
}
@@ -161,26 +173,50 @@ function createRelatedFixtures(date: string) {
650,
],
] as const;
return specs.map(([id, name, description, installs]) => ({
id,
name,
description,
license: "MIT",
categories: ["tools"],
author: { github: "acme", name: "Acme" },
repository: { url: `https://github.com/${id}` },
artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) },
scorecardSummary: {
health: { grade: "good" },
review: { status: "passed", score: 4, noteCount: 0 },
},
media: [],
submittedAt: date,
reviewedAt: date,
updatedAt: date,
publishedAt: date,
installs,
}));
return specs.map(([id, name, description, installs]) => {
const entry: Record<string, unknown> = {
id,
name,
description,
license: "MIT",
categories: ["tools"],
author:
id === "acme/pr-radar"
? {
github: "acme",
name: "Acme",
bio: "Building developer workflow plugins for Paseo.",
website: "https://acme.dev",
}
: { github: "acme", name: "Acme" },
repository: { url: `https://github.com/${id}` },
artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) },
scorecardSummary: {
health: { grade: "good" },
review: { status: "passed", score: 4, noteCount: 0 },
},
media: [],
submittedAt: date,
reviewedAt: date,
updatedAt: date,
publishedAt: date,
installs,
};
if (id === "acme/pr-radar") {
entry.funding = [
{ platform: "github", url: "https://github.com/sponsors/acme" },
{ platform: "kofi", url: "https://ko-fi.com/acme" },
{ platform: "buymeacoffee", url: "https://buymeacoffee.com/acme" },
{ platform: "opencollective", url: "https://opencollective.com/acme" },
{ platform: "patreon", url: "https://patreon.com/acme" },
{ platform: "polar", url: "https://polar.sh/acme" },
{ platform: "liberapay", url: "https://liberapay.com/acme" },
{ platform: "paypal", url: "https://paypal.me/acme" },
{ url: "https://ifdian.net/a/acme" },
];
}
return entry;
});
}
async function startRegistry(listing: Record<string, unknown>) {
@@ -285,20 +321,52 @@ async function startRegistry(listing: Record<string, unknown>) {
readme: `# ${item.name}\n\n${item.description}`,
};
}
let detailDelayMs = 0;
const servedDetails = new Set<string>();
const detailWaiters = new Map<string, Array<() => void>>();
const markDetailServed = (requestUrl: string | undefined) => {
const match = requestUrl ? /^\/plugins\/(.+)\.json$/.exec(requestUrl) : null;
if (!match) return;
const id = match[1]!;
servedDetails.add(id);
const waiters = detailWaiters.get(id);
if (waiters) {
detailWaiters.delete(id);
for (const resolve of waiters) resolve();
}
};
const server = createServer((request, response) => {
const document = request.url ? documents[request.url] : undefined;
if (!document) {
response.writeHead(404).end();
return;
}
response.setHeader("Content-Type", "application/json");
response.end(JSON.stringify(document));
const respond = () => {
response.setHeader("Content-Type", "application/json");
response.end(JSON.stringify(document), () => markDetailServed(request.url));
};
if (detailDelayMs > 0 && request.url?.startsWith("/plugins/")) {
setTimeout(respond, detailDelayMs);
} else {
respond();
}
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Missing registry address");
return {
url: `http://127.0.0.1:${address.port}`,
setDetailDelayMs: (ms: number) => {
detailDelayMs = ms;
},
waitForDetailServed: (listingId: string) => {
if (servedDetails.has(listingId)) return Promise.resolve();
return new Promise<void>((resolve) => {
const list = detailWaiters.get(listingId) ?? [];
list.push(resolve);
detailWaiters.set(listingId, list);
});
},
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
};
}
@@ -372,3 +440,237 @@ export async function openFromInstalledTab(page: Page) {
await selectInstalledTab(page);
await openPluginPage(page, LISTING.name, "directory-example");
}
interface PluginFrameSample {
url: string;
stacked: boolean;
hasSkeleton: boolean;
updatesLabel: string | null;
overviewHeight: number | null;
overviewTextLen: number;
licenseY: number | null;
relatedY: number | null;
}
async function sampleFramesDuring(
page: Page,
{
action,
waitUntilSettled,
}: { action: () => Promise<void>; waitUntilSettled: () => Promise<void> },
): Promise<PluginFrameSample[]> {
await page.evaluate(() => {
const samples: PluginFrameSample[] = [];
const host = window as unknown as {
__pluginFrameSamples?: PluginFrameSample[];
__stopPluginFrameSampling?: () => void;
};
host.__pluginFrameSamples = samples;
let running = true;
host.__stopPluginFrameSampling = () => {
running = false;
};
const isVisible = (el: Element): boolean => {
const rect = el.getBoundingClientRect();
return rect.width > 0 && rect.height > 0;
};
const queryVisible = (selector: string): Element | null => {
const nodes = Array.from(document.querySelectorAll(selector));
for (let i = nodes.length - 1; i >= 0; i -= 1) {
if (isVisible(nodes[i]!)) return nodes[i]!;
}
return null;
};
const findVisibleText = (text: string): Element | null => {
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
let node: Node | null;
let match: Element | null = null;
while ((node = walker.nextNode())) {
if (
node.textContent?.trim() === text &&
node.parentElement &&
isVisible(node.parentElement)
) {
match = node.parentElement;
}
}
return match;
};
const findOverviewCard = (tabsEl: Element | null, stacked: boolean): Element | null => {
if (!tabsEl) return null;
const container = stacked
? (tabsEl.closest('[style*="overflow"]')?.parentElement ??
tabsEl.parentElement?.parentElement?.parentElement)
: tabsEl.parentElement?.parentElement;
if (!container) return null;
const visibleChildren = Array.from(container.children).filter(isVisible);
return visibleChildren[visibleChildren.length - 1] ?? null;
};
const roundRect = (el: Element | null) => el?.getBoundingClientRect() ?? null;
const record = () => {
const tabsEl = queryVisible('[data-testid="plugin-page-tabs"]');
const stacked = Boolean(queryVisible('[data-testid="plugin-page-tab-details"]'));
const updatesTabEl = queryVisible('[data-testid="plugin-page-tab-updates"]');
const skeletonEl = queryVisible('[data-testid="plugin-overview-skeleton"]');
const licenseRect = roundRect(findVisibleText("License"));
const relatedRect = roundRect(findVisibleText("Related plugins"));
const overviewCard = findOverviewCard(tabsEl, stacked);
const overviewRect = roundRect(overviewCard);
samples.push({
url: location.pathname,
stacked,
hasSkeleton: Boolean(skeletonEl),
updatesLabel: updatesTabEl?.textContent?.trim() ?? null,
overviewHeight: overviewRect ? Math.round(overviewRect.height) : null,
overviewTextLen: overviewCard?.textContent?.trim().length ?? 0,
licenseY: licenseRect ? Math.round(licenseRect.y) : null,
relatedY: relatedRect ? Math.round(relatedRect.y) : null,
});
if (running) requestAnimationFrame(record);
};
requestAnimationFrame(record);
});
await action();
await waitUntilSettled();
await page.evaluate(
() =>
new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
),
);
return page.evaluate(() => {
const host = window as unknown as {
__pluginFrameSamples?: PluginFrameSample[];
__stopPluginFrameSampling?: () => void;
};
host.__stopPluginFrameSampling?.();
return host.__pluginFrameSamples ?? [];
});
}
function assertOverviewNeverCollapsed(
frames: PluginFrameSample[],
{ minHeight }: { minHeight: number },
) {
const withOverview = frames.filter((frame) => frame.overviewHeight !== null);
expect(withOverview.length).toBeGreaterThan(0);
for (const frame of withOverview) {
expect(frame.hasSkeleton || frame.overviewTextLen > 0).toBe(true);
expect(frame.overviewHeight).toBeGreaterThanOrEqual(minHeight);
}
}
/** Opens the example listing without hovering first and verifies zero collapse or layout shift. */
export async function expectStableUncachedListingOpen(page: Page) {
const frames = await sampleFramesDuring(page, {
action: async () => {
await listingRow(page).getByText(LISTING.name, { exact: true }).click();
},
waitUntilSettled: async () => {
await expect(page.getByText(LISTING.overview, { exact: true })).toBeVisible();
},
});
const onPage = frames.filter((frame) => frame.url.endsWith(`/${LISTING.id}`));
expect(onPage.length).toBeGreaterThan(0);
for (const frame of onPage) {
expect(frame.stacked).toBe(false);
expect(frame.updatesLabel).not.toBe("Updates · 1");
}
assertOverviewNeverCollapsed(onPage, { minHeight: 200 });
const licensePositions = new Set(
onPage.map((frame) => frame.licenseY).filter((y): y is number => y !== null),
);
expect(licensePositions.size).toBe(1);
const relatedPositions = new Set(
onPage.map((frame) => frame.relatedY).filter((y): y is number => y !== null),
);
expect(relatedPositions.size).toBe(1);
}
/** Hovers a related plugin to prefetch it, clicks it, and asserts Markdown lands on frame 1. */
export async function expectInstantPrefetchedRelatedOpen(
page: Page,
{ waitForDetailServed }: { waitForDetailServed: (listingId: string) => Promise<void> },
) {
const relatedCard = page.getByTestId("plugin-related-acme/pr-radar").filter({ visible: true });
await relatedCard.hover();
await waitForDetailServed("acme/pr-radar");
// Allow the local daemon WebSocket response to reach the browser query cache.
await page.waitForTimeout(200);
const frames = await sampleFramesDuring(page, {
action: async () => {
await relatedCard.click();
},
waitUntilSettled: async () => {
await expect(pluginPageName(page)).toHaveText("PR Radar");
await expect(
page
.getByText("Monitors pull requests and CI checks across connected hosts.")
.filter({ visible: true })
.nth(1),
).toBeVisible();
},
});
const onPage = frames.filter((frame) => frame.url.endsWith("/acme/pr-radar"));
expect(onPage.length).toBeGreaterThan(0);
for (const frame of onPage) {
expect(frame.hasSkeleton).toBe(false);
expect(frame.overviewTextLen).toBeGreaterThan(0);
}
}
/** Goes back to the previous plugin page and asserts it stays two-column on every frame. */
export async function expectStableDesktopBackToListing(page: Page) {
const frames = await sampleFramesDuring(page, {
action: async () => {
await page.goBack();
},
waitUntilSettled: async () => {
await expect(pluginPageName(page)).toHaveText(LISTING.name);
},
});
const onPage = frames.filter((frame) => frame.url.endsWith(`/${LISTING.id}`));
expect(onPage.length).toBeGreaterThan(0);
for (const frame of onPage) {
expect(frame.stacked).toBe(false);
}
}
/** Opens a listing in a narrow desktop split (< 700px detail width) and asserts stacked frame 1. */
export async function expectStackedFirstFrameOnNarrowDesktop(page: Page) {
await page
.getByRole("button", { name: "Back to plugins", exact: true })
.filter({ visible: true })
.click();
await expect(listingRow(page)).toBeVisible();
await page.setViewportSize({ width: 920, height: 960 });
const frames = await sampleFramesDuring(page, {
action: async () => {
await page
.getByTestId("plugin-listing-acme/commit-diff")
.filter({ visible: true })
.getByText("Commit Diff", { exact: true })
.click();
},
waitUntilSettled: async () => {
await expect(pluginPageName(page)).toHaveText("Commit Diff");
await expect(
page
.getByText("Compact commit history and inline file tree diff viewer.")
.filter({ visible: true })
.nth(1),
).toBeVisible();
},
});
const onPage = frames.filter((frame) => frame.url.endsWith("/acme/commit-diff"));
expect(onPage.length).toBeGreaterThan(0);
for (const frame of onPage) {
expect(frame.stacked).toBe(true);
}
assertOverviewNeverCollapsed(onPage, { minHeight: 80 });
}
@@ -175,6 +175,22 @@ export async function reopenWithFreshnessCheckUnanswered(
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toBeVisible();
}
/** Reopens display-only history with the tail held until the app shows the outstanding update. */
export async function reopenWithTimelineTailUnanswered({
page,
gate,
agentId,
}: {
page: Page;
gate: DaemonWebSocketGate;
agentId: string;
}): Promise<void> {
gate.holdTimelineResponses(agentId);
await page.reload();
await gate.waitForHeldTimelineResponse();
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toBeVisible();
}
export async function answerFreshnessCheck(page: Page, gate: DaemonWebSocketGate): Promise<void> {
gate.releaseHeldClientRequest();
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
@@ -327,7 +343,6 @@ export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<st
interface LoadingSurfaceRecord {
loaderText: string[];
spinnerYsByTestId: Record<string, number[]>;
sawUpdatingToast: boolean;
}
declare global {
@@ -340,7 +355,6 @@ function recordLoadingSurfaces(): void {
const record: LoadingSurfaceRecord = {
loaderText: [],
spinnerYsByTestId: {},
sawUpdatingToast: false,
};
window.__loadingSurfaceRecord = record;
@@ -376,9 +390,6 @@ function recordLoadingSurfaces(): void {
record.spinnerYsByTestId[testId] = list;
}
}
if (document.querySelector('[data-testid="agent-updating-toast"]') !== null) {
record.sawUpdatingToast = true;
}
};
const start = () => {
@@ -399,18 +410,20 @@ function recordLoadingSurfaces(): void {
/** Records loading text, spinner Y positions, and any Updating messages toast from first paint. */
export async function watchColdAndReloadLoadingSurfaces(page: Page): Promise<void> {
await page.addInitScript(recordLoadingSurfaces);
await page.addInitScript(recordUpdatingToastTiming);
}
/** Asserts every loading surface stayed textless, unshifted, and free of Updating messages. */
/** Checks loading geometry and verifies the toast waits for a slow daemon reply. */
export async function expectCleanLoadingSurfaces(
page: Page,
gate: DaemonWebSocketGate,
before: TimelineRequestCounts,
): Promise<void> {
await waitForNextPaint(page);
await gate.waitForServerMessage(TIMELINE_RESPONSE, before.fetches + 1);
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
await expectToastWaitedForTheDaemon(page);
const record = await page.evaluate(() => window.__loadingSurfaceRecord as LoadingSurfaceRecord);
expect(record.loaderText, "loading states must not render visible text").toEqual([]);
expect(record.sawUpdatingToast, "Updating messages must not flash after chat loads").toBe(false);
for (const [testId, ys] of Object.entries(record.spinnerYsByTestId)) {
expect(
ys.length,
+3
View File
@@ -14,5 +14,8 @@ import { renderRootComponent } from "expo-router/build/renderRootComponent";
import { startWatchdog } from "./src/watchdog";
import { RootApp } from "./src/root-app";
import { sweepOrphanedWorkspaceDrafts } from "./src/workspace-tabs/sweep-orphaned-drafts";
startWatchdog();
void sweepOrphanedWorkspaceDrafts();
renderRootComponent(RootApp);
+1 -1
View File
@@ -41,7 +41,7 @@
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
"build:apk": "npm --prefix ../.. run build:apk",
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -1,7 +1,7 @@
import { useMemo } from "react";
import { useFetchQuery } from "@/data/query";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import type { GithubRepositoryChoice } from "./model";
import { resolveSearch, type SearchResult } from "./search-result";
@@ -19,8 +19,9 @@ export function useDirectorySearch(input: {
}): SearchResult<string> {
const { hostId } = input;
const client = useHostRuntimeClient(hostId ?? "");
const isConnected = useHostRuntimeIsConnected(hostId ?? "");
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
const enabled = Boolean(client && input.enabled);
const enabled = Boolean(client && isConnected && input.enabled);
const search = useFetchQuery({
queryKey: ["add-project-flow-directories", hostId, debouncedQuery],
queryFn: async () => {
@@ -64,8 +65,9 @@ export function useGithubRepositorySearch(input: {
}): SearchResult<GithubRepositoryChoice> {
const { hostId } = input;
const client = useHostRuntimeClient(hostId ?? "");
const isConnected = useHostRuntimeIsConnected(hostId ?? "");
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
const enabled = Boolean(client && input.enabled);
const enabled = Boolean(client && isConnected && input.enabled);
const search = useFetchQuery({
queryKey: ["add-project-flow-github", hostId, debouncedQuery],
queryFn: async () => {
@@ -69,4 +69,27 @@ describe("host agent skills", () => {
expect(result.current.supported).toBe(false);
expect(client.getAgentSkillsStatus).not.toHaveBeenCalled();
});
it("waits until the host is connected before fetching and fetches once online", async () => {
runtime.connected = false;
const client = {
getAgentSkillsStatus: vi.fn(async () => ({
state: "not-installed",
ops: [],
available: ["paseo"],
installed: [],
selection: { mode: "all" },
})),
};
runtime.clients.set("reconnecting-host", client);
const { result, rerender } = renderHook(() => useAgentSkills("reconnecting-host"), { wrapper });
expect(client.getAgentSkillsStatus).not.toHaveBeenCalled();
runtime.connected = true;
rerender();
await waitFor(() => expect(result.current.status?.available).toEqual(["paseo"]));
expect(client.getAgentSkillsStatus).toHaveBeenCalledOnce();
});
});
@@ -36,7 +36,7 @@ export function useAgentSkills(serverId: string) {
if (!client) throw new Error(t("settings.host.skills.unavailable"));
return client.getAgentSkillsStatus();
},
enabled: supported && client !== null,
enabled: supported && client !== null && connected,
retry: false,
dataShape: "value",
staleTimeMs: 0,
@@ -2,8 +2,9 @@
* Pure state machine for the chat history's flick-to-dismiss gesture.
*
* Native keyboardDismissMode cannot express this interaction: "on-drag"
* dismisses on the first pixel, while "interactive" is iOS-only. We therefore classify the list's existing scroll gesture at
* release instead of introducing a competing pan recognizer.
* dismisses on the first pixel, and iOS "interactive" only follows a finger
* that reaches the keyboard. We therefore classify the list's existing scroll
* gesture at release instead of introducing a competing pan recognizer.
*/
const DISMISS_VELOCITY_POINTS_PER_MS = 1.5;
@@ -0,0 +1,8 @@
import type { ScrollViewProps } from "react-native";
/**
* iOS lets the keyboard follow a drag that reaches it, as in Messages. The
* keyboard controller reports each frame of that drag, so the composer stays on
* the keyboard edge.
*/
export const NATIVE_KEYBOARD_DISMISS_MODE: ScrollViewProps["keyboardDismissMode"] = "interactive";
@@ -0,0 +1,7 @@
import type { ScrollViewProps } from "react-native";
/**
* Android has no interactive keyboard dismissal. The flick classifier in
* `model.ts` is the only drag that closes the keyboard there.
*/
export const NATIVE_KEYBOARD_DISMISS_MODE: ScrollViewProps["keyboardDismissMode"] = "none";
@@ -13,13 +13,15 @@ import {
recordScroll,
releaseDrag,
} from "./model";
import { NATIVE_KEYBOARD_DISMISS_MODE } from "./native-dismiss-mode";
type ScrollEvent = NativeSyntheticEvent<NativeScrollEvent>;
/**
* Owns the chat history's flick-to-dismiss behavior. The native stream only
* forwards the LegendList scroll lifecycle; removing this hook and those three
* calls removes the feature completely.
* Owns how the chat history closes the keyboard: a flick toward older messages,
* a drag into the keyboard on iOS, and a tap on content that no control claims.
* The native stream spreads the two keyboard props and forwards the LegendList
* scroll lifecycle; removing this hook and those calls removes the feature.
*/
export function useScrollKeyboardDismiss() {
const { shift } = useKeyboardShift();
@@ -53,5 +55,13 @@ export function useScrollKeyboardDismiss() {
Keyboard.dismiss();
});
return { onScroll, onScrollBeginDrag, onScrollEndDrag };
return {
keyboardDismissMode: NATIVE_KEYBOARD_DISMISS_MODE,
// "handled" lets links, tool calls, and copy buttons act on the first tap
// while the keyboard is open. A tap that no child claims still closes it.
keyboardShouldPersistTaps: "handled" as const,
onScroll,
onScrollBeginDrag,
onScrollEndDrag,
};
}
@@ -792,6 +792,8 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
onMomentumScrollBegin={handleMomentumScrollBegin}
onMomentumScrollEnd={handleMomentumScrollEnd}
scrollEventThrottle={16}
keyboardDismissMode={scrollKeyboardDismiss.keyboardDismissMode}
keyboardShouldPersistTaps={scrollKeyboardDismiss.keyboardShouldPersistTaps}
onContentSizeChange={handleContentSizeChange}
onItemSizeChanged={handleItemSizeChanged}
onReady={handleListPlaced}
@@ -147,6 +147,9 @@ function HostWorkspaceRouteContent() {
}
function WorkspaceDeck() {
// The compiler caches render-time Date.now() without this directive.
"use no memo";
const activeSelection = useActiveWorkspaceSelection();
const [retainedSelections, setRetainedSelections] = useState<RetainedWorkspaceSelection[]>(() =>
activeSelection ? [{ selection: activeSelection, inactiveSince: null }] : [],
@@ -1,4 +1,4 @@
import { getFileExtension } from "@/attachments/file-types";
import { getFileExtension, getMimeTypeFromPath } from "@/attachments/file-types";
import { copyDesktopAttachmentFile } from "@/desktop/attachments/desktop-file-commands";
import { readDesktopFileBase64 } from "@/desktop/attachments/desktop-preview-url";
@@ -8,6 +8,14 @@ export interface SelectedFile {
readBytes(): Promise<Uint8Array>;
}
export function selectedFileFromWebFile(file: File): SelectedFile {
return {
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
};
}
function base64ToUint8Array(base64: string): Uint8Array {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
@@ -0,0 +1,137 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { DaemonClient, FileReadResult } from "@getpaseo/client/internal/daemon-client";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AssistantFileLinkResolverProvider } from "@/assistant-file-links";
import { ForgeShorthandProvider } from "@/git/forge-shorthand";
import { ChangelogBody } from "./changelog-sheet";
import type { ChangelogState } from "./changelog-source";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
beforeEach(() => vi.stubGlobal("React", React));
let root: Root | null = null;
let container: HTMLDivElement | null = null;
afterEach(() => {
act(() => root?.unmount());
container?.remove();
root = null;
container = null;
});
function noop() {}
const CHANGELOG_FIXTURE_STATE: ChangelogState = {
status: "ready",
releases: [
{
version: "0.19.0",
date: "2026-12-01",
highlights:
"Highlights see #123, [Release](https://paseo.sh/changelog), [Local](/etc/passwd), ![HighlightLocal](/tmp/secret.png)",
sections: [
{
title: "Fixed",
body: "Section ![SectionLocal](./secret.png) ![SectionUnc](\\\\\\\\host\\\\share\\\\x.png) see #456",
},
],
},
{
version: "0.18.0",
date: "2026-11-20",
highlights: "",
sections: [
{
title: "Added",
body: "Only sections ![DirectSectionLocal](/etc/passwd) [Docs](https://paseo.sh/docs) see #789",
},
],
},
],
};
function createFakeFileReader() {
const reads: { cwd: string; path: string }[] = [];
const client = {
async readFile(cwd: string, path: string): Promise<FileReadResult> {
reads.push({ cwd, path });
return {
kind: "image",
path,
mime: "image/png",
size: 4,
modifiedAt: "2026-12-01T00:00:00.000Z",
bytes: new Uint8Array([1, 2, 3, 4]),
};
},
} as unknown as DaemonClient;
return { reads, client };
}
async function settleLayout() {
for (let frame = 0; frame < 2; frame++) {
await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
}
}
describe("changelog Markdown safety", () => {
it("never calls client.readFile and does not link workspace forge shorthand in highlights or sections", async () => {
const { reads, client: fakeClient } = createFakeFileReader();
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<QueryClientProvider client={queryClient}>
<AssistantFileLinkResolverProvider
serverId="server-1"
workspaceRoot="/repo"
client={fakeClient}
>
<ForgeShorthandProvider
forge="github"
remoteUrl="https://github.com/acme/widgets.git"
forgeWeb={null}
>
<ChangelogBody
state={CHANGELOG_FIXTURE_STATE}
shownReleases={2}
onShowMore={noop}
onRetry={noop}
/>
</ForgeShorthandProvider>
</AssistantFileLinkResolverProvider>
</QueryClientProvider>,
),
);
await expect.poll(() => container?.textContent).toContain("HighlightLocal");
await expect.poll(() => container?.textContent).toContain("DirectSectionLocal");
await settleLayout();
expect(reads).toEqual([]);
const links = Array.from(container.querySelectorAll("a")).map((a) => ({
text: a.textContent,
href: a.getAttribute("href"),
}));
expect(links).toContainEqual(
expect.objectContaining({ text: "Release", href: "https://paseo.sh/changelog" }),
);
expect(links).toContainEqual(
expect.objectContaining({ text: "Docs", href: "https://paseo.sh/docs" }),
);
expect(links.some((l) => l.text === "#123" || l.text === "#789" || l.text === "Local")).toBe(
false,
);
const imgs = Array.from(container.querySelectorAll("img"));
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("HighlightLocal");
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("DirectSectionLocal");
});
});
@@ -86,7 +86,7 @@ interface ChangelogBodyProps {
onRetry: () => void;
}
function ChangelogBody({ state, shownReleases, onShowMore, onRetry }: ChangelogBodyProps) {
export function ChangelogBody({ state, shownReleases, onShowMore, onRetry }: ChangelogBodyProps) {
const { t } = useTranslation();
const appVersion = useMemo(() => resolveAppVersion()?.replace(/^v/i, "") ?? null, []);
@@ -168,7 +168,15 @@ const ReleaseView = memo(function ReleaseView({ release, isCurrent }: ReleaseVie
<View style={styles.headingSpacer} />
{date ? <Text style={styles.date}>{date}</Text> : null}
</View>
{hasHighlights ? <MarkdownRenderer text={release.highlights} compact /> : null}
{hasHighlights ? (
<MarkdownRenderer
text={release.highlights}
compact
destinations="https"
forgeShorthand={false}
softBreaks="join"
/>
) : null}
{hasHighlights && release.sections.length > 0 ? (
<Button
variant="ghost"
@@ -188,7 +196,15 @@ function ReleaseSections({ sections }: { sections: readonly ChangelogSection[] }
return keyChangelogSections(sections).map(({ key, section }) => (
<View key={key} style={styles.section}>
{section.title ? <Text style={styles.sectionTitle}>{section.title}</Text> : null}
{section.body ? <MarkdownRenderer text={section.body} compact /> : null}
{section.body ? (
<MarkdownRenderer
text={section.body}
compact
destinations="https"
forgeShorthand={false}
softBreaks="join"
/>
) : null}
</View>
));
}
@@ -66,6 +66,7 @@ import type {
ExplorerEntry,
} from "@/stores/session-store";
import { useSessionStore } from "@/stores/session-store";
import { useHostRuntimeClient, useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
import { FileActionsContextMenuContent } from "@/components/file-actions-menu";
import { ContextMenu, ContextMenuTrigger, useContextMenu } from "@/components/ui/context-menu";
import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
@@ -570,13 +571,33 @@ export function FileExplorerPane({
const treeListRef = useRef<FlatList<ExplorerListRow>>(null);
const scrollbar = useOverlayFlatListScrollbar(treeListRef, { enabled: !isCompact });
const client = useHostRuntimeClient(serverId);
const connectionStatus = useHostRuntimeConnectionStatus(serverId);
const canFetch = Boolean(client && connectionStatus === "online");
const isHostConnecting = connectionStatus === "connecting" || connectionStatus === "idle";
const isHostUnavailable = connectionStatus === "offline" || connectionStatus === "error";
const hasInitializedRef = useRef(false);
const wasCanFetchRef = useRef(canFetch);
useEffect(() => {
hasInitializedRef.current = false;
wasCanFetchRef.current = false;
}, [workspaceStateKey]);
useEffect(() => {
const reconnected = !wasCanFetchRef.current && canFetch;
wasCanFetchRef.current = canFetch;
if (!canFetch) {
return;
}
if (
reconnected &&
workspaceStateKey &&
useSessionStore.getState().sessions[serverId]?.fileExplorer.get(workspaceStateKey)?.lastError
) {
hasInitializedRef.current = false;
}
void initializeExplorer({
hasWorkspaceScope,
hasInitializedRef,
@@ -587,9 +608,12 @@ export function FileExplorerPane({
setExpandedPathsForWorkspace,
});
}, [
canFetch,
client,
expandedPaths,
hasWorkspaceScope,
requestDirectoryListing,
serverId,
setExpandedPathsForWorkspace,
showHiddenFiles,
workspaceStateKey,
@@ -1007,12 +1031,16 @@ export function FileExplorerPane({
onLayout: scrollbar.onLayout,
});
const displayedError =
error ??
(!directories.has(".") && isHostUnavailable ? t("workspace.terminal.hostDisconnected") : null);
const showInitialLoading = resolveShowInitialLoading({
directories,
isExplorerLoading,
pendingRequest,
isHostConnecting,
});
const showBackFromError = Boolean(error && selectedEntryPath);
const showBackFromError = Boolean(displayedError && selectedEntryPath);
const errorRecoveryPath = useMemo(() => getErrorRecoveryPath(explorerState), [explorerState]);
const rowActions = useMemo<EntryRowActions>(
@@ -1184,7 +1212,7 @@ export function FileExplorerPane({
style={styles.container}
>
<FileExplorerPaneContent
error={error}
error={displayedError}
isCompact={isCompact}
serverId={serverId}
workspaceRoot={normalizedWorkspaceRoot}
@@ -1551,14 +1579,19 @@ function resolveShowInitialLoading({
directories,
isExplorerLoading,
pendingRequest,
isHostConnecting,
}: {
directories: Map<string, unknown>;
isExplorerLoading: boolean;
pendingRequest: AgentFileExplorerState["pendingRequest"] | null;
isHostConnecting: boolean;
}): boolean {
if (directories.has(".")) {
return false;
}
if (isHostConnecting) {
return true;
}
return Boolean(
isExplorerLoading && pendingRequest?.mode === "list" && pendingRequest?.path === ".",
);
@@ -17,6 +17,7 @@ import {
resolveProvidersToFetch,
requiresImportSessionsHostUpgrade,
type SessionsQueryResult,
type SessionsListing,
sumFilteredAlreadyImportedCount,
} from "@/components/import-session-sheet-view-model";
@@ -37,15 +38,13 @@ function entry(
}
function settled(
data: SessionsQueryResult["data"],
flags?: Partial<Omit<SessionsQueryResult, "data">>,
response: SessionsListing["response"],
requestError: string | null = null,
): SessionsQueryResult {
return {
data,
isError: false,
data: response || requestError !== null ? { response, requestError } : undefined,
isLoading: false,
isPending: false,
...flags,
};
}
@@ -181,7 +180,7 @@ describe("collectProviderErrorRows", () => {
it("returns a row for each provider whose request failed", () => {
const rows = collectProviderErrorRows(
["claude", "codex"],
[settled(undefined, { isError: true }), settled({ entries: [] })],
[settled(undefined, ""), settled({ entries: [] })],
new Map([["claude", "Claude Code"]]),
);
expect(rows).toEqual([
@@ -206,22 +205,15 @@ describe("collectProviderErrorRows", () => {
});
it("uses provider id when the label map has no entry", () => {
const rows = collectProviderErrorRows(
["codex"],
[settled(undefined, { isError: true })],
new Map(),
);
const rows = collectProviderErrorRows(["codex"], [settled(undefined, "")], new Map());
expect(rows).toEqual([{ provider: "codex", label: "codex", message: null, retrying: false }]);
});
it("shows the current request failure instead of an older provider error", () => {
const query = {
...settled(
{ entries: [], providerErrors: [{ provider: "codex", message: "old provider failure" }] },
{ isError: true },
),
error: new Error(" Connection closed. Reconnect the host and retry. "),
};
const query = settled(
{ entries: [], providerErrors: [{ provider: "codex", message: "old provider failure" }] },
" Connection closed. Reconnect the host and retry. ",
);
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
{
provider: "codex",
@@ -278,7 +270,7 @@ describe("hasMoreSessions", () => {
it("keeps reporting more while the next page replaces placeholder rows", () => {
expect(
hasMoreSessions([settled({ entries: [entry()] }, { isPlaceholderData: true })], 45),
hasMoreSessions([{ ...settled({ entries: [entry()] }), isPlaceholderData: true }], 45),
).toBe(true);
});
});
@@ -30,16 +30,19 @@ export function requiresImportSessionsHostUpgrade(input: {
return !input.supportsSnapshot || (Boolean(input.workspaceId) && !input.supportsWorkspaceTarget);
}
interface SessionsResponse {
entries: FetchRecentProviderSessionEntry[];
filteredAlreadyImportedCount?: number;
providerErrors?: Array<{ provider: string; message: string }>;
}
export interface SessionsListing {
response: SessionsResponse | undefined;
requestError: string | null;
}
export interface SessionsQueryResult {
data:
| {
entries: FetchRecentProviderSessionEntry[];
filteredAlreadyImportedCount?: number;
providerErrors?: Array<{ provider: string; message: string }>;
}
| undefined;
isError: boolean;
error?: Error | null;
data: SessionsListing | undefined;
isFetching?: boolean;
isLoading: boolean;
isPending: boolean;
@@ -78,8 +81,8 @@ export function aggregateSessionEntries(
const seen = new Set<string>();
const collected: FetchRecentProviderSessionEntry[] = [];
for (const query of queries) {
if (!query.data) continue;
for (const entry of query.data.entries) {
if (!query.data?.response) continue;
for (const entry of query.data.response.entries) {
const key = `${entry.providerId}:${entry.providerHandleId}`;
if (seen.has(key)) continue;
seen.add(key);
@@ -97,7 +100,7 @@ export function sumFilteredAlreadyImportedCount(
): number {
let total = 0;
for (const query of queries) {
total += query.data?.filteredAlreadyImportedCount ?? 0;
total += query.data?.response?.filteredAlreadyImportedCount ?? 0;
}
return total;
}
@@ -114,7 +117,7 @@ export function hasMoreSessions(
): boolean {
if (nextPageLimit(limit) === limit) return false;
return queries.some((entryQuery) => {
const count = entryQuery.data?.entries.length ?? 0;
const count = entryQuery.data?.response?.entries.length ?? 0;
return entryQuery.isPlaceholderData ? count > 0 : count >= limit;
});
}
@@ -142,11 +145,12 @@ export function collectProviderErrorRows(
const query = queries[index];
const provider = providersToFetch[index];
if (!query || provider === undefined) continue;
const failed = query.isError || (query.data?.providerErrors?.length ?? 0) > 0;
if (!failed) continue;
const failure = query.data?.providerErrors?.find((error) => error.provider === provider);
const failureMessage = query.isError ? query.error?.message : failure?.message;
const message = failureMessage?.trim() || null;
const failure = query.data?.response?.providerErrors?.find(
(error) => error.provider === provider,
);
const failureMessage = query.data?.requestError ?? failure?.message;
if (failureMessage === undefined) continue;
const message = failureMessage.trim() || null;
rows.push({
provider,
label: providerLabelById.get(provider) ?? provider,
@@ -455,24 +455,43 @@ describe("ImportSessionSheet", () => {
expect(screen.queryByText("No recent sessions to import.")).toBeNull();
});
it("shows a fetch error state when recent provider sessions cannot be loaded", async () => {
const fetchRecentProviderSessions = vi.fn(async () => {
throw new Error("recent sessions unavailable");
});
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
it("keeps a request error visible while Retry is pending and clears it after success", async () => {
const retry =
Promise.withResolvers<Awaited<ReturnType<DaemonClient["fetchRecentProviderSessions"]>>>();
let firstRequest = true;
const client = createRecentSessionsClient(
async () => {
if (firstRequest) {
firstRequest = false;
throw new Error("recent sessions unavailable");
}
return retry.promise;
},
async () => {
throw new Error("Unexpected import");
},
);
await screen.findByText("Could not load Claude Code sessions");
screen.getByTestId("import-session-retry-claude");
renderSheet(client, {
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
await screen.findByText("recent sessions unavailable");
fireEvent.click(screen.getByTestId("import-session-retry-claude"));
try {
await waitFor(() => {
expect(screen.getByText("recent sessions unavailable")).toBeTruthy();
expect(screen.getByRole("button", { name: "Retry" }).getAttribute("aria-disabled")).toBe(
"true",
);
});
} finally {
retry.resolve({ requestId: "retry", entries: [] });
}
await screen.findByText("No recent sessions to import.");
expect(screen.queryByText("recent sessions unavailable")).toBeNull();
});
it("loads recent provider sessions for the workspace and renders descriptor-owned labels", async () => {
@@ -1,6 +1,12 @@
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
import {
queryOptions,
useMutation,
useQueries,
useQueryClient,
type QueryClient,
} from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -42,6 +48,7 @@ import {
PER_PROVIDER_LIMIT,
previousPageLimit,
type ProviderErrorRow,
type SessionsListing,
resolveImportTarget,
resolveProvidersToFetch,
requiresImportSessionsHostUpgrade,
@@ -73,10 +80,6 @@ interface ImportSessionSheetProps {
onImported?: (agent: ImportedAgent) => void;
}
type RecentSessionsResponse = Awaited<
ReturnType<RecentProviderSessionsClient["fetchRecentProviderSessions"]>
>;
type SessionsQueryKey = ReadonlyArray<string | number | null>;
function buildSessionsQueryRoot(serverId: string | null, cwd: string | null) {
@@ -98,18 +101,6 @@ function buildSessionsQueryKey(input: {
];
}
interface SessionsQueryConfig {
queryKey: SessionsQueryKey;
enabled: boolean;
// A provider that cannot answer stays broken until the user asks again. React
// Query's default retry would keep the header spinner turning and pile up
// in-flight daemon requests behind a dead provider (#2512).
retry: false;
refetchOnMount: true;
placeholderData: () => RecentSessionsResponse | undefined;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
queryClient: QueryClient;
providersToFetch: AgentProvider[] | null;
@@ -120,39 +111,63 @@ function buildSessionsQueriesConfig(args: {
query: string;
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
}) {
const { queryClient, providersToFetch, visible, client, serverId, cwd, query, limit } = args;
const { hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
const previousLimit = previousPageLimit(limit);
return providersToFetch.map((provider) => ({
queryKey: buildSessionsQueryKey({ serverId, cwd, query, limit, provider }),
enabled,
retry: false as const,
// An import can invalidate an inactive host. Refresh its listing when observed again.
refetchOnMount: true as const,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () =>
previousLimit === null
? undefined
: queryClient.getQueryData<RecentSessionsResponse>(
buildSessionsQueryKey({ serverId, cwd, query, limit: previousLimit, provider }),
),
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
}
return await client.fetchRecentProviderSessions({
...(cwd ? { cwd } : {}),
providers: [provider],
limit,
...(query ? { query } : {}),
});
},
}));
const defaultStaleTime = queryClient.getDefaultOptions().queries?.staleTime;
return providersToFetch.map((provider) => {
const queryKey = buildSessionsQueryKey({ serverId, cwd, query, limit, provider });
return queryOptions({
queryKey,
enabled,
// Let the user retry a failed listing without an automatic retry loop.
retry: false,
// An import can invalidate an inactive host. Refresh its listing when observed again.
refetchOnMount: true,
// While Load more fetches the next page, keep showing the page it grew from. React Query's
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
// has no previous data, so the rows would vanish and the list would remount at the top.
placeholderData: () => {
if (previousLimit === null) return undefined;
const previous = queryClient.getQueryData<SessionsListing>(
buildSessionsQueryKey({ serverId, cwd, query, limit: previousLimit, provider }),
);
return previous?.response ? { response: previous.response, requestError: null } : undefined;
},
// Refetch failed listings when the sheet reopens.
staleTime: (listingQuery) => {
if (listingQuery.state.data?.requestError != null) return 0;
if (typeof defaultStaleTime !== "function") return defaultStaleTime ?? 0;
const cachedQuery = queryClient.getQueryCache().get(listingQuery.queryHash);
return cachedQuery ? defaultStaleTime(cachedQuery) : 0;
},
queryFn: async (): Promise<SessionsListing> => {
try {
if (!client) {
throw new Error(
hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"),
);
}
const response = await client.fetchRecentProviderSessions({
...(cwd ? { cwd } : {}),
providers: [provider],
limit,
...(query ? { query } : {}),
});
return { response, requestError: null };
} catch (error) {
// Cache the last outcome so a new fetch cannot clear the error row.
return {
response: queryClient.getQueryData<SessionsListing>(queryKey)?.response,
requestError: error instanceof Error ? error.message : String(error),
};
}
},
});
});
}
interface SheetStatusMessagesProps {
@@ -808,7 +823,8 @@ export function ImportSessionSheet({
(isQueryingProviders &&
queries.some((providerQuery) => providerQuery.isLoading || providerQuery.isPending));
const allQueriesErrored =
isQueryingProviders && queries.every((providerQuery) => providerQuery.isError);
isQueryingProviders &&
queries.every((providerQuery) => providerQuery.data?.requestError != null);
const allQueriesSettled =
isQueryingProviders &&
queries.every((providerQuery) => !providerQuery.isLoading && !providerQuery.isPending);
@@ -167,6 +167,79 @@ describe("resolveMarkdownPreviewImageSource", () => {
}),
).toBe("C:/Users/test/repo/images/hero.png");
});
it("keeps extended-length local Windows drive paths and local drive file URIs", () => {
expect(
resolveMarkdownPreviewImageSource({
source: "\\\\?\\C:\\foo\\bar.png",
markdownPath: "docs/guide.md",
workspaceRoot: "C:\\repo",
}),
).toBe("C:/foo/bar.png");
expect(
resolveMarkdownPreviewImageSource({
source: "file:///C:/foo/bar.png",
markdownPath: "docs/guide.md",
workspaceRoot: "C:\\repo",
}),
).toBe("C:/foo/bar.png");
});
it.each([
"\\\\host\\share\\x.png",
"//host/share/x.png",
"\\\\?\\UNC\\host\\share\\x.png",
"file://host/share/x.png",
"\\\\.\\pipe\\foo",
"\\\\?\\Volume{01234567-89ab-cdef-0123-456789abcdef}",
])("rejects UNC, remote file URI, and Windows device source %s", (source) => {
expect(
resolveMarkdownPreviewImageSource({
source,
markdownPath: "docs/guide.md",
workspaceRoot: "C:\\repo",
}),
).toBeNull();
});
it("allows UNC and relative images inside a UNC workspace while rejecting paths outside it", () => {
const uncRoot = "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj";
expect(
resolveMarkdownPreviewImageSource({
source: "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
markdownPath: "docs/guide.md",
workspaceRoot: uncRoot,
}),
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png");
expect(
resolveMarkdownPreviewImageSource({
source: "file://wsl.localhost/Ubuntu/home/me/proj/shot.png?v=1#top",
markdownPath: "docs/guide.md",
workspaceRoot: uncRoot,
}),
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png");
expect(
resolveMarkdownPreviewImageSource({
source: "./images/hero.png",
markdownPath: "docs/guide.md",
workspaceRoot: uncRoot,
}),
).toBe("//wsl.localhost/Ubuntu/home/me/proj/docs/images/hero.png");
expect(
resolveMarkdownPreviewImageSource({
source: "../../../../outside.png",
markdownPath: "docs/guide.md",
workspaceRoot: uncRoot,
}),
).toBeNull();
expect(
resolveMarkdownPreviewImageSource({
source: "\\\\other\\share\\leak.png",
markdownPath: "docs/guide.md",
workspaceRoot: uncRoot,
}),
).toBeNull();
});
});
describe("local assistant Markdown images", () => {
@@ -1,4 +1,9 @@
import { localFileSourceToPath } from "@/attachments/utils";
import {
isUncPathWithinRoot,
parseUncPath,
stripLocalImageQueryAndFragment,
} from "@getpaseo/protocol/path-utils";
import { normalizeLocalImagePath } from "@/utils/assistant-image-source";
import { isAbsolutePath } from "@/utils/path";
function trimTrailingSeparators(value: string): string {
@@ -126,9 +131,10 @@ export function resolveMarkdownPreviewImageSource(input: {
return source;
}
const pathSource = source.replace(/[?#].*$/, "");
const path = localFileSourceToPath(
pathSource.startsWith("file://") ? pathSource : decodeRelativeSource(pathSource),
const pathSource = stripLocalImageQueryAndFragment(source);
const path = normalizeLocalImagePath(
/^file:/i.test(pathSource) ? pathSource : decodeRelativeSource(pathSource),
{ workspaceRoot: input.workspaceRoot },
);
if (!path) {
return null;
@@ -146,5 +152,13 @@ export function resolveMarkdownPreviewImageSource(input: {
return path;
}
return joinAbsolute(directory, path);
const joined = joinAbsolute(directory, path);
if (!joined) {
return null;
}
const joinedUnc = parseUncPath(joined);
if (joinedUnc && !isUncPathWithinRoot(joinedUnc, input.workspaceRoot)) {
return null;
}
return joined;
}
@@ -62,17 +62,24 @@ afterEach(() => {
__setAttachmentStoreForTests(null);
});
function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) {
function renderMarkdownSource(
text: string,
initialProps: MarkdownImageContext,
options?: Parameters<typeof useMarkdownSource>[2],
) {
// No retries: a failed read settles at once. For a host's Markdown this is the state once the
// retries have run out on a host that is slow to connect.
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), {
wrapper,
initialProps,
});
const rendered = renderHook(
(props: MarkdownImageContext) => useMarkdownSource(text, props, options),
{
wrapper,
initialProps,
},
);
return { ...rendered, queryClient };
}
@@ -104,3 +111,32 @@ it("shows the alt text of a file image in Markdown that belongs to no host", asy
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"),
);
});
it("never calls client.readFile when destinations are restricted to https", async () => {
const files = createHostFiles();
const { result, queryClient } = renderMarkdownSource(
"![Local](/etc/passwd) ![Relative](chart.png) ![Unc](\\\\\\\\host\\\\share\\\\x.png) ![RemoteFile](file://host/share/x.png)",
{ serverId: "srv_test", workspaceRoot: "/repo", client: files },
{ destinations: "https" },
);
await waitFor(() => {
expect(queryClient.isFetching()).toBe(0);
expect(result.current.markdown).toBe("Local Relative Unc RemoteFile");
});
expect(files.reads).toEqual([]);
});
it("never calls client.readFile for UNC, remote file URI, or Windows device paths in host Markdown", async () => {
const files = createHostFiles();
const { result, queryClient } = renderMarkdownSource(
"![Unc](\\\\\\\\host\\\\share\\\\x.png) ![SlashUnc](//host/share/x.png) ![Remote](file://host/share/x.png) ![Pipe](\\\\\\\\.\\\\pipe\\\\foo)",
{ serverId: "srv_test", workspaceRoot: "C:/repo", client: files },
);
await waitFor(() => {
expect(queryClient.isFetching()).toBe(0);
expect(result.current.markdown).toBe("Unc SlashUnc Remote Pipe");
});
expect(files.reads).toEqual([]);
});
@@ -14,7 +14,7 @@ import { resolveAssistantImageSource } from "@/utils/assistant-image-source";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import type { AttachmentMetadata } from "@/attachments/types";
import { resolveMarkdownPreviewImageSource } from "./image-source";
import { prepareMarkdownSource } from "./source";
import { prepareMarkdownSource, type MarkdownDestinations } from "./source";
import { decodeMarkdownImage, getMarkdownImageStatus } from "./image-decoding";
const urls = createAssistantImageAcquisitionCache<{ uri: string; attachment: AttachmentMetadata }>({
@@ -41,26 +41,29 @@ export function useMarkdownSource(
links: {
commandNames?: ReadonlySet<string>;
forgeReferencePattern?: string;
external?: boolean;
destinations?: MarkdownDestinations;
} = {},
/** Identity of this occurrence's image acquisitions. Defaults to one per call site. */
occurrence?: string,
) {
const ownOccurrence = useId();
const occurrenceKey = occurrence ?? ownOccurrence;
const { commandNames, forgeReferencePattern, external } = links;
const { commandNames, forgeReferencePattern, destinations = "host" } = links;
const httpsOnly = destinations === "https";
const workspaceRoot = httpsOnly ? undefined : context.workspaceRoot;
const prepared = useMemo(
() =>
prepareMarkdownSource(text, context.workspaceRoot, {
prepareMarkdownSource(text, workspaceRoot, {
supportsSvg: isWeb,
commandNames,
forgeReferencePattern,
external,
destinations,
}),
[text, context.workspaceRoot, commandNames, forgeReferencePattern, external],
[text, workspaceRoot, commandNames, forgeReferencePattern, destinations],
);
const sources = [...new Set(prepared.images.map((image) => image.source))];
const acquisitions = sources.map((source) => {
if (httpsOnly) return null;
const resolved = resolveMarkdownPreviewImageSource({
source,
markdownPath: context.filePath ?? "",
@@ -0,0 +1,43 @@
import { useEffect, useState } from "react";
import {
isMarkdownParserReady,
preloadMarkdownParser as preloadEngineParser,
} from "react-native-enriched-markdown";
/**
* Starts initializing the web Markdown WASM parser ahead of the first render.
* Safe to call repeatedly and a no-op on native.
*/
export function preloadMarkdownParser(): void {
void preloadEngineParser().catch(() => {
// EnrichedMarkdownText renders a plain-text fallback if parser initialization fails.
});
}
/**
* True once synchronous Markdown parsing is available, so surfaces with a loading
* skeleton can keep it visible instead of collapsing to an empty container while
* WASM compiles on cold start.
*/
export function useMarkdownParserReady({ enabled = true }: { enabled?: boolean } = {}): boolean {
const [ready, setReady] = useState(isMarkdownParserReady);
useEffect(() => {
if (!enabled || ready) return;
if (isMarkdownParserReady()) {
setReady(true);
return;
}
let cancelled = false;
void preloadEngineParser()
.catch(() => {
// Still resolve readiness so EnrichedMarkdownText can render its fallback.
})
.finally(() => {
if (!cancelled) setReady(true);
});
return () => {
cancelled = true;
};
}, [enabled, ready]);
return ready;
}
@@ -1,6 +1,11 @@
import { fromMarkdown } from "mdast-util-from-markdown";
import { toNativeLinkRecognition } from "react-native-enriched-markdown/src/utils/regexParser";
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
import {
isMarkdownParserReady,
parseMarkdown,
parseMarkdownSync,
preloadMarkdownParser,
} from "react-native-enriched-markdown/src/web/parseMarkdown";
import { recognizeTextLinks } from "react-native-enriched-markdown/src/web/recognizeTextLinks";
import { matchCommandLink } from "@/agent-commands";
import { createForgeShorthand } from "@/git/forge-shorthand";
@@ -1340,11 +1345,15 @@ it.each([false, true])(
},
);
describe("external Markdown", () => {
const external = (source: string) => prepareMarkdownSource(source, undefined, { external: true });
describe("https-only destinations Markdown", () => {
const httpsOnly = (source: string, forgeReferencePattern?: string) =>
prepareMarkdownSource(source, "/repo", {
destinations: "https",
forgeReferencePattern,
});
it("recognizes no files, forge references or commands, only https URLs", () => {
const { linkRecognition } = external("Needs Node.js 22 and `~/.dsh/.env`, see #12");
it("recognizes no files, forge references or commands when forge shorthand is omitted", () => {
const { linkRecognition } = httpsOnly("Needs Node.js 22 and `~/.dsh/.env`, see #12");
expect("Needs Node.js 22, see #12".match(linkRecognition.text)).toBeNull();
expect(linkRecognition.inlineCode.test("~/.dsh/.env")).toBe(false);
expect("Docs at https://example.com/a.".match(linkRecognition.text)).toEqual([
@@ -1352,17 +1361,48 @@ describe("external Markdown", () => {
]);
});
it("keeps https links and leaves any other destination as its label", () => {
it("keeps forge references alongside https URLs without recognizing local file paths", () => {
const shorthand = createForgeShorthand({
forge: "github",
remoteUrl: "https://github.com/acme/widgets.git",
});
expect(shorthand).not.toBeNull();
const { linkRecognition } = httpsOnly(
"Fixes #123 and other/repo#456, touches src/index.ts and `package.json`, see https://example.com/docs",
shorthand!.pattern,
);
expect(
external(
"[Guide](docs/guide.md), [site](https://example.com), [mail](mailto:a@b.c), [ref][r]\n\n[r]: ./x",
).render(),
).toBe("Guide, [site](https://example.com), mail, ref\n\n[r]: ./x");
"Fixes #123 and other/repo#456, touches src/index.ts, see https://example.com/docs".match(
linkRecognition.text,
),
).toEqual(["#123", "other/repo#456", "https://example.com/docs"]);
expect(linkRecognition.inlineCode.test("package.json")).toBe(false);
expect(linkRecognition.inlineCode.test("https://example.com/docs")).toBe(true);
});
it("shows a relative image as its alt text", () => {
expect(external("![Demo](media/demo.png) ![Shot](https://x/a.png)").render()).toBe(
"Demo ![Shot](https://x/a.png)",
it("keeps https links and leaves any other destination as its label", () => {
expect(
httpsOnly(
"[Guide](docs/guide.md), [Local](/etc/passwd), [site](https://example.com), [mail](mailto:a@b.c), [ref][r]\n\n[r]: ./x",
).render(),
).toBe("Guide, Local, [site](https://example.com), mail, ref\n\n[r]: ./x");
});
it("keeps only https images and leaves relative, local, and UNC images as alt text", () => {
const prepared = httpsOnly(
"![Demo](media/demo.png) ![Local](/etc/passwd) ![Unc](\\\\host\\share\\x.png) ![Shot](https://x/a.png)",
);
expect(prepared.images.map((image) => image.source)).toEqual(["https://x/a.png"]);
expect(prepared.render()).toBe("Demo Local Unc ![Shot](https://x/a.png)");
});
});
describe("web Markdown parser preload", () => {
it("marks the WASM parser ready and enables synchronous parsing after preload", async () => {
await preloadMarkdownParser();
expect(isMarkdownParserReady()).toBe(true);
const ast = parseMarkdownSync("# Heading\n\nBody");
expect(ast).not.toBeNull();
expect(ast?.children?.map((node) => node.type)).toEqual(["Heading", "Paragraph"]);
});
});
@@ -20,7 +20,7 @@ import { MarkdownBlockStack } from "./block-stack";
import { LinkMenu, useLinkMenuLongPress, type LinkMenuSubject } from "./link-menu";
import { WEB_RENDERERS } from "./renderers";
import { createMarkdownStyles } from "./styles";
import { PENDING_MARKDOWN_IMAGE } from "./source";
import { PENDING_MARKDOWN_IMAGE, type MarkdownDestinations } from "./source";
import {
createStreamingMarkdownSplitter,
createStreamingMarkdownStabilizer,
@@ -31,10 +31,12 @@ import { useMarkdownSource, type MarkdownImageContext } from "./images";
import { MermaidFence, splitMermaidFences } from "./fence/mermaid";
export type { MarkdownDestinations };
export type MarkdownSoftBreaks = "break" | "join";
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
// A README is written for its forge, where the lines of a paragraph join into one.
const EXTERNAL_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
const JOINED_SOFT_BREAKS_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
// Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it.
const markdownStyle =
@@ -61,14 +63,17 @@ export interface MarkdownRendererProps extends MarkdownImageContext {
muted?: boolean;
selectable?: boolean;
streaming?: boolean;
onLinkPress?: (url: string) => unknown;
agentCommands?: boolean;
/**
* Author-controlled Markdown from outside this host, such as a plugin README: only its https
* links and images work, nothing is read as a file, forge reference or command, and the lines of
* a paragraph join as they do on its forge.
* Which link and image destinations are allowed.
* - `"host"` (default): host/workspace file links, host images, and web URLs.
* - `"https"`: absolute `https://` links and images only; never reads host files or recognizes local paths.
*/
external?: boolean;
destinations?: MarkdownDestinations;
/** Recognize workspace forge references such as `#123` when a forge context is present. Defaults to `true`. */
forgeShorthand?: boolean;
/** Whether single newlines inside a paragraph break the line (`"break"`, default) or join into one line (`"join"`). */
softBreaks?: MarkdownSoftBreaks;
}
/** All Markdown surfaces share the same engine and source adaptation. */
@@ -143,24 +148,12 @@ function MarkdownText(props: ComponentProps<typeof ThemedMarkdown> & { markdown:
return <ThemedMarkdown {...props} {...longPress} />;
}
const MarkdownPart = memo(function MarkdownPart({
text,
compact = false,
muted = false,
selectable = true,
streaming = false,
preStabilized = false,
onLinkPress,
agentCommands: _agentCommands,
external = false,
commandHints = null,
imageOccurrence,
...imageContext
}: MarkdownPartProps & { commandHints?: CommandHints | null }) {
const environment = useAssistantFileLinkEnvironment();
const actions = useAssistantFileLinkActions();
const workspaceForgeShorthand = useForgeShorthand();
const forgeShorthand = external ? null : workspaceForgeShorthand;
function resolveHostImageContext(
destinations: MarkdownDestinations,
imageContext: MarkdownImageContext,
environment: ReturnType<typeof useAssistantFileLinkEnvironment>,
): MarkdownImageContext {
if (destinations === "https") return {};
const environmentMatchesHost =
!imageContext.serverId || imageContext.serverId === environment.serverId;
const client =
@@ -168,6 +161,34 @@ const MarkdownPart = memo(function MarkdownPart({
(environmentMatchesHost && environment.client?.readFile
? { readFile: environment.client.readFile.bind(environment.client) }
: undefined);
return {
workspaceRoot: environmentMatchesHost ? environment.workspaceRoot : undefined,
serverId: environment.serverId,
...imageContext,
client,
};
}
const MarkdownPart = memo(function MarkdownPart({
text,
compact = false,
muted = false,
selectable = true,
streaming = false,
preStabilized = false,
agentCommands: _agentCommands,
destinations = "host",
forgeShorthand = true,
softBreaks = "break",
commandHints = null,
imageOccurrence,
...imageContext
}: MarkdownPartProps & { commandHints?: CommandHints | null }) {
const httpsOnly = destinations === "https";
const environment = useAssistantFileLinkEnvironment();
const actions = useAssistantFileLinkActions();
const workspaceForgeShorthand = useForgeShorthand();
const activeForgeShorthand = forgeShorthand ? workspaceForgeShorthand : null;
const stabilizerRef = useRef<ReturnType<typeof createStreamingMarkdownStabilizer> | null>(null);
const stabilizedText = useMemo(() => {
if (!streaming || preStabilized) return text;
@@ -175,16 +196,11 @@ const MarkdownPart = memo(function MarkdownPart({
}, [streaming, preStabilized, text]);
const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(
stabilizedText,
{
workspaceRoot: environmentMatchesHost ? environment.workspaceRoot : undefined,
serverId: environment.serverId,
...imageContext,
client,
},
resolveHostImageContext(destinations, imageContext, environment),
{
commandNames: commandHints?.names,
forgeReferencePattern: forgeShorthand?.pattern,
external,
forgeReferencePattern: activeForgeShorthand?.pattern,
destinations,
},
imageOccurrence,
);
@@ -192,15 +208,15 @@ const MarkdownPart = memo(function MarkdownPart({
// What a link is, for pressing it and for its menu alike.
const readLink = useStableEvent(({ url, sourceType }: LinkPressEvent): ReadMarkdownLink => {
if (streaming && url === PENDING_MARKDOWN_LINK) return { kind: "inert" };
if (external) {
const command = commandHints && matchCommandLink(url, sourceType, commandHints.names);
if (command) return { kind: "command", command };
const forgeUrl = sourceType === "text" ? activeForgeShorthand?.resolve(url) : null;
if (forgeUrl) return { kind: "web", url: forgeUrl };
if (httpsOnly) {
// The parser still autolinks bare http, www and email text; only https links open.
const safe = pluginOverviewUrl(url);
return safe ? { kind: "web", url: safe } : { kind: "inert" };
}
const command = commandHints && matchCommandLink(url, sourceType, commandHints.names);
if (command) return { kind: "command", command };
const forgeUrl = sourceType === "text" ? forgeShorthand?.resolve(url) : null;
if (forgeUrl) return { kind: "web", url: forgeUrl };
return { kind: "source", source: linkSource(url, sourceType) };
});
const pressLink = useStableEvent((event: LinkPressEvent) => {
@@ -210,15 +226,14 @@ const MarkdownPart = memo(function MarkdownPart({
} else if (link.kind === "command") {
commandHints?.insert(link.command);
} else if (link.kind === "source") {
if (onLinkPress && !actions.canResolveFile(link.source)) onLinkPress(event.url);
else actions.open(link.source, "preferred");
actions.open(link.source, "preferred");
}
});
const describeLink = useStableEvent((pressed: LinkPressEvent): LinkMenuSubject | null => {
const link = readLink(pressed);
const { serverId, workspaceId, workspaceRoot } = environment;
const workspace =
!external && serverId && workspaceRoot ? { serverId, workspaceId, workspaceRoot } : null;
!httpsOnly && serverId && workspaceRoot ? { serverId, workspaceId, workspaceRoot } : null;
const web = (url: string) =>
isHttpUrl(url) ? ({ kind: "web", url, workspace } as const) : null;
if (link.kind === "web") return web(link.url);
@@ -251,7 +266,7 @@ const MarkdownPart = memo(function MarkdownPart({
uniProps={pickMarkdownStyle(compact, muted)}
flavor="github"
selectable={selectable}
md4cFlags={external ? EXTERNAL_MD4C_FLAGS : MD4C_FLAGS}
md4cFlags={softBreaks === "join" ? JOINED_SOFT_BREAKS_MD4C_FLAGS : MD4C_FLAGS}
linkRecognition={linkRecognition}
enableTaskListItemToggle={false}
enableLinkPreview={false}
+38 -17
View File
@@ -57,11 +57,24 @@ function textPattern(forgeReferencePattern?: string): RegExp {
return pattern;
}
// External Markdown links only what its author wrote as an https URL.
const EXTERNAL_LINKS = {
text: new RegExp(BARE_URL.replace("https?", "https"), "g"),
inlineCode: /^https:\/\/[^\s<>]+$/,
};
// External/https-only Markdown links only what its author wrote as an https URL,
// plus optional forge shorthand when the caller enables it.
const HTTPS_BARE_URL = BARE_URL.replace("https?", "https");
const HTTPS_TEXT_PATTERN = new RegExp(HTTPS_BARE_URL, "g");
const HTTPS_INLINE_CODE_PATTERN = /^https:\/\/[^\s<>]+$/;
const httpsTextPatternsByForgeReference = new Map<string, RegExp>();
function httpsTextPattern(forgeReferencePattern?: string): RegExp {
if (!forgeReferencePattern) return HTTPS_TEXT_PATTERN;
let pattern = httpsTextPatternsByForgeReference.get(forgeReferencePattern);
if (!pattern) {
pattern = new RegExp(String.raw`(?:${HTTPS_BARE_URL}|${forgeReferencePattern})`, "g");
httpsTextPatternsByForgeReference.set(forgeReferencePattern, pattern);
}
return pattern;
}
export type MarkdownDestinations = "host" | "https";
function linkMetadata(inlineCodePaths: ReadonlySet<string>, forgeReferencePattern?: string) {
// The engine accepts regexes on both platforms. Classify complete code spans
@@ -167,11 +180,12 @@ export function prepareMarkdownSource(
/** Regex source for forge references such as `#12`; see `@/git/forge-shorthand`. */
forgeReferencePattern?: string;
/**
* Author-controlled Markdown from outside this host, such as a plugin README. It follows the
* registry's overview contract: only absolute https links and images, and nothing is
* recognized as a file, forge reference or command.
* Allowed link and image destinations:
* - `"host"` (default): host/workspace file links, host images, and web URLs.
* - `"https"`: absolute `https://` links and images only (the registry overview contract);
* nothing is recognized as a local file path.
*/
external?: boolean;
destinations?: MarkdownDestinations;
} = {},
) {
source = normalizeMarkdownHtml(source);
@@ -182,9 +196,15 @@ export function prepareMarkdownSource(
extensions: [gfmTable()],
mdastExtensions: [gfmTableFromMarkdown()],
}));
const external = options.external === true;
const metadata = external
? { linkRecognition: EXTERNAL_LINKS, linkSource: markdownLinkSource }
const httpsOnly = options.destinations === "https";
const metadata = httpsOnly
? {
linkRecognition: {
text: httpsTextPattern(options.forgeReferencePattern),
inlineCode: HTTPS_INLINE_CODE_PATTERN,
},
linkSource: markdownLinkSource,
}
: linkMetadata(
collectInlineCodePaths(source, workspaceRoot, options.commandNames),
options.forgeReferencePattern,
@@ -198,8 +218,8 @@ export function prepareMarkdownSource(
!/^[\t >]*[^\t >\r\n][^\r\n]*(?:\r\n|\r|\n)[^\r\n]+(?:\r\n|\r|\n)(?=[\t >:|-]*\|)[\t >|]*:?-[-\t :|]*$/m.test(
source,
) &&
!mayLinkIntoWorkspace(source, workspaceRoot) &&
!(external && /\]|<[a-z]+:/i.test(source))
!(!httpsOnly && mayLinkIntoWorkspace(source, workspaceRoot)) &&
!(httpsOnly && /\]|<[a-z]+:/i.test(source))
) {
return { images, ...metadata, render: () => source };
}
@@ -218,7 +238,7 @@ export function prepareMarkdownSource(
) {
const target = node.type === "image" ? node : definitions.get(node.identifier);
if (
(external && !pluginOverviewUrl(target?.url)) ||
(httpsOnly && !pluginOverviewUrl(target?.url)) ||
(target &&
options.supportsSvg === false &&
/(?:\.svg(?:[?#]|$)|^data:image\/svg\+xml)/i.test(target.url))
@@ -308,8 +328,9 @@ export function prepareMarkdownSource(
const boundary = lineStart - newline.length;
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
}
if (external) dropUnsafeDestination(node, start, end);
if (node.type === "link") {
if (httpsOnly) {
dropUnsafeDestination(node, start, end);
} else if (node.type === "link") {
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
if (title !== null)
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
@@ -12,6 +12,8 @@ import { withContentDrag } from "@/components/ui/content-drag";
import { useIsCompactFormFactor } from "@/constants/layout";
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
export const PAGE_LAYOUT_WIDE_MAX_WIDTH = 1080;
// Rows on a page drag to reorder, so the page stops scrolling while a drag holds the touch.
const PageScrollView =
Platform.OS === "android"
@@ -198,7 +200,7 @@ const styles = StyleSheet.create((theme) => ({
padding: theme.spacing[4],
paddingTop: theme.spacing[6],
width: "100%",
maxWidth: 1080,
maxWidth: PAGE_LAYOUT_WIDE_MAX_WIDTH,
alignSelf: "center",
},
titleBlock: {
@@ -100,6 +100,21 @@ describe("bottom sheet visibility tracker", () => {
expect(sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }, { type: "dismiss" }]);
});
it("dismisses a sheet hidden after its interrupted open reported -1, once it lands open", () => {
const { sheet, tracker, closeCount } = setup();
tracker.attachController(sheet);
tracker.syncDesired({ visible: true });
// The open animation is interrupted and reports the closed detent, the owner hides the
// sheet, and the sheet then finishes opening anyway.
tracker.handleSheetIndexChange(-1);
tracker.syncDesired({ visible: false });
tracker.handleSheetIndexChange(0);
expect(sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }]);
expect(closeCount()).toBe(0);
});
it("waits to present until the sheet controller becomes available", () => {
const { sheet, tracker } = setup();
tracker.syncDesired({ visible: true });
@@ -117,9 +117,10 @@ export function createBottomSheetVisibilityTracker(opts: {
},
handleSheetIndexChange(index) {
if (index !== -1) {
if (phase === "presenting" || phase === "dismissing") {
setPhase("presented");
}
// An open detent means the sheet is on screen, whatever the tracker last heard. An
// interrupted open can report -1 first, and an owner that hid the sheet in that window
// already moved the tracker to closed.
setPhase("presented");
// A dismiss sent before the sheet measured its layout is dropped, and the sheet still
// finishes opening. The owner wants it hidden, so it goes again.
if (!visible && isEnabled !== false) {
@@ -3,7 +3,7 @@ import { useRouter } from "expo-router";
import { useEffect, useMemo } from "react";
import { useSidebarCallouts } from "@/contexts/sidebar-callout-context";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspaceFields } from "@/stores/session-store-hooks";
import {
@@ -21,6 +21,7 @@ export function WorktreeSetupCalloutSource() {
);
const activeProject = selectedWorkspaceProject;
const client = useHostRuntimeClient(activeProject?.serverId ?? "");
const isConnected = useHostRuntimeIsConnected(activeProject?.serverId ?? "");
const callouts = useSidebarCallouts();
const router = useRouter();
const openProjectSettings = useStableEvent(() => {
@@ -38,7 +39,7 @@ export function WorktreeSetupCalloutSource() {
}
return client.readProjectConfig(activeProject.repoRoot);
},
enabled: Boolean(client && activeProject),
enabled: Boolean(client && isConnected && activeProject),
retry: false,
});
+59
View File
@@ -995,6 +995,65 @@ describe("attachments restored from a queued message", () => {
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
});
it("clears the optimistic timeline bubble when a direct send is queued behind a boundary", async () => {
const client = createFakeSendClient();
client.sendAgentMessage = async (agentId, text, options) => {
client.calls.push({ agentId, text, options });
return { deliveryStatus: "queued", messageId: options.messageId };
};
const stream = createFakeStream();
await dispatchComposerAgentMessage({
client,
agentId: "agent",
text: "follow up",
attachments: [],
submission: stream,
activeTurnBehavior: "interrupt",
});
expect(stream.tail.get("agent") ?? []).toEqual([]);
expect(stream.head.get("agent") ?? []).toEqual([]);
});
it("clears the optimistic timeline bubble and settles staged switch via queued callback when a direct provider switch is queued", async () => {
const client = createFakeSendClient();
client.switchAgentProvider = async () => ({
deliveryStatus: "queued",
agent: undefined,
});
const stream = createFakeStream();
let committed = 0;
let queued = 0;
await dispatchComposerAgentMessage({
client,
agentId: "agent",
text: "switch later",
attachments: [],
submission: stream,
currentProvider: "claude",
stagedProviderSwitch: {
provider: "codex",
model: null,
thinkingOptionId: null,
modeId: null,
providerOptions: {},
},
onProviderSwitchCommitted: () => {
committed += 1;
},
onProviderSwitchQueued: () => {
queued += 1;
},
});
expect(committed).toBe(0);
expect(queued).toBe(1);
expect(stream.tail.get("agent") ?? []).toEqual([]);
expect(stream.head.get("agent") ?? []).toEqual([]);
});
it("counts a restored forge item as selected and toggles it off", () => {
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
+20 -1
View File
@@ -217,6 +217,7 @@ export interface DispatchComposerAgentMessageInput {
currentModel?: string | null;
stagedProviderSwitch?: StagedProviderSwitch | null;
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
onProviderSwitchQueued?: () => void;
}
function buildPendingProviderSwitch(
@@ -242,6 +243,15 @@ function buildPendingProviderSwitch(
});
}
function isQueuedDeliveryResult(result: unknown): boolean {
return (
typeof result === "object" &&
result !== null &&
"deliveryStatus" in result &&
result.deliveryStatus === "queued"
);
}
export async function dispatchComposerAgentMessage(
input: DispatchComposerAgentMessageInput,
): Promise<void> {
@@ -281,16 +291,25 @@ export async function dispatchComposerAgentMessage(
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
});
if (isQueuedDeliveryResult(result)) {
input.submission.reject(input.agentId, clientMessageId);
input.onProviderSwitchQueued?.();
return;
}
input.submission.accept(input.agentId, clientMessageId);
await input.onProviderSwitchCommitted?.(result.agent);
return;
}
await input.client.sendAgentMessage(input.agentId, input.text, {
const result = await input.client.sendAgentMessage(input.agentId, input.text, {
messageId: clientMessageId,
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
...(imagePayload.images ? { images: imagePayload.images } : {}),
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
});
if (isQueuedDeliveryResult(result)) {
input.submission.reject(input.agentId, clientMessageId);
return;
}
input.submission.accept(input.agentId, clientMessageId);
} catch (error) {
input.submission.reject(input.agentId, clientMessageId);
@@ -3,7 +3,11 @@ import {
isRasterImageFile,
isRasterImagePath,
} from "@/attachments/file-types";
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
import {
readDesktopFileBytes,
selectedFileFromWebFile,
type SelectedFile,
} from "@/attachments/selected-file";
import type { DroppedItem } from "@/components/file-drop/types";
interface DroppedAttachmentsRuntime {
@@ -36,12 +40,7 @@ export function droppedItemsToSelectedFiles(
if (isRasterImageFile(item.file)) {
continue;
}
const file = item.file;
files.push({
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
});
files.push(selectedFileFromWebFile(item.file));
continue;
}
+9 -21
View File
@@ -24,7 +24,6 @@ import {
} from "@/provider-selection/provider-selection";
import { findThinkingOptionReplacement } from "@/provider-selection/resolve-agent-form";
import { useDraftStore, type DraftInput } from "@/stores/draft-store";
import { AfterPaintPublication } from "@/composer/after-paint-publication";
import { useShallow } from "zustand/shallow";
import type { ComposerTextSource } from "@/composer/text-source";
import { isWeb } from "@/constants/platform";
@@ -147,14 +146,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
[draftKey],
);
const textPublication = useMemo(
() =>
new AfterPaintPublication<string>((nextText) => {
useDraftStore.getState().editDraftText({ draftKey, text: nextText });
}),
[draftKey],
);
// Text another module put in the draft (a plugin writing to a composer that is not on screen)
// reaches the input the way a rewind restore does.
const replacementRequest = useDraftStore(
@@ -165,28 +156,26 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
const shown = shownReplacementRequestRef.current;
if (shown.draftKey === draftKey && shown.request === replacementRequest) return;
shownReplacementRequestRef.current = { draftKey, request: replacementRequest };
textPublication.cancel();
publishTextReplacement("replace", textSource.getSnapshot());
}, [draftKey, publishTextReplacement, replacementRequest, textPublication, textSource]);
}, [draftKey, publishTextReplacement, replacementRequest, textSource]);
const editText = useCallback(
(nextText: string) => {
if (isWeb) {
textPublication.stage(nextText);
useDraftStore.getState().stageDraftText({ draftKey, text: nextText });
} else {
useDraftStore.getState().editDraftText({ draftKey, text: nextText });
}
},
[draftKey, textPublication],
[draftKey],
);
const replaceText = useCallback(
(nextText: string) => {
textPublication.cancel();
useDraftStore.getState().editDraftText({ draftKey, text: nextText });
publishTextReplacement("replace", nextText);
},
[draftKey, publishTextReplacement, textPublication],
[draftKey, publishTextReplacement],
);
const setAttachments = useCallback(
@@ -208,18 +197,17 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
const clear = useCallback(
(lifecycle: "sent" | "abandoned") => {
textPublication.cancel();
useDraftStore.getState().clearDraftInput({ draftKey, lifecycle });
if (lifecycle === "sent") useDraftStore.getState().clearDraftMetadata({ draftKey });
},
[draftKey, textPublication],
[draftKey],
);
useEffect(() => {
const flush = () => useDraftStore.getState().flushDraftText(draftKey);
const flushWhenHidden = () => {
if (document.visibilityState === "hidden") textPublication.flush();
if (document.visibilityState === "hidden") flush();
};
const flush = () => textPublication.flush();
const canListenForPageHide =
isWeb && typeof window !== "undefined" && typeof window.addEventListener === "function";
if (isWeb && typeof document !== "undefined") {
@@ -235,9 +223,9 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
if (canListenForPageHide) {
window.removeEventListener("pagehide", flush);
}
textPublication.flush();
flush();
};
}, [textPublication]);
}, [draftKey]);
useEffect(() => {
let cancelled = false;
+14 -1
View File
@@ -166,7 +166,7 @@ import type {
WorkspaceFileComposerAttachment,
WorkspaceComposerAttachment,
} from "@/attachments/types";
import type { SelectedFile } from "@/attachments/selected-file";
import { selectedFileFromWebFile, type SelectedFile } from "@/attachments/selected-file";
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
import { ComposerInputProvider, type ComposerInput } from "@/composer/session";
import type { ComposerFocusOptions } from "@/composer/model";
@@ -1775,6 +1775,11 @@ function ComposerContentImpl({
}
}
},
onProviderSwitchQueued: () => {
if (stagedProviderSwitch) {
settleStagedProviderSwitch(serverId, targetAgentId, stagedProviderSwitch);
}
},
activeTurnBehavior,
activeTurnId:
activeTurnBehavior === "steer"
@@ -2041,6 +2046,13 @@ function ComposerContentImpl({
[addFiles, client, t],
);
const handlePasteFiles = useCallback(
(files: File[]) => {
void uploadSelectedFiles(files.map(selectedFileFromWebFile));
},
[uploadSelectedFiles],
);
const handlePickFile = useCallback(async () => {
if (!client) {
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
@@ -2698,6 +2710,7 @@ function ComposerContentImpl({
attachmentMenuItems={attachmentMenuItems}
onAttachButtonRef={handleAttachButtonRef}
onAddImages={addImages}
onPasteFiles={handlePasteFiles}
onPasteImages={handleNativePasteImages}
client={client}
isReadyForDictation={isDictationReady}
+29 -2
View File
@@ -21,6 +21,7 @@ import {
useRef,
useCallback,
useEffect,
useEffectEvent,
useLayoutEffect,
useImperativeHandle,
useMemo,
@@ -64,6 +65,7 @@ import {
collectImageFilesFromClipboardData,
filesToImageAttachments,
} from "@/utils/image-attachments-from-files";
import { isRasterImageFile } from "@/attachments/file-types";
import type { ComposerAttachment } from "@/attachments/types";
import type { ImageAttachment, MessagePayload, TextReplacement } from "@/composer/types";
import { focusWithRetries } from "@/utils/web-focus";
@@ -81,7 +83,7 @@ import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
import { getShortcutOs } from "@/utils/shortcut-platform";
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
import { isNative, isWeb } from "@/constants/platform";
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
import { RenderProfile } from "@/utils/render-profiler";
@@ -173,6 +175,7 @@ export interface MessageInputProps {
attachmentMenuItems: AttachmentMenuItem[];
onAttachButtonRef?: (node: View | null) => void;
onAddImages?: (images: ImageAttachment[]) => void;
onPasteFiles?: (files: File[]) => void;
onPasteImages?: (files: readonly NativePastedFile[]) => void;
client: DaemonClient | null;
/** Dictation start gate from host runtime (socket connected + directory ready). */
@@ -520,22 +523,36 @@ function getTextInputNativeElement(current: ComposerTextInputHandle | null): HTM
interface PasteEffectArgs {
textarea: HTMLElement | null;
isConnected: boolean;
isSubmitLoading: boolean;
disabled: boolean;
isDictating: boolean;
isRealtimeVoiceForCurrentAgent: boolean;
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
onPasteFiles: ((files: File[]) => void) | undefined;
}
function usePasteEffect(args: PasteEffectArgs): void {
const {
textarea,
isConnected,
isSubmitLoading,
disabled,
isDictating,
isRealtimeVoiceForCurrentAgent,
onAddImages,
onPasteFiles,
} = args;
const pasteFiles = useEffectEvent((clipboardData: DataTransfer | null) => {
if (!isConnected || isSubmitLoading || !onPasteFiles || getIsElectron()) return false;
const files = Array.from(clipboardData?.files ?? []).filter((file) => !isRasterImageFile(file));
if (files.length === 0) return false;
onPasteFiles(files);
return true;
});
useEffect(() => {
if (!isWeb) return;
@@ -546,8 +563,13 @@ function usePasteEffect(args: PasteEffectArgs): void {
if (disabled || isDictating || isRealtimeVoiceForCurrentAgent) return;
const imageFiles = collectImageFilesFromClipboardData(event.clipboardData);
const didPasteFiles = pasteFiles(event.clipboardData);
if (didPasteFiles) event.preventDefault();
if (imageFiles.length === 0) {
if (pasteLinkedClipboardText(textarea, event.clipboardData)) event.preventDefault();
if (!didPasteFiles && pasteLinkedClipboardText(textarea, event.clipboardData)) {
event.preventDefault();
}
return;
}
if (!isConnected || !onAddImages) return;
@@ -1191,6 +1213,7 @@ interface ResolvedMessageInputProps {
attachmentMenuItems: AttachmentMenuItem[];
onAttachButtonRef: ((node: View | null) => void) | undefined;
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
onPasteFiles: ((files: File[]) => void) | undefined;
onPasteImages: ((files: readonly NativePastedFile[]) => void) | undefined;
client: DaemonClient | null;
isReadyForDictation: boolean | undefined;
@@ -1239,6 +1262,7 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu
attachmentMenuItems: props.attachmentMenuItems,
onAttachButtonRef: props.onAttachButtonRef,
onAddImages: props.onAddImages,
onPasteFiles: props.onPasteFiles,
onPasteImages: props.onPasteImages,
client: props.client,
isReadyForDictation: props.isReadyForDictation,
@@ -1321,6 +1345,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
attachmentMenuItems,
onAttachButtonRef,
onAddImages,
onPasteFiles,
onPasteImages,
client,
isReadyForDictation,
@@ -1874,6 +1899,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
isDictating,
isRealtimeVoiceForCurrentAgent,
onAddImages,
onPasteFiles,
isSubmitLoading,
});
const handleSelectionChange = useCallback(
@@ -7,7 +7,7 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useOverlayFlatListScrollbar } from "@/components/ui/overlay-scrollbar/use-overlay-flat-list-scrollbar";
import { useFetchQuery } from "@/data/query";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useSessionStore } from "@/stores/session-store";
import { useHostRuntimeClient, useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
import type { Theme } from "@/styles/theme";
import { toErrorMessage } from "@/utils/error-messages";
import { resolveFileFilterView, type FileFilterMatch, type FileFilterResponse } from "./model";
@@ -40,7 +40,10 @@ export function FileFilterResults({
renderMatch: (match: FileFilterMatch, index: number) => ReactElement;
}): ReactElement {
const { t } = useTranslation();
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const client = useHostRuntimeClient(serverId);
const connectionStatus = useHostRuntimeConnectionStatus(serverId);
const canFetch = Boolean(client && connectionStatus === "online");
const isHostUnavailable = connectionStatus === "offline" || connectionStatus === "error";
const debouncedQuery = useDebouncedValue(query, SEARCH_DEBOUNCE_MS);
const search = useFetchQuery({
queryKey: [FILE_FILTER_QUERY_KEY, serverId, workspaceRoot, debouncedQuery],
@@ -56,14 +59,18 @@ export function FileFilterResults({
if (payload.error) throw new Error(payload.error);
return { query: debouncedQuery, entries: payload.entries };
},
enabled: canFetch,
dataShape: "list",
staleTimeMs: 0,
retry: false,
});
const queryError = search.error && debouncedQuery === query ? toErrorMessage(search.error) : null;
const view = resolveFileFilterView({
query,
response: search.data,
error: search.error && debouncedQuery === query ? toErrorMessage(search.error) : null,
error:
queryError ??
(!canFetch && isHostUnavailable ? t("workspace.terminal.hostDisconnected") : null),
isFetching: search.isFetching,
showHiddenFiles,
});
@@ -75,7 +82,9 @@ export function FileFilterResults({
[renderMatch],
);
const { refetch } = search;
const handleRetry = useCallback(() => void refetch(), [refetch]);
const handleRetry = useCallback(() => {
if (canFetch) void refetch();
}, [canFetch, refetch]);
if (view.status === "results") {
return (
+4 -3
View File
@@ -14,7 +14,7 @@ import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
import { useFileDownload } from "@/hooks/use-file-download";
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
import { usePublishPanelInstanceAttributes } from "@/panels/panel-instance-attributes";
import { useSessionStore } from "@/stores/session-store";
import { useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
import { buildAbsoluteExplorerPath } from "@/utils/explorer-paths";
import { formatFileSize } from "@/utils/format-file-size";
import type { WorkspaceFileLocation } from "@/workspace/file-open";
@@ -38,7 +38,8 @@ export function FilePane({
navigationRevision: number;
}) {
const { t } = useTranslation();
const connected = useSessionStore((state) => Boolean(state.sessions[serverId]?.client));
const connectionStatus = useHostRuntimeConnectionStatus(serverId);
const isHostUnavailable = connectionStatus === "offline" || connectionStatus === "error";
const root = workspaceRoot.trim();
const path = location.path.trim();
const target = useMemo(
@@ -90,7 +91,7 @@ export function FilePane({
);
let body;
if (!connected && target) {
if (isHostUnavailable && snapshot.status !== "ready" && target) {
body = <Text style={styles.errorText}>{t("workspace.terminal.hostDisconnected")}</Text>;
} else if (!handle || snapshot.status === "loading") {
return (
+2 -1
View File
@@ -1,4 +1,5 @@
import { useEffect, useState, useSyncExternalStore } from "react";
import { useHostRuntimeClient } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { createDaemonFileSession } from "./daemon-session";
import { FileHandle, type FileHandleSnapshot, type FileTarget } from "./handle";
@@ -11,7 +12,7 @@ export function useFileHandle(input: {
observing: boolean;
}): FileHandle | null {
const { serverId, target, absolutePath, observing } = input;
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const client = useHostRuntimeClient(serverId);
// COMPAT(workspaceFileEditing): added in v0.2.0, remove after 2027-01-18 once daemon floor >= v0.2.0.
const workspaceFileEditing = useSessionStore(
(state) => state.sessions[serverId]?.serverInfo?.features?.workspaceFileEditing === true,
@@ -1,12 +1,16 @@
import React, { act } from "react";
import { createRoot, type Root } from "react-dom/client";
import { within } from "@testing-library/dom";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import type { DaemonClient, FileReadResult } from "@getpaseo/client/internal/daemon-client";
import { SafeAreaInsetsContext } from "react-native-safe-area-context";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { AssistantFileLinkResolverProvider } from "@/assistant-file-links";
import { ForgeShorthandProvider } from "@/git/forge-shorthand";
import { i18n } from "@/i18n/i18next";
import { ToastApiProvider } from "@/contexts/toast-context";
import type { ToastApi } from "@/components/toast-host";
import type { PrPaneCheck, PrPaneData } from "./data";
import type { PrPaneActivity, PrPaneCheck, PrPaneData } from "./data";
import { PullRequestPane } from "./pane";
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
@@ -229,3 +233,133 @@ describe("pull request pane layout", () => {
await expect.poll(() => Math.round(checksRegionBottom(pane) - before)).toBe(120);
});
});
function createFakeFileReader() {
const reads: { cwd: string; path: string }[] = [];
const client = {
async readFile(cwd: string, path: string): Promise<FileReadResult> {
reads.push({ cwd, path });
return {
kind: "image",
path,
mime: "image/png",
size: 4,
modifiedAt: "2026-12-01T00:00:00.000Z",
bytes: new Uint8Array([1, 2, 3, 4]),
};
},
} as unknown as DaemonClient;
return { reads, client };
}
const PR_MARKDOWN_ACTIVITY: PrPaneActivity[] = [
{
provider: "github",
id: "comment-1",
kind: "comment",
author: "alice",
avatarColor: "#4f46e5",
body: [
"See #123 and [Docs](https://example.test/docs) and [Local](/etc/passwd) and src/index.ts",
"![CommentLocal](/tmp/secret.png)",
"![CommentUnc](\\\\\\\\attacker\\\\share\\\\x.png)",
"![Badge](https://example.test/badge.png)",
].join("\n\n"),
age: "2m",
url: "https://example.test/pull/42#issuecomment-1",
},
{
provider: "github",
id: "review-1",
kind: "review",
author: "bob",
avatarColor: "#16a34a",
reviewState: "commented",
body: "Review fixes other/repo#456 ![ReviewLocal](./secret.png)",
age: "1m",
url: "https://example.test/pull/42#pullrequestreview-1",
},
{
provider: "github",
id: "thread-comment-1",
kind: "comment",
author: "bob",
avatarColor: "#16a34a",
reviewId: "review-1",
threadId: "thread-1",
location: { path: "src/app.ts", line: 10, threadId: "thread-1" },
body: "Thread references #789 ![ThreadLocal](file://attacker/share/x.png)",
age: "1m",
url: "https://example.test/pull/42#discussion_r1",
},
];
const PR_MARKDOWN_DATA: PrPaneData = { ...pullRequest([]), activity: PR_MARKDOWN_ACTIVITY };
describe("pull request pane Markdown safety and forge shorthand", () => {
it("never calls client.readFile for local or UNC images across comments, reviews, and threads while keeping #123 and https links", async () => {
const { reads, client: fakeClient } = createFakeFileReader();
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
container = document.createElement("div");
container.style.height = "900px";
container.style.width = "600px";
container.style.display = "flex";
container.style.flexDirection = "column";
document.body.appendChild(container);
root = createRoot(container);
act(() =>
root?.render(
<QueryClientProvider client={queryClient}>
<SafeAreaInsetsContext.Provider value={NO_INSETS}>
<ToastApiProvider api={silentToasts}>
<AssistantFileLinkResolverProvider
serverId="server-1"
workspaceRoot="/repo"
client={fakeClient}
>
<ForgeShorthandProvider
forge="github"
remoteUrl="https://github.com/acme/widgets.git"
forgeWeb={null}
>
<PullRequestPane
serverId="server-1"
cwd="/repo"
data={PR_MARKDOWN_DATA}
activityLoading={false}
/>
</ForgeShorthandProvider>
</AssistantFileLinkResolverProvider>
</ToastApiProvider>
</SafeAreaInsetsContext.Provider>
</QueryClientProvider>,
),
);
await expect.poll(() => container?.textContent).toContain("CommentLocal");
await expect.poll(() => container?.textContent).toContain("ReviewLocal");
await expect.poll(() => container?.textContent).toContain("ThreadLocal");
await settleLayout();
expect(reads).toEqual([]);
const links = Array.from(container.querySelectorAll("a")).map((a) => ({
text: a.textContent,
href: a.getAttribute("href"),
}));
expect(links).toContainEqual(expect.objectContaining({ text: "#123" }));
expect(links).toContainEqual(expect.objectContaining({ text: "other/repo#456" }));
expect(links).toContainEqual(expect.objectContaining({ text: "#789" }));
expect(links).toContainEqual(
expect.objectContaining({ text: "Docs", href: "https://example.test/docs" }),
);
expect(links.some((l) => l.text === "Local" || l.text === "src/index.ts")).toBe(false);
const imgs = Array.from(container.querySelectorAll("img"));
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("CommentLocal");
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("CommentUnc");
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("ReviewLocal");
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("ThreadLocal");
});
});
@@ -137,11 +137,6 @@ const ADD_TO_CHAT_MENU_ICON = (
const COPY_MENU_ICON = <ThemedCopy size={14} uniProps={foregroundMutedColorMapping} />;
const OPEN_MENU_ICON = <ThemedExternalLink size={14} uniProps={foregroundMutedColorMapping} />;
function handleMarkdownLinkPress(url: string): boolean {
void openExternalUrl(url);
return false;
}
function entryHeaderPressableStyle({ hovered }: { hovered?: boolean }) {
return [styles.entryHeaderPressable, Boolean(hovered) && styles.hoverable];
}
@@ -877,7 +872,7 @@ function SingleActivityCard({
{collapsed ? null : (
<>
<View style={styles.cardBody}>
<MarkdownRenderer text={activity.body} compact onLinkPress={handleMarkdownLinkPress} />
<MarkdownRenderer text={activity.body} compact destinations="https" />
</View>
{attachEnabled && canAddPullRequestActivityToChat(activity) ? (
<View style={styles.cardFooter}>
@@ -988,7 +983,7 @@ function ReviewCard({
<>
{hasBody ? (
<View style={styles.cardBody}>
<MarkdownRenderer text={review.body} compact onLinkPress={handleMarkdownLinkPress} />
<MarkdownRenderer text={review.body} compact destinations="https" />
</View>
) : null}
{attachEnabled && canAddPullRequestActivityToChat(review) ? (
@@ -1185,7 +1180,7 @@ function ThreadComment({
</View>
{comment.body.trim() !== "" ? (
<View style={styles.threadCommentBody}>
<MarkdownRenderer text={comment.body} compact onLinkPress={handleMarkdownLinkPress} />
<MarkdownRenderer text={comment.body} compact destinations="https" />
</View>
) : null}
</View>
@@ -1,3 +1,4 @@
import { File } from "expo-file-system";
import { ImageManipulator, SaveFormat } from "expo-image-manipulator";
import {
normalizePickedImageAssetsWith,
@@ -10,9 +11,25 @@ export type {
ExpoImagePickerAssetLike,
PickedImageAttachmentInput,
PickedImageSource,
ReadPickedImageHeader,
RenderPickedImage,
} from "./picked-image-normalizer";
const HEADER_SNIFF_BYTES = 12;
async function readPickedImageHeader(uri: string): Promise<Uint8Array | null> {
try {
const handle = new File(uri).open();
try {
return handle.readBytes(HEADER_SNIFF_BYTES);
} finally {
handle.close();
}
} catch {
return null;
}
}
async function renderPickedImage(uri: string, options: RenderPickedImageOptions): Promise<string> {
const context = ImageManipulator.manipulate(uri);
let image: Awaited<ReturnType<typeof context.renderAsync>> | null = null;
@@ -37,7 +54,7 @@ async function renderPickedImage(uri: string, options: RenderPickedImageOptions)
export async function normalizePickedImageAssets(
assets: readonly ExpoImagePickerAssetLike[],
): Promise<PickedImageAttachmentInput[]> {
return normalizePickedImageAssetsWith(assets, renderPickedImage);
return normalizePickedImageAssetsWith(assets, renderPickedImage, readPickedImageHeader);
}
export async function pickImagesWithDesktopDialog(
@@ -2,10 +2,28 @@ import { describe, expect, it } from "vitest";
import {
MAX_PICKED_IMAGE_EDGE,
normalizePickedImageAssetsWith,
type ReadPickedImageHeader,
type RenderPickedImage,
type RenderPickedImageOptions,
} from "./picked-image-normalizer";
const PNG_HEADER = new Uint8Array([
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d,
]);
const JPEG_HEADER = new Uint8Array([
0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0x4a, 0x46, 0x49, 0x46, 0x00, 0x01,
]);
const AVIF_HEADER = new Uint8Array([
0x00, 0x00, 0x00, 0x20, 0x66, 0x74, 0x79, 0x70, 0x61, 0x76, 0x69, 0x66,
]);
const HEIC_HEADER = new Uint8Array([
0x00, 0x00, 0x00, 0x18, 0x66, 0x74, 0x79, 0x70, 0x68, 0x65, 0x69, 0x63,
]);
function headerReader(headers: Record<string, Uint8Array | null>): ReadPickedImageHeader {
return async (uri) => headers[uri] ?? null;
}
function fakeRenderer(): {
render: RenderPickedImage;
calls: { uri: string; options: RenderPickedImageOptions }[];
@@ -191,4 +209,111 @@ describe("native image attachment picker", () => {
expect(result[0]?.mimeType).toBe("image/png");
expect(calls[0]?.options).toEqual({ format: "png", compress: 0.85, resize: null });
});
it("converts Android RawImageExporter AVIF and HEIC files copied with a .jpeg URI", async () => {
const { render, calls } = fakeRenderer();
const result = await normalizePickedImageAssetsWith(
[
{
uri: "file:///cache/ImagePicker/9e64c1a2.jpeg",
mimeType: "image/avif",
fileName: "1000000225.jpg",
width: 800,
height: 600,
},
{
uri: "file:///cache/ImagePicker/a1b2c3.jpeg",
mimeType: "image/heic",
fileName: "IMG_20261202.heic",
width: 4032,
height: 3024,
},
],
render,
);
expect(result).toEqual([
{
source: { kind: "file_uri", uri: "file:///cache/ImageManipulator/rendered.png" },
mimeType: "image/png",
fileName: "1000000225.png",
},
{
source: { kind: "file_uri", uri: "file:///cache/ImageManipulator/rendered.jpg" },
mimeType: "image/jpeg",
fileName: "IMG_20261202.jpg",
},
]);
expect(calls).toEqual([
{
uri: "file:///cache/ImagePicker/9e64c1a2.jpeg",
options: { format: "png", compress: 0.85, resize: null },
},
{
uri: "file:///cache/ImagePicker/a1b2c3.jpeg",
options: { format: "jpeg", compress: 0.85, resize: { width: MAX_PICKED_IMAGE_EDGE } },
},
]);
});
it("trusts magic bytes when URI and MIME mislabel AVIF, HEIC, PNG, or JPEG", async () => {
const { render, calls } = fakeRenderer();
const readHeader = headerReader({
"file:///cache/fake-avif.jpg": AVIF_HEADER,
"file:///cache/fake-heic.jpg": HEIC_HEADER,
"file:///cache/screen.jpg": PNG_HEADER,
"file:///cache/photo.png": JPEG_HEADER,
});
const result = await normalizePickedImageAssetsWith(
[
{ uri: "file:///cache/fake-avif.jpg", mimeType: "image/jpeg", fileName: "fake-avif.jpg" },
{
uri: "file:///cache/fake-heic.jpg",
mimeType: "image/jpeg",
fileName: "fake-heic.jpg",
width: 4032,
height: 3024,
},
{ uri: "file:///cache/screen.jpg", mimeType: "image/jpeg", fileName: "screen.jpg" },
{ uri: "file:///cache/photo.png", mimeType: "image/png", fileName: "photo.png" },
],
render,
readHeader,
);
expect(result).toEqual([
{
source: { kind: "file_uri", uri: "file:///cache/ImageManipulator/rendered.png" },
mimeType: "image/png",
fileName: "fake-avif.png",
},
{
source: { kind: "file_uri", uri: "file:///cache/ImageManipulator/rendered.jpg" },
mimeType: "image/jpeg",
fileName: "fake-heic.jpg",
},
{
source: { kind: "file_uri", uri: "file:///cache/screen.jpg" },
mimeType: "image/png",
fileName: "screen.png",
},
{
source: { kind: "file_uri", uri: "file:///cache/photo.png" },
mimeType: "image/jpeg",
fileName: "photo.jpg",
},
]);
expect(calls).toEqual([
{
uri: "file:///cache/fake-avif.jpg",
options: { format: "png", compress: 0.85, resize: null },
},
{
uri: "file:///cache/fake-heic.jpg",
options: { format: "jpeg", compress: 0.85, resize: { width: MAX_PICKED_IMAGE_EDGE } },
},
]);
});
});
@@ -32,6 +32,7 @@ export interface RenderPickedImageOptions {
}
export type RenderPickedImage = (uri: string, options: RenderPickedImageOptions) => Promise<string>;
export type ReadPickedImageHeader = (uri: string) => Promise<Uint8Array | null>;
interface SupportedPickedImageFormat {
mimeType: "image/jpeg" | "image/png";
@@ -51,6 +52,8 @@ const PNG_FORMAT: SupportedPickedImageFormat = {
render: "png",
};
const HEIF_BRANDS = new Set(["heic", "heix", "hevc", "hevx", "mif1", "msf1"]);
function extensionFromPath(path: string | null | undefined): string | null {
const match = path?.match(/\.([a-z0-9]+)(?:[?#].*)?$/i);
return match?.[1]?.toLowerCase() ?? null;
@@ -69,7 +72,7 @@ function supportedFormatForExtension(extension: string | null): SupportedPickedI
function supportedFormatForMimeType(
mimeType: string | null | undefined,
): SupportedPickedImageFormat | null {
const normalizedMimeType = mimeType?.toLowerCase();
const normalizedMimeType = mimeType?.split(";")[0]?.trim().toLowerCase();
if (normalizedMimeType === "image/jpeg" || normalizedMimeType === "image/jpg") {
return JPEG_FORMAT;
}
@@ -79,24 +82,76 @@ function supportedFormatForMimeType(
return null;
}
function detectHeaderFormat(header: Uint8Array): SupportedPickedImageFormat | null {
if (
header.length >= 8 &&
header[0] === 0x89 &&
header[1] === 0x50 &&
header[2] === 0x4e &&
header[3] === 0x47 &&
header[4] === 0x0d &&
header[5] === 0x0a &&
header[6] === 0x1a &&
header[7] === 0x0a
) {
return PNG_FORMAT;
}
if (header.length >= 3 && header[0] === 0xff && header[1] === 0xd8 && header[2] === 0xff) {
return JPEG_FORMAT;
}
return null;
}
function isHeifHeader(header: Uint8Array | null): boolean {
if (!header || header.length < 12) {
return false;
}
if (
header[4] !== 0x66 || // f
header[5] !== 0x74 || // t
header[6] !== 0x79 || // y
header[7] !== 0x70 // p
) {
return false;
}
const brand = String.fromCharCode(header[8]!, header[9]!, header[10]!, header[11]!).toLowerCase();
return HEIF_BRANDS.has(brand);
}
function pickedAssetSupportedFormat(
asset: ExpoImagePickerAssetLike,
header: Uint8Array | null,
): SupportedPickedImageFormat | null {
// Trust the container signature over picker metadata when readable (Android
// RawImageExporter and iOS slow-path fallback can write raw HEIC/AVIF bytes to .jpeg/.jpg).
if (header && header.length >= 4) {
return detectHeaderFormat(header);
}
const uriExtension = extensionFromPath(asset.uri);
const uriFormat = supportedFormatForExtension(uriExtension);
if (uriExtension && !uriFormat) {
return null;
}
return (
supportedFormatForMimeType(asset.mimeType) ??
supportedFormatForExtension(extensionFromPath(asset.fileName)) ??
uriFormat
);
const explicitMime = asset.mimeType?.trim();
if (explicitMime) {
return supportedFormatForMimeType(explicitMime);
}
const fileNameExtension = extensionFromPath(asset.fileName);
if (fileNameExtension) {
return supportedFormatForExtension(fileNameExtension);
}
return uriFormat;
}
function isHeifAsset(asset: ExpoImagePickerAssetLike): boolean {
const mimeType = asset.mimeType?.toLowerCase();
function isHeifAsset(asset: ExpoImagePickerAssetLike, header: Uint8Array | null): boolean {
if (isHeifHeader(header)) {
return true;
}
const mimeType = asset.mimeType?.split(";")[0]?.trim().toLowerCase();
if (mimeType === "image/heic" || mimeType === "image/heif") {
return true;
}
@@ -110,8 +165,11 @@ function isHeifAsset(asset: ExpoImagePickerAssetLike): boolean {
* Camera photos (HEIC on iPhone) have no transparency, so JPEG keeps them small.
* Other unsupported formats may carry alpha and become lossless PNG.
*/
function convertedFormat(asset: ExpoImagePickerAssetLike): SupportedPickedImageFormat {
return isHeifAsset(asset) ? JPEG_FORMAT : PNG_FORMAT;
function convertedFormat(
asset: ExpoImagePickerAssetLike,
header: Uint8Array | null,
): SupportedPickedImageFormat {
return isHeifAsset(asset, header) ? JPEG_FORMAT : PNG_FORMAT;
}
function resizeToFit(asset: ExpoImagePickerAssetLike): RenderPickedImageOptions["resize"] {
@@ -137,10 +195,12 @@ function replaceFileExtension(
export async function normalizePickedImageAssetsWith(
assets: readonly ExpoImagePickerAssetLike[],
render: RenderPickedImage,
readHeader?: ReadPickedImageHeader,
): Promise<PickedImageAttachmentInput[]> {
return await Promise.all(
assets.map(async (asset) => {
const supportedFormat = pickedAssetSupportedFormat(asset);
const header = readHeader ? await readHeader(asset.uri) : null;
const supportedFormat = pickedAssetSupportedFormat(asset, header);
if (supportedFormat) {
return {
source: { kind: "file_uri", uri: asset.uri },
@@ -149,8 +209,8 @@ export async function normalizePickedImageAssetsWith(
};
}
const outputFormat = convertedFormat(asset);
const resize = isHeifAsset(asset) ? resizeToFit(asset) : null;
const outputFormat = convertedFormat(asset, header);
const resize = isHeifAsset(asset, header) ? resizeToFit(asset) : null;
const renderedUri = await render(asset.uri, {
format: outputFormat.render,
compress: JPEG_COMPRESS,
+6 -10
View File
@@ -4,7 +4,11 @@ import { File } from "expo-file-system";
import { getDesktopHost, isElectronRuntime } from "@/desktop/host";
import { isWeb } from "@/constants/platform";
import { getMimeTypeFromPath } from "@/attachments/file-types";
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
import {
readDesktopFileBytes,
selectedFileFromWebFile,
type SelectedFile,
} from "@/attachments/selected-file";
async function pickFilesWithDesktopDialog(): Promise<SelectedFile[] | null> {
const dialog = getDesktopHost()?.dialog;
@@ -52,15 +56,7 @@ function pickFilesWithWebInput(): Promise<SelectedFile[] | null> {
return;
}
const result: SelectedFile[] = [];
for (const file of files) {
result.push({
fileName: file.name,
mimeType: file.type || getMimeTypeFromPath(file.name),
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
});
}
resolve(result);
resolve(files.map(selectedFileFromWebFile));
});
input.addEventListener("cancel", () => {
@@ -1,4 +1,4 @@
import { useHostFeatureMap } from "@/runtime/host-features";
import { useHostFeatureAvailabilityMap } from "@/runtime/host-features";
import { useCallback, useEffect, useMemo } from "react";
import { useStoreWithEqualityFn } from "zustand/traditional";
import { useCreateFlowStore } from "@/stores/create-flow-store";
@@ -142,8 +142,9 @@ export function useSidebarWorkspacesList(options?: {
const workspaceSort = useSidebarViewStore((state) => state.workspaceSort);
const groupMode = useSidebarViewStore((state) => state.groupMode);
const sortSupport = useHostFeatureMap(directoryServerIds, "workspaceSortTimes");
const workspaceSortSupported = [...sortSupport.values()].every(Boolean);
const sortSupport = useHostFeatureAvailabilityMap(directoryServerIds, "workspaceSortTimes");
// Cached workspaces are visible before their host sends server info.
const workspaceSortSupported = ![...sortSupport.values()].includes(false);
const sort =
groupMode === "project" && (workspaceSort === "manual" || workspaceSortSupported)
? workspaceSort
@@ -41,6 +41,16 @@ export const pluginGallery = {
reportBug: "Report a bug",
viewOnNpm: "View on npm",
sponsor: "Sponsor",
sponsorPlatforms: {
github: "Sponsor on GitHub",
kofi: "Support on Ko-fi",
buymeacoffee: "Buy Me a Coffee",
opencollective: "Sponsor on Open Collective",
patreon: "Support on Patreon",
polar: "Sponsor on Polar",
liberapay: "Donate on Liberapay",
paypal: "Donate via PayPal",
},
},
off: { title: "Plugins are off on {{host}}" },
empty: { noMatches: "No plugins match" },
@@ -179,6 +189,16 @@ export const pluginGallery = {
reportBug: "الإبلاغ عن خطأ",
viewOnNpm: "عرض على npm",
sponsor: "رعاية",
sponsorPlatforms: {
github: "رعاية على GitHub",
kofi: "دعم على Ko-fi",
buymeacoffee: "Buy Me a Coffee",
opencollective: "رعاية على Open Collective",
patreon: "دعم على Patreon",
polar: "رعاية على Polar",
liberapay: "تبرع عبر Liberapay",
paypal: "تبرع عبر PayPal",
},
},
off: { title: "الإضافات متوقفة على {{host}}" },
empty: { noMatches: "لا توجد إضافات مطابقة" },
@@ -309,6 +329,16 @@ export const pluginGallery = {
reportBug: "Informar un error",
viewOnNpm: "Ver en npm",
sponsor: "Patrocinar",
sponsorPlatforms: {
github: "Patrocinar en GitHub",
kofi: "Apoyar en Ko-fi",
buymeacoffee: "Buy Me a Coffee",
opencollective: "Patrocinar en Open Collective",
patreon: "Apoyar en Patreon",
polar: "Patrocinar en Polar",
liberapay: "Donar en Liberapay",
paypal: "Donar con PayPal",
},
},
off: { title: "Los plugins están desactivados en {{host}}" },
empty: { noMatches: "Ningún plugin coincide" },
@@ -445,6 +475,16 @@ export const pluginGallery = {
reportBug: "Signaler un bug",
viewOnNpm: "Voir sur npm",
sponsor: "Soutenir",
sponsorPlatforms: {
github: "Soutenir sur GitHub",
kofi: "Soutenir sur Ko-fi",
buymeacoffee: "Buy Me a Coffee",
opencollective: "Soutenir sur Open Collective",
patreon: "Soutenir sur Patreon",
polar: "Soutenir sur Polar",
liberapay: "Donner sur Liberapay",
paypal: "Donner via PayPal",
},
},
off: { title: "Les plugins sont désactivés sur {{host}}" },
empty: { noMatches: "Aucun plugin ne correspond" },
@@ -584,6 +624,16 @@ export const pluginGallery = {
reportBug: "バグを報告",
viewOnNpm: "npm で表示",
sponsor: "スポンサー",
sponsorPlatforms: {
github: "GitHub でスポンサー",
kofi: "Ko-fi で支援",
buymeacoffee: "Buy Me a Coffee",
opencollective: "Open Collective でスポンサー",
patreon: "Patreon で支援",
polar: "Polar でスポンサー",
liberapay: "Liberapay で寄付",
paypal: "PayPal で寄付",
},
},
off: { title: "{{host}} ではプラグインがオフです" },
empty: { noMatches: "一致するプラグインはありません" },
@@ -719,6 +769,16 @@ export const pluginGallery = {
reportBug: "버그 신고",
viewOnNpm: "npm에서 보기",
sponsor: "후원하기",
sponsorPlatforms: {
github: "GitHub에서 후원",
kofi: "Ko-fi에서 지원",
buymeacoffee: "Buy Me a Coffee",
opencollective: "Open Collective에서 후원",
patreon: "Patreon에서 지원",
polar: "Polar에서 후원",
liberapay: "Liberapay로 기부",
paypal: "PayPal로 기부",
},
},
off: { title: "{{host}}에서 플러그인이 꺼져 있습니다" },
empty: { noMatches: "일치하는 플러그인이 없습니다" },
@@ -848,6 +908,16 @@ export const pluginGallery = {
reportBug: "Reportar bug",
viewOnNpm: "Ver no npm",
sponsor: "Patrocinar",
sponsorPlatforms: {
github: "Patrocinar no GitHub",
kofi: "Apoiar no Ko-fi",
buymeacoffee: "Buy Me a Coffee",
opencollective: "Patrocinar no Open Collective",
patreon: "Apoiar no Patreon",
polar: "Patrocinar no Polar",
liberapay: "Doar no Liberapay",
paypal: "Doar via PayPal",
},
},
off: { title: "Os plugins estão desativados em {{host}}" },
empty: { noMatches: "Nenhum plugin corresponde" },
@@ -988,6 +1058,16 @@ export const pluginGallery = {
reportBug: "Сообщить об ошибке",
viewOnNpm: "Открыть на npm",
sponsor: "Поддержать",
sponsorPlatforms: {
github: "Поддержать на GitHub",
kofi: "Поддержать на Ko-fi",
buymeacoffee: "Buy Me a Coffee",
opencollective: "Поддержать на Open Collective",
patreon: "Поддержать на Patreon",
polar: "Поддержать на Polar",
liberapay: "Пожертвовать на Liberapay",
paypal: "Пожертвовать через PayPal",
},
},
off: { title: "Плагины выключены на {{host}}" },
empty: { noMatches: "Нет подходящих плагинов" },
@@ -1119,6 +1199,16 @@ export const pluginGallery = {
reportBug: "报告问题",
viewOnNpm: "在 npm 查看",
sponsor: "赞助作者",
sponsorPlatforms: {
github: "在 GitHub 赞助",
kofi: "在 Ko-fi 支持",
buymeacoffee: "Buy Me a Coffee",
opencollective: "在 Open Collective 赞助",
patreon: "在 Patreon 支持",
polar: "在 Polar 赞助",
liberapay: "在 Liberapay 捐赠",
paypal: "通过 PayPal 捐赠",
},
},
off: { title: "{{host}} 上的插件已关闭" },
empty: { noMatches: "没有匹配的插件" },
+4 -1
View File
@@ -1273,6 +1273,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
const streamContent = (
<View
style={animatedStaticStyles.content}
pointerEvents="box-none"
onStartShouldSetResponderCapture={handleAttentionInteraction}
>
{showsComposer ? null : <SheetAgentFacts serverId={serverId} agentId={agentId} />}
@@ -1304,8 +1305,10 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
</View>
);
// Empty space stays box-none so a tap there reaches the dock background, which closes the
// keyboard. A new agent's draft has no list to claim it.
const dockContent = (
<View style={styles.contentContainer}>
<View style={styles.contentContainer} pointerEvents="box-none">
{streamContent}
{showHistorySyncError ? (
@@ -16,6 +16,7 @@ import { usePaneContext } from "@/panels/pane-context";
import { PaneSubtitle } from "@/panels/pane-subtitle";
import { definePanel, type PanelDescriptor } from "@/panels/panel-registry";
import { providerSubagentTabLabel } from "@/panels/tab-labels";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import type { SheetTab } from "@/stores/workspace-layout-store";
import { ParentAgentCallout } from "@/subagents/parent";
@@ -131,7 +132,8 @@ function ProviderSubagentPanel() {
state.sessions[serverId]?.agentDetails.get(target.parentAgentId) ??
null,
);
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
const client = useHostRuntimeClient(serverId);
const isConnected = useHostRuntimeIsConnected(serverId);
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
// COMPAT(projectedSubagentTimeline): added after v0.8.0, remove after 2027-03-14.
const supported = serverInfo?.features?.projectedSubagentTimeline === true;
@@ -155,12 +157,12 @@ function ProviderSubagentPanel() {
);
useEffect(() => {
if (!client || !supported) return;
if (!client || !isConnected || !supported) return;
void refreshProviderSubagents(client, serverId, target.parentAgentId).catch(() => undefined);
}, [client, serverId, supported, target.parentAgentId]);
}, [client, isConnected, serverId, supported, target.parentAgentId]);
useEffect(() => {
if (!client || !supported) return;
if (!client || !isConnected || !supported) return;
return observeProviderSubagentTimeline({
client,
serverId,
@@ -176,7 +178,7 @@ function ProviderSubagentPanel() {
});
},
});
}, [client, supported, serverId, target.parentAgentId, target.subagentId]);
}, [client, isConnected, supported, serverId, target.parentAgentId, target.subagentId]);
const loadOlder = useCallback(async (): Promise<boolean> => {
if (!client || !supported || isLoadingOlder || !timeline?.hasOlder || !timeline.epoch) {
@@ -30,7 +30,7 @@ import {
} from "./listing";
import { usePluginOperation } from "./operations";
import { PluginMeta, PluginRow, PluginTile } from "./plugin-row";
import { usePluginDirectory } from "./queries";
import { usePluginDirectory, usePrefetchPluginListing } from "./queries";
import { buildPluginListingRoute } from "./routes";
import { PluginRowsSkeleton } from "./skeletons";
import { pluginErrorText } from "./error-text";
@@ -62,6 +62,7 @@ function ListingRow({
uninstalling,
onInstall,
onUninstall,
onPrepareOpen,
}: {
serverId: string;
listing: PluginListing;
@@ -69,6 +70,7 @@ function ListingRow({
uninstalling: boolean;
onInstall(listing: PluginListing): void;
onUninstall(plugin: PluginListItem): void;
onPrepareOpen(listingId: string): void;
}) {
const { i18n } = useTranslation();
const meta = useListingMeta();
@@ -78,6 +80,7 @@ function ListingRow({
() => router.push(buildPluginListingRoute(serverId, listing.id)),
[listing.id, serverId],
);
const prepare = useCallback(() => onPrepareOpen(listing.id), [listing.id, onPrepareOpen]);
return (
<PluginRow
name={name}
@@ -87,6 +90,7 @@ function ListingRow({
authorAvatar={listingAuthorAvatar(listing)}
error={!installedPlugin && operation?.status === "failed" ? operation.error : undefined}
onPress={open}
onPrepareOpen={prepare}
accessibilityLabel={name}
testID={`plugin-listing-${listing.id}`}
>
@@ -104,7 +108,15 @@ function ListingRow({
type HoverState = PressableStateCallbackType & { hovered?: boolean };
function FeaturedCard({ serverId, listing }: { serverId: string; listing: PluginListing }) {
function FeaturedCard({
serverId,
listing,
onPrepareOpen,
}: {
serverId: string;
listing: PluginListing;
onPrepareOpen(listingId: string): void;
}) {
const { i18n } = useTranslation();
const meta = useListingMeta();
const { name, description } = listingText(listing, i18n.language);
@@ -114,6 +126,7 @@ function FeaturedCard({ serverId, listing }: { serverId: string; listing: Plugin
() => router.push(buildPluginListingRoute(serverId, listing.id)),
[listing.id, serverId],
);
const prepare = useCallback(() => onPrepareOpen(listing.id), [listing.id, onPrepareOpen]);
const cardStyle = useCallback(
({ hovered }: HoverState) => [styles.featured, hovered && styles.featuredHovered],
[],
@@ -123,6 +136,8 @@ function FeaturedCard({ serverId, listing }: { serverId: string; listing: Plugin
accessibilityRole="button"
accessibilityLabel={name}
onPress={open}
onHoverIn={prepare}
onPressIn={prepare}
style={cardStyle}
highlightStyle={styles.featuredPressed}
testID={`plugin-featured-${listing.id}`}
@@ -147,7 +162,15 @@ function FeaturedCard({ serverId, listing }: { serverId: string; listing: Plugin
}
/** Every featured listing: a row to swipe on a phone, a grid of four or two columns otherwise. */
function Featured({ serverId, listings }: { serverId: string; listings: PluginListing[] }) {
function Featured({
serverId,
listings,
onPrepareOpen,
}: {
serverId: string;
listings: PluginListing[];
onPrepareOpen(listingId: string): void;
}) {
const { t } = useTranslation();
const compact = useIsCompactFormFactor();
const grid = useContainerWidthBelow(FEATURED_FOUR_COLUMNS, { initialIsBelow: false });
@@ -162,7 +185,7 @@ function Featured({ serverId, listings }: { serverId: string; listings: PluginLi
>
{listings.map((listing) => (
<View key={listing.id} style={styles.cellSwipe}>
<FeaturedCard serverId={serverId} listing={listing} />
<FeaturedCard serverId={serverId} listing={listing} onPrepareOpen={onPrepareOpen} />
</View>
))}
</ScrollView>
@@ -170,7 +193,7 @@ function Featured({ serverId, listings }: { serverId: string; listings: PluginLi
<View style={styles.featuredGrid} onLayout={grid.onLayout}>
{listings.map((listing) => (
<View key={listing.id} style={cellStyle}>
<FeaturedCard serverId={serverId} listing={listing} />
<FeaturedCard serverId={serverId} listing={listing} onPrepareOpen={onPrepareOpen} />
</View>
))}
</View>
@@ -242,11 +265,13 @@ function ListingList({
listings,
installed,
onInstall,
onPrepareOpen,
}: {
serverId: string;
listings: PluginListing[];
installed: ReadonlyMap<string, PluginListItem>;
onInstall(listing: PluginListing): void;
onPrepareOpen(listingId: string): void;
}) {
const { t } = useTranslation();
const actions = usePluginActions(serverId);
@@ -281,6 +306,7 @@ function ListingList({
}
onInstall={onInstall}
onUninstall={uninstall}
onPrepareOpen={onPrepareOpen}
/>
))}
</SettingsCard>
@@ -309,6 +335,7 @@ function Directory({
onInstall(listing: PluginListing): void;
}) {
const { t, i18n } = useTranslation();
const prefetchListing = usePrefetchPluginListing(serverId);
const [category, setCategory] = useState<string>(ALL_CATEGORIES);
const [sort, setSort] = useState<DirectorySort>("popular");
const listings = filterDirectory(index, { query, category, sort }, i18n.language);
@@ -348,7 +375,9 @@ function Directory({
testID="plugin-sort"
/>
</View>
{featured.length ? <Featured serverId={serverId} listings={featured} /> : null}
{featured.length ? (
<Featured serverId={serverId} listings={featured} onPrepareOpen={prefetchListing} />
) : null}
<SettingsSection title={listTitle}>
<ListingList
key={`${query}\n${category}\n${sort}`}
@@ -356,6 +385,7 @@ function Directory({
listings={listings}
installed={installed}
onInstall={onInstall}
onPrepareOpen={prefetchListing}
/>
</SettingsSection>
</>
@@ -0,0 +1,62 @@
import type { TFunction } from "i18next";
import { describe, expect, it } from "vitest";
import { KNOWN_PLUGIN_FUNDING_PLATFORMS } from "@getpaseo/protocol/plugin-registry";
import { pluginGallery } from "@/i18n/resources/plugin-gallery";
import { darkTheme, lightTheme } from "@/styles/theme";
import { contrastRatio } from "@/utils/color";
import {
FUNDING_BRAND_PALETTES,
FUNDING_ICON_SPECS,
galleryFundingButtonLabel,
} from "./funding-brand";
const enT = ((key: string) => {
const prefix = "settings.plugins.gallery.";
const path = key.startsWith(prefix) ? key.slice(prefix.length).split(".") : key.split(".");
let current: unknown = pluginGallery.en;
for (const part of path) {
if (current && typeof current === "object" && part in current) {
current = (current as Record<string, unknown>)[part];
} else {
return key;
}
}
return typeof current === "string" ? current : key;
}) as unknown as TFunction;
describe("gallery funding branding", () => {
it("provides icon specs, localized labels, and light/dark palettes for every recognized platform", () => {
for (const platform of KNOWN_PLUGIN_FUNDING_PLATFORMS) {
expect(FUNDING_ICON_SPECS[platform].primary.length).toBeGreaterThan(20);
const label = galleryFundingButtonLabel({ platform, url: "https://example.com" }, enT);
expect(label).not.toContain("sponsorPlatforms");
expect(label.length).toBeGreaterThan(0);
}
expect(
galleryFundingButtonLabel(
{ platform: "kofi", url: "https://ko-fi.com/acme", label: "Buy me tea" },
enT,
),
).toBe("Buy me tea");
expect(galleryFundingButtonLabel({ url: "https://ifdian.net/a/xrsec" }, enT)).toBe("Sponsor");
});
it("clears WCAG non-text contrast for brand icons on built-in light and dark Paseo card surfaces", () => {
const builtInThemes = [
{ name: "light", theme: lightTheme },
{ name: "dark", theme: darkTheme },
] as const;
for (const option of builtInThemes) {
const surface = option.theme.colors.surface1;
for (const platform of KNOWN_PLUGIN_FUNDING_PLATFORMS) {
const palette = FUNDING_BRAND_PALETTES[platform][option.theme.colorScheme];
expect(
contrastRatio(palette.icon, surface),
`${platform} icon contrast in ${option.name} mode`,
).toBeGreaterThanOrEqual(3);
}
}
});
});
@@ -0,0 +1,181 @@
import type { TFunction } from "i18next";
import type {
KnownPluginFundingPlatform,
ResolvedPluginFundingLink,
} from "@getpaseo/protocol/plugin-registry";
export interface FundingBrandPalette {
icon: string;
background: string;
border: string;
}
export interface FundingIconSpec {
viewBox: string;
primary: string;
secondary?: string;
}
export const FUNDING_BRAND_PALETTES: Record<
KnownPluginFundingPlatform,
Record<"light" | "dark", FundingBrandPalette>
> = {
github: {
light: {
icon: "#bf3989",
background: "rgba(191, 57, 137, 0.08)",
border: "rgba(191, 57, 137, 0.30)",
},
dark: {
icon: "#ea7bb3",
background: "rgba(219, 97, 162, 0.10)",
border: "rgba(219, 97, 162, 0.32)",
},
},
kofi: {
light: {
icon: "#d94340",
background: "rgba(217, 67, 64, 0.08)",
border: "rgba(217, 67, 64, 0.30)",
},
dark: {
icon: "#ff7a78",
background: "rgba(255, 94, 91, 0.10)",
border: "rgba(255, 94, 91, 0.32)",
},
},
buymeacoffee: {
light: {
icon: "#a67400",
background: "rgba(255, 221, 0, 0.16)",
border: "rgba(181, 129, 0, 0.34)",
},
dark: {
icon: "#ffdd00",
background: "rgba(255, 221, 0, 0.09)",
border: "rgba(255, 221, 0, 0.30)",
},
},
opencollective: {
light: {
icon: "#2b6cb0",
background: "rgba(43, 108, 176, 0.08)",
border: "rgba(43, 108, 176, 0.30)",
},
dark: {
icon: "#7fb3f5",
background: "rgba(127, 179, 245, 0.10)",
border: "rgba(127, 179, 245, 0.30)",
},
},
patreon: {
light: {
icon: "#c93b27",
background: "rgba(201, 59, 39, 0.08)",
border: "rgba(201, 59, 39, 0.30)",
},
dark: {
icon: "#ff6b57",
background: "rgba(255, 107, 87, 0.10)",
border: "rgba(255, 107, 87, 0.30)",
},
},
polar: {
light: {
icon: "#0052cc",
background: "rgba(0, 98, 255, 0.07)",
border: "rgba(0, 82, 204, 0.28)",
},
dark: {
icon: "#6ea8ff",
background: "rgba(92, 156, 255, 0.10)",
border: "rgba(92, 156, 255, 0.30)",
},
},
liberapay: {
light: {
icon: "#9c7600",
background: "rgba(246, 201, 21, 0.15)",
border: "rgba(156, 118, 0, 0.32)",
},
dark: {
icon: "#f6c915",
background: "rgba(246, 201, 21, 0.09)",
border: "rgba(246, 201, 21, 0.30)",
},
},
paypal: {
light: {
icon: "#005ea6",
background: "rgba(0, 112, 186, 0.07)",
border: "rgba(0, 94, 166, 0.28)",
},
dark: {
icon: "#5eadff",
background: "rgba(77, 163, 255, 0.10)",
border: "rgba(77, 163, 255, 0.30)",
},
},
};
export const FUNDING_ICON_SPECS: Record<KnownPluginFundingPlatform, FundingIconSpec> = {
github: {
viewBox: "0 0 16 16",
primary:
"M4.25 2.5c-1.336 0-2.75 1.164-2.75 3 0 2.15 1.58 4.144 3.365 5.682A20.565 20.565 0 0 0 8 13.393a20.561 20.561 0 0 0 3.135-2.211C12.92 9.644 14.5 7.65 14.5 5.5c0-1.836-1.414-3-2.75-3-1.373 0-2.609.986-3.029 2.456a.749.749 0 0 1-1.442 0C6.859 3.486 5.623 2.5 4.25 2.5ZM8 14.25l-.345.666-.002-.001-.006-.003-.018-.01a7.643 7.643 0 0 1-.31-.17 22.075 22.075 0 0 1-3.434-2.414C2.045 10.731 0 8.35 0 5.5 0 2.836 2.086 1 4.25 1 5.797 1 7.153 1.802 8 3.02 8.847 1.802 10.203 1 11.75 1 13.914 1 16 2.836 16 5.5c0 2.85-2.045 5.231-3.885 6.818a22.08 22.08 0 0 1-3.744 2.584l-.018.01-.006.003h-.002L8 14.25Z",
},
kofi: {
viewBox: "0 0 24 24",
primary:
"M23.881 8.948c-.773-4.085-4.859-4.593-4.859-4.593H.723c-.604 0-.679.798-.679.798s-.082 7.324-.022 11.822c.164 2.424 2.586 2.672 2.586 2.672s8.267-.023 11.966-.049c2.438-.426 2.683-2.566 2.658-3.734 4.352.24 7.422-2.831 6.649-6.916zm-11.062 3.511c-1.246 1.453-4.011 3.976-4.011 3.976s-.121.119-.31.023c-.076-.057-.108-.09-.108-.09-.443-.441-3.368-3.049-4.034-3.954-.709-.965-1.041-2.7-.091-3.71.951-1.01 3.005-1.086 4.363.407 0 0 1.565-1.782 3.468-.963 1.904.82 1.832 3.011.723 4.311zm6.173.478c-.928.116-1.682.028-1.682.028V7.284h1.77s1.971.551 1.971 2.638c0 1.913-.985 2.667-2.059 3.015z",
},
buymeacoffee: {
viewBox: "0 0 24 24",
primary:
"M20.216 6.415l-.132-.666c-.119-.598-.388-1.163-1.001-1.379-.197-.069-.42-.098-.57-.241-.152-.143-.196-.366-.231-.572-.065-.378-.125-.756-.192-1.133-.057-.325-.102-.69-.25-.987-.195-.4-.597-.634-.996-.788a5.723 5.723 0 00-.626-.194c-1-.263-2.05-.36-3.077-.416a25.834 25.834 0 00-3.7.062c-.915.083-1.88.184-2.75.5-.318.116-.646.256-.888.501-.297.302-.393.77-.177 1.146.154.267.415.456.692.58.36.162.737.284 1.123.366 1.075.238 2.189.331 3.287.37 1.218.05 2.437.01 3.65-.118.299-.033.598-.073.896-.119.354-.054.577.313.438.589-.067.133-.198.248-.342.29-.441.129-.9.205-1.356.262-1.216.152-2.444.19-3.666.153-1.26-.04-2.517-.156-3.75-.433-.504-.113-.997-.273-1.452-.517a2.927 2.927 0 01-.312-.19c-.185-.13-.441-.015-.456.21l-.002.026c-.043.652.008 1.326.155 1.96.133.572.37 1.125.714 1.602.185.257.414.487.68.654.252.16.544.249.84.287.179.023.359.035.539.043l.716 6.279c.074.647.149 1.294.222 1.94.086.75.172 1.5.258 2.25.048.414.122.847.344 1.208.288.468.78.742 1.297.878.938.247 1.947.274 2.912.238.94-.035 1.915-.126 2.81-.425.432-.144.847-.39 1.104-.778.18-.271.263-.594.303-.914.095-.76.178-1.522.266-2.283.144-1.257.287-2.514.432-3.77l.378-3.307c.19-.015.38-.035.568-.065.573-.09 1.117-.368 1.464-.844.369-.506.484-1.158.404-1.77-.026-.2-.062-.398-.1-.596zm-3.82 10.675c-.06.516-.122 1.031-.182 1.547-.026.224-.051.45-.124.664-.114.337-.374.544-.707.649-.726.229-1.533.275-2.291.281-.768.006-1.573-.043-2.307-.277-.29-.093-.567-.246-.733-.508-.135-.214-.175-.468-.204-.716l-.395-3.443-.363-3.173c1.019.069 2.043.095 3.065.08 1.023-.015 2.045-.071 3.06-.18l-.819 5.08z",
},
opencollective: {
viewBox: "0 0 24 24",
primary:
"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12c2.54 0 4.894-.79 6.834-2.135l-3.107-3.109a7.715 7.715 0 1 1 0-13.512l3.107-3.109A11.943 11.943 0 0 0 12 0z",
secondary:
"M21.865 5.166l-3.109 3.107a7.7 7.7 0 0 1 0 7.454l3.109 3.107A11.948 11.948 0 0 0 24 12c0-2.54-.79-4.894-2.135-6.834z",
},
patreon: {
viewBox: "0 0 24 24",
primary:
"M22.957 7.21c-.004-3.064-2.391-5.576-5.191-6.482-3.478-1.125-8.064-.962-11.384.604C2.357 3.231 1.093 7.391 1.046 11.54c-.039 3.411.302 12.396 5.369 12.46 3.765.047 4.326-4.804 6.068-7.141 1.24-1.662 2.836-2.132 4.801-2.618 3.376-.836 5.678-3.501 5.673-7.031Z",
},
polar: {
viewBox: "0 0 24 24",
primary:
"M12 1C5.925 1 1 5.925 1 12s4.925 11 11 11 11-4.925 11-11S18.075 1 12 1zm0 2.2c4.86 0 8.8 3.94 8.8 8.8 0 4.86-3.94 8.8-8.8 8.8-1.76 0-3.4-.52-4.78-1.41 3.78-.7 6.66-4.01 6.66-7.99 0-3.38-2.06-6.28-5-7.52A8.74 8.74 0 0 1 12 3.2zm-1.15 2.4c2.99.55 5.25 3.17 5.25 6.32 0 3.55-2.88 6.43-6.43 6.43-.88 0-1.72-.18-2.49-.5 2.26-1.08 3.82-3.39 3.82-6.06 0-2.55-1.42-4.77-3.51-5.91a6.4 6.4 0 0 1 3.36-.28z",
},
liberapay: {
viewBox: "0 0 24 24",
primary:
"M12 0C5.373 0 0 5.373 0 12s5.373 12 12 12 12-5.373 12-12S18.627 0 12 0zm-1.158 5.23h3.07l-1.925 9.094c-.114.534-.134.938-.06 1.213.073.274.267.448.58.523.314.074.742.063 1.285-.034l-.435 2.238c-.974.212-1.894.253-2.761.124-.868-.13-1.484-.472-1.85-1.028-.366-.555-.465-1.32-.298-2.295L10.842 5.23z",
},
paypal: {
viewBox: "0 0 24 24",
primary:
"M7.076 21.337H2.47a.641.641 0 0 1-.633-.74L4.944.901C5.026.382 5.474 0 5.998 0h7.46c2.57 0 4.578.543 5.69 1.81 1.01 1.15 1.304 2.42 1.012 4.287-.023.143-.047.288-.077.437-.983 5.05-4.349 6.797-8.647 6.797h-2.19c-.524 0-.968.382-1.05.9l-1.12 7.106zm14.146-14.42a3.35 3.35 0 0 0-.607-.541c-.013.076-.026.175-.041.254-.93 4.778-4.005 7.201-9.138 7.201h-2.19a.563.563 0 0 0-.556.479l-1.187 7.527h-.506l-.24 1.516a.56.56 0 0 0 .554.647h3.882c.46 0 .85-.334.922-.788.06-.26.76-4.852.816-5.09a.932.932 0 0 1 .923-.788h.58c3.76 0 6.705-1.528 7.565-5.946.36-1.847.174-3.388-.777-4.471z",
},
};
export function fundingBrandPalette(
platform: KnownPluginFundingPlatform,
colorScheme: "light" | "dark" | undefined,
): FundingBrandPalette {
return colorScheme === "light"
? FUNDING_BRAND_PALETTES[platform].light
: FUNDING_BRAND_PALETTES[platform].dark;
}
export function galleryFundingButtonLabel(entry: ResolvedPluginFundingLink, t: TFunction): string {
if (entry.label) return entry.label;
if (entry.platform) {
return t(`settings.plugins.gallery.actions.sponsorPlatforms.${entry.platform}`);
}
return t("settings.plugins.gallery.actions.sponsor");
}
@@ -0,0 +1,132 @@
import { Heart } from "lucide-react-native";
import type { TFunction } from "i18next";
import { useCallback, useMemo } from "react";
import Svg, { Path } from "react-native-svg";
import { withUnistyles } from "react-native-unistyles";
import {
KNOWN_PLUGIN_FUNDING_PLATFORMS,
type KnownPluginFundingPlatform,
type ResolvedPluginFundingLink,
} from "@getpaseo/protocol/plugin-registry";
import { Button } from "@/components/ui/button";
import type { Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { openExternalUrl } from "@/utils/open-external-url";
import {
FUNDING_ICON_SPECS,
fundingBrandPalette,
galleryFundingButtonLabel,
} from "./funding-brand";
interface FundingThemeProps {
surfaceBackground?: string;
surfaceBorder?: string;
iconColor: string;
}
const PLATFORM_THEME_MAPPINGS: Record<
KnownPluginFundingPlatform,
(theme: Theme) => FundingThemeProps
> = Object.fromEntries(
KNOWN_PLUGIN_FUNDING_PLATFORMS.map((platform) => [
platform,
(theme: Theme) => {
const palette = fundingBrandPalette(platform, theme.colorScheme);
return {
surfaceBackground: palette.background,
surfaceBorder: palette.border,
iconColor: palette.icon,
};
},
]),
) as Record<KnownPluginFundingPlatform, (theme: Theme) => FundingThemeProps>;
const GENERIC_THEME_MAPPING = (theme: Theme): FundingThemeProps => ({
surfaceBackground: undefined,
surfaceBorder: undefined,
iconColor: theme.colors.statusDanger,
});
function FundingPlatformMark({
platform,
size = 14,
color,
}: {
platform?: KnownPluginFundingPlatform;
size?: number;
color: string;
}) {
if (!platform) {
return <Heart size={size} color={color} />;
}
const spec = FUNDING_ICON_SPECS[platform];
return (
<Svg width={size} height={size} viewBox={spec.viewBox} fill={color}>
<Path d={spec.primary} />
{spec.secondary ? <Path d={spec.secondary} opacity={0.55} /> : null}
</Svg>
);
}
interface FundingButtonInnerProps extends FundingThemeProps {
url: string;
platform?: KnownPluginFundingPlatform;
label: string;
}
function FundingButtonInner({
url,
platform,
label,
surfaceBackground,
surfaceBorder,
iconColor,
}: FundingButtonInnerProps) {
const open = useCallback(() => {
void openExternalUrl(url);
}, [url]);
const buttonStyle = useMemo(
() =>
surfaceBackground && surfaceBorder
? inlineUnistylesStyle({
backgroundColor: surfaceBackground,
borderColor: surfaceBorder,
})
: undefined,
[surfaceBackground, surfaceBorder],
);
const leftIcon = useMemo(
() => <FundingPlatformMark platform={platform} size={14} color={iconColor} />,
[platform, iconColor],
);
return (
<Button
variant="outline"
onPress={open}
numberOfLines={1}
style={buttonStyle}
testID={`funding-button-${platform ?? "custom"}`}
leftIcon={leftIcon}
>
{label}
</Button>
);
}
const ThemedFundingButton = withUnistyles(FundingButtonInner);
export function FundingButton({ entry, t }: { entry: ResolvedPluginFundingLink; t: TFunction }) {
const mapping = entry.platform ? PLATFORM_THEME_MAPPINGS[entry.platform] : GENERIC_THEME_MAPPING;
return (
<ThemedFundingButton
url={entry.url}
platform={entry.platform}
label={galleryFundingButtonLabel(entry, t)}
uniProps={mapping}
/>
);
}
@@ -1,8 +1,9 @@
import { useCallback, useMemo, useState } from "react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import type { PluginListing } from "@getpaseo/protocol/plugin-registry";
import { preloadMarkdownParser } from "@/components/markdown/parser-ready";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { SearchField } from "@/components/ui/search-field";
@@ -29,6 +30,9 @@ export function PluginGalleryPage({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const connected = useHostRuntimeIsConnected(serverId);
const supported = useHostFeature(serverId, "pluginManagement");
useEffect(() => {
preloadMarkdownParser();
}, []);
useInstalledPlugins();
const plugins = useLivePluginList(serverId);
const directory = usePluginDirectory(serverId);
@@ -20,7 +20,7 @@ import { usePluginActions } from "./actions";
import { listingAuthor, listingAuthorAvatar, installedListingId } from "./listing";
import { updatePlugins, usePluginOperation } from "./operations";
import { PluginRow } from "./plugin-row";
import { usePluginUpdates } from "./queries";
import { usePluginUpdates, usePrefetchPluginListing } from "./queries";
import { buildPluginPageRoute } from "./routes";
function shortRevision(revision: string | undefined): string | undefined {
@@ -77,12 +77,14 @@ function UpdateRow({
preview,
listing,
onUpdate,
onPrepareOpen,
}: {
serverId: string;
plugin: PluginListItem;
preview: PluginUpdatePreview;
listing?: PluginListing;
onUpdate(previews: PluginUpdatePreview[]): void;
onPrepareOpen(listingId: string | undefined): void;
}) {
const { t } = useTranslation();
const operation = usePluginOperation(serverId, plugin.id);
@@ -95,6 +97,10 @@ function UpdateRow({
() => router.push(buildPluginPageRoute(serverId, plugin.id)),
[plugin.id, serverId],
);
const prepare = useCallback(
() => onPrepareOpen(installedListingId(plugin)),
[onPrepareOpen, plugin],
);
const update = useCallback(() => onUpdate([preview]), [onUpdate, preview]);
let label = t("settings.plugins.gallery.actions.update");
if (running) label = t("settings.plugins.gallery.actions.updating");
@@ -107,6 +113,7 @@ function UpdateRow({
meta={current && target ? `${current} → ${target}` : target}
error={operation?.status === "failed" ? operation.error : undefined}
onPress={open}
onPrepareOpen={prepare}
accessibilityLabel={name}
testID={`plugin-update-${plugin.id}`}
>
@@ -123,12 +130,14 @@ function InstalledRow({
listing,
pending,
onToggle,
onPrepareOpen,
}: {
serverId: string;
plugin: PluginListItem;
listing?: PluginListing;
pending: boolean;
onToggle(plugin: PluginListItem, enabled: boolean): void;
onPrepareOpen(listingId: string | undefined): void;
}) {
const { t } = useTranslation();
const name = pluginDisplayName(plugin);
@@ -138,6 +147,10 @@ function InstalledRow({
() => router.push(buildPluginPageRoute(serverId, plugin.id)),
[plugin.id, serverId],
);
const prepare = useCallback(
() => onPrepareOpen(installedListingId(plugin)),
[onPrepareOpen, plugin],
);
const toggle = useCallback((enabled: boolean) => onToggle(plugin, enabled), [onToggle, plugin]);
const badge = useMemo(
() =>
@@ -156,6 +169,7 @@ function InstalledRow({
authorAvatar={listing && listingAuthorAvatar(listing)}
error={error}
onPress={open}
onPrepareOpen={prepare}
accessibilityLabel={name}
testID={`plugin-row-${plugin.id}`}
>
@@ -189,6 +203,7 @@ export function InstalledTab({
const actions = usePluginActions(serverId);
const updates = usePluginUpdates(serverId);
const update = useUpdate(serverId);
const prefetchListing = usePrefetchPluginListing(serverId);
const normalizedQuery = query.trim().toLowerCase();
const shown = plugins.filter((plugin) => matchesQuery(plugin, normalizedQuery));
const byId = new Map(plugins.map((plugin) => [plugin.id, plugin]));
@@ -232,6 +247,7 @@ export function InstalledTab({
preview={preview}
listing={listingOf(plugin)}
onUpdate={update}
onPrepareOpen={prefetchListing}
/>
);
})}
@@ -249,6 +265,7 @@ export function InstalledTab({
listing={listingOf(plugin)}
pending={actions.pending?.pluginId === plugin.id}
onToggle={toggle}
onPrepareOpen={prefetchListing}
/>
))
) : (
@@ -3,7 +3,7 @@ import { router } from "expo-router";
import { Download } from "lucide-react-native";
import { useCallback, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { Image, ScrollView, Text, View, type LayoutChangeEvent } from "react-native";
import { Image, ScrollView, Text, View, useWindowDimensions } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import type { PluginListItem, PluginUpdatePreview } from "@getpaseo/protocol/messages";
import {
@@ -14,7 +14,9 @@ import {
type PluginListingDetail,
} from "@getpaseo/protocol/plugin-registry";
import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox";
import { useMarkdownParserReady } from "@/components/markdown/parser-ready";
import { MarkdownRenderer } from "@/components/markdown/renderer";
import { PAGE_LAYOUT_WIDE_MAX_WIDTH } from "@/components/page-layout";
import { SettingsBackLink, SettingsCard, SettingsSection } from "@/components/settings";
import { Alert } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
@@ -23,8 +25,13 @@ import { PressHighlight } from "@/components/ui/press-highlight";
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
import { StatusBadge } from "@/components/ui/status-badge";
import { Switch } from "@/components/ui/switch";
import { useIsCompactFormFactor } from "@/constants/layout";
import {
SETTINGS_DESKTOP_DETAIL_MIN_WIDTH,
SETTINGS_DESKTOP_SIDEBAR_WIDTH,
useIsCompactFormFactor,
} from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import { useContainerWidthBelow } from "@/hooks/use-container-width";
import { pluginDisplayName } from "@/plugins/plugin-list";
import {
useInstalledPlugin,
@@ -34,6 +41,7 @@ import {
import { PluginSettingsContent } from "@/plugins/settings";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { SPACING } from "@/styles/theme";
import { usePluginActions, type PluginAction } from "./actions";
import { pluginErrorText } from "./error-text";
import { ListingInstallControl } from "./install-control";
@@ -63,9 +71,24 @@ import {
} from "./queries";
import { RelatedPluginsSection } from "./related-plugins";
import { buildPluginListingRoute } from "./routes";
import { OverviewSkeleton, PluginPageSkeleton } from "./skeletons";
import { OverviewSkeleton, OverviewSkeletonBody, PluginPageSkeleton } from "./skeletons";
const ThemedDownload = withUnistyles(Download);
const PLUGIN_PAGE_STACKED_WIDTH = 700;
/** Matches PageLayout width="wide" inside SettingsScreen so the first frame picks the final layout. */
function estimatePluginPageWidth({
windowWidth,
compact,
}: {
windowWidth: number;
compact: boolean;
}): number {
const paneWidth = compact
? windowWidth
: Math.max(SETTINGS_DESKTOP_DETAIL_MIN_WIDTH, windowWidth - SETTINGS_DESKTOP_SIDEBAR_WIDTH);
return Math.min(PAGE_LAYOUT_WIDE_MAX_WIDTH, paneWidth) - SPACING[4] * 2;
}
/** Which plugin the page is for: one installed on the host, or one listed in the directory. */
export type PluginPageSubject =
@@ -397,6 +420,7 @@ function PluginTabPanel({
reviewPolicyUrl,
scorecardsSupported,
overviewLoading,
markdownReady,
model,
settings,
categoryLabels,
@@ -410,6 +434,7 @@ function PluginTabPanel({
reviewPolicyUrl?: string;
scorecardsSupported: boolean;
overviewLoading: boolean;
markdownReady: boolean;
model: PluginPageModel;
settings?: { pluginId: string; screenId: string };
categoryLabels: readonly string[];
@@ -460,17 +485,27 @@ function PluginTabPanel({
</View>
);
}
if (model.overview) {
return (
<SettingsCard>
// Keep one SettingsCard mounted and hold the skeleton until both the README and the web
// Markdown WASM parser are ready so the card never collapses to an empty box between frames.
const showOverview = Boolean(model.overview && markdownReady);
const showOverviewSkeleton = overviewLoading || Boolean(model.overview && !markdownReady);
if (!showOverview && !showOverviewSkeleton) return null;
return (
<SettingsCard>
{showOverview && model.overview ? (
<View style={styles.overview}>
<MarkdownRenderer text={model.overview} external />
<MarkdownRenderer
text={model.overview}
destinations="https"
forgeShorthand={false}
softBreaks="join"
/>
</View>
</SettingsCard>
);
}
if (overviewLoading) return <OverviewSkeleton />;
return null;
) : (
<OverviewSkeletonBody />
)}
</SettingsCard>
);
}
function UnlistedPluginView({
@@ -542,11 +577,13 @@ function UnlistedPluginView({
function usePluginPageTabs({
listing,
detail,
detailLoading,
settings,
stacked,
}: {
listing?: PluginListing;
detail?: PluginListingDetail;
detailLoading: boolean;
settings?: { pluginId: string; screenId: string };
stacked: boolean;
}) {
@@ -575,9 +612,10 @@ function usePluginPageTabs({
},
{
value: "updates",
label: stacked
? t("settings.plugins.gallery.page.tabs.updates")
: t("settings.plugins.gallery.page.tabs.updatesCount", { count: revisionCount }),
label:
stacked || detailLoading
? t("settings.plugins.gallery.page.tabs.updates")
: t("settings.plugins.gallery.page.tabs.updatesCount", { count: revisionCount }),
testID: "plugin-page-tab-updates",
},
);
@@ -589,7 +627,7 @@ function usePluginPageTabs({
});
}
return options;
}, [listing, revisionCount, settings, stacked, t]);
}, [detailLoading, listing, revisionCount, settings, stacked, t]);
}
function ListedPluginLayout({
@@ -601,6 +639,7 @@ function ListedPluginLayout({
reviewPolicyUrl,
scorecardsSupported,
overviewLoading,
markdownReady,
model,
settings,
tabs,
@@ -621,6 +660,7 @@ function ListedPluginLayout({
reviewPolicyUrl?: string;
scorecardsSupported: boolean;
overviewLoading: boolean;
markdownReady: boolean;
model: PluginPageModel;
settings?: { pluginId: string; screenId: string };
tabs: SegmentedControlOption<PluginPageTab>[];
@@ -675,6 +715,7 @@ function ListedPluginLayout({
reviewPolicyUrl={reviewPolicyUrl}
scorecardsSupported={scorecardsSupported}
overviewLoading={overviewLoading}
markdownReady={markdownReady}
model={model}
settings={settings}
categoryLabels={categoryLabels}
@@ -807,10 +848,12 @@ export function PluginPage({
}) {
const { t } = useTranslation();
const compact = useIsCompactFormFactor();
const { width: windowWidth } = useWindowDimensions();
const { plugin, listingId, listing, detail, directory, loading } = useResolvedPlugin(
serverId,
subject,
);
const markdownReady = useMarkdownParserReady({ enabled: Boolean(listing) });
const settings = usePluginPageSettings(serverId, subject, plugin);
// COMPAT(pluginRegistryScorecards): added in v0.18.2, remove gate after 2027-06-01.
const scorecardsSupported = useHostFeature(serverId, "pluginRegistryScorecards");
@@ -827,12 +870,11 @@ export function PluginPage({
});
const [installTarget, setInstallTarget] = useState<InstallTarget | null>(null);
const [chosenTab, setChosenTab] = useState<PluginPageTab | null>(null);
const [containerWidth, setContainerWidth] = useState<number | null>(null);
const onLayout = useCallback((event: LayoutChangeEvent) => {
const nextWidth = Math.round(event.nativeEvent.layout.width);
setContainerWidth((prev) => (prev === nextWidth ? prev : nextWidth));
}, []);
const stacked = compact || (containerWidth !== null && containerWidth < 700);
const narrow = useContainerWidthBelow(PLUGIN_PAGE_STACKED_WIDTH, {
initialIsBelow: estimatePluginPageWidth({ windowWidth, compact }) < PLUGIN_PAGE_STACKED_WIDTH,
});
const stacked = compact || narrow.isBelow;
const detailPending = detail.isLoading && !detail.data;
const install = useCallback(
(target: PluginListing) =>
setInstallTarget({ kind: "listing", listing: target, detail: detail.data }),
@@ -850,7 +892,13 @@ export function PluginPage({
listing,
directory,
);
const tabs = usePluginPageTabs({ listing, detail: detail.data, settings, stacked });
const tabs = usePluginPageTabs({
listing,
detail: detail.data,
detailLoading: detailPending,
settings,
stacked,
});
const defaultTab: PluginPageTab =
subject.kind === "installed" && settings ? "settings" : "overview";
const activeTab: PluginPageTab =
@@ -896,7 +944,7 @@ export function PluginPage({
}
return (
<View onLayout={onLayout}>
<View onLayout={narrow.onLayout}>
<PageBackLink compact={compact} onBack={onBack} />
<ListedPluginLayout
stacked={stacked}
@@ -907,6 +955,7 @@ export function PluginPage({
reviewPolicyUrl={directory?.registry.reviewPolicyUrl}
scorecardsSupported={scorecardsSupported}
overviewLoading={detail.isLoading}
markdownReady={markdownReady}
model={model}
settings={settings}
tabs={tabs}
@@ -920,7 +969,9 @@ export function PluginPage({
authorPluginCount={authorPluginCount}
/>
<RelatedPluginsSection serverId={serverId} plugins={relatedPlugins} />
{!detailPending && markdownReady ? (
<RelatedPluginsSection serverId={serverId} plugins={relatedPlugins} />
) : null}
{installTarget ? (
<InstallPluginSheet serverId={serverId} target={installTarget} onClose={closeInstall} />
@@ -73,6 +73,8 @@ export interface PluginRowProps {
/** The row's control: a switch, or the install or update button. The chevron follows it. */
children?: ReactNode;
onPress(): void;
/** Called on hover-in and press-in so detail data can warm before navigation. */
onPrepareOpen?: () => void;
accessibilityLabel: string;
testID?: string;
}
@@ -91,6 +93,7 @@ export function PluginRow({
error,
children,
onPress,
onPrepareOpen,
accessibilityLabel,
testID,
}: PluginRowProps) {
@@ -103,6 +106,8 @@ export function PluginRow({
accessibilityRole="button"
accessibilityLabel={accessibilityLabel}
onPress={onPress}
onHoverIn={onPrepareOpen}
onPressIn={onPrepareOpen}
style={rowStyle}
highlightStyle={styles.pressed}
testID={testID}
@@ -1,9 +1,8 @@
import { Heart } from "lucide-react-native";
import type { TFunction } from "i18next";
import { useCallback, type ReactNode } from "react";
import type { ReactNode } from "react";
import { useTranslation } from "react-i18next";
import { Text, View } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { StyleSheet } from "react-native-unistyles";
import type { PluginListItem } from "@getpaseo/protocol/messages";
import {
pluginFundingLinks,
@@ -13,10 +12,8 @@ import {
} from "@getpaseo/protocol/plugin-registry";
import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference";
import { SettingsCard } from "@/components/settings";
import { Button } from "@/components/ui/button";
import { ExternalLink } from "@/components/ui/external-link";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { openExternalUrl } from "@/utils/open-external-url";
import { FundingButton } from "./funding-button";
import {
formatPluginDate,
listingAuthor,
@@ -26,9 +23,6 @@ import {
} from "./listing";
import { AuthorAvatar } from "./plugin-row";
const ThemedHeart = withUnistyles(Heart);
const sponsorHeartIcon = <ThemedHeart size={14} uniProps={mutedIconColorMapping} />;
function DetailValue({ children, mono = false }: { children: ReactNode; mono?: boolean }) {
return (
<Text style={[styles.detailValue, mono && styles.detailValueMono]} numberOfLines={1}>
@@ -106,12 +100,6 @@ export function DetailsCard({
value: `Paseo ${compatibility}`,
mono: true,
});
if (platforms)
rows.push({
key: "platforms",
label: t("settings.plugins.gallery.details.platforms"),
value: platforms,
});
if (listing?.license)
rows.push({
key: "license",
@@ -130,6 +118,13 @@ export function DetailsCard({
value: formatPluginDate(listing.updatedAt),
});
}
// Platforms arrives with the detail document; placing it last keeps the listing rows above put.
if (platforms)
rows.push({
key: "platforms",
label: t("settings.plugins.gallery.details.platforms"),
value: platforms,
});
if (source)
rows.push({
key: "source",
@@ -160,17 +155,6 @@ export function DetailsCard({
);
}
function SponsorButton({ label, url }: { label: string; url: string }) {
const open = useCallback(() => {
void openExternalUrl(url);
}, [url]);
return (
<Button variant="outline" onPress={open} leftIcon={sponsorHeartIcon}>
{label}
</Button>
);
}
export function AuthorCard({
listing,
authorPluginCount,
@@ -219,11 +203,7 @@ export function AuthorCard({
{fundingLinks.length > 0 ? (
<View style={styles.fundingStack}>
{fundingLinks.map((entry) => (
<SponsorButton
key={entry.url}
url={entry.url}
label={entry.label ?? t("settings.plugins.gallery.actions.sponsor")}
/>
<FundingButton key={entry.url} entry={entry} t={t} />
))}
</View>
) : null}
+50 -10
View File
@@ -1,7 +1,8 @@
import { useCallback, useEffect } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { preloadMarkdownParser } from "@/components/markdown/parser-ready";
import { usePluginList } from "@/plugins/plugin-list";
import { useFetchQuery } from "@/data/query";
import { fetchQueryOptions, useFetchQuery } from "@/data/query";
import { useHostFeature } from "@/runtime/host-features";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { pluginUpdatesQueryKey } from "./operations";
@@ -35,22 +36,61 @@ export function usePluginDirectory(serverId: string) {
return { supported, query };
}
/** One listing with its overview. */
export function usePluginListing(serverId: string, listingId: string | undefined) {
const { client, ready } = useHostReady(serverId);
// COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15.
const supported = useHostFeature(serverId, "pluginRegistry");
return useFetchQuery({
function pluginListingQueryInput({
client,
serverId,
listingId,
enabled,
}: {
client: ReturnType<typeof useHostRuntimeClient>;
serverId: string;
listingId: string | undefined;
enabled: boolean;
}) {
return {
queryKey: ["plugin-listing", serverId, listingId] as const,
queryFn: () => {
if (!client || !listingId) throw new Error("Plugin host is offline");
return client.getRegistryPlugin(listingId);
},
enabled: ready && supported && listingId !== undefined,
dataShape: "value",
enabled,
dataShape: "value" as const,
staleTimeMs: DIRECTORY_STALE_MS,
refetchOnMount: true,
});
};
}
/** One listing with its overview. */
export function usePluginListing(serverId: string, listingId: string | undefined) {
const { client, ready } = useHostReady(serverId);
// COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15.
const supported = useHostFeature(serverId, "pluginRegistry");
return useFetchQuery(
pluginListingQueryInput({
client,
serverId,
listingId,
enabled: ready && supported && listingId !== undefined,
}),
);
}
/** Prefetches a listing's overview and warms the Markdown parser before navigation commits. */
export function usePrefetchPluginListing(serverId: string) {
const queryClient = useQueryClient();
const { client, ready } = useHostReady(serverId);
// COMPAT(pluginRegistry): added in v0.16.0, remove gate after 2027-05-15.
const supported = useHostFeature(serverId, "pluginRegistry");
return useCallback(
(listingId: string | undefined) => {
preloadMarkdownParser();
if (!ready || !supported || !client || !listingId) return;
void queryClient.prefetchQuery(
fetchQueryOptions(pluginListingQueryInput({ client, serverId, listingId, enabled: true })),
);
},
[client, queryClient, ready, serverId, supported],
);
}
/** Installed plugins with a newer reviewed version, by plugin ID. */
@@ -14,6 +14,7 @@ import { PressHighlight } from "@/components/ui/press-highlight";
import { useIsCompactFormFactor } from "@/constants/layout";
import { formatInstallCount, listingAuthor, listingText } from "./listing";
import { PluginTile } from "./plugin-row";
import { usePrefetchPluginListing } from "./queries";
import { buildPluginListingRoute } from "./routes";
function toneDotStyle(tone: PluginMeterTone) {
@@ -26,10 +27,12 @@ function RelatedPluginCard({
serverId,
listing,
wide,
onPrepareOpen,
}: {
serverId: string;
listing: PluginListing;
wide: boolean;
onPrepareOpen(listingId: string): void;
}) {
const { t, i18n } = useTranslation();
const text = listingText(listing, i18n.language);
@@ -40,12 +43,15 @@ function RelatedPluginCard({
() => router.push(buildPluginListingRoute(serverId, listing.id)),
[listing.id, serverId],
);
const prepare = useCallback(() => onPrepareOpen(listing.id), [listing.id, onPrepareOpen]);
return (
<PressHighlight
accessibilityRole="button"
accessibilityLabel={text.name}
onPress={open}
onHoverIn={prepare}
onPressIn={prepare}
style={[styles.card, wide && styles.cardWide]}
highlightStyle={styles.pressed}
testID={`plugin-related-${listing.id}`}
@@ -99,6 +105,7 @@ export function RelatedPluginsSection({
}) {
const { t } = useTranslation();
const compact = useIsCompactFormFactor();
const prefetchListing = usePrefetchPluginListing(serverId);
if (plugins.length === 0) return null;
return (
@@ -111,6 +118,7 @@ export function RelatedPluginsSection({
serverId={serverId}
listing={listing}
wide={!compact}
onPrepareOpen={prefetchListing}
/>
))}
</View>
+41 -9
View File
@@ -6,7 +6,6 @@ import { SkeletonPulse, useSkeletonPulse } from "@/components/ui/skeleton";
import { settingsStyles } from "@/styles/settings";
const ROWS = [0, 1, 2, 3];
const LINES = [0, 1, 2];
function RowSkeleton({ pulse }: { pulse: Animated.Value }) {
const rowStyle = useMemo(() => [settingsStyles.row, styles.row], []);
@@ -34,16 +33,37 @@ export function PluginRowsSkeleton({ testID }: { testID?: string }) {
);
}
/** Lines of text in a card, where the overview will be. */
export function OverviewSkeleton() {
/** Document-proportioned skeleton bars inside an already-mounted card while overview data loads. */
export function OverviewSkeletonBody() {
const pulse = useSkeletonPulse();
return (
<SettingsCard>
<View style={styles.overview}>
{LINES.map((line) => (
<SkeletonPulse key={line} pulse={pulse} style={line === 2 ? styles.short : styles.line} />
))}
<View style={styles.overview} testID="plugin-overview-skeleton">
<SkeletonPulse pulse={pulse} style={styles.heading} />
<View style={styles.paragraph}>
<SkeletonPulse pulse={pulse} style={styles.lineFull} />
<SkeletonPulse pulse={pulse} style={styles.lineFull} />
<SkeletonPulse pulse={pulse} style={styles.lineMedium} />
</View>
<SkeletonPulse pulse={pulse} style={styles.subheading} />
<View style={styles.paragraph}>
<SkeletonPulse pulse={pulse} style={styles.lineFull} />
<SkeletonPulse pulse={pulse} style={styles.lineWide} />
<SkeletonPulse pulse={pulse} style={styles.short} />
</View>
<SkeletonPulse pulse={pulse} style={styles.subheading} />
<View style={styles.paragraph}>
<SkeletonPulse pulse={pulse} style={styles.lineFull} />
<SkeletonPulse pulse={pulse} style={styles.lineMedium} />
</View>
</View>
);
}
/** Lines of text in a card, where the overview, scorecard, or updates panel will be. */
export function OverviewSkeleton() {
return (
<SettingsCard>
<OverviewSkeletonBody />
</SettingsCard>
);
}
@@ -96,8 +116,20 @@ const styles = StyleSheet.create((theme) => {
},
name: { ...shape, width: 180, height: theme.fontSize.xl },
title: { ...shape, width: 140, height: theme.fontSize.sm },
heading: { ...shape, width: "42%", maxWidth: 240, height: theme.fontSize.xl },
subheading: {
...shape,
width: "30%",
maxWidth: 180,
height: theme.fontSize.lg,
marginTop: theme.spacing[2],
},
paragraph: { gap: theme.spacing[2] },
line: { ...shape, width: "100%", maxWidth: 420, height: theme.fontSize.sm },
short: { ...shape, width: "60%", maxWidth: 260, height: theme.fontSize.sm },
lineFull: { ...shape, width: "100%", height: theme.fontSize.sm },
lineWide: { ...shape, width: "88%", height: theme.fontSize.sm },
lineMedium: { ...shape, width: "74%", height: theme.fontSize.sm },
short: { ...shape, width: "56%", maxWidth: 280, height: theme.fontSize.sm },
control: { ...shape, width: 72, height: 28, borderRadius: theme.borderRadius.md },
overview: { padding: theme.spacing[4], gap: theme.spacing[3] },
description: { gap: theme.spacing[2], marginBottom: theme.spacing[6] },
@@ -110,6 +110,27 @@ it("unloads on a requirement-only edit and recovers after correction", () => {
expect(result.getEvaluationError("host", "example")).toBeUndefined();
});
it("unloads on a requirements.app-only edit", () => {
const { result, starts, cleanups } = registry("0.10.0");
const install = (app: string) =>
result.installCatalog(
"host",
[{ id: "example", clientBundle, requirements: { paseo: ">=0.8.0", app } }],
{ client, audio },
);
install(">=0.10.0");
expect(result.getSnapshot().map(({ id }) => id)).toEqual(["example"]);
install(">=0.11.0");
expect(cleanups()).toBe(1);
expect(result.getSnapshot()).toEqual([]);
expect(result.getEvaluationError("host", "example")).toBe(
'Plugin "example" requires Paseo app >=0.11.0. Your app is 0.10.0. Use a compatible plugin version or update the app.',
);
install(">=0.10.0");
expect(starts()).toBe(2);
expect(result.getSnapshot().map(({ id }) => id)).toEqual(["example"]);
});
it("rejects the unreleased translation API on 0.12.0 before evaluating its imports", () => {
const { result, starts } = registry("0.12.0");
result.installCatalog(
+2 -1
View File
@@ -78,7 +78,8 @@ export class PluginRegistry {
plugin.id !== options.replacePluginId &&
plugin.id === entry.id &&
plugin.clientBundle === entry.clientBundle &&
plugin.requirements?.paseo === entry.requirements?.paseo,
plugin.requirements?.paseo === entry.requirements?.paseo &&
plugin.requirements?.app === entry.requirements?.app,
);
return existing ? [existing] : [];
});
@@ -151,6 +151,17 @@ describe("createWorkspaceAgentInBackground", () => {
expect(draftText()).toBe("a different idea");
});
it("keeps text typed while workspace creation was pending that has not been published yet", () => {
const clearConsumedDraft = captureCleanup();
useDraftStore.getState().stageDraftText({ draftKey: DRAFT_KEY, text: "Keep this newer draft" });
// Creation completes before the staged text is published after the next paint.
clearConsumedDraft();
useDraftStore.getState().flushDraftText(DRAFT_KEY);
expect(draftText()).toBe("Keep this newer draft");
});
it("keeps a newer draft written while workspace creation was pending", async () => {
useWorkspaceAttachmentsStore.getState().addWorkspaceAttachment({
scopeKey: SCOPE_KEY,
@@ -40,6 +40,8 @@ export function captureWorkspaceDraftCleanup(input: WorkspaceDraftCleanupInput):
const attachments = useWorkspaceAttachmentsStore.getState().attachmentsByScope[scopeKey];
return () => {
// Text typed into a newer draft is published after the next paint; it is newer state too.
useDraftStore.getState().flushDraftText(input.draftKey);
// These stores update independently. A context-only edit does not bump the text version.
// Any newer draft state owns the whole draft, including its unchanged context.
if (
@@ -10,6 +10,8 @@ import { getPanelRegistration, type PanelIconProps } from "@/panels/panel-regist
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import type { SidebarStateBucket } from "@/utils/sidebar-agent-state";
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
import { buildDraftStoreKey } from "@/stores/draft-keys";
import { hasUnsavedDraft, useDraftStore } from "@/stores/draft-store";
import { usePanelInstanceAttributes } from "@/panels/panel-instance-attributes";
export interface WorkspaceTabPresentation {
@@ -72,6 +74,15 @@ function WorkspaceTabPresentationResolverInner({
});
const attributes = usePanelInstanceAttributes({ serverId, workspaceId, tabId: tab.tabId });
const draftKey =
tab.target.kind === "draft"
? buildDraftStoreKey({ serverId, agentId: "", draftId: tab.target.draftId })
: null;
const draftModified = useDraftStore(
(state) => draftKey !== null && hasUnsavedDraft(state, draftKey),
);
const modified = attributes.modified || draftModified;
const presentation = useMemo(
() => ({
key: tab.key,
@@ -79,7 +90,7 @@ function WorkspaceTabPresentationResolverInner({
label: descriptor.label,
subtitle: descriptor.subtitle,
tooltip: descriptor.tooltip,
modified: attributes.modified,
modified,
showCloseButton: registration.showCloseButton,
titleState: descriptor.titleState,
icon: descriptor.icon,
@@ -94,7 +105,7 @@ function WorkspaceTabPresentationResolverInner({
descriptor.titleState,
tab.key,
tab.kind,
attributes.modified,
modified,
registration.showCloseButton,
],
);
+6 -1
View File
@@ -1,6 +1,7 @@
import { generateMessageId } from "@/types/stream";
export const NEW_WORKSPACE_DRAFT_KEY = "new-workspace";
const WORKSPACE_TAB_DRAFT_PREFIX = "draft:";
const NEW_WORKSPACE_FORK_DRAFT_PREFIX = `${NEW_WORKSPACE_DRAFT_KEY}:draft:`;
export function generateDraftId(): string {
@@ -22,6 +23,10 @@ export function isLegacyNewWorkspaceDraftKey(draftKey: string): boolean {
);
}
export function isWorkspaceTabDraftKey(draftKey: string): boolean {
return draftKey.startsWith(WORKSPACE_TAB_DRAFT_PREFIX);
}
export function buildDraftStoreKey(input: {
serverId: string;
agentId: string;
@@ -30,7 +35,7 @@ export function buildDraftStoreKey(input: {
const serverId = input.serverId.trim();
const explicitDraftId = input.draftId?.trim();
if (explicitDraftId) {
return `draft:${serverId}:${explicitDraftId}`;
return `${WORKSPACE_TAB_DRAFT_PREFIX}${serverId}:${explicitDraftId}`;
}
return `agent:${serverId}:${input.agentId.trim()}`;
}
@@ -9,6 +9,7 @@ import {
persistAttachmentFromFileUri,
} from "@/attachments/service";
import { collectRetainedAttachmentIds } from "@/attachments/gc-retention";
import { isWorkspaceTabDraftKey } from "@/stores/draft-keys";
import { useCreateFlowStore } from "@/stores/create-flow-store";
import { useSessionStore, type SessionState } from "@/stores/session-store";
import { useWorkspaceAttachmentsStore } from "@/attachments/workspace-attachments-store";
@@ -37,6 +38,7 @@ import {
import { createDraftPersistStorage } from "./persistence";
import { createValidatedPersistStorage } from "@/storage/validated-persist-storage";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import { AfterPaintPublication } from "@/composer/after-paint-publication";
import { applyMetadataPatch } from "@/composer/draft/metadata";
import { hasDraftContent } from "@/composer/draft/input-draft-core";
@@ -51,6 +53,8 @@ interface DraftStoreActions {
draftKey: string;
update: (current: DraftInput) => DraftInput;
}) => void;
stageDraftText: (input: { draftKey: string; text: string }) => void;
flushDraftText: (draftKey: string) => void;
editDraftText: (input: { draftKey: string; text: string }) => void;
/**
* Sets the text on behalf of something other than the input, which then shows it. Use
@@ -62,6 +66,7 @@ interface DraftStoreActions {
draftKey: string;
lifecycle?: Exclude<DraftLifecycleState, "active">;
}) => void;
discardOrphanedWorkspaceDrafts: (openDraftKeys: ReadonlySet<string>) => boolean;
/** Plugin metadata the draft will create its agent with; see `composer/draft/metadata`. */
patchDraftMetadata: (input: { draftKey: string; patch: Record<string, JsonValue> }) => void;
clearDraftMetadata: (input: { draftKey: string }) => void;
@@ -87,6 +92,18 @@ interface DraftStoreRuntimeState {
type DraftStore = DraftStoreState & DraftStoreRuntimeState & DraftStoreActions;
export function hasUnsavedDraft(state: DraftStoreState, draftKey: string): boolean {
const record = state.drafts[draftKey];
return record?.lifecycle === "active" && hasDraftContent(record.input);
}
const stagedDraftText = new Map<string, AfterPaintPublication<string>>();
function cancelStagedDraftText(draftKey: string): void {
stagedDraftText.get(draftKey)?.cancel();
stagedDraftText.delete(draftKey);
}
let gcScheduled = false;
const draftPersistStorage = createDraftPersistStorage(
createValidatedPersistStorage(AsyncStorage, PersistedDraftStoreSchema),
@@ -328,12 +345,28 @@ export const useDraftStore = create<DraftStore>()(
},
updateDraftInput: ({ draftKey, update }) => {
get().flushDraftText(draftKey);
const next = update(get().getDraftInput(draftKey) ?? { text: "", attachments: [] });
if (hasDraftContent(next)) get().saveDraftInput({ draftKey, draft: next });
else get().clearDraftInput({ draftKey, lifecycle: "abandoned" });
},
stageDraftText: ({ draftKey, text }) => {
let publication = stagedDraftText.get(draftKey);
if (!publication) {
publication = new AfterPaintPublication((stagedText) => {
stagedDraftText.delete(draftKey);
get().editDraftText({ draftKey, text: stagedText });
});
stagedDraftText.set(draftKey, publication);
}
publication.stage(text);
},
flushDraftText: (draftKey) => stagedDraftText.get(draftKey)?.flush(),
editDraftText: ({ draftKey, text }) => {
cancelStagedDraftText(draftKey);
set((state) => {
const previous = state.drafts[draftKey];
const next = editDraftRecordText(previous, text, Date.now());
@@ -373,6 +406,7 @@ export const useDraftStore = create<DraftStore>()(
},
clearDraftInput: ({ draftKey, lifecycle }) => {
cancelStagedDraftText(draftKey);
set((state) => {
const existing = state.drafts[draftKey];
if (!existing) {
@@ -399,6 +433,18 @@ export const useDraftStore = create<DraftStore>()(
scheduleAttachmentGc();
},
discardOrphanedWorkspaceDrafts: (openDraftKeys) => {
const { drafts } = get();
const retained = Object.entries(drafts).filter(
([key, record]) =>
record.lifecycle !== "active" || !isWorkspaceTabDraftKey(key) || openDraftKeys.has(key),
);
if (retained.length === Object.keys(drafts).length) return false;
set({ drafts: Object.fromEntries(retained) });
scheduleAttachmentGc();
return true;
},
patchDraftMetadata: ({ draftKey, patch }) => {
set((state) => {
const next = applyMetadataPatch(state.metadataByDraftKey[draftKey] ?? {}, patch);
@@ -8,10 +8,18 @@ describe("resolveAssistantImageSource", () => {
kind: "direct",
uri: "https://example.com/image.png",
});
expect(resolveAssistantImageSource({ source: "http://example.com/image.png" })).toEqual({
kind: "direct",
uri: "http://example.com/image.png",
});
expect(resolveAssistantImageSource({ source: "data:image/png;base64,abc" })).toEqual({
kind: "direct",
uri: "data:image/png;base64,abc",
});
expect(resolveAssistantImageSource({ source: "blob:https://example.com/123" })).toEqual({
kind: "direct",
uri: "blob:https://example.com/123",
});
});
it("uses the workspace root for relative paths", () => {
@@ -104,4 +112,102 @@ describe("resolveAssistantImageSource", () => {
path: "C:/Users/test/Desktop/screenshot.png",
});
});
it.each([
["backslash drive path", "C:\\foo\\bar.png"],
["extended-length local drive path", "\\\\?\\C:\\foo\\bar.png"],
["local Windows drive file URI", "file:///C:/foo/bar.png"],
])("resolves %s to a local drive read target", (_label, source) => {
expect(resolveAssistantImageSource({ source, workspaceRoot: "D:/repo" })).toEqual({
kind: "file_rpc",
cwd: "C:/",
path: "C:/foo/bar.png",
});
});
it.each([
["UNC backslash path", "\\\\host\\share\\x.png"],
["UNC forward-slash path", "//host/share/x.png"],
["UNC mixed-slash path", "/\\host\\share\\x.png"],
["UNC reversed mixed-slash path", "\\/host/share/x.png"],
["extended UNC path", "\\\\?\\UNC\\host\\share\\x.png"],
["remote file URI", "file://host/share/x.png"],
["uppercase remote file URI", "FILE://host/share/x.png"],
["quad-slash file URI", "file:////host/share/x.png"],
["backslash UNC in file URI", "file:///\\\\host\\share\\x.png"],
["percent-encoded UNC in file URI", "file:///%5C%5Chost%5Cshare%5Cx.png"],
["Win32 device pipe path", "\\\\.\\pipe\\foo"],
["Win32 forward-slash device pipe path", "//./pipe/foo"],
["Win32 volume device path", "\\\\?\\Volume{01234567-89ab-cdef-0123-456789abcdef}\\x.png"],
["Win32 bare volume device path", "\\\\?\\Volume{01234567-89ab-cdef-0123-456789abcdef}"],
["Win32 globalroot device path", "\\\\?\\GLOBALROOT\\Device\\HarddiskVolume1\\x.png"],
])("rejects %s (%s) outside a matching UNC workspace", (_label, source) => {
expect(resolveAssistantImageSource({ source, workspaceRoot: "C:/repo" })).toBeNull();
expect(resolveAssistantImageSource({ source, workspaceRoot: "/repo" })).toBeNull();
expect(
resolveAssistantImageSource({
source,
workspaceRoot: "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj",
}),
).toBeNull();
expect(resolveAssistantImageSource({ source })).toBeNull();
});
it.each([
[
"UNC backslash path",
"\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
"\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
],
[
"UNC forward-slash path",
"//wsl.localhost/Ubuntu/home/me/proj/shot.png",
"\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
],
[
"extended UNC path",
"\\\\?\\UNC\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
"\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
],
[
"UNC file URI",
"file://wsl.localhost/Ubuntu/home/me/proj/shot.png",
"\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
],
[
"case-insensitive UNC path",
"//WSL.LOCALHOST/ubuntu/home/me/proj/sub/../shot.png",
"\\\\WSL.LOCALHOST\\ubuntu\\home\\me\\proj\\shot.png",
],
])("allows %s inside a matching UNC workspace root", (_label, source, expectedCanonical) => {
const uncRoot = "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj";
expect(resolveAssistantImageSource({ source, workspaceRoot: uncRoot })).toEqual({
kind: "file_rpc",
cwd: uncRoot,
path: expectedCanonical,
});
const extendedRoot = "\\\\?\\UNC\\wsl.localhost\\Ubuntu\\home\\me\\proj";
expect(resolveAssistantImageSource({ source, workspaceRoot: extendedRoot })).toEqual({
kind: "file_rpc",
cwd: extendedRoot,
path: "shot.png",
});
});
it.each([
["sibling prefix directory", "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj2\\shot.png"],
[
"parent traversal outside workspace",
"\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\..\\other\\shot.png",
],
["different share", "\\\\wsl.localhost\\Debian\\home\\me\\proj\\shot.png"],
])("rejects %s outside a UNC workspace root", (_label, source) => {
expect(
resolveAssistantImageSource({
source,
workspaceRoot: "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj",
}),
).toBeNull();
});
});
@@ -1,3 +1,9 @@
import {
isUncPathWithinRoot,
parseLocalImagePath,
parseUncPath,
relativeUncPath,
} from "@getpaseo/protocol/path-utils";
import { localFileSourceToPath } from "@/attachments/utils";
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
@@ -5,6 +11,39 @@ export type AssistantImageSourceResolution =
| { kind: "direct"; uri: string }
| { kind: "file_rpc"; cwd: string; path: string };
/**
* Normalize a local image path or `file:` URI while rejecting Win32 device namespace
* paths (`\\.\...`, `\\?\...` outside local drives and `\\?\UNC\...`), malformed `file:`
* URIs, and UNC network paths outside `workspaceRoot`.
*/
export function normalizeLocalImagePath(
source: string,
options?: { workspaceRoot?: string },
): string | null {
const trimmed = source.trim();
if (!trimmed) {
return null;
}
let parsed = parseLocalImagePath(trimmed);
if (parsed?.kind === "relative") {
const converted = localFileSourceToPath(trimmed);
if (converted !== trimmed) {
parsed = parseLocalImagePath(converted);
}
}
if (!parsed) {
return null;
}
if (parsed.kind === "unc") {
return isUncPathWithinRoot(parsed, options?.workspaceRoot) ? parsed.canonical : null;
}
return parsed.path;
}
export function resolveAssistantImageSource(input: {
source: string;
workspaceRoot?: string;
@@ -18,8 +57,29 @@ export function resolveAssistantImageSource(input: {
return { kind: "direct", uri: source };
}
const localPath = normalizeLocalImagePath(source, { workspaceRoot: input.workspaceRoot });
if (!localPath) {
return null;
}
const parsedUnc = parseUncPath(localPath);
if (parsedUnc) {
const workspaceRoot = input.workspaceRoot?.trim();
if (!workspaceRoot) {
return null;
}
const targetPath = /^[\\/]{2}\?[\\/]UNC[\\/]/i.test(workspaceRoot)
? (relativeUncPath(parsedUnc, workspaceRoot) ?? localPath)
: localPath;
return {
kind: "file_rpc",
cwd: workspaceRoot,
path: targetPath,
};
}
const readTarget = resolveFilePreviewReadTarget({
path: localFileSourceToPath(source),
path: localPath,
workspaceRoot: input.workspaceRoot,
});
if (!readTarget) {
@@ -1,3 +1,5 @@
import { buildDraftStoreKey } from "@/stores/draft-keys";
import { useDraftStore } from "@/stores/draft-store";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { QueryClient } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -166,6 +168,7 @@ afterEach(() => {
);
}
seedSessionHosts([]);
useDraftStore.setState({ drafts: {} });
});
describe("closing a tab with no guard", () => {
@@ -221,6 +224,78 @@ describe("closing a tab with unsaved work", () => {
});
});
describe("closing a New Agent tab", () => {
const draftId = "new-agent-draft";
const draftKey = buildDraftStoreKey({ serverId: SERVER_ID, agentId: "", draftId });
it("closes an empty draft without a prompt", async () => {
const { closeTab, dialog } = setup();
const tabId = open({ kind: "draft", draftId });
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
expect(openTabIds()).not.toContain(tabId);
expect(dialog.prompts).toEqual([]);
});
it("keeps the conversation if it starts while the discard prompt is open", async () => {
const { closeTab, dialog } = setup();
const tabId = open({ kind: "draft", draftId });
useDraftStore.getState().editDraftText({ draftKey, text: "My first prompt" });
const answer = Promise.withResolvers<boolean>();
dialog.answer(answer.promise);
const close = closeTab(WORKSPACE_KEY, tabId);
expect(dialog.prompts).toHaveLength(1);
useWorkspaceLayoutStore.getState().replaceTab(WORKSPACE_KEY, tabId, {
kind: "agent",
agentId: "started-agent",
});
answer.resolve(true);
await expect(close).resolves.toBe(false);
expect(openTabIds()).toContain(tabId);
});
it("keeps the tab and unsent text when the user cancels", async () => {
const { closeTab, dialog } = setup();
const tabId = open({ kind: "draft", draftId });
useDraftStore.getState().stageDraftText({ draftKey, text: "Keep my prompt" });
expect(useDraftStore.getState().getDraftInput(draftKey)).toBeUndefined();
dialog.answer(false);
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(false);
expect(dialog.prompts).toHaveLength(1);
expect(openTabIds()).toContain(tabId);
expect(useDraftStore.getState().getDraftInput(draftKey)?.text).toBe("Keep my prompt");
});
it("abandons an attachment-only draft when the user confirms", async () => {
const { closeTab, dialog } = setup();
const tabId = open({ kind: "draft", draftId });
useDraftStore.getState().saveDraftInput({
draftKey,
draft: {
text: "",
attachments: [
{ kind: "workspace_file", path: "README.md", selection: { kind: "whole_file" } },
],
},
});
dialog.answer(true);
await expect(closeTab(WORKSPACE_KEY, tabId)).resolves.toBe(true);
expect(openTabIds()).not.toContain(tabId);
expect(dialog.prompts).toHaveLength(1);
expect(useDraftStore.getState().drafts[draftKey]).toMatchObject({
lifecycle: "abandoned",
input: { text: "", attachments: [] },
});
});
});
describe("closing a terminal tab", () => {
function openTerminal(queryClient: QueryClient): string {
queryClient.setQueryData(TERMINALS_KEY, {
@@ -14,6 +14,8 @@ import {
type ListTerminalsPayload,
} from "@/screens/workspace/terminals/state";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import { buildDraftStoreKey } from "@/stores/draft-keys";
import { hasUnsavedDraft, useDraftStore } from "@/stores/draft-store";
import { useSessionStore } from "@/stores/session-store";
import {
canDismissPaneInLayout,
@@ -104,8 +106,25 @@ function pickTabs(workspaceKey: string, tabIds: readonly string[]): WorkspaceTab
});
}
function isDraftModified(serverId: string, target: WorkspaceTabTarget | undefined): boolean {
if (target?.kind !== "draft") return false;
const draftKey = buildDraftStoreKey({ serverId, agentId: "", draftId: target.draftId });
useDraftStore.getState().flushDraftText(draftKey);
return hasUnsavedDraft(useDraftStore.getState(), draftKey);
}
/** Removes the tab and everything this client holds for it. Daemon resources are the caller's. */
function removeTab(workspaceKey: string, tabId: string, target: WorkspaceTabTarget): void {
function removeTab(
workspaceKey: string,
serverId: string,
tabId: string,
target: WorkspaceTabTarget,
): boolean {
if (target.kind === "draft") {
const current = getLayoutTabs(workspaceKey).find((tab) => tab.tabId === tabId)?.target;
// The draft can become an agent while the discard prompt is open.
if (current?.kind !== "draft" || current.draftId !== target.draftId) return false;
}
const layout = useWorkspaceLayoutStore.getState();
if (target.kind === "agent") {
layout.unpinAgent(workspaceKey, target.agentId);
@@ -118,6 +137,13 @@ function removeTab(workspaceKey: string, tabId: string, target: WorkspaceTabTarg
void getDesktopHost()?.browser?.unregisterWorkspaceBrowser?.(browserId);
}
layout.closeTab(workspaceKey, tabId);
if (target.kind === "draft") {
const draftKey = buildDraftStoreKey({ serverId, agentId: "", draftId: target.draftId });
const drafts = useDraftStore.getState();
drafts.clearDraftInput({ draftKey, lifecycle: "abandoned" });
drafts.clearDraftMetadata({ draftKey });
}
return true;
}
export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
@@ -149,9 +175,13 @@ export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
}
}
async function confirmDiscardChanges(workspaceKey: string, tabId: string): Promise<boolean> {
async function confirmDiscardChanges(
workspaceKey: string,
tabId: string,
draftModified = false,
): Promise<boolean> {
const attributes = getWorkspacePanelAttributes(workspaceKey, tabId);
if (!attributes.modified) return true;
if (!attributes.modified && !draftModified) return true;
const resumePendingSave = attributes.suspendPendingSave?.();
const confirmed = await ports.confirm({
title: i18n.t("workspace.tabs.confirmations.unsavedTitle"),
@@ -205,7 +235,7 @@ export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
},
removeTerminalFromPayload(terminalId),
);
removeTab(workspaceKey, tabId, { kind: "terminal", terminalId });
removeTab(workspaceKey, serverId, tabId, { kind: "terminal", terminalId });
void killTerminal(serverId, terminalId).catch(
() => void ports.queryClient.invalidateQueries({ queryKey }),
@@ -256,7 +286,7 @@ export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
}
}
removeTab(workspaceKey, tabId, { kind: "agent", agentId });
removeTab(workspaceKey, serverId, tabId, { kind: "agent", agentId });
if (closePolicy.kind === "archive-on-close") {
// A failed archive restores the agent inside archiveAgent.
@@ -283,7 +313,10 @@ export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
}
const tab = getLayoutTabs(workspaceKey).find((candidate) => candidate.tabId === tabId);
if (!tab || !(await confirmDiscardChanges(workspaceKey, tabId))) {
if (
!tab ||
!(await confirmDiscardChanges(workspaceKey, tabId, isDraftModified(serverId, tab.target)))
) {
return false;
}
const { target } = tab;
@@ -299,8 +332,7 @@ export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
closeAgentTab({ workspaceKey, serverId, tabId, agentId }),
);
}
removeTab(workspaceKey, tabId, target);
return true;
return removeTab(workspaceKey, serverId, tabId, target);
}
/** One prompt for the whole set. Resolves false when the user declines it. */
@@ -327,7 +359,9 @@ export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
: "archive",
);
const modifiedCount = tabsToClose.filter(
(tab) => getWorkspacePanelAttributes(workspaceKey, tab.tabId).modified,
(tab) =>
isDraftModified(serverId, tab.target) ||
getWorkspacePanelAttributes(workspaceKey, tab.tabId).modified,
).length;
const message = buildBulkCloseConfirmationMessage(groups, BULK_CLOSE_LABELS);
const confirmed = await ports.confirm({
@@ -367,7 +401,7 @@ export function createWorkspaceTabClose(ports: WorkspaceTabClosePorts) {
}
},
closeWorkspaceTabWithCleanup: ({ tabId, target }) => {
if (target) removeTab(workspaceKey, tabId, target);
if (target) removeTab(workspaceKey, serverId, tabId, target);
},
logLabel,
warn: (warning, payload) => {
@@ -0,0 +1,56 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
import { buildDraftStoreKey } from "@/stores/draft-keys";
import { flushDraftPersistStorage, useDraftStore } from "@/stores/draft-store";
import { collectAllTabs, useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { parseWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
const SWEEP_KEY = "paseo:orphaned-workspace-drafts-swept";
function whenHydrated(store: {
hasHydrated: () => boolean;
onFinishHydration: (listener: () => void) => () => void;
}): Promise<void> {
if (store.hasHydrated()) return Promise.resolve();
return new Promise((resolve) => {
const unsubscribe = store.onFinishHydration(() => {
unsubscribe();
resolve();
});
});
}
/** Removes drafts left behind by versions that closed New Agent tabs without discarding them. */
export async function sweepOrphanedWorkspaceDrafts(): Promise<void> {
try {
if (await AsyncStorage.getItem(SWEEP_KEY)) return;
await Promise.all([
whenHydrated(useWorkspaceLayoutStore.persist),
whenHydrated(useDraftStore.persist),
]);
const openDraftKeys = new Set<string>();
for (const [workspaceKey, layout] of Object.entries(
useWorkspaceLayoutStore.getState().layoutByWorkspace,
)) {
const identity = parseWorkspaceTabPersistenceKey(workspaceKey);
if (!identity) continue;
for (const { target } of collectAllTabs(layout.root)) {
if (target.kind === "draft") {
openDraftKeys.add(
buildDraftStoreKey({ ...identity, agentId: "", draftId: target.draftId }),
);
}
}
}
const removed = useDraftStore.getState().discardOrphanedWorkspaceDrafts(openDraftKeys);
if (removed) {
// Only record completion on a launch that reads the cleaned state back from disk.
await flushDraftPersistStorage();
} else {
await AsyncStorage.setItem(SWEEP_KEY, "1");
}
} catch (error) {
console.warn("[DraftStore] Failed to remove orphaned New Agent drafts", error);
}
}
@@ -79,6 +79,7 @@ describe("unlisted agent resolution", () => {
status: "archived",
archivedAt: "2026-11-15T00:00:00.000Z",
});
expect(client.fetchAgentsCallCount).toBe(0);
expect(client.fetchAgentCalls).toEqual([unlistedId]);
expect(client.archived).toEqual([unlistedId]);
expect(client.closed).toBe(true);
@@ -0,0 +1,13 @@
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
export function resolveDisplayModel({
runtimeInfo,
model,
}: Pick<AgentSnapshotPayload, "runtimeInfo" | "model">): string | null {
const runtimeModel = runtimeInfo?.model?.trim();
if (runtimeModel) return runtimeModel;
// Older saved configurations used "default" to defer to the provider.
const savedModel = model?.trim();
return savedModel && savedModel.toLowerCase() !== "default" ? savedModel : null;
}
+2 -12
View File
@@ -3,6 +3,7 @@ import { PARENT_AGENT_ID_LABEL } from "@getpaseo/protocol/agent-labels";
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
import { connectToDaemon } from "../../utils/client.js";
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
import { resolveDisplayModel } from "./display-model.js";
export function addInspectOptions(cmd: Command): Command {
return cmd
@@ -94,17 +95,6 @@ function formatCost(costUsd: number): string {
return `$${costUsd.toFixed(2)}`;
}
function normalizeModelId(value: string | null | undefined): string | null {
if (typeof value !== "string") return null;
const normalized = value.trim();
if (!normalized || normalized.toLowerCase() === "default") return null;
return normalized;
}
function resolveModel(snapshot: AgentSnapshotPayload): string | null {
return normalizeModelId(snapshot.runtimeInfo?.model) ?? normalizeModelId(snapshot.model);
}
function buildLastUsage(snapshot: AgentSnapshotPayload): AgentInspect["LastUsage"] {
if (!snapshot.lastUsage) return null;
return {
@@ -131,7 +121,7 @@ function toInspectData(snapshot: AgentSnapshotPayload): AgentInspect {
Id: snapshot.id,
Name: snapshot.title ?? "-",
Provider: snapshot.provider,
Model: resolveModel(snapshot) ?? "-",
Model: resolveDisplayModel(snapshot) ?? "-",
Thinking: snapshot.effectiveThinkingOptionId ?? "auto",
Status: snapshot.status,
Archived: snapshot.archivedAt != null,
@@ -81,6 +81,11 @@ describe("buildAgentLsFetchOptions", () => {
});
});
it("preserves empty values and punctuation in repeated label filters", () => {
const options = buildAgentLsFetchOptions({ label: ["tag=v=1,rc", "empty="] });
expect(options.filter?.labels).toEqual({ tag: "v=1,rc", empty: "" });
});
it("asks the daemon for internal agents only with --internal", () => {
expect(buildAgentLsFetchOptions({ background: true, global: true })).toEqual({
filter: { includeBackground: true },
@@ -126,6 +131,17 @@ describe("buildAgentLsFetchOptions", () => {
});
describe("runLsCommand", () => {
it.each(["team", "=blue", " =blue"])(
"rejects the whole listing when a label filter is malformed (%j)",
async (label) => {
await expect(
listAgents({ daemonTarget, label: ["bot=worker", label] }, async () =>
createPagingClient(),
),
).rejects.toMatchObject({ code: "INVALID_LABEL", message: `Invalid label format: ${label}` });
},
);
it("includes agent snapshot metadata in JSON listings", async () => {
const result = await listAgents({ daemonTarget, global: true }, async () =>
createPagingClient(),
+19 -21
View File
@@ -5,6 +5,7 @@ import { fetchAllAgents } from "../../utils/agent-directory.js";
import type { CommandOptions, ListResult, OutputSchema, CommandError } from "../../output/index.js";
import { collectMultiple } from "../../utils/command-options.js";
import { isSameOrDescendantPath } from "../../utils/paths.js";
import { resolveDisplayModel } from "./display-model.js";
type FetchAgentsOptions = NonNullable<
Parameters<Awaited<ReturnType<typeof connectToDaemon>>["fetchAgents"]>[0]
@@ -64,13 +65,6 @@ function shortenPath(path: string): string {
return path;
}
function normalizeModelId(modelId: string | null | undefined): string | null {
if (typeof modelId !== "string") return null;
const normalized = modelId.trim();
if (!normalized || normalized.toLowerCase() === "default") return null;
return normalized;
}
/** Schema for agent ls output */
export const agentLsSchema: OutputSchema<AgentListItem> = {
idField: "shortId",
@@ -106,7 +100,7 @@ const agentLsInclusiveSchema: OutputSchema<AgentListItem> = {
/** Transform agent snapshot to AgentListItem */
function toListItem(agent: AgentSnapshotPayload): AgentListItem {
const model = normalizeModelId(agent.runtimeInfo?.model) ?? normalizeModelId(agent.model);
const model = resolveDisplayModel(agent);
return {
id: agent.id,
shortId: agent.id.slice(0, 7),
@@ -147,16 +141,20 @@ export interface AgentLsOptions extends CommandOptions {
}
function parseLabelFilters(labels: string[] | undefined): Record<string, string> {
const labelFilters: Record<string, string> = {};
for (const labelStr of labels ?? []) {
const eqIndex = labelStr.indexOf("=");
if (eqIndex !== -1) {
const key = labelStr.slice(0, eqIndex);
const value = labelStr.slice(eqIndex + 1);
labelFilters[key] = value;
}
}
return labelFilters;
return Object.fromEntries(
(labels ?? []).map((label) => {
const separator = label.indexOf("=");
const key = label.slice(0, separator);
if (separator === -1 || !key.trim()) {
throw {
code: "INVALID_LABEL",
message: `Invalid label format: ${label}`,
details: "Labels must include a non-empty key in key=value format",
} satisfies CommandError;
}
return [key, label.slice(separator + 1)];
}),
);
}
export function buildAgentLsFetchOptions(
@@ -217,6 +215,7 @@ export async function listAgents(
options: Parameters<typeof connectToDaemon>[0],
) => Promise<AgentLsClient> = connectToDaemon,
): Promise<AgentLsResult> {
const fetchOptions = buildAgentLsFetchOptions(options);
const client = await connect({ target: options.daemonTarget });
try {
@@ -229,8 +228,6 @@ export async function listAgents(
throw error;
}
const labelFilters = parseLabelFilters(options.label);
const fetchOptions = buildAgentLsFetchOptions(options);
let agents = await fetchAllAgents(client, fetchOptions);
// By default, exclude archived agents. `-a` includes them.
@@ -249,7 +246,8 @@ export async function listAgents(
}
// Apply label filtering only when explicitly requested.
if (Object.keys(labelFilters).length > 0) {
const labelFilters = fetchOptions.filter?.labels;
if (labelFilters) {
agents = agents.filter((a) => {
const agentLabels = a.labels;
for (const [key, value] of Object.entries(labelFilters)) {
@@ -110,6 +110,7 @@ async function probeDaemonStatus(
tailscale: status.tailscale,
extraListeners: status.extraListeners,
...(status.terminalsUnavailable ? { terminals: status.terminalsUnavailable } : {}),
terminalCleanupUnconfirmed: status.terminalCleanupUnconfirmed,
};
}
} finally {

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