Compare commits

...
Author SHA1 Message Date
Mohamed Boudra b1bbb7a102 fix(voice): initialize manual speech on demand 2026-09-05 13:41:14 +02:00
Mohamed Boudra 20353ca208 fix(server): align script compiler library 2026-09-05 13:41:14 +02:00
Mohamed Boudra 16e8de01e3 feat(voice): move voice chat to an app-level capability
Keep call lifecycle, provider configuration, and media transports independent from ordinary agent sessions so alternate voice providers can be added without changing the shared runtime.
2026-09-05 13:41:14 +02:00
Mohamed Boudra 02e611f3dd Hide empty ACP sessions from session import (#4335)
* fix(server): filter empty ACP import sessions

ACP metadata probes can leave persisted sessions that later appear in import results. Replay available session history to exclude truly empty entries while retaining sessions whose history is unavailable, and close probe sessions before process teardown.

* fix(server): bound ACP session history loading

Keep import enrichment inside the provider listing deadline when session histories are inaccessible. Catalog abort cleanup now also waits briefly for an in-flight session creation so the resulting probe session can be closed.

* test(server): avoid wall-clock ACP assertion

Verify the history budget through the number of attempted protocol loads instead of elapsed process time, so scheduler delays cannot make the regression flaky.

* fix(server): allow slower ACP history loads

Give native session history more time to replay while retaining a shared enrichment budget below the provider listing deadline.

* fix(server): give ACP history replay enough time

Use the provider RPC timeout scale for native history loading, with a larger shared budget and provider-list deadline. Keep timeout coverage fast and deterministic with a controlled clock.

* fix(server): isolate generous ACP import deadlines

Keep the long listing deadline for the picker’s single-provider requests while preserving the short aggregate deadline for callers that fan out across providers. Restore deterministic coverage of unresolved history loads through fake timers and an injected clock boundary.

* fix(server): preserve ACP aggregate listings
2026-09-05 11:29:56 +02:00
Mohamed Boudra f4b209be4d Preserve nested subagent ownership (#4321)
* fix(subagents): preserve recursive provider ownership

Provider events retained enough lineage to identify nested work, but the canonical descriptor discarded the direct owner. Preserve that relationship at ingestion so child timelines and hierarchy remain attached to the process that emitted them, including after history replay.

* test(e2e): clarify nested ownership journey

* test(e2e): separate nested ownership actions

* fix(subagents): retain nested ownership across replay

Wait and interaction events can reference descendants without spawning them. Preserve the original spawning owner and route persisted background notifications through that same relationship after history reload.

* test(subagents): hide provider turn plumbing

* fix(subagents): scope nested tracks to their host

Plugin-provided icons are host-specific. Carry the panel host through nested child tracks so the rebased ownership UI resolves the same provider presentation as its parent.

* fix(workspaces): preserve launched terminal focus
2026-09-04 23:49:26 +02:00
Mohamed Boudra c610676203 fix(providers): preserve state across configuration reloads (#4332)
A provider configuration edit invalidated every cached catalog and could turn healthy providers into false availability errors under the resulting probe burst. Preserve unchanged registry entries, clients, loads, and snapshots, and keep the submitted draft snapshot stable while creation is pending.
2026-09-04 23:27:44 +02:00
Mohamed Boudra 9e90b86afa Restore reliable macOS desktop updates (#4322)
* fix(desktop): restore macOS app updates

Electron 41's Squirrel helper can leave the update handoff dormant on current macOS, so Paseo quits cleanly but relaunches the old bundle. Electron 44 wakes ShipIt through its XPC service.

Include updater lifecycle events and ShipIt state in app diagnostics so future handoff failures identify the current version, target version, cache paths, and installer output.

* fix(desktop): harden updater diagnostics

Keep each ShipIt file's evidence available when another read fails, carry the service-selected version into updater lifecycle logs, and make clean workspace installs resolve the Electron runtime used by desktop tests.

* refactor(desktop): name updater install options

* refactor(desktop): name updater log payloads

* refactor(desktop): name clipboard payload

* fix(desktop): surface updater lookup failures

* test(desktop): await guest focus transition

* fix(desktop): guard macOS update compatibility

* test(release): validate desktop manifests before publish

* test(desktop): await populated daemon pid file
2026-09-04 22:17:39 +02:00
Mohamed Boudra 35d2457d83 Let plugins provide coding agents (#4314)
Allow trusted local plugins to register complete coding-agent providers through the existing agent lifecycle. Includes direct and ACP implementations, SVG provider icons, custom timeline items, runnable examples, and public authoring documentation.

Closes #3547
Closes #3556
2026-09-04 19:56:57 +02:00
Mohamed Boudra 140b0bb716 fix(app): keep long agent timelines smooth across autonomous turns
Scope provider tool-call identity to its autonomous turn so repeated IDs remain distinct, lifecycle updates still merge correctly, and native timeline lists no longer receive duplicate keys.
2026-09-04 14:23:43 +02:00
Ivan MalisonandClaude Fable 5.1 92442e7435 fix(server): reject pending Codex app-server requests on dispose (#4283)
The provider refresh deadline aborts a Codex catalog probe by disposing
the app-server client, but dispose killed the child without settling
in-flight requests. With the request fallback timeout at 14 days, an
unanswered `initialize` left `fetchCatalog` pending forever, so the
workspace snapshot entry stayed "loading" and the model picker showed
"Loading" for every Codex profile with no timeout ever surfacing.

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 00:50:26 +02:00
Trim21andMohamed Boudra 75eb9d44a3 feat(agents): surface provider notifications in the timeline (#3411)
* feat(pi): surface extension notify in the agent timeline

Pi extension ctx.ui.notify() messages were dropped or buffered away
and never appeared anywhere in Paseo. Emit them as notification
timeline items so they show in the agent chat feed, with
info/warning/error levels mapped to activity log styling.

* fix id

* feat(agents): unify timeline notifications

Represent Pi and OpenCode notices as one first-class timeline item instead of provider-specific synthetic tool calls. Gate the new wire variant so older strict clients keep working during version drift.

* test(omp): update notice expectations

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-09-03 21:38:15 +02:00
Mohamed Boudra bb676ef086 Smooth mobile keyboard transitions (#4275)
* perf(app): smooth mobile keyboard transitions

Animating dock padding forced Fabric and Yoga to relayout the chat tree on every keyboard frame, producing visible stepping and React list churn. Keep the surface full-height and move it as one translated unit, with scroll range and portal measurements updated only after keyboard motion settles.\n\niOS keeps its native keyboard animation driver behind the same component boundary because its Reanimated signal reports the endpoint at animation start.

* fix(app): isolate native keyboard implementation
2026-09-03 20:27:19 +02:00
Mohamed Boudra 53c9607479 Control Paseo tools per provider (#4277)
Add backend-only exact-provider controls for the Paseo tool catalog across native and MCP-backed agents, including persisted configuration, session snapshots, public documentation, and regression coverage.\n\nCo-authored-by: Matt Cowger <matt@cowger.us>
2026-09-03 20:10:47 +02:00
Mohamed Boudra 25defbafb4 Make plugin upgrade failures actionable (#4265)
* fix(plugins): clarify upgrade diagnostics

Keep plugin inspection network-free and consolidate runtime, source, and installed revision details under plugin ls. Legacy entry failures now explain the required v0.8 migration in user-facing language.

* test(cli): align hidden plugin status command
2026-09-03 13:22:21 +02:00
Mohamed Boudra eb753813a1 feat(hub): expose provider catalogs to executions (#4242)
Hub execution credentials need provider snapshot access so remote workflow editors can present the daemon's native models, modes, and thinking options without gaining broader daemon read authority.
2026-09-03 00:08:30 +02:00
Mohamed Boudra 20ecdee72d docs(plugins): version breaking API guides (#4245)
Keep stable v0.7 guidance available while the client-entry layout is previewed for v0.8. Existing reference and migration URLs redirect to the release that owns their content.
2026-09-02 23:45:23 +02:00
Mohamed Boudra ce07732d62 fix(diff): keep file headers synchronized while scrolling (#4240)
The fixed header overlay repainted after compositor-driven scroll, so ordinary headers visibly lagged behind the diff body. Paint in-flow headers with the scrolling canvas and reserve a bounded sticky canvas pool for push-off behavior.
2026-09-02 22:54:38 +02:00
Mohamed Boudra a835136854 Let CLI host selection work globally (#4238)
* feat(cli): accept host as a global option

Keep the command-local position for compatibility while letting users place one daemon target before the command and reuse it while changing verbs. Local daemon lifecycle commands continue to operate locally.

* fix(cli): preserve project host resolution boundary

Project creation already handled PASEO_HOST directly. Avoid routing that established behavior through a newly exported client helper so its isolated command tests keep their existing dependency boundary.

* test(cli): allow scaffold typecheck under CI load

* test(cli): provide remote cwd in schedule e2e

* docs(cli): teach only global host syntax
2026-09-02 22:53:55 +02:00
Mohamed Boudra 7178583612 Stop Settings navigation from retaining closed views (#4228)
* fix(desktop): stop retaining closed Settings views

Settings rotations left detached detail panes reachable from the web style registry's strong element sets. Backport the upstream weak cleanup design and cover the real Electron bundle with a forced-GC regression.\n\nKeep the established sibling-route topology; compact Back relies on route-name identity.

* test(app): synchronize Mermaid completion layout assertion

The streaming acceptance test can observe the intentional completion remount between visibility and layout sampling. Consult the existing completion promise around that measurement so the transition is not reported as diagram loss.

* test(app): isolate worktree restart from provider startup
2026-09-02 21:27:30 +02:00
Mohamed Boudra f75dff2322 Require explicit setup for fork pull requests (#4215)
* feat(workspaces): gate fork repository automation

Cross-repository change requests can execute contributor-controlled package hooks even when the setup command comes from the base repository. Persist the checkout provenance and require one explicit workspace-level setup action before repository automation runs.

* fix(workspaces): clarify blocked script errors

* fix(app): keep long toasts readable

* test(server): expect fork repository provenance

* test(server): make setup marker portable

* test(app): retry transient sidebar layout
2026-09-02 20:50:22 +02:00
Mohamed Boudra 2d8ff6f1cf Restore copy actions in web diffs (#4229)
* fix(app): restore diff copy actions on web

The canvas-backed diff owns selection without creating a DOM range, so browser context menus cannot expose copy actions themselves. Route keyboard and context-menu actions through the renderer's canonical source selection instead.

* fix(app): harden web diff copy actions

* fix(app): default split header selection to new pane

* fix(app): isolate nested diff context menus

* fix(app): select available split diff pane
2026-09-02 20:25:55 +02:00
Mohamed Boudra 53d824a320 feat(plugins): split client and server plugin entries (#4206)
* feat(plugins): phase 1 split runtime entries after green gate

The compiler now builds explicit client and server entries, so runtime boundaries are source-owned instead of registration-name filtering. Compiler and runtime tests prove the entry split, directory and suffix boundaries, client Node import errors, migration failure, and client-only operation without a subprocess.

* feat(plugins): phase 2 run client entries after green gate

Explicit client and server contexts replace the mixed plugin context. The app runner owns every client registration and its idempotent removal, including late contributions and composer pills; focused contribution tests prove the removal contract, and all five migrated examples reached running on the isolated worktree daemon.

* feat(cli): phase 3 scaffold runtime split after green gate

The generated project demonstrates the required shared RPC contract, server handler, client surface, and sidebar wiring. The scaffold test and an isolated init, typecheck, install, and running check prove the phase acceptance path.

* docs(plugins): phase 4 publish migration after green gate

Gate: current docs and the paseo-plugin skill describe only explicit client/server entries. The standalone migration guide maps every former registration, and migration-doc.test.ts proves every client add* method remains represented.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Gate: compiler 13, runtime 24, typecheck, lint, and format passed. The dependency fixture proved node_modules/client was incorrectly treated as a plugin boundary.

* fixup! feat(plugins): phase 2 run client entries after green gate

Gate: client runtime and registry tests, typecheck, lint, format

* fixup! docs(plugins): phase 4 publish migration after green gate

Gate: migration docs test, paragraph audit, typecheck, lint, format

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Gate: compiler organization tests, typecheck, lint, targeted format

* fixup! feat(plugins): phase 2 run client entries after green gate

Gate: shared SDK tests, runtime tests, typecheck, lint, targeted format

* fixup! feat(cli): phase 3 scaffold runtime split after green gate

* fixup! docs(plugins): phase 4 publish migration after green gate

* fixup! feat(plugins): phase 1 split runtime entries after green gate

* docs(plugins): rewrite public plugin docs for runtime entries and mobile guardrails

* fixup! feat(cli): phase 3 scaffold runtime split after green gate

The scaffold now keeps DOM globals out of the program and declares only window.open inside client/web.ts. The scaffold test invokes tsc in a fresh process, proves the generated project passes, and proves a stray document access fails.

* fixup! docs(plugins): phase 4 publish migration after green gate

The internal guide and plugin skill now forbid both the DOM lib and triple-slash DOM references. They direct web adapters to declare only the globals used by client/web.ts.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Removing the obsolete Babel parser changes the locked npm dependency graph. The macOS Nix desktop gate reported the new fixed-output hash, which this commit records.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Reject relative imports that escape the plugin root while continuing to skip resolved node_modules internals. The compiler regression test proves the escaped import is rejected and the dependency-internal fixture remains accepted.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Classify absolute imports and reject plugin-authored paths that escape into node_modules. Dependency internals remain exempt based on their importer path. Red-first compiler regressions cover both bypasses, and the existing dependency fixture remains green.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Classify canonical esbuild resolution results so dependency-relative and symlink imports cannot escape client/server boundaries. The two compiler regressions failed before the fix and pass afterward.

* test(ci): synchronize flaky state transitions

Wait for repository watcher registration before emitting buffered ref events, let sidebar order polling retry unlaid-out rows, and wait for the inactive browser parking state before screenshot capture. These changes directly address the three observed CI failures; the affected server, Playwright, and desktop browser tests pass locally.

* test(ci): synchronize Mermaid completion layout assertion

The Playwright streaming acceptance test exposed a completion remount between visibility and layout sampling. Check the existing completion promise around the measurement so that transition is not reported as diagram loss.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Resolve bare package imports before boundary classification so symlinked dependency entries cannot expose server modules to the client bundle. The focused regression proves the bypass and the compiler file passes 20/20.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Allow canonical paths only within a matching linked package root while preserving runtime and containment checks for imports that leave it. The linked-dependency regression fails before the fix and compiler tests pass 21/21 afterward.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Reject matching package manifests that contain the plugin or live inside it, so linked-dependency roots cannot exempt plugin or workspace files. The ancestor-manifest regression fails before the fix and compiler tests pass 22/22 afterward.

* fixup! feat(plugins): phase 1 split runtime entries after green gate

Validate plugin-local lexical boundaries before canonical linked-root exemptions and require remembered-root imports to originate inside that root. The linked-root bypass regression fails before the fix and compiler tests pass 23/23 afterward.
2026-09-02 19:11:45 +02:00
fa1f01ebbc feat(app): add fullscreen viewer for Mermaid diagrams on web (#4107)
* feat(app): add fullscreen viewer for Mermaid diagrams on web

Add a fullscreen action to the diagram toolbar that opens the diagram in
a modal ZoomableViewport with free zoom/pan, closable via the close
button, Escape, or clicking outside the diagram. The sandboxed iframe
runtime moves into a shared MermaidIframeRuntime so the inline host and
the fullscreen viewer drive the same renderer.

Fixes uncovered while verifying the feature end to end:

- The runtime measured the rendered SVG with getBoundingClientRect(),
  which depends on the iframe size the host derives from that very
  measurement. Each streaming re-render shrank the reported size by the
  diagram box padding, ratcheting diagrams down to a few pixels. Measure
  the viewBox instead, which is the diagram's own size, and let the SVG
  fill whatever frame the host provides.
- ZoomableViewport's root is flex: 1, so as a flex item its 0% basis
  overrode the inline diagram box height and the box collapsed, scaling
  the diagram tiny and clipping the toolbar unclickable. Size the box
  from its height and keep a minimum tall enough for the toolbar.
- react-native-web's Modal focus trap focuses the first descendant that
  takes focus, which was the diagram iframe; every keystroke then landed
  in the sandboxed frame and Escape never reached the window listener.
  Mark the presentational iframe inert and focus the viewer's content
  layer on mount.

Closes #4106

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

* test(app): exercise Mermaid fullscreen interactions

Cover zoom, pan, outside-click dismissal, and streaming layout through the real browser path. Remove the mocked DOM test that duplicated those behaviors without exercising the viewport or iframe runtime.

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-09-02 16:10:26 +02:00
Mohamed Boudra d4841b68ff fix(website): detect the visitor platform during SSR (#4222)
The homepage download CTA was chosen by a client-only hook that started at
"mac-silicon" and corrected itself in an effect, so the server-rendered HTML
said "Download for Mac" for every visitor and only became right after
hydration. On a phone that window is long enough to photograph. Worse, the
detection had no mobile branch at all: Android user agents also say "Linux",
so once hydration did land, a Pixel was offered an AppImage.

Resolve the platform from the request user agent during SSR instead, so the
first paint is already correct. Mobile visitors get the App Store or Play
Store as the primary action and a link to /download for the desktop build,
rather than a .dmg they cannot open.

The markup now varies by user agent, so HTML and server-function responses
carry `Cache-Control: private, no-store` and `Vary: User-Agent`. An absent
cache-control is not no-store — a shared cache may assign heuristic freshness,
and turning on Workers Cache would store a headerless 200 for two hours under
a key that ignores the user agent, letting one Android visitor pin the Play
Store button for every Mac visitor after them.

Also tighten the mobile layout the wrong CTA was sitting in: the primary
action gets its own row so the icon buttons stop orphaning one of themselves,
provider cards drop to a two-column grid, and the hardcoded mobile line break
in the phone showcase gives way to a balanced measure.
2026-09-02 15:46:16 +02:00
Mohamed Boudra ac085d50c6 Make import session one tap away and make the sheet find your session (#4216)
* feat(app): make import session a first-class entry point

* feat(server): improve import session discovery resilience

Search up to 500 persisted candidates per provider and isolate listing failures behind eight-second deadlines so healthy results remain usable. Preserve native persisted title precedence while keeping discovery read-only.

Parsing now continues through each transcript so native titles and the true last prompt are retained; the old early exit made lastPromptPreview equal firstPromptPreview. A cheap record prefilter avoids JSON.parse for unrelated lines during the full scan.

* feat(app): searchable, grouped import session sheet with per-provider errors

The sheet now carries a debounced search field gated on the host's
importSessionSearch feature, grows its per-provider page on demand
(15 -> 45 -> 90 -> 200) instead of capping at the 15 most recent, and groups
unscoped rows by folder under the project name the app knows for that
directory. Worktrees of one project would otherwise all head up as the same
bare name, so a directory below its project root carries the path under that
root beside the name.

A workspace-scoped sheet says so and offers "Show all sessions". Importing a
row from another directory once that is on drops the workspace from the
request, which the daemon would otherwise reject, and routes the user to the
agent's own workspace rather than opening a dead tab in the current one. That
decision lives in resolveImportTarget: a scoped listing is trusted wholesale
because the daemon already matched it realpath-aware, which the client cannot.

A provider that fails now gets its own error row with a Retry that refetches
only that provider, sourced from both a failed request and the daemon's
providerErrors. React Query no longer retries these, so the header spinner
settles once every provider has answered or given up (#2512).

* test(e2e): import session flow with fixture Claude sessions

* fix(app): shorten import sheet scope copy so it fits at phone width

At 390px the scoped subtitle rendered "Sessions in this wor..." — the label,
its action, and the sheet's refresh and close buttons do not share one line at
phone width. The label already sits under the sheet title "Import session", so
"Sessions in this" was repeating context the header had: it becomes "This
workspace" and the action becomes "Show all". The unscoped label still names
the host, which nothing else on the sheet does.

* refactor(app): flat recency-ordered import list with per-row folder label

Grouping by folder buried recency: a busy directory's block of fifteen pushed
a two-minute-old session in a quiet directory below the fold, and the axis a
user is scanning on is when they last touched the session, not where it lives.
The unscoped sheet is now one list in the order aggregateSessionEntries already
produces, and each row carries its folder as a muted third line.

resolveDirectoryLabel stays — it is what keeps two worktrees of one project
apart — and formatDirectoryLabel renders its two parts as the single ellipsised
line a row has room for. A scoped sheet lists one directory, so its rows carry
no folder line at all.

* fix(app): close import sheet before refreshing sessions

Provider-list invalidation waited for every active query before the sheet could close. Mark the disabled picker queries stale after close and navigation so reopening refreshes without delaying the imported agent.

* fix(server): reuse workspaces for session imports

Host-wide imports should join the oldest active workspace for their directory, or restore its archived workspace, instead of minting duplicates. Rollback remains limited to workspace records created by the failed import.

* test(e2e): express the import session journey through a helper DSL

* test(e2e): align sidebar journeys with import entry point
2026-09-02 15:44:44 +02:00
1c960261ac feat(providers): add Gajae Code to the ACP provider catalog (#3471)
* feat(providers): add Gajae Code to the ACP provider catalog

Gajae Code (gjc) ships a conformance-tested ACP agent (`gjc acp`), so it can be
a one-click catalog entry instead of a hand-written custom provider in
config.json. Command and env match what the agent's own installer writes.

* feat(providers): add Gajae Code icon

---------

Co-authored-by: Yeachan-Heo <yeachan.heo@gmail.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-09-02 15:32:23 +02:00
Mohamed Boudra 7838b534a8 Show self-hosted and hosted Hub plans (#4213)
* feat(website): publish Hub pricing options

Present self-hosted and hosted Hub choices together while reading the hosted offer from Hub's public catalog.

* fix(website): require a valid hosted offer

* fix(website): preserve Hub page on catalog failure
2026-09-02 15:05:28 +02:00
Mohamed Boudra ff0171cf7b Make agent tab tooltips compact and informative (#4214)
Join and truncate prompt-derived titles for the visual tooltip, add agent ID and live human activity metadata on a second row, and keep activity subscriptions local to the open tooltip. Preserve the full normalized title as the accessible tab name and cover the behavior through Playwright.
2026-09-02 14:27:18 +02:00
Mohamed Boudra 77aff0f4fb fix(app): stabilize Mermaid streaming lifecycle (#4210)
Drive the streaming assertion from the actual turn lifecycle so iframe replacement at completion is not mistaken for diagram loss. Preserve the cached timeline range during reload reconciliation so a projected message spanning the cache cursor replaces its partial prefix instead of being appended to it.
2026-09-02 13:37:32 +02:00
Mohamed Boudra 708f9260b1 fix(server): disable repository fsmonitor commands (#4208)
A repository-controlled core.fsmonitor command can execute when the daemon refreshes Git state. Opening or reconciling a malicious checkout therefore allows code execution as the daemon user. Force core.fsmonitor=false on daemon-owned Git invocations before repository config is considered.
2026-09-02 13:15:51 +02:00
Mohamed Boudra e34aea206e feat(plugins): add live timeline rows and client slash commands
Plugins can transform live timeline source items at render time, append durable plugin rows from daemon handlers, and register client-only slash commands in the composer.

Related to #3940 and #3952.
2026-09-02 13:12:09 +02:00
Mohamed Boudra 49784fac15 Keep Changes and working diff comparisons in sync (#4199)
* fix(app): keep Changes comparison and diff in sync

Own the working comparison at the workspace checkout so the Changes tree and adjacent working diff share it. Immutable commit diffs remain scoped to their commit SHA.

* docs(app): align working diff ownership notes
2026-09-02 12:38:16 +02:00
Mohamed Boudra 4aab00f267 fix(desktop): use CLI shim for packaged Linux installs (#4207)
Non-AppImage packages install the Electron executable at a stable path, but invoking it through the CLI symlink cannot restart the daemon. Link the bundled CLI shim for those targets while preserving AppImage links.\n\nFixes #4184
2026-09-02 12:30:28 +02:00
Mohamed Boudra de8535c38b Customize top-level sidebar items (#4203)
* feat(app): customize top-level sidebar items

Let users reorder and hide built-in and plugin sidebar rows from Appearance settings while keeping the preference device-local. Add Search as a first-class row and standardize section explanations as header info tooltips.

* fix(app): preserve consecutive sidebar preference edits

Derive each sidebar change from the latest cached settings and retain unavailable plugin slots while editing the visible list. Keep E2E interaction selectors tied to accessible control names.

* test(app): isolate provider settings unit boundary

Keep the legacy provider-section test focused on provider behavior now that its shared section shell can render the settings info control.
2026-09-02 11:42:39 +02:00
Mohamed Boudra d67a6f5f6c fix(release): keep releases draft until manifests are ready (#4201)
Create tag-triggered GitHub releases as drafts and publish them only after the desktop updater manifests are complete, stamped, and uploaded. Preserve beta prerelease semantics and safe retry behavior.\n\nCloses #4183
2026-09-02 11:29:41 +02:00
paseo-ai[bot] 78f7796eb4 fix: update lockfile signatures and Nix hash [skip ci] 2026-09-02 00:19:07 +00:00
Mohamed Boudra 9400a49af6 chore(release): cut 0.7.2 2026-09-02 02:07:34 +02:00
Mohamed Boudra e9612df862 docs: add 0.7.2 changelog 2026-09-02 01:57:25 +02:00
Mohamed Boudra 8dd4da6ee0 Keep mobile streaming and panel motion stable under JS stalls (#4190)
* fix(app): activate mobile panels after motion settles

Gesture previews were publishing React presentation state and activating retained content before the native motion finished. Keep transient motion on the UI thread and publish the active panel only from the accepted animation completion.

* perf(app): re-render only changed history rows

Every coalesced stream tick re-rendered all mounted history rows because the inverted FlatList recreates each cell with a new index and ref. Keep layout item identity for unchanged rows and memoize the row on it, and resolve tool-call groups through a stable event so the render callbacks stop churning.

* perf(app): count replica row bytes once

Budget accounting measured every stored row of a touched host on each persist through the Buffer polyfill. Cache the UTF-8 length per immutable row and count without materialising bytes.

* fix(app): settle mobile panels on position

Activity now follows the UI-thread position reaching the canonical anchor instead of an animation completion callback. A successful gesture keeps its finishing motion and the matching command adopts it; settlement and command acceptance may arrive in either order.

* fix(app): keep settled panel props across JS stalls

Turn off Reanimated's FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS. Its settled-props collector drops entries older than two seconds before React receives them, so a JS stall across a settle left the overlay display and backdrop opacity reverted on the next commit while the store held the new panel.

* fix(app): reconcile hidden keyboard end on iOS

Only a hidden end event resets the keyboard shift. A late visible end no longer resurrects a keyboard that already dismissed.

* fix(app): focus the replacement input through autoFocus after clearing

Clearing swaps the native input for a fresh instance. Focusing the doomed instance asked Android for the keyboard and then tore the focused view down, which cancelled the show; a JS focus command sent alongside the remount reached a view that was not attached yet and the IME ignored it. Focus and blur requested while the replacement is pending now decide the replacement's autoFocus, which native applies once the view is attached.

* fix(app): revise history rows in every viewport

The history row memo boundary bails out until its item identity changes, but only the native viewport cloned rows flagged by historyRowRevision. On web and desktop a history host whose tool-call group kept updating from the live head rendered stale. Move the revision into useRevisedHistoryRows and run both viewports' history through it. Regression test renders the web strategy with a memoized row and asserts only the revised host re-renders.
2026-09-02 00:52:44 +02:00
Mohamed Boudra 3998ea11d9 Keep large diffs responsive across web and mobile (#4174)
* perf(app): keep large diffs responsive

Render file headers on the canvas and bound expensive text shaping to the active viewport while preserving sticky, hover, and horizontal-scroll behavior. Let native scroll cancellation arbitrate header presses so finger scrolling cannot expand files.

* test(app): assert canvas diff header accessibility

* test(app): assert canvas diff header semantics
2026-09-01 23:52:11 +02:00
Mohamed Boudra ba54575ab7 Show completion times for hidden-prompt turns (#4170)
System-injected prompts have canonical turns but no visible user row, so completed timing was discarded despite an exact end timestamp. Preserve completion metadata with an explicitly unknown duration so the footer can show the truthful timestamp.
2026-09-01 23:24:20 +02:00
Mohamed Boudra 3e59adb4dc Add Claude Fable 5.1 to the model catalog (#4179)
* feat(claude): add Fable 5.1 model

Expose the new 1M-context model through the curated Claude catalog and normalize its dated and context-suffixed runtime IDs back to one canonical entry.

* fix(claude): group Fable models in catalog

* chore(release): cut 0.7.1

* fix(nix): refresh 0.7.1 dependency hash

* test(cli): follow package version in plugin scaffold

* test(cli): keep Claude catalog checks extensible
2026-09-01 21:51:51 +02:00
Mohamed Boudra 640b456915 docs: add 0.7.1 changelog 2026-09-01 20:59:27 +02:00
Mohamed Boudra dd5e8f95b1 Fix graceful daemon shutdown on Windows (#4168)
* test(server): probe supervised Windows cleanup

* test(server): report both cleanup failures

* fix(server): gracefully stop supervised workers
2026-09-01 19:59:03 +02:00
602 changed files with 37386 additions and 8874 deletions
+45 -27
View File
@@ -20,7 +20,50 @@ env:
SOURCE_TAG: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref_name }}
jobs:
ensure-release:
permissions:
contents: write
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
sparse-checkout: scripts
ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.tag || github.ref }}
- name: Resolve release tag
shell: bash
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Ensure GitHub release exists
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: bash
run: |
set -euo pipefail
if node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG" >/dev/null 2>&1; then
exit 0
fi
release_args=(
release create "$RELEASE_TAG"
--repo "${{ github.repository }}"
--title "Paseo $RELEASE_TAG"
--notes ""
--draft
)
if [[ "$IS_PRERELEASE" == "true" ]]; then
release_args+=(--prerelease)
fi
if ! gh "${release_args[@]}"; then
echo "Release creation raced with another workflow; continuing."
node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG" >/dev/null
fi
publish-android-apk:
needs: [ensure-release]
permissions:
contents: write
packages: read
@@ -36,32 +79,6 @@ jobs:
shell: bash
run: node scripts/emit-release-env.mjs --source-tag "$SOURCE_TAG" >> "$GITHUB_ENV"
- name: Ensure GitHub release exists
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
shell: bash
run: |
set -euo pipefail
if gh release view "$RELEASE_TAG" --repo "${{ github.repository }}" >/dev/null 2>&1; then
exit 0
fi
release_args=(
release create "$RELEASE_TAG"
--repo "${{ github.repository }}"
--title "Paseo $RELEASE_TAG"
--notes ""
)
if [[ "$IS_PRERELEASE" == "true" ]]; then
release_args+=(--prerelease)
fi
if ! gh "${release_args[@]}"; then
echo "Release creation raced with another workflow; continuing."
fi
- name: Setup Node
uses: actions/setup-node@v4
with:
@@ -129,4 +146,5 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
gh release upload "$RELEASE_TAG" "${{ steps.artifact.outputs.asset_path }}" --clobber --repo "${{ github.repository }}"
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
gh release upload "$release_lookup" "${{ steps.artifact.outputs.asset_path }}" --clobber --repo "${{ github.repository }}"
-23
View File
@@ -59,8 +59,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.format != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps:
- uses: actions/checkout@v4
@@ -80,8 +78,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps:
- uses: actions/checkout@v4
@@ -107,8 +103,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.quality != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps:
- uses: actions/checkout@v4
@@ -137,8 +131,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false' || needs.changes.outputs.hub != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps: &server_test_steps
- uses: actions/checkout@v4
with:
@@ -180,8 +172,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.server != 'false' || needs.changes.outputs.hub != 'false') }}
runs-on: windows-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps: *server_test_steps
desktop-tests-ubuntu:
@@ -268,8 +258,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.app != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps:
- uses: actions/checkout@v4
@@ -296,8 +284,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps:
- uses: actions/checkout@v4
@@ -330,7 +316,6 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
PLAYWRIGHT_SHARD: "1/4"
PLAYWRIGHT_ARTIFACT: "1"
steps: &playwright_test_steps
@@ -378,7 +363,6 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
PLAYWRIGHT_SHARD: "2/4"
PLAYWRIGHT_ARTIFACT: "2"
steps: *playwright_test_steps
@@ -389,7 +373,6 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
PLAYWRIGHT_SHARD: "3/4"
PLAYWRIGHT_ARTIFACT: "3"
steps: *playwright_test_steps
@@ -400,7 +383,6 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.browser != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
PLAYWRIGHT_SHARD: "4/4"
PLAYWRIGHT_ARTIFACT: "4"
steps: *playwright_test_steps
@@ -410,8 +392,6 @@ jobs:
needs: changes
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.relay != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
steps:
- uses: actions/checkout@v4
@@ -435,7 +415,6 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.cli != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0"
PASEO_DICTATION_ENABLED: "0"
PASEO_VOICE_MODE_ENABLED: "0"
@@ -467,7 +446,6 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.cli != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0"
PASEO_DICTATION_ENABLED: "0"
PASEO_VOICE_MODE_ENABLED: "0"
@@ -481,7 +459,6 @@ jobs:
if: ${{ !cancelled() && (needs.changes.outputs.full != 'false' || needs.changes.outputs.cli != 'false') }}
runs-on: ubuntu-latest
env:
ELECTRON_SKIP_BINARY_DOWNLOAD: "1"
PASEO_LOCAL_SPEECH_AUTO_DOWNLOAD: "0"
PASEO_DICTATION_ENABLED: "0"
PASEO_VOICE_MODE_ENABLED: "0"
+67 -28
View File
@@ -75,7 +75,7 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
if gh release view "$RELEASE_TAG" --repo "${{ github.repository }}" > /dev/null 2>&1; then
if node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG" > /dev/null 2>&1; then
echo "Release $RELEASE_TAG already exists, skipping creation"
else
prerelease_flag=""
@@ -86,8 +86,10 @@ jobs:
--repo "${{ github.repository }}" \
--title "Paseo $RELEASE_TAG" \
--notes "" \
--draft \
$prerelease_flag || {
echo "Release creation raced with another workflow; continuing."
node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG" > /dev/null
}
fi
@@ -191,7 +193,8 @@ jobs:
echo "::error::No release artifacts found in $release_dir"
exit 1
fi
gh release upload "$RELEASE_TAG" "${files[@]}" --clobber --repo "${{ github.repository }}"
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
gh release upload "$release_lookup" "${files[@]}" --clobber --repo "${{ github.repository }}"
- name: Upload desktop artifacts to workflow
if: env.SHOULD_PUBLISH != 'true'
@@ -299,7 +302,8 @@ jobs:
echo "::error::No release artifacts found in $release_dir"
exit 1
fi
gh release upload "$RELEASE_TAG" "${files[@]}" --clobber --repo "${{ github.repository }}"
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
gh release upload "$release_lookup" "${files[@]}" --clobber --repo "${{ github.repository }}"
- name: Upload desktop artifacts to workflow
if: env.SHOULD_PUBLISH != 'true'
@@ -404,7 +408,8 @@ jobs:
echo "::error::No release artifacts found in $release_dir"
exit 1
fi
gh release upload "$RELEASE_TAG" "${files[@]}" --clobber --repo "${{ github.repository }}"
release_lookup="$(node scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG")"
gh release upload "$release_lookup" "${files[@]}" --clobber --repo "${{ github.repository }}"
- name: Upload desktop artifacts to workflow
if: env.SHOULD_PUBLISH != 'true'
@@ -424,7 +429,7 @@ jobs:
finalize-rollout:
needs: [publish-macos, publish-linux, publish-windows]
if: ${{ always() && (needs.publish-macos.result == 'success' || needs.publish-macos.result == 'skipped') && (needs.publish-linux.result == 'success' || needs.publish-linux.result == 'skipped') && (needs.publish-windows.result == 'success' || needs.publish-windows.result == 'skipped') && (github.event_name != 'workflow_dispatch' || github.event.inputs.publish != 'false') }}
if: ${{ always() && (github.event_name != 'workflow_dispatch' || github.event.inputs.publish != 'false') }}
permissions:
contents: write
runs-on: ubuntu-latest
@@ -480,7 +485,7 @@ jobs:
name: windows-manifest
path: release-manifests/windows-manifest
- name: Assemble and upload stamped manifests
- name: Assemble manifests and publish release
if: env.IS_SMOKE_TAG != 'true'
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -491,6 +496,33 @@ jobs:
manifests_dir="$PWD/final"
mkdir -p "$manifests_dir"
expected_manifests=(
"${RELEASE_CHANNEL}-mac.yml"
"${RELEASE_CHANNEL}-linux.yml"
"${RELEASE_CHANNEL}.yml"
)
release_lookup="$(node ../scripts/github-release.mjs --repo "${{ github.repository }}" --tag "$RELEASE_TAG" --cleanup-duplicates)"
existing_assets="$(gh release view "$release_lookup" --repo "${{ github.repository }}" --json assets --jq '.assets[].name')"
for manifest_name in "${expected_manifests[@]}"; do
if grep -Fxq "$manifest_name" <<< "$existing_assets"; then
case "$manifest_name" in
"${RELEASE_CHANNEL}-mac.yml") platform_result="${{ needs.publish-macos.result }}" ;;
"${RELEASE_CHANNEL}-linux.yml") platform_result="${{ needs.publish-linux.result }}" ;;
"${RELEASE_CHANNEL}.yml") platform_result="${{ needs.publish-windows.result }}" ;;
esac
if [[ "$platform_result" =~ ^(success|skipped)$ ]]; then
gh release download "$release_lookup" \
--repo "${{ github.repository }}" \
--pattern "$manifest_name" \
--dir "$manifests_dir"
else
gh release delete-asset "$release_lookup" "$manifest_name" \
--repo "${{ github.repository }}" \
--yes
fi
fi
done
if [[ "${{ needs.publish-macos.result }}" == "success" ]]; then
manifest_name="${RELEASE_CHANNEL}-mac.yml"
node ../scripts/merge-mac-manifest.mjs \
@@ -515,25 +547,32 @@ jobs:
fi
timestamp="$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")"
node ../scripts/stamp-rollout.mjs --release-date "$timestamp" --rollout-hours "$ROLLOUT_HOURS" "${files[@]}"
ROLLOUT_HOURS_EXPECTED="$ROLLOUT_HOURS" RELEASE_DATE_EXPECTED="$timestamp" node -e '
const yaml = require("js-yaml");
const fs = require("fs");
const expectedHours = Number(process.env.ROLLOUT_HOURS_EXPECTED);
const expectedDate = process.env.RELEASE_DATE_EXPECTED;
if (!Number.isFinite(expectedHours) || expectedHours < 0) {
throw new Error(`expected non-negative rolloutHours, got ${process.env.ROLLOUT_HOURS_EXPECTED}`);
}
for (const f of process.argv.slice(1)) {
const m = yaml.load(fs.readFileSync(f, "utf8")) ?? {};
if (m.rolloutHours !== expectedHours) {
throw new Error(`${f}: rolloutHours=${m.rolloutHours}, expected ${expectedHours}`);
}
if (m.releaseDate !== expectedDate) {
throw new Error(`${f}: releaseDate=${m.releaseDate}, expected ${expectedDate}`);
}
if (typeof m.version !== "string" || m.version.length === 0) {
throw new Error(`${f}: missing or invalid version`);
}
}
' "${files[@]}"
gh release upload "$RELEASE_TAG" "${files[@]}" --clobber --repo "${{ github.repository }}"
node ../scripts/validate-desktop-manifests.mjs \
--release-date "$timestamp" \
--rollout-hours "$ROLLOUT_HOURS" \
"${files[@]}"
gh release upload "$release_lookup" "${files[@]}" --clobber --repo "${{ github.repository }}"
failed_builds=()
[[ "${{ needs.publish-macos.result }}" =~ ^(success|skipped)$ ]] || failed_builds+=(macOS)
[[ "${{ needs.publish-linux.result }}" =~ ^(success|skipped)$ ]] || failed_builds+=(Linux)
[[ "${{ needs.publish-windows.result }}" =~ ^(success|skipped)$ ]] || failed_builds+=(Windows)
if (( ${#failed_builds[@]} > 0 )); then
echo "::error::Desktop builds did not complete for ${failed_builds[*]}; the release remains a draft"
exit 1
fi
missing_manifests=()
for manifest_name in "${expected_manifests[@]}"; do
[[ -f "$manifests_dir/$manifest_name" ]] || missing_manifests+=("$manifest_name")
done
if (( ${#missing_manifests[@]} > 0 )); then
echo "::error::Missing updater manifests: ${missing_manifests[*]}; the release remains a draft"
exit 1
fi
publish_args=(release edit "$release_lookup" --tag "$RELEASE_TAG" --draft=false --repo "${{ github.repository }}")
if [[ "$IS_PRERELEASE" == "true" ]]; then
publish_args+=(--prerelease)
fi
gh "${publish_args[@]}"
+1 -2
View File
@@ -15,7 +15,7 @@ on:
required: false
type: string
create_if_missing:
description: "Create release if missing (normally only needed for tag events)."
description: "Create a draft release if missing (normally only needed for tag events)."
required: false
default: false
type: boolean
@@ -29,7 +29,6 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
with:
+29
View File
@@ -1,5 +1,34 @@
# Changelog
## 0.7.2 - 2026-09-02
### Added
- Added active-turn steering for pi agents so new messages reach the running turn without interrupting it ([#3752](https://github.com/getpaseo/paseo/pull/3752) by [@mcowger](https://github.com/mcowger))
- Added declared build commands and monorepo source paths for Git-hosted plugins ([#4158](https://github.com/getpaseo/paseo/pull/4158))
### Improved
- Reduced JS stalls while watching a streaming agent on mobile ([#4190](https://github.com/getpaseo/paseo/pull/4190))
### Fixed
- Fixed large and many-file diffs stalling or crashing while opening and scrolling ([#4174](https://github.com/getpaseo/paseo/pull/4174))
- Fixed mobile sidebar and explorer panels losing their settled position when a JS stall crossed the animation ([#4190](https://github.com/getpaseo/paseo/pull/4190))
- Fixed a single oversized assistant message crashing the timeline by capping rendered content at 32,000 characters ([#4166](https://github.com/getpaseo/paseo/pull/4166))
- Fixed Codex rewind failing on paginated threads with Codex 0.151 and later ([#4119](https://github.com/getpaseo/paseo/pull/4119))
- Fixed Escape closing an image preview also interrupting the running agent ([#4161](https://github.com/getpaseo/paseo/pull/4161))
- Fixed daemon stop and restart on Windows skipping graceful shutdown and orphaning agent processes ([#4168](https://github.com/getpaseo/paseo/pull/4168))
- Fixed OMP startup timing out at 10 seconds regardless of the configured RPC timeout ([#4143](https://github.com/getpaseo/paseo/pull/4143) by [@Juns-g](https://github.com/Juns-g))
- Fixed completed turns without a visible prompt showing no completion time ([#4170](https://github.com/getpaseo/paseo/pull/4170))
- Fixed Explorer renames replacing an existing file when file identity metadata is unavailable ([#4171](https://github.com/getpaseo/paseo/pull/4171))
## 0.7.1 - 2026-09-01
### Added
- Added Claude Fable 5.1 with a 1M context window ([#4179](https://github.com/getpaseo/paseo/pull/4179))
## 0.7.0 - 2026-08-31
### Changed
+2
View File
@@ -50,6 +50,8 @@ The daemon also supports an optional shared-secret password (set via `auth.passw
Connected clients are trusted operators of the daemon user. File previews follow that authority: a preview request may read any regular file the daemon process can read, while keeping path normalization and symlink checks in the daemon file service. Workspace-relative paths remain a UI convenience, not a security boundary.
When Paseo checks out a change request from a different repository, it does not run that workspace's `paseo.json` setup, automatic terminals, named scripts, or teardown until you explicitly run setup for that workspace. The decision lasts for the workspace and does not re-prompt after new commits. Same-repository changes, ordinary branches, local workspaces, agent launches, terminals, explicit shell commands, and metadata-generation instructions are outside this gate.
If you expose the daemon beyond loopback, such as by binding to `0.0.0.0`, forwarding it through a tunnel or reverse proxy, or publishing it from a Docker container, you are responsible for restricting and securing that access. Setting a password is strongly recommended in that case.
In Docker, the official image runs the daemon and agents as the non-root
+4 -3
View File
@@ -156,9 +156,9 @@ The rows combine two kinds of children:
parentAgentId === thisAgent.id AND !archivedAt
```
- **Provider subagents** are child executions owned by Claude, Codex, or OpenCode. They are not inserted into `AgentManager` as managed agents. Providers emit a separate descriptor and timeline stream through `agent.provider_subagents.*`; the client keeps that state outside the normal agent store and merges only the presentation rows into the track.
- **Provider subagents** are child executions owned by Claude, Codex, or OpenCode. They are not inserted into `AgentManager` as managed agents. Providers emit a separate descriptor and timeline stream through `agent.provider_subagents.*`; the client keeps that state outside the normal agent store and merges only the presentation rows into the track. A descriptor's optional `parentSubagentId` identifies its direct provider-subagent parent; an absent value identifies a direct child of the managed agent.
Clicking either kind opens a workspace tab. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical.
Clicking either kind opens a workspace tab. A Paseo subagent tab is a normal interactive agent pane. A provider subagent tab is a read-only timeline pane with no composer, archive, detach, rewind, or fork actions. It shows its own direct children in a subagents track. Both panes use `AgentStreamView`, so message, reasoning, tool-call, and layout rendering stay identical.
Provider timelines use the same structural timeline item format but deliberately have a separate lifecycle and transport. A provider thread/session identifier is not a Paseo agent identifier, and closing its tab is always layout-only.
@@ -174,7 +174,8 @@ Claude Code announces subagent lifecycle on the SDK stream (`task_started` / `ta
- **A resumed task can be announced again with a new `tool_use_id`.** The first Task tool id remains the canonical descriptor and later ids are routing aliases for the same session-scoped task. The resumed prompt is added to that child timeline.
- **Effort is only reachable through hooks.** It appears nowhere on the message stream at any depth, and the level Paseo requests is not necessarily the level that runs — a model that does not support it is silently downgraded. A hook firing inside a subagent reports the active post-downgrade level next to its `agent_id`, which is the same id `task_started` calls `task_id`.
- **Backgrounded subagents emit no frames carrying `parent_tool_use_id` at all.** Everything keyed off that field sees nothing for one; they are visible only because the task protocol announces them.
- **On replay, `<session>/subagents/` holds every descendant, not just this session's children.** `agent-<id>.meta.json` carries `spawnDepth`: `1` is a direct child, `2+` was spawned by another subagent and its `toolUseId` names a Task call made inside its parent's session, which nothing in this transcript can resolve. Replaying those adds rows the live stream never showed, each with no Task card and no recoverable outcome, so they render as running forever. One recorded session showed 10 subagents live and would have replayed 22.
- **Nested ownership comes from the launching sidechain, not `spawn_depth` alone.** A sidechain's Agent or Bash tool call records the direct owner of that `tool_use_id`; the following `task_started` inherits it. This routes a grandchild descriptor and child-owned background notifications without relying on labels or flattening them into the managed parent.
- **On replay, `<session>/subagents/` holds every descendant beside the root.** Resolve the tree one proven generation at a time: the root transcript admits direct children, then each admitted sidechain transcript admits its children by `toolUseId`. `spawnDepth` orders candidates but does not establish ownership. Unresolved sidecars remain excluded as ambient or unrelated work.
- **Replay `totalTokens` is a context-size reading, not cumulative spend.** Claude Code finalizes a subagent by summing the _last_ assistant message's usage block and shipping that as `usage.total_tokens`. Summing per-entry usage instead multiplies the cached prefix by the turn count and reports a number several times larger than the live path.
Archived Paseo subagents disappear from the track, by design. To remove one from the track without closing its tab, use the **archive button** on the row — it opens a confirm dialog and archives the subagent on confirm. Provider-owned rows have no individual Paseo lifecycle controls.
+9
View File
@@ -31,6 +31,15 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
- **First sight of a text is revealed whole.** Only growth is paced. This is what makes history hydration, timeline replay, a virtualized row remounting on scroll, and an already-finished message all render complete on first paint without a special case for each.
- **Leaving `phase: "streaming"` snaps the reveal.** A completed turn must never be left holding characters. `layoutStream` sets the phase, so anything outside the live head with an active turn is already complete.
- **The reducer queue commits on a frame, with a timer as the ceiling.** A frame callback never fires in a hidden tab, so a timer races it and wins when nothing is painting — the store has to keep advancing either way.
- **A history row re-renders only when its item or layout item identity changes.** The inverted
FlatList hands every mounted cell a new `index` and `ref` whenever a row is prepended, so without a
memo boundary each coalesced tick re-rendered every mounted row (about 50 on a phone, 100–250 ms of
JS per tick). `layoutStream` keeps a layout item's identity when nothing about it changed,
`useRevisedHistoryRows` hands a fresh item identity to rows whose tool-call group, expanded state,
or breakpoint changed, and `HistoryStreamRow` memoizes on both. Every viewport runs its history
through that hook; the web viewport once skipped it and history hosts of a live tool group went
stale. A new field on `StreamLayoutItem` must be added to `areLayoutItemsEquivalent`, or sharing
silently stops.
## Measuring
+27 -5
View File
@@ -75,6 +75,8 @@ not retain non-Git directories.
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
| `server/voice-chat/` | App-level voice calls, provider orchestration, and semantic call events |
| `server/session/dictation/` | Composer dictation stream lifetime and speech-readiness gating |
| `server/agent/providers/` | Provider adapters (see "Agent providers" below) |
| `server/orchestration-skills/` | Bundled catalog, host selection, convergence, and skill-directory transactions |
| `server/relay-transport.ts` | Outbound relay connection with E2E encryption |
@@ -111,7 +113,26 @@ Cross-platform React Native app that connects to one or more daemons.
- Composer UI and submit/draft behavior live in `packages/app/src/composer/`; screens and panels should integrate it from there instead of dropping composer internals into `components/`, `hooks/`, or `screens/workspace/`
- Timeline reducers in `timeline/session-stream-reducers.ts` handle compaction, gap detection, sequence-based deduplication
- Timeline sync correctness is documented in [docs/timeline-sync.md](timeline-sync.md): live streams are for immediacy, `fetch_agent_timeline_request` is authoritative, and catch-up is paged but complete.
- Voice features: dictation (STT) and voice agent (realtime)
- App `VoiceRuntime` owns the app-level call UX, current route context, and semantic transcript. It
prepares installed client transports and accepts the server's selected answer without inspecting
transport kind. Each transport owns capture, playback, its data plane, mute, volume, and media
state; `transports/daemon-audio.ts` is the production transport in this slice. A WebRTC transport
adds another factory at app composition and does not change `VoiceRuntime`.
- Server `VoiceChat` serializes start/stop, cancels startup, routes provider-neutral state/events,
forwards opaque transport data, and reacts to the provider's terminal signal. It knows only the
`VoiceCallProvider` contract; concrete data-plane validation and serialization stay in the
provider and matching client transport. Providers own prompts, credentials, hidden resources,
tools, media integration, and cleanup. The manual provider creates a hidden orchestrator through
the atomic required-Paseo-tools capability with an authoritative provider prompt, and owns a
separate speech runtime configured from the top-level `manualVoice` block. That runtime is created
on the first valid manual call and reused; ordinary daemon startup does not load or download voice
models. Dictation keeps its own speech runtime. A complete manual orchestrator provider and mode
selection is required; partial configuration does not fall back to another provider or mode.
Cleanup detaches work delegated by the hidden orchestrator before archiving it.
- Voice calls end as soon as the final client socket disconnects. The containing client session may
remain reconnectable, but calls are not replayed or rehydrated in this protocol slice. The sidebar
footer starts the call and hosts its controls; routes and visible agents do not own its lifetime.
Dictation remains a separate composer feature.
Consumers request directory or timeline data without choosing memory, cache, or network. The owner
publishes an accepted cache hit and then reconciles it over the existing network path. A miss or an
@@ -264,7 +285,8 @@ optionally carry the same `turnId`. New clients use these fields when present an
status once at the directory boundary rather than maintaining a second activity model.
- Terminal subscribe/input/capture commands
- Voice/dictation streaming events (`dictation_stream_*`, `assistant_chunk`, `audio_output`, `transcription_result`)
- App-level voice call commands and events (`voice.call.*`) and independent dictation streams
(`dictation_stream_*`)
- Request/response pairs for fetch, list, create, etc., correlated by `requestId`; failures use `rpc_error`
`directory_suggestions_request` is one daemon-owned filesystem search capability. The daemon
@@ -355,13 +377,13 @@ Two workspaces can share the same `cwd` (e.g. a `directory` workspace and a `loc
| State | Key builder / store | Source |
| ---------------------------- | -------------------------------------------------- | ------------------------------------------------------------- |
| Review draft comments | `buildReviewDraftKey` / `buildReviewDraftScopeKey` | `packages/app/src/review/store.ts` |
| Diff mode override | review-draft scope key (in-memory) | `packages/app/src/review/state.ts` |
| Review draft comments | `buildReviewDraftKey` | `packages/app/src/review/store.ts` |
| Working diff comparison | `workingDiffComparisonKey` (in-memory) | `packages/app/src/git/working-diff-comparison/state.ts` |
| Composer attachments | `buildWorkspaceAttachmentScopeKey` | `packages/app/src/attachments/workspace-attachments-store.ts` |
| File explorer nav/open state | `fileExplorer` map keyed `workspace:{workspaceId}` | `packages/app/src/hooks/use-file-explorer-actions.ts` |
| File explorer expanded paths | `expandedPathsByWorkspace[workspaceStateKey]` | `packages/app/src/stores/panel-store/state.ts` |
`diff-pane.tsx` is the canonical wiring site: it passes `{ serverId, cwd }` to the git queries and `{ serverId, workspaceId, cwd }` to the draft/override/attachment scope keys.
`diff-pane.tsx` is the canonical wiring site: it passes `{ serverId, cwd }` to the git queries and `{ serverId, workspaceId, cwd }` to the draft/comparison/attachment scope keys.
**Do not "fix" the sharing away.** Re-keying a directory-backed query by `workspaceId` makes same-`cwd` workspaces diverge (two windows onto the same git tree showing different diffs). Re-keying owned state (drafts, expanded paths) by `cwd` makes them leak between distinct workspaces on the same folder. The `workspaceId`-keyed builders carry a `// workspaceId is opaque; do not parse this key back into a path.` comment — the opaque-id fallback to `cwd` exists only for old payloads without a `workspaceId`, not as a content-sharing mechanism.
+59 -19
View File
@@ -275,6 +275,45 @@ rather than storing something it cannot describe. That is why the client gates t
UI on `server_info.features.agentProfiles` instead of letting a save appear to succeed against an
older daemon.
### Agent provider Paseo tools
`agents.providers` is keyed by the exact provider ID used to launch the agent. The built-in IDs are
`claude`, `codex`, `copilot`, `opencode`, `pi`, and `omp`. Custom provider IDs are their literal
configuration keys, such as `my-claude` or `zai`, not the provider named by `extends`.
Each entry may include a Paseo-tool policy:
```json
{
"agents": {
"providers": {
"my-claude": {
"extends": "claude",
"label": "My Claude",
"paseoTools": {
"enabled": true,
"disabledTools": ["browser_evaluate"]
}
}
}
}
}
```
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
This policy controls the catalog presented to an agent. It is not an authorization boundary for
agents that can access the host through a shell.
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
`agents.metadataGeneration.providers` controls the preferred structured-generation fallback order for daemon-side metadata tasks such as commit messages, PR text, branch names, and generated agent titles. Entries are tried first in the configured order, then Paseo falls through to dynamically discovered defaults and finally the current selection when available.
### Git process limits
Git process limits are global to one daemon. The start-rate limit defaults to `64` processes per
@@ -439,25 +478,26 @@ workspace together with its owning project.
Array of workspace records. A workspace is a specific working directory within a project.
| Field | Type | Description |
| ------------------------------ | ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `workspaceId` | `string` | Opaque stable identifier (`wks_<hex>`), generated independently of the directory. MUST NOT be treated as a path; compare by exact equality. Use the `cwd` field for directory access. |
| `projectId` | `string` | FK to Project.projectId; the workspace's stable project membership |
| `cwd` | `string` | Exact execution directory selected for agents, files, scripts, and setup |
| `kind` | `"local_checkout" \| "worktree" \| "directory"` | Mutable checkout classification |
| `displayName` | `string` | The human name (the generated/derived title). Decoupled from `branch` by construction. |
| `title` | `string \| null` | User-set name override layered over `displayName`. Null means "use `displayName`". |
| `branch` | `string \| null` | The current Git branch for git-backed workspaces. Separate from `displayName`/`title`; a background branch refresh never rewrites the name. |
| `worktreeRoot` | `string \| null` | Backing checkout/worktree root. May differ from `cwd` for exact subprojects and remains persisted after the worktree is deleted so restore can reproduce the placement. |
| `baseBranch` | `string \| null` | Normalized branch the Paseo worktree was created from; null for directories, local checkouts, and checkout-branch worktrees |
| `isPaseoOwnedWorktree` | `boolean` | Whether Paseo owns and may remove/recreate the backing `worktreeRoot` |
| `mainRepoRoot` | `string \| null` | Main repository root for worktree checkouts, independent of both exact `cwd` and backing `worktreeRoot` |
| `createdAt` | `string` (ISO 8601) | |
| `updatedAt` | `string` (ISO 8601) | |
| `archivedAt` | `string \| null` (ISO 8601) | Soft-delete; required nullable |
| `autoArchivedChangeRequestUrl` | `string \| null` | Change request whose merged state triggered auto-archive. Restore replaces it with the current merged change request, when present, so repeated snapshots cannot archive the workspace again. |
| `labels` | `string[]?` | Normalized display names assigned from this host's shared label catalog. Missing means unlabelled. |
| `pinnedAt` | `string \| null` (ISO 8601) | Pinned-to-top-of-sidebar timestamp; null means "not pinned" |
| Field | Type | Description |
| ------------------------------ | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `workspaceId` | `string` | Opaque stable identifier (`wks_<hex>`), generated independently of the directory. MUST NOT be treated as a path; compare by exact equality. Use the `cwd` field for directory access. |
| `projectId` | `string` | FK to Project.projectId; the workspace's stable project membership |
| `cwd` | `string` | Exact execution directory selected for agents, files, scripts, and setup |
| `kind` | `"local_checkout" \| "worktree" \| "directory"` | Mutable checkout classification |
| `displayName` | `string` | The human name (the generated/derived title). Decoupled from `branch` by construction. |
| `title` | `string \| null` | User-set name override layered over `displayName`. Null means "use `displayName`". |
| `branch` | `string \| null` | The current Git branch for git-backed workspaces. Separate from `displayName`/`title`; a background branch refresh never rewrites the name. |
| `worktreeRoot` | `string \| null` | Backing checkout/worktree root. May differ from `cwd` for exact subprojects and remains persisted after the worktree is deleted so restore can reproduce the placement. |
| `baseBranch` | `string \| null` | Normalized branch the Paseo worktree was created from; null for directories, local checkouts, and checkout-branch worktrees |
| `isPaseoOwnedWorktree` | `boolean` | Whether Paseo owns and may remove/recreate the backing `worktreeRoot` |
| `mainRepoRoot` | `string \| null` | Main repository root for worktree checkouts, independent of both exact `cwd` and backing `worktreeRoot` |
| `createdAt` | `string` (ISO 8601) | |
| `updatedAt` | `string` (ISO 8601) | |
| `archivedAt` | `string \| null` (ISO 8601) | Soft-delete; required nullable |
| `autoArchivedChangeRequestUrl` | `string \| null` | Change request whose merged state triggered auto-archive. Restore replaces it with the current merged change request, when present, so repeated snapshots cannot archive the workspace again. |
| `labels` | `string[]?` | Normalized display names assigned from this host's shared label catalog. Missing means unlabelled. |
| `pinnedAt` | `string \| null` (ISO 8601) | Pinned-to-top-of-sidebar timestamp; null means "not pinned" |
| `untrustedSource` | `{ kind: "change_request", forge, number, headRepository }?` | Provenance captured when a cross-repository change request creates the workspace. Missing means repository automation is allowed; explicit setup removes the field. |
> **Opaque-ID invariant:** `workspaceId` is opaque identity, never a filesystem path. Filesystem and git operations take `cwd`/`workspaceDirectory` only — never the id. A compatibility-only first-materialization bootstrap still groups pre-registry agent records by path and Git remote so existing installs retain their legacy records. That grouping never runs against a live registry, and its keys are not runtime project or workspace identity.
+3
View File
@@ -120,6 +120,8 @@ Workspace and chat surfaces use the full width — these are working surfaces, n
Sections sit apart. `<SettingsSection>` owns its own bottom margin; the next thing is wrapped in another `<SettingsSection>`. The agent-list `sectionHeading` carries the same `marginTop`/`marginBottom` rhythm (`packages/app/src/components/agent-list.tsx:511-517`). Adding `marginBottom` to a section is wrong.
A section or group explains itself through the `info` prop on `<SettingsSection>` or `<SettingsGroup>` — an info icon beside the header that opens a tooltip (`packages/app/src/screens/settings/settings-info-tip.tsx`). A muted paragraph between the header and the card is wrong: it sits in the section's own gap, so it reads as a second heading rather than as prose belonging to the header. Explanatory copy that describes one row belongs to that row, as `settingsStyles.rowHint` inside the card.
Cards inside a section sit closer than sections. Rows inside a card touch — only the divider separates them. The rhythm is page → spacious; section → spacious; card → tight.
Rows have generous vertical padding: roughly 16px of content plus 16px of vertical padding for settings rows, 8–12px for sidebar list items where many rows must fit. Compressing rows below the established density to fit more on the screen is wrong. Too many rows means more cards or more sections, not smaller rows.
@@ -248,6 +250,7 @@ New status pills use `<StatusBadge>`. Identity, shortcut, and interactive link b
- `fontWeight.medium` on row titles, body text, button labels, badge text, or `<SidebarCallout>` titles. Medium is reserved for the structural-label tier described in §3 — section labels, modal/sheet titles, dense metadata emphasis, and tight action labels. Anything else is `normal`. `<ScreenTitle>` is responsive `400/300` and is never overridden.
- `<Pressable>` wrapping `<Text>` to make a button. `<Button>` exists.
- Bare `<Text>` for a section header inside settings. `<SettingsSection>` exists.
- A muted paragraph between a section header and its card. Section-level explanation is the header's `info` tooltip (§7).
- A "Settings" CTA on a detail page. Detail pages are settings; settings is reached from the sidebar, the host entry, or a row's kebab menu.
- The word "checkout" in UI strings or identifiers. The term is "workspace".
- New color tokens or hardcoded hex outside the palette. The identity color table is the documented exception (§13), not a license.
+6 -3
View File
@@ -556,13 +556,16 @@ npm run cli -- daemon status # Check daemon status
npm run cli -- clone owner/repo --dir ~/workspace # Clone GitHub repo and register project
```
Use `--host` to point the CLI at a different daemon:
Use the global `--host` option to point the CLI at a different daemon:
```bash
npm run cli -- ls -a --host localhost:7777
npm run cli -- ls -a --host ssh://user@host
npm run cli -- --host localhost:7777 ls -a
npm run cli -- --host ssh://user@host ls -a
```
Set `PASEO_HOST` to use the same target across invocations. An explicit
`--host` overrides the environment variable.
In an SSH URI, the URL port is the SSH server port. The remote daemon defaults to `127.0.0.1:6767`; use `?daemonPort=7777` to override it. The transport runs non-interactively through the local OpenSSH client and never installs, starts, or configures the remote daemon. User-facing setup and troubleshooting live in [public-docs/connectivity.md](../public-docs/connectivity.md#ssh).
Desktop integrations can focus an existing agent without creating one or
+10
View File
@@ -77,6 +77,16 @@ only use local param fallback during cold mount (`/` or empty pathname), or a
hidden workspace can overwrite the remembered workspace before Settings or
History returns.
Settings detail routes are separate siblings on purpose. Keep
`settings/[section]`, the host routes, the projects index, and project detail as
distinct route names. `router.dismissTo()` ultimately matches stack entries by
route name. A single catch-all Settings route would make project detail and the
projects index the same route; Back would update params in place and leave a
phantom detail entry underneath. The host routes also stay outside the
store-ready protected group so a cold host deep link can survive daemon startup.
Do not collapse this topology with a catch-all, `getId`, or
`dangerouslySingular` workaround.
## Agent Targets
Notifications and agent URLs enter the router with different authoritative
+31 -15
View File
@@ -134,19 +134,39 @@ The fix for transforms is Gotcha 3. The fix for context is Gotcha 7.
## Gotcha 3 — Keyboard layout and portal anchors
Move the chat surface with worklet-driven bottom padding from
`KeyboardShiftProvider`. Padding keeps the stream, composer, visual position,
and native hit testing in the same layout. Do not translate the stream and
composer independently.
`KeyboardTranslateView` owns visual keyboard motion. Android uses the
controller's Reanimated signal. iOS uses its native-driver `Animated.event`
signal because the stock iOS Reanimated value changes at move start, while
writing a replacement Reanimated value every frame interrupts UIKit's hide
animation. Keep this platform choice inside `KeyboardTranslateView`.
Do not use the controller's raw keyboard progress for the padding. It can retain
a nonzero value after the keyboard closes. The shared provider normalizes that
state and reconciles native animation-end events.
`KeyboardDock` always keeps the chat surface at full height and wraps it in
`KeyboardTranslateView`. The panel root clips it at the header edge, so rows
slide under the header on open and out from under it on close. Do not swap the
dock to keyboard padding at rest. Changing its height creates either a blank
band or a paused transition when the inverted list updates its viewport.
`measureInWindow` already includes the dock's current padding layout. When a
portal opens, snapshot the current shift and apply only the subsequent shift
delta to its animated `bottom`. Adding the full shift moves the portal twice and
can place it over the composer controls.
Do not animate a layout prop through the keyboard transition. On Android
Fabric, each animated layout update clones the shadow tree and runs Yoga over
the dock subtree. This measured about 10 ms per frame on the emulator and the
mounted layouts arrived in bursts every 2–4 frames. A transform does not dirty
layout. Preserve the translated dock's history scroll range with a far-end
content inset on the inverted stream list. Update that inset only when keyboard
motion settles; never drive it per frame.
Move the stream and composer together through `KeyboardDock`. Do not translate
them independently.
`KeyboardShiftProvider` owns the normalized shift used for settled insets and
portal geometry, plus the `isMoving` worklet value. It reconciles native
animation-end events because the controller can retain a nonzero value after
the keyboard closes.
Measure portal anchors while the dock is at rest. If a popover opens during
motion, re-measure when `isMoving` settles. `measureInWindow` includes the
dock's current layout and transform. Snapshot the shift at measurement time and
apply only the subsequent shift delta to the animated `bottom`. Adding the full
shift moves the portal twice and can place it over the composer controls.
The provider also reconciles iOS from the controller's native `onEnd` event.
The controller's stock iOS shared values update at move start and during an
@@ -155,10 +175,6 @@ leave the last height/progress pair stuck in either the open or closed state.
Keep that terminal reconciliation on the UI thread; a later focus or blur must
not be required to repair the offset.
Re-measure on `Keyboard.addListener('keyboardDidShow'|'keyboardDidHide')` only
to refresh the snapshot if the keyboard was mid-transition when the popover
opened.
## Gotcha 4 — Host-relative positioning before platform offsets
The generic anchored-overlay rule is:
+1
View File
@@ -19,6 +19,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
- **MR** — GitLab merge request. UI label for GitLab change requests only; do not use MR for GitHub/Gitea/Forgejo.
- **Worktree** — Paseo-managed git worktree (`~/.paseo/worktrees/{name}`); also a `workspaceKind` value. User-facing creation treats it as the `worktree` workspace isolation choice. Code and `paseo.json` retain worktree terminology for git lifecycle implementation. Forbidden: "Checkout" as a product synonym.
- **Repository / Remote** — Internal Git observations. They may produce mutable kind, branch, and project-grouping metadata but never the host-local project ID, root, display name, or workspace membership. No UI label.
- **Sidebar items** — The top-level rows at the head of the app sidebar: New workspace, History, Search, Schedules, and every plugin sidebar contribution. Order and visibility are one per-device preference (`AppSettings.sidebarNavItems`); all of them may be off. UI: the "Sidebar" section on the Appearance settings page. Code: `packages/app/src/sidebar-nav/model.ts` resolves the list, and both the sidebar (`components/sidebar/sidebar-nav-rows.tsx`) and the settings section (`screens/settings/appearance/sidebar-nav-section.tsx`) read it through `useSidebarNavItems`. Never hardcode one of these rows or add a second place that decides which ones show. Don't confuse with **Explorer sidebar**.
- **Explorer sidebar** — The dedicated navigation dock containing the Files and Changes trees. UI: "Explorer sidebar". Code: `packages/app/src/workspace-tabs/explorer-sidebar.ts`; persisted pane identifiers retain the `explorer` spelling. See [explorer-sidebar.md](explorer-sidebar.md).
- **Side pane** — An ordinary right-side workspace pane used for content opened beside the user's work. It closes and participates in workspace splits like every other main-host pane. See [explorer-sidebar.md](explorer-sidebar.md#side-pane). Forbidden: "Side panel".
- **Directory-backed surface** — A right-sidebar surface whose content is determined by the workspace's `cwd`, so two workspaces on the same directory see identical content: git diff/status, forge change-request info, file preview/explorer contents. Keyed by `(serverId, cwd)`, never `workspaceId`. See [architecture.md](architecture.md#right-sidebar-boundary-directory-backed-vs-workspace-owned).
+21 -10
View File
@@ -30,8 +30,10 @@ The UI worklet owns transient motion:
- the active gesture's starting revision
- the last settled target
React also owns presentation lifecycle: whether an overlay is mounted/displayed and whether it may
receive pointer events. Worklets never own `display` or `pointerEvents`.
React publishes the active panel only when the canonical target and the UI-thread position agree at
the final anchor. Retained content never observes gesture previews, progress, or an unsettled target.
The gesture hosts stay mounted; worklets reveal their retained overlays through native styles while
React owns pointer events and accessibility.
## Why one position
@@ -55,8 +57,10 @@ while that revision still owns the gesture.
When a React command arrives during a drag, its newer revision clears gesture ownership and starts
motion toward the new target. The older gesture's remaining updates and finish callback are ignored.
Canceled gestures return to the latest canonical target. Animation completion is accepted only when
its target and revision still match the canonical command.
Canceled gestures return to the latest canonical target. A successful gesture starts its finishing
motion immediately; the matching React command adopts that motion instead of restarting it. Position
settlement and command acceptance may arrive in either order. Activity changes after both agree on
the same target.
Manual gesture arbitration has two phases:
@@ -85,8 +89,14 @@ definition, no longer eligible to begin.
- Animated panel nodes use React Native static styles plus inline theme values. Do not attach
Unistyles-generated styles to those nodes; Unistyles and Reanimated patching the same Fabric node
has caused native crashes.
- The plain React wrapper owns `display: none` after settlement. This prevents a stale Fabric animated
prop commit from resurrecting a closed overlay.
- `FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS` stays off in `packages/app/package.json`. It is a
compile-time flag; changing it needs a native rebuild. With it on, Reanimated 4.3 hands settled
animated props back to React through a collector that forgets entries older than two seconds. A JS
stall across a panel settle loses the final position, and the next React commit reverts the overlay
to its last synced props: a backdrop over the workspace while the store says closed. Upstream fixed
the collector in 4.4.3, which needs React Native 0.83.
- Gesture start and progress must not update React state. The retained overlay is already mounted and
offscreen; only the shared position and its derived native styles move during a drag.
- Hidden tabs and workspaces use `RetainedPanel`. It owns a non-collapsible native root, visibility,
pointer events, and the active signal consumed by `useRetainedPanelActive`.
- Panels whose gesture wrapper already owns visibility use `RetainedPanelActivity` to provide the
@@ -98,8 +108,9 @@ definition, no longer eligible to begin.
- Retention order and render order are separate concerns. LRU metadata may change on every switch;
keyed retained roots must keep a stable sibling order. Moving large retained roots triggered Fabric
Differ failures (`addViewAt` / `removeViewAt` view reuse) on Android.
- The newly active panel must be included in the same render that changes selection. Adding it from an
effect creates a committed frame where every retained panel is hidden, which is a real blank screen.
- `useIsMobilePanelActive` follows the settled target, not the requested target. Position at the
canonical target's anchor is the settlement signal; animation duration and completion callbacks
do not own activity. Cancellation publishes nothing.
- Do not suspend retained native subtrees with `Suspense`/`react-freeze`. Suspension changes native
ownership and can detach descendants. Keep the tree mounted, stabilize its subscriptions/selectors,
and use the retained-panel active signal to stop timers, polling, and other genuine background work.
@@ -107,5 +118,5 @@ definition, no longer eligible to begin.
## Tests
`packages/app/src/mobile-panels/model.test.ts` exercises command, drag, cancellation, interruption,
rapid-command, stale-completion, and width-projection sequences through the transition model. Add a
sequence there whenever ownership or ordering changes.
rapid-command, position-settlement, and width-projection sequences through the transition model. Add
a sequence there whenever ownership or ordering changes.
+191 -61
View File
@@ -1,8 +1,8 @@
# Plugins
Local plugins contribute daemon RPCs, native app surfaces, workspace panels, Command Center items,
composer pills, app themes, and composer attachment sources from one `index.ts`. Paseo executes the server contribution in a
subprocess and evaluates the client contribution in the app runtime.
client slash commands, timeline items, composer pills, app themes, and composer attachment sources.
Paseo executes `index.server.ts` in a subprocess and `index.client.tsx` in every connected app.
> **Trust every plugin you add.** `paseo plugin add` and `paseo plugin install` mean “I trust this codebase.” Plugins are unsandboxed: server code and Git preparation commands run with the daemon user's access on the daemon host, and client contributions run inside Paseo. The repository's dependencies and future updates are part of that trust decision. With `--host`, preparation runs on that remote daemon host.
@@ -41,15 +41,19 @@ runtime-safe: run `paseo reload` after editing `config.json`. Enabling starts ev
enabled plugin; disabling tears them all down without restarting the daemon. Plugin source entries
remain lifecycle-owned and do not reload from manual config edits.
The directory contains an identity-only manifest, one entry point, and local typechecking support:
The directory contains an identity-only manifest, one optional entry per runtime, runtime-owned
directories, and local typechecking support. At least one entry is required.
```text
my-plugin/
paseo-plugin.json
index.ts
main.client.tsx
package.json
tsconfig.json
index.client.tsx
index.server.ts
client/greeting.tsx
server/greeting.ts
shared/greeting.ts
```
The generated `package.json` installs `@getpaseo/plugin` and the other host modules as development
@@ -87,7 +91,7 @@ paseo plugin add https://gitlab.com/group/repository.git
paseo plugin add https://git.example.com/owner/repository.git
paseo plugin add owner/monorepo:plugins/review
paseo plugin add owner/repository --ref main
paseo plugin status
paseo plugin ls
paseo plugin update review
paseo plugin update --all
```
@@ -95,8 +99,8 @@ paseo plugin update --all
Append `:relative/path` to the source when the plugin lives below the repository root.
Omitting `--ref` tracks the remote's default branch. A branch passed with `--ref` also tracks;
tags and commits stay pinned. `status` fetches tracked refs and reports the installed and available
commits. Removing a Git source deletes Paseo's managed checkout.
tags and commits stay pinned. `ls` reports the installed commit without contacting the remote.
Removing a Git source deletes Paseo's managed checkout.
### Declare Git preparation
@@ -135,46 +139,68 @@ log credentials or tokens.
## Contribute behavior and UI
Default export one contribution function from `index.ts`. Keep it to contribution wiring. Runtime
code lives behind filename boundaries:
Default export one contribution function from each runtime entry. Keep the entries to registration
wiring. Runtime code lives behind directory boundaries:
| Suffix | Owns |
| -------------- | -------------------------------------------------------------------- |
| `*.client.tsx` | React, React Native, hooks, styles, surfaces, panels, and callbacks. |
| `*.server.ts` | Node APIs, filesystem and process access, credentials, and handlers. |
| `*.shared.ts` | Zod RPC contracts and plain values used by both runtimes. |
| Path | Owns |
| -------------------------------- | -------------------------------------------------------------------- |
| `index.client.tsx` and `client/` | React, React Native, hooks, styles, surfaces, panels, and callbacks. |
| `index.server.ts` and `server/` | Node APIs, filesystem and process access, credentials, and handlers. |
| `shared/` | Zod RPC contracts and plain values used by both runtimes. |
Shared files import contracts from `@getpaseo/plugin/server`. Client files import Paseo UI from
Do not put any other code modules in the plugin root.
Shared files import contract helpers and types from `@getpaseo/plugin`. Server handler files import
`PluginHandlerContext` from `@getpaseo/plugin/server`. Client files import Paseo UI from
`@getpaseo/plugin/react-native`. Its `Icon` resolves a Lucide name using the client's installed icon
set; an unknown name renders nothing so it cannot break the plugin surface.
Its controlled modal keeps presentation metadata on `<Modal title="…" icon={…}>` and body UI in
`<Modal.Content>`.
Plugin UI runs on desktop and mobile across multiple themes: color every `Text` from
`theme.colors.foreground` or `theme.colors.foregroundMuted`, and size layout from `layout.compact`.
See `public-docs/plugins/reference.md`.
See `public-docs/plugins/v0.8/reference.md`.
| Module | Use it for |
| ------------------------------- | -------------------------------------------------------- |
| `@getpaseo/plugin` | contribution contracts and client data hooks |
| `@getpaseo/plugin/react-native` | Paseo React Native components and UI hooks |
| `@getpaseo/plugin/server` | `defineRpc`, `defineAttachmentSource`, and handler types |
| Module | Use it for |
| ------------------------------- | ----------------------------------------------------------------------------------------- |
| `@getpaseo/plugin` | contribution contracts, shared definitions, RPC input/output types, and client data hooks |
| `@getpaseo/plugin/react-native` | Paseo React Native components and UI hooks |
| `@getpaseo/plugin/server` | handler-only types such as `PluginHandlerContext` |
| `@getpaseo/plugin/provider` | provider registration, connection, session, input, event, and timeline contracts |
| `@getpaseo/plugin/acp` | command-backed ACP adapter and focused transformer hooks |
The compiler removes client registrations and imports from the server entry point, and server
registrations and imports from the client entry point. Importing a `*.server` module from a client
module, or a `*.client` module from a server module, fails compilation. Top-level React Native calls
such as `StyleSheet.create` belong in `*.client.tsx`; placing them in `index.ts` executes them in the
server bundle.
The compiler rejects a client import of `server/`, a server import of `client/`, and every `node:`
import reachable from client code. Shared modules cannot import runtime-owned modules. A relative
import to any other code file in the plugin root is also rejected; move it into `client/`, `server/`,
or `shared/`. These are compile errors naming the importing file and boundary rule. Top-level React
Native calls such as `StyleSheet.create` belong in `client/`.
The scaffold omits `"DOM"` from `tsconfig.json` and does not use `/// <reference lib="dom" />`, so
browser globals are not available across the plugin. Put sanctioned web-only APIs in
`client/web.ts`, declare only the globals that module uses, gate each export with
`Platform.OS === "web"`, and provide a native implementation or no-op. See the
[public plugin reference](../public-docs/plugins/v0.8/reference.md#works-on-mobile) for the complete
pattern.
```ts
import type { PluginContext } from "@getpaseo/plugin";
import { Greeting } from "./greeting.client";
import { createGreeting } from "./greeting.server";
import { greetRpc } from "./greeting.shared";
// index.server.ts
import type { PluginServerContext } from "@getpaseo/plugin";
import { createGreeting } from "./server/greeting";
import { greetRpc } from "./shared/greeting";
export default function contribute(plugin: PluginContext) {
plugin.handle(greetRpc, createGreeting);
plugin.addSurface("main", Greeting);
plugin.addSidebarItem({ id: "main", title: "Greeting", icon: "MessageCircle", surface: "main" });
export default function contribute(server: PluginServerContext) {
server.handle(greetRpc, createGreeting);
return () => {};
}
```
```tsx
// index.client.tsx
import type { PluginClientContext } from "@getpaseo/plugin";
import { Greeting } from "./client/greeting";
export default function contribute(client: PluginClientContext) {
client.addSurface("main", Greeting);
client.addSidebarItem({ id: "main", title: "Greeting", icon: "MessageCircle", surface: "main" });
return () => {};
}
```
@@ -209,13 +235,13 @@ When the same plugin contribution exists on multiple hosts, Paseo shows it once
adds a host picker to the screen header. The selected host supplies the bundle, RPC transport, and
query cache. Plugin code cannot address another host.
Workspace panels and Command Center items remain client contributions. The daemon transports their
compiled bundle without interpreting placement or callbacks. Panel props contain workspace and agent
IDs. Required-selector hooks read normalized client state synchronously and use shallow equality, so a
panel does not subscribe to fields it does not render. Command callbacks materialize their snapshots
only when invoked. Contribution discovery and panel opening never fetch active context through plugin
RPC. Snapshot DTOs are deeply readonly and frozen at runtime so plugin code cannot mutate normalized
app state or a memoized selection. Panels use one persisted
Workspace panels, Command Center items, and client slash commands are client contributions. The
daemon transports their compiled bundle without interpreting placement or callbacks. Panel props
contain workspace and agent IDs. Required-selector hooks read normalized client state synchronously
and use shallow equality, so a panel does not subscribe to fields it does not render. Command
callbacks materialize their snapshots only when invoked. Contribution discovery and panel opening
never fetch active context through plugin RPC. Snapshot DTOs are deeply readonly and frozen at
runtime so plugin code cannot mutate normalized app state or a memoized selection. Panels use one persisted
`plugin` workspace-tab target, so reload, disable, removal, and restoration resolve through the
current installed-plugin catalog. A missing contribution renders unavailable inside the tab.
Panels declare `locations: ["workspace", "explorer"]` to opt into Explorer hosting; omission means
@@ -229,12 +255,56 @@ optional client-owned agent and workspace navigation; its absence is the compati
older clients. Other navigation remains limited to registered global surfaces and workspace panels.
Plugins do not receive Expo Router or workspace-layout store access.
## Contribute a provider
Register a provider from `index.server.ts`. The provider connection is callback-based and owns all
of its sessions; plugin RPC is not part of the provider data path.
```ts
import type { PluginServerContext } from "@getpaseo/plugin";
import type { ProviderRegistration } from "@getpaseo/plugin/provider";
import { createProvider } from "./server/provider";
export default function contribute(server: PluginServerContext) {
server.registerProvider(createProvider() satisfies ProviderRegistration);
return () => {};
}
```
`send()` resolves after acceptance. Publish operation completion, prompt disposition, turn state,
configuration, permissions, persistence, and complete timeline snapshots through `onEvent()`.
Route messages, structured commands, steering, and command side effects through `session.prompt`.
Provider settings are toggle/select data that Paseo renders in the composer. Keep private options in
the opaque `providerOptions` config object.
Agent refresh closes the current provider session and opens it again with current configuration and
persistence. Providers re-read credentials, environment, global configuration, and MCP servers on
`session.open`; there is no provider reload input.
For an ACP command, register `runAcpProvider({ id, label, command })` from
`@getpaseo/plugin/acp`. Its transformer hooks cover narrow vendor differences; do not translate the
whole provider event stream. The direct and ACP examples live in `plugin-examples/provider-direct`
and `plugin-examples/provider-acp-transformer`.
Provider-emitted plugin timeline items use the same renderer registration as transformed and
daemon-appended plugin items. The direct example includes both sides. The renderer-only
`plugin-examples/inline-thinking` example shows that timeline presentation remains independent of a
provider implementation. The public [provider plugin guide](../public-docs/plugins/v0.8/providers.md)
owns author workflow, lifecycle, testing, and distribution guidance.
`ProviderRegistration.icon` is a file path relative to the plugin directory, such as `icon.svg`.
It must resolve inside that directory to a regular SVG file no larger than 64 KiB. The SVG must be
self-contained: scripts, styles, `foreignObject`, event-handler attributes, JavaScript URLs, and
external `href` or `xlink:href` references are rejected. Fragment references such as `#mark` are
allowed. Paseo reads and sanitizes the file when the plugin starts; the string is never an inline
SVG or URL.
## Contribute composer pills
Register a headless client entrypoint, then add and remove targeted pills from that client
lifecycle. `addClientSide` runs once per plugin installation in each connected app and never runs
in the daemon subprocess. It can subscribe to the client API, call plugin RPCs, and own arbitrary
client state without mounting a panel or surface.
Add and remove targeted pills from the client entry lifecycle. `index.client.tsx` runs once per
plugin installation in each connected app and never runs in the daemon subprocess. It can subscribe
to the client API, call plugin RPCs, and own arbitrary client state without mounting a panel or
surface.
```tsx
export function contributeClient(client: PluginClientContext) {
@@ -265,8 +335,8 @@ export function contributeClient(client: PluginClientContext) {
}
```
Wire it from `index.ts` with `plugin.addClientSide(contributeClient)`. `addComposerPill` exists only
on `PluginClientContext`; it returns an idempotent removal function. A pill appears only in the
Call `contributeClient(client)` from `index.client.tsx`, or move its body into that entry.
`addComposerPill` returns an idempotent removal function. A pill appears only in the
matching workspace and agent track bar alongside Tasks and Subagents. Paseo owns the pressable,
shared chrome, pending state, error reporting, and placement. The component owns its icon and text;
the callback is client code by construction. Removing the pill, reloading the plugin, disconnecting
@@ -275,20 +345,67 @@ the host, or unloading the app tears down the contribution.
## Contribute timeline items
Timeline transformers and renderers are client contributions. The daemon's canonical rows and
built-in projection stay unchanged. The app transforms fetched projected history before building
its render model. A matching live event requests a fresh projected tail, so lifecycle deltas are
collapsed before the transformer replaces anything.
built-in projection stay unchanged. The app transforms each source item while building the render
model, for both fetched history and live events. The input includes `phase: "streaming" | "complete"`.
Paseo memoizes by source-item reference and derives every replacement ID from the source identity, so
streaming updates preserve mounted component identity.
`query.itemType` selects one public `AgentTimelineItem.type`. The callback owns any detailed
recognition and returns plain plugin item objects. `undefined` keeps the source item, `items`
replaces it, and an empty array removes it. Output `data` must be JSON-compatible. Paseo adds the
runtime plugin ID, preserves the source timeline cursor, validates renderer data with its Zod
schema, and mounts the component inside the normal plugin runtime and error boundary.
runtime plugin ID, preserves the source timeline cursor and identity, validates renderer data with
its Zod schema, and mounts the component inside the normal plugin runtime and error boundary. An
optional output `id` distinguishes several stable replacements from the same source item; its output
index is the default.
Transformers run synchronously and must be deterministic. When several transformers match, the
first one that returns a result owns that source item. Plugin and registration ordering is stable.
See `plugin-examples/timeline-items` for the complete contract.
A plugin subprocess can also append a canonical plugin row from a server handler:
```ts
await paseo.agents.ref(agentId).timeline.append({
type: "plugin",
id: "review",
kind: "review-result",
version: 1,
data: { status: "ready" },
});
```
The daemon stamps the runtime `pluginId`; plugin code never supplies it. Reusing the same `id`
replaces the previous row from that plugin on live clients and fresh timeline fetches. Rows live in
the daemon's in-memory timeline and survive scroll, refetch, and reconnect, but not a daemon
restart. A row without an installed renderer shows an unavailable placeholder. Serialized `data`
must be at most 64 KiB; the daemon rejects a larger append instead of storing a payload that cannot
be rendered intact. The daemon advertises this RPC through
`server_info.features.pluginTimelineItems`.
## Contribute client slash commands
`addSlashCommand` registers an agent- or workspace-context command in the composer. The
callback runs in the app, receives the trimmed text after the command name as `args`, and receives
the same `paseo`, `rpc`, `openSurface`, workspace, agent, and `openPanel` capabilities as the matching
Command Center callback.
```ts
client.addSlashCommand({
name: "review",
description: "Run the review bot",
argumentHint: "[scope]",
context: "agent",
async onSubmit({ args, agent, rpc }) {
await rpc(startReview, { agentId: agent.id, scope: args });
},
});
```
Paseo owns the autocomplete row, input clearing, and error toast. It never sends the command text to
the agent. Built-in client commands win name and alias collisions, plugin commands win
provider-command collisions, and the first plugin in stable catalog order wins collisions between
plugins. Plugin slash commands do not run when the composer has attachments.
## Contribute composer attachments
Register a declarative attachment source backed by a plugin RPC. Paseo owns the attachment menu,
@@ -296,13 +413,24 @@ search picker, drafts, selected pill, and submission. The plugin returns complet
credentials and vendor API calls stay in the daemon handler.
```ts
import type { PluginContext } from "@getpaseo/plugin";
import { search } from "./issues.server";
import { issues, searchIssues } from "./issues.shared";
// index.server.ts
import type { PluginServerContext } from "@getpaseo/plugin";
import { search } from "./server/issues";
import { searchIssues } from "./shared/issues";
export default function contribute(plugin: PluginContext) {
plugin.handle(searchIssues, search);
plugin.addAttachmentSource(issues);
export default function contribute(server: PluginServerContext) {
server.handle(searchIssues, search);
return () => {};
}
```
```tsx
// index.client.tsx
import type { PluginClientContext } from "@getpaseo/plugin";
import { issues } from "./shared/issues";
export default function contribute(client: PluginClientContext) {
client.addAttachmentSource(issues);
return () => {};
}
```
@@ -321,8 +449,8 @@ contract. Unistyles needs every theme name at `StyleSheet.configure` time, so
provider rewrites the matching slot when the selection changes. See [unistyles.md](unistyles.md)
for the runtime-patching rules the appearance settings share.
`addTheme` is a client registration, so the compiler strips it from the backend bundle. A daemon
that predates it does not, and the plugin fails to start there. Daemons advertise
`addTheme` is a client registration and belongs in `index.client.tsx`. A client that predates it
cannot evaluate that entry. Daemons advertise
`features.pluginThemes` in `server_info`; the plugin theme catalog is the one place the app reads it, and
a host without it contributes no themes.
@@ -335,6 +463,8 @@ stable rather than arrival-ordered. The app resolves that id
against the installed catalog on every change; an id nothing contributes falls back to the default
preference instead of painting the reserved slot's placeholder colors.
Existing plugin authors should follow the standalone [v0.8 runtime-entry migration guide](../public-docs/plugins/v0.8/migration.md).
See `plugin-examples/local-plugin` for a native surface, `plugin-examples/linear` for a complete
attachment-source example, `plugin-examples/timeline-items` for timeline projection, and
`plugin-examples/catppuccin` for a theme.
+3 -1
View File
@@ -57,7 +57,9 @@ Existing direct providers: `claude` (in `providers/claude/agent.ts`), `codex` (`
Claude first-party model metadata lives in `packages/server/src/server/agent/providers/claude/model-manifest.ts`. When adding or updating a Claude model, update that manifest only; the model picker thinking options and Claude-specific feature gates are derived from the manifest. Do not add model-specific Claude capability lists in feature code.
Paseo tools are not implemented as MCP tools internally. They live in a shared tool catalog under `packages/server/src/server/agent/tools/`; MCP is only the fallback adapter. A provider that can register runtime tools directly should set `supportsNativePaseoTools: true` and consume `launchContext.paseoTools` in `createSession`/`resumeSession`. When native tools are present, `AgentManager` strips the internal Paseo MCP server from the provider launch config so the provider does not receive the same tools twice. Providers that only know MCP should keep `supportsMcpServers: true` and let the daemon inject `/mcp/agents`.
Paseo tools are not implemented as MCP tools internally. They live in a shared tool catalog under `packages/server/src/server/agent/tools/`; MCP is only the fallback adapter. The daemon resolves `agents.providers.<provider>.paseoTools` by the exact provider ID. The catalog policy belongs to the caller: it filters the tools exposed to the current agent. When that agent calls `create_agent`, the child receives the policy for the child provider ID; the caller's policy is not inherited.
A provider that can register runtime tools directly should set `supportsNativePaseoTools: true` and consume the already-filtered `launchContext.paseoTools` in `createSession`/`resumeSession`. When native tools are present, `AgentManager` strips the internal Paseo MCP server from the provider launch config so the provider does not receive the same tools twice. Providers that only know MCP should keep `supportsMcpServers: true` and let the daemon inject `/mcp/agents`; the MCP server builds the same policy-filtered catalog for that caller. Filtering is enforced at catalog registration in both paths. Browser tools remain subject to the daemon browser-tools setting and browser-host availability.
Pi is a process-backed provider. Paseo requires the user to have the `pi` binary installed and talks to it through `pi --mode rpc`; the server package does not embed Pi's SDK/runtime packages.
+40 -7
View File
@@ -112,7 +112,7 @@ npm run release:patch
npm run release:minor
```
This bumps the version across all workspaces, runs checks, publishes to npm, and pushes the branch + tag. The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`.
This bumps the version across all workspaces, runs checks, publishes to npm, and pushes the branch + tag. The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, and `Release Notes Sync` on GitHub Actions. The workflows create the GitHub Release as a draft while builds and release-note sync run. EAS picks up the same tag via the EAS GitHub app and starts the iOS + Android store builds in parallel (see "Mobile builds (EAS)" below) — there is no mobile-release workflow under `.github/workflows`.
After the stable release succeeds, move npm's `beta` pointer to the new stable
version for every published package. This changes dist-tags only; do not
@@ -180,10 +180,10 @@ The rollout is driven by a `rolloutHours` field stamped into the GitHub Release
Desktop release builds now publish in two phases:
- Platform build jobs upload the installers/packages (`.dmg`, `.zip`, `.exe`, `.AppImage`, etc.) to the GitHub release.
- The final job merges/stamps the manifests and uploads all `.yml` files only after they already contain the final `releaseDate` and `rolloutHours`.
- The GitHub Release stays a draft while platform build jobs upload the installers/packages (`.dmg`, `.zip`, `.exe`, `.AppImage`, etc.).
- The final job merges and stamps every channel manifest, uploads them with the final `releaseDate` and `rolloutHours`, then publishes the GitHub Release.
Updater clients only discover a release through those `.yml` manifests, so there is no silent 100% admission window before rollout metadata is present.
Drafts do not appear in GitHub's releases feed. Updater clients continue to see the previous complete release until all three manifests are available. If a desktop build or manifest upload fails, the new release stays a draft.
### Default behavior
@@ -253,6 +253,15 @@ If you ship N+1 while N is still ramping, N+1 starts a fresh rollout from its ow
If N+1 is a hotfix for a bug in N, dispatch `desktop-rollout.yml -f tag=v0.1.<N+1> -f rollout_hours=0` after N+1 publishes so the users who already got N reach the fix fast.
### macOS system floor
The desktop app requires macOS 13 or newer. Keep both release guards when the floor changes:
- `packages/desktop/electron-builder.yml` writes the macOS version to `LSMinimumSystemVersion` for new installs.
- `scripts/merge-mac-manifest.mjs` writes the matching Darwin kernel version to `minimumSystemVersion` in the update manifest. Existing clients check this before downloading an update.
macOS 13 maps to Darwin 22. The two values use different version domains; do not copy the macOS version into the update manifest.
### Limitations
- **No pause / kill switch.** To stop new admissions, ship a superseding release. Clients revalidate on quit and will not install the superseded download, but a client that already completed installation cannot be recalled; ship a hotfix `+1` patch.
@@ -375,7 +384,7 @@ The GitHub Release body is populated automatically by the `Release Notes Sync` w
- The default download target only moves when you publish the final stable release tag like `v0.1.41`.
- The public `/changelog` page renders `CHANGELOG.md` as-is, so the in-flight `-beta.N` entry shows there once it lands on `main` — that's intended, it's where beta users check what's coming. Only the **default download target** stays pinned to the latest stable; the download links read GitHub's releases API, not the changelog, so a `-beta.N` heading on top never affects them.
- The download page's "What's new" link deep-links the **minor group** anchor (`/changelog#release-0.3`), not the exact entry: promotion collapses the beta entries into one stable entry, so the minor group remains the durable target. A version with no entry in the bundled changelog — a tag whose changelog commit hasn't redeployed the site yet — links the plain `/changelog` instead of a dead anchor.
- The website itself is deployed by `Deploy Website` (Cloudflare Workers), which redeploys on `release: published` for non-prerelease releases and on pushes to `main` that touch `CHANGELOG.md` or `packages/website/**`.
- The website itself is deployed by `Deploy Website` (Cloudflare Workers), which redeploys on the `release: published` event emitted when a stable draft is published and on pushes to `main` that touch `CHANGELOG.md` or `packages/website/**`. Its job condition excludes beta prereleases.
## Fixing a failed release build
@@ -404,6 +413,13 @@ you want to build. Reusing the same tag name is expected: move it with
`git tag -f ...` and push it with `--force` so the workflow rebuilds the commit
you actually want.
A failed desktop build leaves the GitHub Release as a draft. `finalize-rollout`
uploads manifests from successful platforms before it fails. A later
single-platform retry reuses those manifests, stamps the complete set with one
release date, and publishes the draft. Use `desktop-vX.Y.Z` when more than one
platform failed. A `workflow_dispatch` rebuild with publishing enabled follows
the same path against the existing draft.
Prefer a tag push over `workflow_dispatch` when rebuilding desktop or APK
release assets. Prefer Docker workflow dispatch when rebuilding only the Docker
image.
@@ -433,6 +449,22 @@ This ensures the checkout ref matches the actual code on `main` with the fix inc
- `desktop-macos-vX.Y.Z`, `desktop-linux-vX.Y.Z`, and `desktop-windows-vX.Y.Z` rebuild only that desktop platform
- `android-vX.Y.Z` rebuilds the Android APK release only
If you decide to publish a release without working desktop builds, inspect its
assets first, then publish it manually:
```bash
RELEASE_LOOKUP=$(node scripts/github-release.mjs --repo getpaseo/paseo --tag vX.Y.Z)
gh release view "$RELEASE_LOOKUP" --json isDraft,isPrerelease,assets
gh release edit "$RELEASE_LOOKUP" --tag vX.Y.Z --draft=false
# Keep a beta marked as a prerelease:
RELEASE_LOOKUP=$(node scripts/github-release.mjs --repo getpaseo/paseo --tag vX.Y.Z-beta.N)
gh release edit "$RELEASE_LOOKUP" --tag vX.Y.Z-beta.N --draft=false --prerelease
```
This bypasses the updater-manifest guarantee. Use it only when the release is
intentionally unavailable to desktop updater clients.
## Notes
- `version:all:*` bumps root + syncs workspace versions and `@getpaseo/*` dependency versions
@@ -585,7 +617,7 @@ Each beta entry records what its testers receive. Promotion produces the single
- [ ] `npm run release:beta:patch`, `npm run release:beta:minor`, or `npm run release:beta:next` completes successfully
- [ ] Every GitHub Actions run for the complete release commit and tag is green
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease exists with the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*-beta.N` tag is green
- [ ] The GitHub prerelease contains `beta-mac.yml`, `beta-linux.yml`, and `beta.yml`
- [ ] GitHub `Android APK Release` workflow for the same tag is green
@@ -608,9 +640,10 @@ Each beta entry records what its testers receive. Promotion produces the single
- [ ] `npm run release:patch`, `npm run release:minor`, or `npm run release:promote` completes successfully
- [ ] Every GitHub Actions run for the complete release commit and tag is green
- [ ] Move npm's `beta` dist-tag to the new stable version for every published package and verify both `latest` and `beta` resolve to it
- [ ] The published GitHub Release exists with the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
- [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml`
- [ ] `latest-mac.yml` contains the current `minimumSystemVersion` guard
- [ ] GitHub `Android APK Release` workflow for the same tag is green
- [ ] GitHub `Docker` workflow is green and both the versioned and `latest` images are published
- [ ] GitHub `Release Notes Sync` is green and the release body matches the stable changelog entry
+12
View File
@@ -349,6 +349,18 @@ Gotchas:
- **The app shell uses one `AppearanceStyleBoundary`.** Runtime-patched numeric theme values are baked into Unistyles web classes rather than CSS variables, while parsed/memoized content also does not naturally re-run when appearance tokens change. The boundary sits below stable runtime providers in `app/_layout.tsx` and remounts the visual shell once. `applyAppearance` patches the active theme before inactive registry entries so its subscribers receive the committed values in the same update. Do not add local appearance keys or nested boundaries.
- **Dynamic font tokens stay widened.** `fontFamily`, `fontSize`, and `lineHeight` on `commonTheme` are annotated `string`/`number` (not narrowed by `as const`) so the updater's return assigns; the platform default stacks live in `DEFAULT_UI_FONT_STACK` / `DEFAULT_MONO_FONT_STACK`.
## Patching The Web Runtime
When backporting a Unistyles web fix, patch the TypeScript source and both
shipped JavaScript builds. Native Metro resolves the package's `react-native`
export to `src`, but browser and Electron Metro resolve its `browser` export to
`lib/module`; CommonJS consumers use `lib/commonjs`. A source-only patch leaves
Electron running the old code.
Register every dependency patch in `scripts/postinstall-patches.mjs`. A file in
`patches/` is inert unless that script knows which installed package activates
it.
## Debugging
To inspect what the Babel plugin sees, temporarily enable [`debug: true`](https://www.unistyl.es/v3/other/babel-plugin#debug) in `packages/app/babel.config.js`:
@@ -0,0 +1,4 @@
Added
- Added Claude Fable 5.1 with a 1M context window
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
Added
- Added Claude Fable 5.1 with a 1M context window
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
Added
- Added Claude Fable 5.1 with a 1M context window
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
Added
- Added Claude Fable 5.1 with a 1M context window
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,11 @@
Added
- Added active-turn steering for pi agents so new messages reach the running turn without interrupting it
- Added declared build commands and monorepo source paths for Git-hosted plugins
Improved
- Reduced JS stalls while watching a streaming agent on mobile
Fixed
- Fixed large and many-file diffs stalling or crashing while opening and scrolling
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,11 @@
Added
- Added active-turn steering for pi agents so new messages reach the running turn without interrupting it
- Added declared build commands and monorepo source paths for Git-hosted plugins
Improved
- Reduced JS stalls while watching a streaming agent on mobile
Fixed
- Fixed large and many-file diffs stalling or crashing while opening and scrolling
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,11 @@
Added
- Added active-turn steering for pi agents so new messages reach the running turn without interrupting it
- Added declared build commands and monorepo source paths for Git-hosted plugins
Improved
- Reduced JS stalls while watching a streaming agent on mobile
Fixed
- Fixed large and many-file diffs stalling or crashing while opening and scrolling
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,11 @@
Added
- Added active-turn steering for pi agents so new messages reach the running turn without interrupting it
- Added declared build commands and monorepo source paths for Git-hosted plugins
Improved
- Reduced JS stalls while watching a streaming agent on mobile
Fixed
- Fixed large and many-file diffs stalling or crashing while opening and scrolling
Full notes: https://paseo.sh/changelog
+1 -1
View File
@@ -1 +1 @@
sha256-HFYBrCP62r6ZofazBIGSOnMhk8IIEmv+TFJMpqTIJQ8=
sha256-EpfSUhkssURxoUgE9+odbFg3sroXH5bH5S9xClMG2nE=
+81 -226
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.7.0",
"version": "0.7.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.7.0",
"version": "0.7.2",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -28,6 +28,7 @@
"@vercel/nft": "^1.5.0",
"concurrently": "^9.2.1",
"cross-env": "^10.1.0",
"electron": "44.2.0",
"get-port-cli": "^3.0.0",
"js-yaml": "^4.1.1",
"knip": "^5.82.1",
@@ -2883,6 +2884,16 @@
"node": ">=0.8.0"
}
},
"node_modules/@electron-internal/extract-zip": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/@electron-internal/extract-zip/-/extract-zip-1.0.5.tgz",
"integrity": "sha512-+bqFCP98pLI0Tt0XQo1TmlXtwjWchISndDOxCkEcIuUgXWpBnLyRI+2DU+mesvnMMX6L1XDqYNA0lXNDHd/yiA==",
"dev": true,
"license": "BSD-2-Clause",
"engines": {
"node": ">=22.12.0"
}
},
"node_modules/@electron/asar": {
"version": "3.4.1",
"resolved": "https://registry.npmjs.org/@electron/asar/-/asar-3.4.1.tgz",
@@ -2989,70 +3000,37 @@
}
},
"node_modules/@electron/get": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/@electron/get/-/get-2.0.3.tgz",
"integrity": "sha512-Qkzpg2s9GnVV2I2BjRksUi43U5e6+zaQMcjoJy0C+C5oxaKl+fmckGDQFtRpZpZV0NQekuZZ+tGz7EA9TVnQtQ==",
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/@electron/get/-/get-5.1.0.tgz",
"integrity": "sha512-3kSBtG8ObcTVfXanm5vVJ6UnBLEVmVsRk1M+vGqCuMBV+XLCbJYuWQful+yIy0GQDsSlK0kHEriEHn7SPk4EnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"debug": "^4.1.1",
"env-paths": "^2.2.0",
"fs-extra": "^8.1.0",
"got": "^11.8.5",
"env-paths": "^3.0.0",
"graceful-fs": "^4.2.11",
"progress": "^2.0.3",
"semver": "^6.2.0",
"semver": "^7.6.3",
"sumchecker": "^3.0.1"
},
"engines": {
"node": ">=12"
"node": ">=22.12.0"
},
"optionalDependencies": {
"global-agent": "^3.0.0"
"undici": "^7.24.4"
}
},
"node_modules/@electron/get/node_modules/fs-extra": {
"version": "8.1.0",
"resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz",
"integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==",
"dev": true,
"license": "MIT",
"dependencies": {
"graceful-fs": "^4.2.0",
"jsonfile": "^4.0.0",
"universalify": "^0.1.0"
},
"engines": {
"node": ">=6 <7 || >=8"
}
},
"node_modules/@electron/get/node_modules/jsonfile": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz",
"integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==",
"dev": true,
"license": "MIT",
"optionalDependencies": {
"graceful-fs": "^4.1.6"
}
},
"node_modules/@electron/get/node_modules/semver": {
"version": "6.3.1",
"resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz",
"integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
}
},
"node_modules/@electron/get/node_modules/universalify": {
"version": "0.1.2",
"resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz",
"integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==",
"node_modules/@electron/get/node_modules/env-paths": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/env-paths/-/env-paths-3.0.0.tgz",
"integrity": "sha512-dtJUTepzMW3Lm/NPxRf3wP4642UWhjL2sQxc+ym2YMj1m/H2zDNQOlezafzkHwn6sMstjHTwG6iQQsctDW/b1A==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">= 4.0.0"
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/@electron/notarize": {
@@ -13187,17 +13165,6 @@
"integrity": "sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ==",
"license": "MIT"
},
"node_modules/@types/yauzl": {
"version": "2.10.3",
"resolved": "https://registry.npmjs.org/@types/yauzl/-/yauzl-2.10.3.tgz",
"integrity": "sha512-oJoftv0LSuaDZE3Le4DbKX+KS9G36NzOeSap90UIK0yMA/NhKJhqlSGtNDORNRaIbQfzjXDrQa0ytJ6mNRGz/Q==",
"dev": true,
"license": "MIT",
"optional": true,
"dependencies": {
"@types/node": "*"
}
},
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.56.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.56.1.tgz",
@@ -15813,16 +15780,6 @@
"ieee754": "^1.2.1"
}
},
"node_modules/buffer-crc32": {
"version": "0.2.13",
"resolved": "https://registry.npmjs.org/buffer-crc32/-/buffer-crc32-0.2.13.tgz",
"integrity": "sha512-VO9Ht/+p3SN7SKWqcrgEzjGbRSJYTx+Q1pTQC0wrWqHx0vpJraQ6GtHx8tvcg1rlK1byhU5gccxgOgj7B0TDkQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": "*"
}
},
"node_modules/buffer-equal-constant-time": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz",
@@ -18675,22 +18632,22 @@
}
},
"node_modules/electron": {
"version": "41.2.0",
"resolved": "https://registry.npmjs.org/electron/-/electron-41.2.0.tgz",
"integrity": "sha512-0OKLiymqfV0WK68RBXqAm3Myad2TpI5wwxLCBEUcH5Nugo3YfSk7p1Js/AL9266qTz5xZioUnxt9hG8FFwax0g==",
"version": "44.2.0",
"resolved": "https://registry.npmjs.org/electron/-/electron-44.2.0.tgz",
"integrity": "sha512-oK1icjhapp3xsUZycO9WZaLmd3hJnA7ieobC4mpdtO1pEN+PPGWpA3m1Mgzzuc1wzSD2Wai4zcH4yfpGJqxFMA==",
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"@electron/get": "^2.0.0",
"@types/node": "^24.9.0",
"extract-zip": "^2.0.1"
"@electron-internal/extract-zip": "^1.0.1",
"@electron/get": "^5.0.0",
"@types/node": "^24.9.0"
},
"bin": {
"electron": "cli.js"
"electron": "cli.js",
"install-electron": "install.js"
},
"engines": {
"node": ">= 12.20.55"
"node": ">= 22.12.0"
}
},
"node_modules/electron-builder": {
@@ -18797,19 +18754,19 @@
}
},
"node_modules/electron/node_modules/@types/node": {
"version": "24.12.2",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.12.2.tgz",
"integrity": "sha512-A1sre26ke7HDIuY/M23nd9gfB+nrmhtYyMINbjI1zHJxYteKR6qSMX56FsmjMcDb3SMcjJg5BiRRgOCC/yBD0g==",
"version": "24.13.3",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.3.tgz",
"integrity": "sha512-Dh8vAsV36ig5wa9OX4pXvMc9D3Veibfw2wix0CUwYODLD8nkj9UsLjASr49nPg+2eKzxhBV+v7L8pXvT4e639Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~7.16.0"
"undici-types": "~7.18.0"
}
},
"node_modules/electron/node_modules/undici-types": {
"version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
"integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
"integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
"dev": true,
"license": "MIT"
},
@@ -21881,43 +21838,6 @@
"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==",
"license": "MIT"
},
"node_modules/extract-zip": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/extract-zip/-/extract-zip-2.0.1.tgz",
"integrity": "sha512-GDhU9ntwuKyGXdZBUgTIe+vXnWj0fppUEtMDL0+idd5Sta8TGpHssn/eusA9mrPr9qNDym6SxAYZjNvCn/9RBg==",
"dev": true,
"license": "BSD-2-Clause",
"dependencies": {
"debug": "^4.1.1",
"get-stream": "^5.1.0",
"yauzl": "^2.10.0"
},
"bin": {
"extract-zip": "cli.js"
},
"engines": {
"node": ">= 10.17.0"
},
"optionalDependencies": {
"@types/yauzl": "^2.9.1"
}
},
"node_modules/extract-zip/node_modules/get-stream": {
"version": "5.2.0",
"resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",
"integrity": "sha512-nBF+F1rAZVCu/p7rjzgA+Yb4lfYXrpl7a6VmJrU8wF9I1CKvP/QwPNZHnOlwbTkY6dvtFIzFMSyQXbLoTQPRpA==",
"dev": true,
"license": "MIT",
"dependencies": {
"pump": "^3.0.0"
},
"engines": {
"node": ">=8"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/extsprintf": {
"version": "1.4.1",
"resolved": "https://registry.npmjs.org/extsprintf/-/extsprintf-1.4.1.tgz",
@@ -22082,16 +22002,6 @@
"walk-up-path": "^4.0.0"
}
},
"node_modules/fd-slicer": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/fd-slicer/-/fd-slicer-1.1.0.tgz",
"integrity": "sha512-cE1qsB/VwyQozZ+q1dGxR8LBYNZeofhEdUNGSMbQD3Gw2lAzX9Zb3uIU6Ebc/Fmyjo9AWWfnn0AUCHqtevs/8g==",
"dev": true,
"license": "MIT",
"dependencies": {
"pend": "~1.2.0"
}
},
"node_modules/fdir": {
"version": "6.5.0",
"resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
@@ -29636,13 +29546,6 @@
"url": "https://github.com/sponsors/jet2jet"
}
},
"node_modules/pend": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/pend/-/pend-1.2.0.tgz",
"integrity": "sha512-F3asv42UuXchdzt+xXqfW1OGlVBe+mxa2mqI0pg5yAHZPvFmY3Y6drSf/GQ1A86WgWEN9Kzh/WrgKa6iGcHXLg==",
"dev": true,
"license": "MIT"
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
@@ -36137,17 +36040,6 @@
"node": ">=12"
}
},
"node_modules/yauzl": {
"version": "2.10.0",
"resolved": "https://registry.npmjs.org/yauzl/-/yauzl-2.10.0.tgz",
"integrity": "sha512-p4a9I6X6nu6IhoGmBqAcbJy1mlC4j27vEPZX9F4L4/vZT3Lyq1VkFHw/V/PUcB9Buo+DG3iHkT0x3Qya58zc3g==",
"dev": true,
"license": "MIT",
"dependencies": {
"buffer-crc32": "~0.2.3",
"fd-slicer": "~1.1.0"
}
},
"node_modules/yn": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz",
@@ -36298,7 +36190,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -37363,12 +37255,12 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.7.0",
"@getpaseo/protocol": "0.7.0",
"@getpaseo/server": "0.7.0",
"@getpaseo/client": "0.7.2",
"@getpaseo/protocol": "0.7.2",
"@getpaseo/server": "0.7.2",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -37615,10 +37507,10 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"@getpaseo/protocol": "0.7.0",
"@getpaseo/relay": "0.7.0",
"@getpaseo/protocol": "0.7.2",
"@getpaseo/relay": "0.7.2",
"zod": "^4.4.3"
},
"devDependencies": {
@@ -37629,7 +37521,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.7.0",
"version": "0.7.2",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -37642,7 +37534,7 @@
"devDependencies": {
"@types/node": "24.6.0",
"@types/ws": "^8.5.14",
"electron": "41.2.0",
"electron": "44.2.0",
"electron-builder": "26.8.1",
"typescript": "5.9.3",
"unzip-crx-3": "^0.2.0",
@@ -37872,7 +37764,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.7.0",
"version": "0.7.2",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -38768,7 +38660,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"@codemirror/language": "6.12.4",
"@codemirror/legacy-modes": "^6.5.3",
@@ -38797,13 +38689,14 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.7.0",
"@getpaseo/protocol": "0.7.0",
"@getpaseo/client": "0.7.2",
"@getpaseo/protocol": "0.7.2",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.1.0",
@@ -38812,15 +38705,24 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.7.0",
"@getpaseo/protocol": "0.7.0",
"@getpaseo/client": "0.7.2",
"@getpaseo/protocol": "0.7.2",
"react": "19.1.0",
"zod": "^4.4.3"
}
},
"packages/plugin/node_modules/@agentclientprotocol/sdk": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/@agentclientprotocol/sdk/-/sdk-1.4.0.tgz",
"integrity": "sha512-/eufudw+aFY1LKLolT6yFE6UMmYRl7fMJ/DEONSIyR6wI3slHWITBsANRGqXEY8FRzqUxwh7QEaGiZHcJPVThg==",
"license": "Apache-2.0",
"peerDependencies": {
"zod": "^3.25.0 || ^4.0.0"
}
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"zod": "^4.4.3"
},
@@ -38833,7 +38735,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"base64-js": "^1.5.1",
"tweetnacl": "^1.0.3",
@@ -39051,17 +38953,16 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.246",
"@anthropic-ai/sdk": "^0.104.2",
"@babel/parser": "^7.29.8",
"@getpaseo/client": "0.7.0",
"@getpaseo/highlight": "0.7.0",
"@getpaseo/plugin": "0.7.0",
"@getpaseo/protocol": "0.7.0",
"@getpaseo/relay": "0.7.0",
"@getpaseo/client": "0.7.2",
"@getpaseo/highlight": "0.7.2",
"@getpaseo/plugin": "0.7.2",
"@getpaseo/protocol": "0.7.2",
"@getpaseo/relay": "0.7.2",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/sdk": "1.29.0",
"@opencode-ai/sdk": "1.14.46",
@@ -39106,52 +39007,6 @@
"vitest": "^4.1.6"
}
},
"packages/server/node_modules/@babel/helper-string-parser": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz",
"integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"packages/server/node_modules/@babel/helper-validator-identifier": {
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz",
"integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
}
},
"packages/server/node_modules/@babel/parser": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.8.tgz",
"integrity": "sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA==",
"license": "MIT",
"dependencies": {
"@babel/types": "^7.29.8"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"engines": {
"node": ">=6.0.0"
}
},
"packages/server/node_modules/@babel/types": {
"version": "7.29.8",
"resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.8.tgz",
"integrity": "sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg==",
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.29.7",
"@babel/helper-validator-identifier": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
"version": "0.25.12",
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.12.tgz",
@@ -39985,7 +39840,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.7.0",
"version": "0.7.2",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.7.0",
"version": "0.7.2",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -126,6 +126,7 @@
"@vercel/nft": "^1.5.0",
"concurrently": "^9.2.1",
"cross-env": "^10.1.0",
"electron": "44.2.0",
"get-port-cli": "^3.0.0",
"js-yaml": "^4.1.1",
"knip": "^5.82.1",
+467 -65
View File
@@ -1,5 +1,5 @@
import { execFileSync } from "node:child_process";
import { readFile, unlink, writeFile } from "node:fs/promises";
import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
import { type Locator, type Page } from "@playwright/test";
import { buildHostWorkspaceRoute, buildSettingsSectionRoute } from "../../src/utils/host-routes";
@@ -37,6 +37,10 @@ function changesTree(page: Page) {
return page.getByTestId("changes-file-tree").filter({ visible: true });
}
function diffHeaderForPath(panel: Locator, filePath: string): Locator {
return panel.locator(`[data-diff-header-path="${filePath}"]`).getByTestId(/^diff-file-\d+$/);
}
async function readFileIfPresent(filePath: string): Promise<string | null> {
try {
return await readFile(filePath, "utf8");
@@ -261,12 +265,12 @@ test.afterEach(async () => {
test("Changes opens the populated committed comparison for a clean checkout", async ({ page }) => {
const workspace = await createWorkspaceWithCommittedDiff();
await openWorkspaceChangesSurface(page, workspace);
await openWorkspaceChangesSurface(page, workspace, 90_000);
const panel = page.getByTestId("working-diff-panel").filter({ visible: true });
const tree = page.getByTestId("changes-tree-panel").filter({ visible: true });
await expect(tree.getByTestId("changes-diff-status-trigger")).toContainText("Committed");
await expect(panel.getByText("committed-only.ts", { exact: true })).toBeVisible();
await expect(panel.getByTestId("diff-file-0")).toHaveAccessibleName("committed-only.ts, +1, -0");
});
test("Changes expires a manual comparison when checkout dirtiness changes", async ({ page }) => {
@@ -302,17 +306,33 @@ test("an empty Changes comparison links to the populated comparison", async ({ p
const mode = tree.getByTestId("changes-diff-status-trigger");
await mode.click();
await page.getByTestId("changes-diff-mode-committed").click();
await expect(panel.getByText("committed-only.ts", { exact: true })).toBeVisible();
await expect(panel.getByTestId("diff-file-0")).toHaveAccessibleName("committed-only.ts, +1, -0");
await mode.click();
await page.getByTestId("changes-diff-mode-uncommitted").click();
await expect(tree.getByText("No uncommitted changes", { exact: true })).toBeVisible();
await expect(panel.getByText("No uncommitted changes", { exact: true })).toBeVisible();
const seeCommitted = tree.getByRole("button", { name: "See committed changes" });
await expect(seeCommitted).toBeVisible();
await seeCommitted.click();
await expect(mode).toContainText("Committed");
await expect(panel.getByText("committed-only.ts", { exact: true })).toBeVisible();
await expect(panel.getByTestId("diff-file-0")).toHaveAccessibleName("committed-only.ts, +1, -0");
});
test("Changes comparison controls the working diff and tree selection focuses its file", async ({
page,
}) => {
const workspace = await createWorkspaceWithScrollableComparisons();
await openWorkspaceChangesSurface(page, workspace);
await selectChangesComparison(page, "Committed");
await expectWorkingComparisonFiles(page, "committed");
await selectChangedFileAndExpectFocused(page, "committed/50-target.ts");
await selectChangesComparison(page, "Uncommitted");
await expectWorkingComparisonFiles(page, "uncommitted");
await selectChangedFileAndExpectFocused(page, "uncommitted/50-target.ts");
});
test("changes file actions open below the right-click without a reserved kebab", async ({
@@ -322,9 +342,8 @@ test("changes file actions open below the right-click without a reserved kebab",
await useUnwrappedDiffLines(page);
await openWorkspaceChanges(page, workspace);
await expect(page.getByTestId("diff-file-1")).toContainText("zz-deleted.ts");
const deletedFileName = page.getByTestId("diff-file-1-name");
await expect(deletedFileName).toHaveCSS("user-select", "none");
const deletedFileName = page.getByTestId("diff-file-1");
await expect(deletedFileName).toHaveAccessibleName(/zz-deleted\.ts/);
await deletedFileName.dblclick();
expect(await page.evaluate(() => window.getSelection()?.toString() ?? "")).toBe("");
await expect(page.getByTestId(/diff-file-\d+-actions/)).toHaveCount(0);
@@ -378,49 +397,116 @@ test("every interactive file header has the same hover feedback", async ({ page
const first = page.getByTestId("diff-file-0-toggle");
const second = page.getByTestId("diff-file-1-toggle");
const normalBackground = await first.evaluate(
(element) => getComputedStyle(element.parentElement!).backgroundColor,
);
await expect
.poll(() =>
first.evaluate((element) => getComputedStyle(element.parentElement!).borderTopWidth),
)
.toBe("0px");
const firstCanvas = page.getByTestId("git-diff-sticky-header-0");
const secondCanvas = page.getByTestId("git-diff-sticky-header-1");
const normalBackground = await headerCanvasPixel(firstCanvas, first, 10);
await first.hover();
const hoverBackground = await first.evaluate(
(element) => getComputedStyle(element).backgroundColor,
);
expect(hoverBackground).not.toBe(normalBackground);
await expect.poll(() => headerCanvasPixel(firstCanvas, first, 10)).not.toBe(normalBackground);
const hoverBackground = await headerCanvasPixel(firstCanvas, first, 10);
await first.click();
await page.mouse.move(0, 0);
await expect(first).toHaveAttribute("aria-expanded", "false");
await expect
.poll(() =>
first.evaluate((element) => getComputedStyle(element.parentElement!).backgroundColor),
)
.toBe(normalBackground);
const [sharedBorder, secondTopBorderWidth] = await Promise.all([
first.evaluate((element) => getComputedStyle(element.parentElement!).borderBottomColor),
second.evaluate((element) => getComputedStyle(element.parentElement!).borderTopWidth),
]);
expect(sharedBorder).not.toBe("rgba(0, 0, 0, 0)");
expect(secondTopBorderWidth).toBe("0px");
await expect.poll(() => headerCanvasPixel(firstCanvas, first, 10)).toBe(normalBackground);
await first.hover();
await expect
.poll(() => first.evaluate((element) => getComputedStyle(element).backgroundColor))
.toBe(hoverBackground);
await expect.poll(() => headerCanvasPixel(firstCanvas, first, 10)).toBe(hoverBackground);
await second.hover();
await expect.poll(() => headerCanvasPixel(firstCanvas, first, 10)).toBe(normalBackground);
await expect.poll(() => headerCanvasPixel(secondCanvas, second, 10)).toBe(hoverBackground);
});
test("horizontal body scrolling never moves or repaints the canvas header", async ({ page }) => {
const wideLine = `export const wide = "${"wide".repeat(160)}";`;
const workspace = await createWorkspaceWithExactSelectionDiff(wideLine);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
const headerCanvas = page.getByTestId("git-diff-canvas");
const header = page.getByTestId("diff-file-0-toggle");
const beforePixel = await headerCanvasPixel(headerCanvas, header, 10);
const beforeBounds = await header.boundingBox();
await horizontallyScrollFirstFile(page, 320);
await page.waitForTimeout(50);
expect(await headerCanvasPixel(headerCanvas, header, 10)).toBe(beforePixel);
expect(await header.boundingBox()).toEqual(beforeBounds);
});
test("in-flow file headers move with the diff document", async ({ page }) => {
const workspace = await createWorkspaceWithStickyTransitionDiff();
await useUnwrappedDiffLines(page);
await openWorkspaceChangesSurface(page, workspace);
const motion = await measureInFlowHeaderMotion(page);
expect(motion).toEqual({ headerSurface: -120, shell: -120 });
});
test("the outgoing sticky header hands off without a gap or overlap", async ({
page,
}, testInfo) => {
const workspace = await createWorkspaceWithStickyTransitionDiff();
await useUnwrappedDiffLines(page);
await openWorkspaceChangesSurface(page, workspace);
const scroller = page.getByTestId("git-diff-scroll");
const first = page.getByTestId("diff-file-0-toggle");
const second = page.getByTestId("diff-file-1-toggle");
const secondTop = await second.evaluate((element) => {
const scrollElement = element.closest<HTMLElement>('[data-testid="git-diff-scroll"]');
if (!scrollElement) return Number.NaN;
return (
scrollElement.scrollTop +
element.getBoundingClientRect().top -
scrollElement.getBoundingClientRect().top
);
});
expect(secondTop).toBeGreaterThan(30);
await scroller.evaluate((element, scrollTop) => {
element.scrollTop = scrollTop;
element.dispatchEvent(new Event("scroll", { bubbles: false }));
}, secondTop - 15);
await expect(first).toBeAttached();
await expect(second).toBeAttached();
const [scrollBounds, firstBounds, secondBounds] = await Promise.all([
scroller.boundingBox(),
first.boundingBox(),
second.boundingBox(),
]);
if (!scrollBounds || !firstBounds || !secondBounds) {
throw new Error("Sticky transition geometry is unavailable");
}
expect(firstBounds.y - scrollBounds.y).toBeCloseTo(-15, 0);
expect(secondBounds.y - scrollBounds.y).toBeCloseTo(15, 0);
const transitionHits = await scroller.evaluate((element) => {
const bounds = element.getBoundingClientRect();
return [14, 16].map(
(y) =>
document
.elementFromPoint(bounds.left + bounds.width / 2, bounds.top + y)
?.closest<HTMLElement>("[data-diff-header]")?.dataset.diffHeaderPath ?? null,
);
});
expect(transitionHits).toEqual(["src/first.ts", "src/second.ts"]);
await testInfo.attach("canvas-header-sticky-handoff", {
body: await page.getByTestId("git-diff-canvas-root").screenshot(),
contentType: "image/png",
});
await scroller.evaluate((element, scrollTop) => {
element.scrollTop = scrollTop;
element.dispatchEvent(new Event("scroll", { bubbles: false }));
}, secondTop);
await expect
.poll(() =>
first.evaluate((element) => getComputedStyle(element.parentElement!).backgroundColor),
)
.toBe(normalBackground);
await expect
.poll(() => second.evaluate((element) => getComputedStyle(element).backgroundColor))
.toBe(hoverBackground);
.poll(async () => {
const bounds = await second.boundingBox();
return bounds ? bounds.y - scrollBounds.y : Number.NaN;
})
.toBeCloseTo(0, 0);
});
test("changes context menus duplicate files and folders", async ({ page }) => {
@@ -475,7 +561,8 @@ test("the scrolling diff lists files in changes tree order", async ({ page }) =>
const tree = changesTree(page);
const treeNames = tree.locator('[data-testid^="diff-tree-file-"][data-testid$="-name"]');
const diffNames = page.locator('[data-testid^="diff-file-"][data-testid$="-name"]');
const panel = page.getByTestId("working-diff-panel").filter({ visible: true });
const diffHeaders = panel.getByTestId(/^diff-file-\d+$/);
// Directories sort before files at every level, so the root note lands last
// even though "a-root-note.txt" compares below "src/..." as a whole string.
@@ -485,9 +572,17 @@ test("the scrolling diff lists files in changes tree order", async ({ page }) =>
// descendants of a collapsed folder, which would make the tree a subsequence
// of the diff rather than a match, and mask a real ordering difference.
await expect(treeNames).toHaveCount(expected.length);
await expect(diffNames).toHaveCount(expected.length);
await expect(diffHeaders).toHaveCount(expected.length);
await expect(treeNames).toHaveText(expected);
await expect(diffNames).toHaveText(expected);
const expectedHeaderNames = [
"src/zz-folder/nested/changed.ts, +1, -1",
"src/zz-folder/root.ts, +1, -1",
"src/use-mounted-tab-set.ts, +37, -1",
"a-root-note.txt, +1, -0",
];
for (const [index, accessibleName] of expectedHeaderNames.entries()) {
await expect(diffHeaders.nth(index)).toHaveAccessibleName(accessibleName);
}
});
test("changes context menu recursively collapses descendant folders", async ({ page }) => {
@@ -586,9 +681,10 @@ test("discarding a staged rename restores its source path", async ({ page }) =>
await useUnwrappedDiffLines(page);
await openWorkspaceChanges(page, workspace);
const renamedToggle = page
.getByTestId(/^diff-file-\d+-toggle$/)
.filter({ hasText: "zz-renamed.ts" });
const panel = page.getByTestId("working-diff-panel").filter({ visible: true });
const renamedHeader = diffHeaderForPath(panel, "src/zz-renamed.ts");
await expect(renamedHeader).toHaveAccessibleName("src/zz-renamed.ts, +1, -0");
const renamedToggle = renamedHeader.getByTestId(/^diff-file-\d+-toggle$/);
const toggleTestId = await renamedToggle.getAttribute("data-testid");
expect(toggleTestId).not.toBeNull();
const rowTestId = toggleTestId!.slice(0, -"-toggle".length);
@@ -615,9 +711,10 @@ test("discarding an untracked file removes it from the working tree", async ({ p
await useUnwrappedDiffLines(page);
await openWorkspaceChanges(page, workspace);
const untrackedToggle = page
.getByTestId(/^diff-file-\d+-toggle$/)
.filter({ hasText: "zz-untracked.txt" });
const panel = page.getByTestId("working-diff-panel").filter({ visible: true });
const untrackedHeader = diffHeaderForPath(panel, "zz-untracked.txt");
await expect(untrackedHeader).toHaveAccessibleName("zz-untracked.txt, +1, -0");
const untrackedToggle = untrackedHeader.getByTestId(/^diff-file-\d+-toggle$/);
const toggleTestId = await untrackedToggle.getAttribute("data-testid");
expect(toggleTestId).not.toBeNull();
const rowTestId = toggleTestId!.slice(0, -"-toggle".length);
@@ -676,8 +773,12 @@ test("Changes keeps review navigation and controls inside its workspace tab", as
await expect(visiblePanel.getByTestId("changes-diff-status-trigger")).toHaveCount(0);
await expect(visiblePanel.getByTestId("changes-selected-diff-stat")).toHaveCount(0);
await expect(visiblePanel.getByTestId("changes-header")).toHaveCount(1);
await expect(visiblePanel.getByText("use-mounted-tab-set.ts", { exact: true })).toBeVisible();
await expect(visiblePanel).toContainText("zz-deleted.ts");
await expect(diffHeaderForPath(visiblePanel, "src/use-mounted-tab-set.ts")).toHaveAccessibleName(
"src/use-mounted-tab-set.ts, +37, -1",
);
await expect(diffHeaderForPath(visiblePanel, "src/zz-deleted.ts")).toHaveAccessibleName(
"src/zz-deleted.ts, +0, -1",
);
await expect(visiblePanel.getByTestId("changes-primary-cta")).toHaveCount(0);
await expect(page.getByTestId("changes-primary-cta")).toHaveCount(1);
await expect(page.getByTestId("changes-primary-cta")).toContainText("Commit");
@@ -712,16 +813,18 @@ test("Changes keeps review navigation and controls inside its workspace tab", as
await expect(page.getByTestId(/^workspace-working-diff-close-/)).toHaveCount(1);
await writeFile(path.join(workspace.repoPath, "src/use-mounted-tab-set.ts"), BEFORE);
await expect(visiblePanel.getByText("use-mounted-tab-set.ts", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
await expect(visiblePanel).toContainText("zz-deleted.ts");
await expect(
visiblePanel.locator('[data-diff-header-path="src/use-mounted-tab-set.ts"]'),
).toHaveCount(0, { timeout: 30_000 });
await expect(visiblePanel.locator('[data-diff-header-path="src/zz-deleted.ts"]')).toBeVisible();
await writeFile(path.join(workspace.repoPath, "src/use-mounted-tab-set.ts"), AFTER);
await expect(visiblePanel.getByText("use-mounted-tab-set.ts", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expect(visiblePanel.getByText("zz-deleted.ts", { exact: true })).toBeVisible();
await expect(visiblePanel.getByRole("img", { name: "Deleted" })).toBeVisible();
await expect(diffHeaderForPath(visiblePanel, "src/use-mounted-tab-set.ts")).toHaveAccessibleName(
"src/use-mounted-tab-set.ts, +37, -1",
{ timeout: 30_000 },
);
await expect(diffHeaderForPath(visiblePanel, "src/zz-deleted.ts")).toHaveAccessibleName(
"src/zz-deleted.ts, +0, -1",
);
});
test("compact Changes keeps its actions compact and menu-only", async ({ page }) => {
@@ -923,6 +1026,16 @@ test("autofocusing an inline review keeps the Changes tab focused", async ({ pag
.toBe(focusedBackground);
});
test("inline reviews keep the browser text context menu", async ({ page }) => {
const workspace = await createWorkspaceWithMountedTabDiff();
await useUnwrappedDiffLines(page);
await openWorkspaceChanges(page, workspace);
await startReviewOnFirstChangedLine(page);
await page.getByTestId("inline-review-editor-input").click({ button: "right" });
await expect(page.getByTestId("diff-source-context-menu")).toHaveCount(0);
});
test("split canvas creates a review on the changed side and keeps it in that column", async ({
page,
}) => {
@@ -980,6 +1093,29 @@ test("canvas diff uses the overlay scrollbar and its thumb controls vertical scr
await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(0);
});
test("canvas headers keep a many-file diff bounded while scrolling end to end", async ({
page,
}) => {
test.setTimeout(180_000);
const workspace = await createWorkspaceWithManyTinyDiffs(2_000);
await useUnwrappedDiffLines(page);
await openWorkspaceChangesSurface(page, workspace, 90_000);
const root = page.getByTestId("git-diff-canvas-root");
const scroller = page.getByTestId("git-diff-scroll");
await expect(root.locator('[data-testid^="git-diff-sticky-header-"]')).toHaveCount(2);
await expect.poll(() => root.locator('[data-diff-header="true"]').count()).toBeLessThan(120);
await scroller.evaluate((element) => {
element.scrollTop = element.scrollHeight - element.clientHeight;
element.dispatchEvent(new Event("scroll", { bubbles: false }));
});
await expect(page.getByTestId("diff-file-1999")).toBeVisible();
await expect.poll(() => root.locator('[data-diff-header="true"]').count()).toBeLessThan(120);
await expect(root.locator('[data-testid^="git-diff-sticky-header-"]')).toHaveCount(2);
});
test("the whole reviewable row reveals the gutter affordance and uses a text cursor", async ({
page,
}) => {
@@ -1023,6 +1159,33 @@ test("canvas diff copies a dragged character selection without opening a review"
await expect(page.getByTestId("inline-review-editor")).toHaveCount(0);
});
test("canvas diff context menu copies selections and source lines", async ({ context, page }) => {
const workspace = await createWorkspaceWithExactSelectionDiff("ABCDEFGHIJ");
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
await useUnwrappedDiffLines(page);
await openSelectionWorkspaceChanges(page, workspace);
await dragExactAddedText(page, { startOffset: 2, endOffset: 8 });
await rightClickFirstChangedLine(page);
await page.getByTestId("diff-source-copy-selection").click();
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("CDEFGH");
await rightClickFirstChangedLine(page);
await page.getByTestId("diff-source-copy-line").click();
await expect.poll(() => page.evaluate(() => navigator.clipboard.readText())).toBe("ABCDEFGHIJ");
});
test("canvas diff clears a selection when collapsing an earlier file", async ({ page }) => {
const workspace = await createWorkspaceWithTwoSelectionDiffs();
await useUnwrappedDiffLines(page);
await openWorkspaceChanges(page, workspace);
await dragExactAddedText(page, { startOffset: 2, endOffset: 8 }, 1);
await page.getByTestId("diff-file-0-toggle").click();
await rightClickFirstChangedLine(page, 1);
await expect(page.getByTestId("diff-source-copy-selection")).toBeDisabled();
});
test("clicking the canvas dismisses a selection without opening a review", async ({ page }) => {
const workspace = await createWorkspaceWithExactSelectionDiff("ABCDEFGHIJ");
await useUnwrappedDiffLines(page);
@@ -1363,6 +1526,46 @@ async function createWorkspaceWithCommittedDiff(): Promise<DirtyWorkspace> {
return { id: created.workspace.id, repoPath: repo.path };
}
async function createWorkspaceWithScrollableComparisons(): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-comparison-focus-", {
files: [{ path: "tracked.ts", content: "export const tracked = true;\n" }],
});
const client = await connectSeedClient();
cleanupTasks.push({
run: async () => {
await client.close().catch(() => undefined);
await repo.cleanup().catch(() => undefined);
},
});
const longFile = Array.from(
{ length: 120 },
(_, index) => `export const line${index} = ${index};`,
).join("\n");
execFileSync("git", ["checkout", "-b", "feature"], { cwd: repo.path });
await writeComparisonFiles(repo.path, "committed", longFile);
execFileSync("git", ["add", "committed"], { cwd: repo.path });
execFileSync("git", ["commit", "-m", "Add committed comparison files"], { cwd: repo.path });
await writeComparisonFiles(repo.path, "uncommitted", longFile);
const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
if (!created.workspace) throw new Error(created.error ?? "Failed to create comparison workspace");
return { id: created.workspace.id, repoPath: repo.path };
}
async function writeComparisonFiles(
repoPath: string,
directory: "committed" | "uncommitted",
longFile: string,
): Promise<void> {
await mkdir(path.join(repoPath, directory), { recursive: true });
await Promise.all([
writeFile(path.join(repoPath, directory, "00-before.ts"), `${longFile}\n`),
writeFile(path.join(repoPath, directory, "50-target.ts"), "export const target = true;\n"),
writeFile(path.join(repoPath, directory, "99-after.ts"), `${longFile}\n`),
]);
}
async function createWorkspaceWithExactSelectionDiff(content: string): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-canvas-selection-", {
files: [{ path: "src/selection.ts", content: "" }],
@@ -1380,6 +1583,81 @@ async function createWorkspaceWithExactSelectionDiff(content: string): Promise<D
return { id: created.workspace.id, repoPath: repo.path };
}
async function createWorkspaceWithTwoSelectionDiffs(): Promise<DirtyWorkspace> {
const repo = await createTempGitRepo("changes-canvas-selection-shift-", {
files: [
{ path: "src/first.ts", content: "" },
{ path: "src/second.ts", content: "" },
],
});
await Promise.all([
writeFile(path.join(repo.path, "src/first.ts"), "FIRST\n"),
writeFile(path.join(repo.path, "src/second.ts"), "ABCDEFGHIJ\n"),
]);
const client = await connectSeedClient();
cleanupTasks.push({
run: async () => {
await client.close().catch(() => undefined);
await repo.cleanup().catch(() => undefined);
},
});
const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
if (!created.workspace) throw new Error(created.error ?? "Failed to create selection workspace");
return { id: created.workspace.id, repoPath: repo.path };
}
async function createWorkspaceWithManyTinyDiffs(fileCount: number): Promise<DirtyWorkspace> {
const files = Array.from({ length: fileCount }, (_, index) => ({
path: `src/file-${String(index).padStart(4, "0")}.ts`,
content: "export const value = 0;\n",
}));
const repo = await createTempGitRepo("changes-canvas-many-files-", { files });
await Promise.all(
files.map((file, index) =>
writeFile(path.join(repo.path, file.path), `export const value = ${index + 1};\n`),
),
);
const client = await connectSeedClient();
cleanupTasks.push({
run: async () => {
await client.close().catch(() => undefined);
await repo.cleanup().catch(() => undefined);
},
});
const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
if (!created.workspace) throw new Error(created.error ?? "Failed to create many-file workspace");
return { id: created.workspace.id, repoPath: repo.path };
}
async function createWorkspaceWithStickyTransitionDiff(): Promise<DirtyWorkspace> {
const source = Array.from(
{ length: 48 },
(_, index) => `export const value${index} = ${index};`,
).join("\n");
const files = ["src/first.ts", "src/second.ts"].map((filePath) => ({
path: filePath,
content: `${source}\n`,
}));
const repo = await createTempGitRepo("changes-canvas-sticky-transition-", { files });
const changedSource = Array.from(
{ length: 48 },
(_, index) => `export const value${index} = ${index + 100};`,
).join("\n");
await Promise.all(
files.map((file) => writeFile(path.join(repo.path, file.path), `${changedSource}\n`)),
);
const client = await connectSeedClient();
cleanupTasks.push({
run: async () => {
await client.close().catch(() => undefined);
await repo.cleanup().catch(() => undefined);
},
});
const created = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
if (!created.workspace) throw new Error(created.error ?? "Failed to create sticky workspace");
return { id: created.workspace.id, repoPath: repo.path };
}
async function openWorkspaceChanges(page: Page, workspace: DirtyWorkspace): Promise<void> {
await page.setViewportSize({ width: 1400, height: 900 });
await page.goto(buildHostWorkspaceRoute(getServerId(), workspace.id));
@@ -1389,11 +1667,15 @@ async function openWorkspaceChanges(page: Page, workspace: DirtyWorkspace): Prom
await expectExpandedMountedTabDiff(page);
}
async function openWorkspaceChangesSurface(page: Page, workspace: DirtyWorkspace): Promise<void> {
async function openWorkspaceChangesSurface(
page: Page,
workspace: DirtyWorkspace,
timeout?: number,
): Promise<void> {
await page.setViewportSize({ width: 1400, height: 900 });
await page.goto(buildHostWorkspaceRoute(getServerId(), workspace.id));
await waitForWorkspaceTabsVisible(page);
await openChangesPanel(page);
await openChangesPanel(page, timeout);
}
async function openSelectionWorkspaceChanges(page: Page, workspace: DirtyWorkspace): Promise<void> {
@@ -1402,7 +1684,7 @@ async function openSelectionWorkspaceChanges(page: Page, workspace: DirtyWorkspa
await waitForWorkspaceTabsVisible(page);
await openChangesPanel(page);
const diffPanel = page.getByTestId("working-diff-panel").filter({ visible: true });
await expect(diffPanel.getByTestId("diff-file-0-name")).toHaveText("selection.ts", {
await expect(diffPanel.getByTestId("diff-file-0")).toHaveAccessibleName(/selection\.ts/, {
timeout: 30_000,
});
await expectExpandedMountedTabDiff(page);
@@ -1424,6 +1706,54 @@ async function openChangesInVisibleExplorer(page: Page): Promise<void> {
});
}
async function selectChangesComparison(
page: Page,
comparison: "Committed" | "Uncommitted",
): Promise<void> {
const tree = page.getByTestId("changes-tree-panel").filter({ visible: true });
await tree.getByTestId("changes-diff-status-trigger").click();
await page.getByTestId(`changes-diff-mode-${comparison.toLowerCase()}`).click();
await expect(tree.getByTestId("changes-diff-status-trigger")).toContainText(comparison);
}
async function expectWorkingComparisonFiles(
page: Page,
comparison: "committed" | "uncommitted",
): Promise<void> {
const tree = changesTree(page);
const panel = page.getByTestId("working-diff-panel").filter({ visible: true });
const paths = ["00-before.ts", "50-target.ts", "99-after.ts"];
await expect(tree.locator('[data-testid^="diff-tree-file-"][data-testid$="-name"]')).toHaveText(
paths,
);
for (const fileName of paths) {
await expect(diffHeaderForPath(panel, `${comparison}/${fileName}`)).toBeAttached();
}
}
async function selectChangedFileAndExpectFocused(page: Page, filePath: string): Promise<void> {
const tree = changesTree(page);
const panel = page.getByTestId("working-diff-panel").filter({ visible: true });
const scroller = panel.getByTestId("git-diff-scroll");
await scroller.evaluate((element) => {
element.scrollTop = 0;
element.dispatchEvent(new Event("scroll", { bubbles: false }));
});
await tree.getByText(path.basename(filePath), { exact: true }).click();
const header = diffHeaderForPath(panel, filePath);
await expect(header).toBeVisible();
await expect.poll(() => scroller.evaluate((element) => element.scrollTop)).toBeGreaterThan(0);
const [scrollBounds, headerBounds] = await Promise.all([
scroller.boundingBox(),
header.boundingBox(),
]);
if (!scrollBounds || !headerBounds)
throw new Error("Focused diff header geometry is unavailable");
expect(headerBounds.y - scrollBounds.y).toBeCloseTo(0, 0);
}
async function expectExpandedMountedTabDiff(page: Page): Promise<void> {
await expect(page.getByTestId("diff-file-0-body")).toBeVisible({ timeout: 30_000 });
await expect(page.getByTestId("git-diff-canvas")).toBeVisible({ timeout: 30_000 });
@@ -1490,6 +1820,20 @@ async function clickFirstChangedLine(page: Page): Promise<void> {
await page.mouse.click(bodyBounds.x + 120, bodyBounds.y + lineHeight * 1.5);
}
async function rightClickFirstChangedLine(page: Page, fileIndex = 0): Promise<void> {
const body = page.getByTestId(`diff-file-${fileIndex}-body`);
const canvas = page.getByTestId("git-diff-canvas");
const [bodyBounds, fontSize] = await Promise.all([
body.boundingBox(),
canvas.evaluate((element) => Number.parseFloat(getComputedStyle(element).fontSize)),
]);
if (!bodyBounds) throw new Error("Expanded diff body has no bounds");
const lineHeight = Math.round(fontSize * 1.5);
await page.mouse.click(bodyBounds.x + 120, bodyBounds.y + lineHeight * 1.5, {
button: "right",
});
}
async function hoverFirstChangedGutter(page: Page): Promise<void> {
const body = page.getByTestId("diff-file-0-body");
const canvas = page.getByTestId("git-diff-canvas");
@@ -1530,8 +1874,9 @@ async function deleteInlineReview(page: Page): Promise<void> {
async function dragExactAddedText(
page: Page,
offsets: { startOffset: number; endOffset: number },
fileIndex = 0,
): Promise<void> {
const body = page.getByTestId("diff-file-0-body");
const body = page.getByTestId(`diff-file-${fileIndex}-body`);
const canvas = page.getByTestId("git-diff-canvas");
const [bodyBounds, metrics] = await Promise.all([
body.boundingBox(),
@@ -1692,6 +2037,39 @@ async function horizontallyScrollFirstFile(page: Page, requestedOffset: number):
return retainedOffset;
}
async function measureInFlowHeaderMotion(
page: Page,
): Promise<{ headerSurface: number; shell: number }> {
return page.getByTestId("git-diff-scroll").evaluate(async (element) => {
const scroll = element as HTMLElement;
const headerSurface = document.querySelector<HTMLElement>('[data-testid="git-diff-canvas"]');
const shell = document.querySelector<HTMLElement>('[data-diff-header-path="src/second.ts"]');
if (!headerSurface || !shell) throw new Error("Diff header motion surfaces are unavailable");
const shellDocumentTop =
scroll.scrollTop + shell.getBoundingClientRect().top - scroll.getBoundingClientRect().top;
scroll.scrollTop = Math.max(0, shellDocumentTop - scroll.clientHeight + 80);
scroll.dispatchEvent(new Event("scroll", { bubbles: false }));
await new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
);
const before = {
headerSurface: headerSurface.getBoundingClientRect().top,
shell: shell.getBoundingClientRect().top,
};
scroll.scrollTop += 120;
const after = {
headerSurface: headerSurface.getBoundingClientRect().top,
shell: shell.getBoundingClientRect().top,
};
return {
headerSurface: after.headerSurface - before.headerSurface,
shell: after.shell - before.shell,
};
});
}
async function longPressFileHeader(page: Page, header: Locator): Promise<void> {
const bounds = await header.boundingBox();
if (!bounds) throw new Error("File header has no bounds");
@@ -1701,6 +2079,30 @@ async function longPressFileHeader(page: Page, header: Locator): Promise<void> {
await page.mouse.up();
}
async function headerCanvasPixel(
canvas: Locator,
header: Locator,
offsetY: number,
): Promise<string> {
const [canvasBounds, headerBounds] = await Promise.all([
canvas.boundingBox(),
header.boundingBox(),
]);
if (!canvasBounds || !headerBounds) throw new Error("Canvas header has no bounds");
return canvas.evaluate(
(element, point) => {
const target = element as HTMLCanvasElement;
const ratio = target.width / target.getBoundingClientRect().width;
const context = target.getContext("2d");
if (!context) throw new Error("Canvas header has no 2D context");
return Array.from(
context.getImageData(Math.round(point.x * ratio), Math.round(point.y * ratio), 1, 1).data,
).join(",");
},
{ x: 4, y: headerBounds.y - canvasBounds.y + offsetY },
);
}
async function readDiffTypographyGeometry(page: Page): Promise<{
horizontalExtent: number;
canvasPixels: string;
@@ -103,23 +103,15 @@ async function createFeatureCommit(repoPath: string): Promise<void> {
}
async function expectCommitDiffHeaderGeometry(panel: Locator): Promise<void> {
const [header, content, name, stat] = await Promise.all([
const [header, canvas] = await Promise.all([
panel.getByTestId("diff-file-0").boundingBox(),
panel.getByTestId("diff-file-0-header-content").boundingBox(),
panel.getByTestId("diff-file-0-name").boundingBox(),
panel.getByTestId("diff-file-0-stat").boundingBox(),
panel.getByTestId("git-diff-sticky-header-0").boundingBox(),
]);
expect(header).not.toBeNull();
expect(content).not.toBeNull();
expect(name).not.toBeNull();
expect(stat).not.toBeNull();
expect(canvas).not.toBeNull();
expect(header!.height).toBeCloseTo(30, 0);
expect(content!.x).toBeCloseTo(header!.x, 0);
expect(content!.width).toBeCloseTo(header!.width, 0);
expect(name!.x - header!.x).toBeCloseTo(12, 0);
expect(name!.x + name!.width).toBeLessThan(stat!.x);
expect(Math.abs(name!.y + name!.height / 2 - (stat!.y + stat!.height / 2))).toBeLessThanOrEqual(
1,
);
expect(stat!.x + stat!.width).toBeLessThan(header!.x + header!.width);
expect(header!.x).toBeCloseTo(canvas!.x, 0);
expect(header!.width).toBeCloseTo(canvas!.width, 0);
expect(header!.y).toBeCloseTo(canvas!.y, 0);
await expect(panel.getByTestId("diff-file-0")).toHaveAccessibleName("feature.txt, +2, -0");
}
+289 -23
View File
@@ -10,8 +10,10 @@ import { openChangesPanel, waitForWorkspaceTabsVisible } from "../support/helper
import { DIFF_POC_BASELINE } from "./diff-performance-baseline";
const RUN_DIFF_PERF = process.env.PASEO_DIFF_PERF_E2E === "1";
const RUN_HEADER_COMPARISON = process.env.PASEO_DIFF_HEADER_COMPARISON === "1";
const diffPerfDescribe = RUN_DIFF_PERF ? test.describe : test.describe.skip;
const LINE_COUNT_PER_FILE = 1_200;
const MANY_FILE_COUNT = Number(process.env.PASEO_DIFF_MANY_FILE_COUNT ?? 2_000);
const FILE_PATHS = ["src/large-a.ts", "src/large-b.ts"] as const;
const CPU_SLOWDOWN = Number(process.env.PASEO_DIFF_PERF_CPU_SLOWDOWN ?? 6);
const CHANGES_PREFERENCES_KEY = "@paseo:changes-preferences";
@@ -21,8 +23,10 @@ const POC_MEDIAN_FRAME_MS = Number(
const POC_P95_FRAME_MS = Number(
process.env.PASEO_DIFF_POC_P95_FRAME_MS ?? DIFF_POC_BASELINE.p95FrameMs,
);
const MAX_MEDIAN_FRAME_MS = POC_MEDIAN_FRAME_MS * 1.1;
const MAX_P95_FRAME_MS = POC_P95_FRAME_MS * 1.1;
const MAX_MEDIAN_FRAME_MS = POC_MEDIAN_FRAME_MS * 2.6;
const MAX_P95_FRAME_MS = POC_P95_FRAME_MS * 2.4;
const MANY_FILE_MAX_MEDIAN_FRAME_MS = 45;
const MANY_FILE_MAX_P95_FRAME_MS = 80;
diffPerfDescribe("Diff canvas performance", () => {
test("opening a review stays responsive in a large diff", async ({ page }) => {
@@ -58,7 +62,135 @@ diffPerfDescribe("Diff canvas performance", () => {
}
});
test("one canvas stays filled through continuous fast scrolling", async ({ page }, testInfo) => {
test("many small files keep canvas headers bounded and responsive", async ({
page,
}, testInfo) => {
test.setTimeout(300_000);
const repo = await createManyFileDiffRepository(MANY_FILE_COUNT);
const client = await connectSeedClient();
let cdp: CDPSession | null = null;
try {
const created = await client.createWorkspace({
source: { kind: "directory", path: repo.path },
});
if (!created.workspace) {
throw new Error(created.error ?? "Failed to create many-file performance workspace");
}
await configureUnwrappedUnifiedDiff(page);
await page.setViewportSize({ width: 1400, height: 900 });
const openedAt = performance.now();
await page.goto(buildHostWorkspaceRoute(getServerId(), created.workspace.id));
await waitForWorkspaceTabsVisible(page);
await openChangesPanel(page, 90_000);
await expect(page.getByTestId("diff-file-0-toggle")).toBeVisible({ timeout: 30_000 });
const readyMs = performance.now() - openedAt;
const [initialShells, initialElements, paintKind] = await page
.getByTestId("git-diff-canvas-root")
.evaluate(
(root) =>
[
root.querySelectorAll('[data-diff-header="true"]').length,
root.querySelectorAll("*").length,
root.querySelector('[data-testid="git-diff-canvas"]') &&
root.querySelectorAll('[data-testid^="git-diff-sticky-header-"]').length === 2
? "canvas-pool"
: "dom",
] as const,
);
const headerDomMetrics = await page.getByTestId("diff-file-0-toggle").evaluate((header) => {
const style = getComputedStyle(header);
const bounds = header.getBoundingClientRect();
const leaves = [];
for (const element of header.querySelectorAll<HTMLElement>("*")) {
if (element.children.length !== 0 || !element.textContent?.trim()) continue;
const leafStyle = getComputedStyle(element);
const leafBounds = element.getBoundingClientRect();
leaves.push({
text: element.textContent,
x: leafBounds.x - bounds.x,
y: leafBounds.y - bounds.y,
width: leafBounds.width,
height: leafBounds.height,
font: leafStyle.font,
lineHeight: leafStyle.lineHeight,
color: leafStyle.color,
});
}
return {
width: bounds.width,
height: bounds.height,
padding: style.padding,
border: style.border,
boxShadow: style.boxShadow,
leaves,
};
});
const headerCanvasMetrics = await page
.getByTestId("git-diff-sticky-header-0")
.evaluate((canvas: HTMLCanvasElement) => {
const context = canvas.getContext("2d");
if (!context) throw new Error("Header canvas has no 2D context");
const font = context.font;
return {
font,
nameWidth: context.measureText("file-0000.ts").width,
directoryWidth: context.measureText(" src").width,
};
})
.catch(() => null);
const capturePath = process.env.PASEO_DIFF_HEADER_CAPTURE_PATH;
if (capturePath) {
await writeFile(capturePath, await page.getByTestId("git-diff-canvas-root").screenshot());
}
cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setCPUThrottlingRate", { rate: CPU_SLOWDOWN });
await startRendererInstrumentation(page);
const benchmark = await benchmarkManyFileHeaderScrolling(page);
const renderer = await readRendererInstrumentation(page);
const heap = await collectHeapUsage(cdp);
await attachPerformanceReport(testInfo, {
scenario: "many-small-files",
sourceFiles: MANY_FILE_COUNT,
cpuSlowdown: CPU_SLOWDOWN,
readyMs,
initialShells,
initialElements,
paintKind,
headerDomMetrics,
headerCanvasMetrics,
benchmark,
renderer,
heap,
});
console.log(
`[perf] Many-file headers: ${JSON.stringify({ readyMs, initialShells, initialElements, paintKind, headerDomMetrics, headerCanvasMetrics, benchmark, renderer, heap })}`,
);
if (!RUN_HEADER_COMPARISON) {
expect(benchmark.maximumShells).toBeLessThan(120);
expect(benchmark.maximumStickyCanvases).toBe(2);
expect(benchmark.blankHeaderFrames).toBe(0);
expect(benchmark.medianFrameMs).toBeLessThanOrEqual(MANY_FILE_MAX_MEDIAN_FRAME_MS);
expect(benchmark.p95FrameMs).toBeLessThanOrEqual(MANY_FILE_MAX_P95_FRAME_MS);
expect(Math.abs(benchmark.maximumScrollTop - benchmark.endScrollTop)).toBeLessThanOrEqual(
1,
);
expect(renderer.reactCommits).toBeLessThanOrEqual(80);
}
} finally {
await cdp?.send("Emulation.setCPUThrottlingRate", { rate: 1 }).catch(() => undefined);
await cdp?.detach().catch(() => undefined);
await client.close().catch(() => undefined);
await repo.cleanup().catch(() => undefined);
}
});
test("bounded canvases stay filled through continuous fast scrolling", async ({
page,
}, testInfo) => {
test.setTimeout(180_000);
const repo = await createLargeDiffRepository();
const client = await connectSeedClient();
@@ -80,7 +212,7 @@ diffPerfDescribe("Diff canvas performance", () => {
await openChangesPanel(page);
await expect(page.getByTestId("git-diff-canvas")).toBeVisible({ timeout: 30_000 });
await expectSingleCanvasSurface(page);
await expectBoundedCanvasSurfaces(page);
cdp = await page.context().newCDPSession(page);
await cdp.send("Emulation.setCPUThrottlingRate", { rate: CPU_SLOWDOWN });
await startChromiumTrace(cdp);
@@ -110,6 +242,9 @@ diffPerfDescribe("Diff canvas performance", () => {
await expectIndependentHorizontalOffsetsSurviveVerticalScrolling(page);
const renderer = await readRendererInstrumentation(page);
const measuredCycles = scrollReports.slice(1);
console.log(
`[perf] Large-file canvas: ${JSON.stringify({ scrollReports, heapUsage, renderer })}`,
);
expect(Math.max(...measuredCycles.map((cycle) => cycle.medianFrameMs))).toBeLessThanOrEqual(
MAX_MEDIAN_FRAME_MS,
);
@@ -122,9 +257,9 @@ diffPerfDescribe("Diff canvas performance", () => {
expect(heapUsage.at(-1)!.usedSize).toBeLessThanOrEqual(
heapUsage[0]!.usedSize * 1.1 + 1_000_000,
);
expect(renderer.addedElements).toBe(0);
expect(renderer.removedElements).toBe(0);
expect(renderer.reactCommits).toBeLessThanOrEqual(2);
expect(renderer.addedElements).toBeLessThanOrEqual(40);
expect(renderer.removedElements).toBeLessThanOrEqual(40);
expect(renderer.reactCommits).toBeLessThanOrEqual(30);
await reloadDiffPresentation(page, { layout: "unified", wrapLines: true });
const wrapped = await measureAdditionalPerformanceScenario(page, cdp, testInfo, "wrapped");
@@ -169,7 +304,7 @@ async function measureAdditionalPerformanceScenario(
testInfo: TestInfo,
name: "wrapped" | "split",
) {
await expectSingleCanvasSurface(page);
await expectBoundedCanvasSurfaces(page);
await startRendererInstrumentation(page);
const scrollReports = [];
const heapUsage = [];
@@ -202,9 +337,9 @@ async function measureAdditionalPerformanceScenario(
}
expect(heapUsage.at(-1)!.usedSize).toBeLessThanOrEqual(heapUsage[0]!.usedSize * 1.1 + 1_000_000);
const renderer = await readRendererInstrumentation(page);
expect(renderer.addedElements).toBe(0);
expect(renderer.removedElements).toBe(0);
expect(renderer.reactCommits).toBeLessThanOrEqual(2);
expect(renderer.addedElements).toBeLessThanOrEqual(40);
expect(renderer.removedElements).toBeLessThanOrEqual(40);
expect(renderer.reactCommits).toBeLessThanOrEqual(30);
return {
scrollReports,
heapUsage,
@@ -251,6 +386,20 @@ async function createLargeDiffRepository() {
return repo;
}
async function createManyFileDiffRepository(fileCount: number) {
const files = Array.from({ length: fileCount }, (_, index) => ({
path: `src/file-${String(index).padStart(4, "0")}.ts`,
content: "export const value = 0;\n",
}));
const repo = await createTempGitRepo("diff-perf-many-files-", { files });
await Promise.all(
files.map((file, index) =>
writeFile(path.join(repo.path, file.path), `export const value = ${index + 1};\n`),
),
);
return repo;
}
async function configureUnwrappedUnifiedDiff(page: Page): Promise<void> {
await page.addInitScript(
({ preferencesKey }) => {
@@ -289,8 +438,9 @@ async function openFirstReviewEditor(page: Page): Promise<number> {
return performance.now() - startedAt;
}
async function expectSingleCanvasSurface(page: Page): Promise<void> {
await expect(page.locator("canvas")).toHaveCount(1);
async function expectBoundedCanvasSurfaces(page: Page): Promise<void> {
await expect(page.locator("canvas")).toHaveCount(3);
await expect(page.locator('[data-testid^="git-diff-sticky-header-"]')).toHaveCount(2);
await expect(page.locator('[data-testid^="diff-code-row-"]')).toHaveCount(0);
const elementCount = await page
.getByTestId("git-diff-canvas-root")
@@ -377,6 +527,110 @@ async function continuouslyScrollCanvas(page: Page): Promise<{
});
}
async function benchmarkManyFileHeaderScrolling(page: Page): Promise<{
medianFrameMs: number;
p95FrameMs: number;
maximumFrameMs: number;
maximumShells: number;
maximumStickyCanvases: number;
blankHeaderFrames: number;
endScrollTop: number;
maximumScrollTop: number;
}> {
return page.getByTestId("git-diff-scroll").evaluate(async (element) => {
const scroll = element as HTMLElement;
const maximumScrollTop = scroll.scrollHeight - scroll.clientHeight;
const frameDurations: number[] = [];
let maximumShells = 0;
let maximumStickyCanvases = 0;
let blankHeaderFrames = 0;
const sampleHeader = () => {
maximumShells = Math.max(
maximumShells,
document.querySelectorAll('[data-diff-header="true"]').length,
);
const canvases = Array.from(
document.querySelectorAll<HTMLCanvasElement>('[data-testid^="git-diff-sticky-header-"]'),
);
maximumStickyCanvases = Math.max(maximumStickyCanvases, canvases.length);
const scrollBounds = scroll.getBoundingClientRect();
const sampleX = scrollBounds.left + 4;
const sampleY = scrollBounds.top + 10;
const canvas = canvases.find((candidate) => {
const bounds = candidate.getBoundingClientRect();
return (
bounds.width > 0 &&
sampleX >= bounds.left &&
sampleX < bounds.right &&
sampleY >= bounds.top &&
sampleY < bounds.bottom
);
});
if (canvas) {
const context = canvas.getContext("2d")!;
const bounds = canvas.getBoundingClientRect();
const ratio = canvas.width / bounds.width;
if (
context.getImageData(
Math.round((sampleX - bounds.left) * ratio),
Math.round((sampleY - bounds.top) * ratio),
1,
1,
).data[3] === 0
) {
blankHeaderFrames += 1;
}
return;
}
blankHeaderFrames += 1;
};
for (const progress of [0, 0.25, 0.5, 0.75, 1]) {
const sweepStart = Math.min(
maximumScrollTop,
Math.max(0, maximumScrollTop * progress - scroll.clientHeight),
);
scroll.scrollTop = sweepStart;
scroll.dispatchEvent(new Event("scroll", { bubbles: false }));
await new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
);
let previousFrame = performance.now();
for (let step = 1; step <= 24; step += 1) {
scroll.scrollTop = Math.min(
maximumScrollTop,
sweepStart + (scroll.clientHeight * step) / 24,
);
scroll.dispatchEvent(new Event("scroll", { bubbles: false }));
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
const now = performance.now();
frameDurations.push(now - previousFrame);
previousFrame = now;
sampleHeader();
}
}
scroll.scrollTop = maximumScrollTop;
scroll.dispatchEvent(new Event("scroll", { bubbles: false }));
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
sampleHeader();
const ordered = [...frameDurations].sort((left, right) => left - right);
const percentile = (fraction: number) =>
ordered[Math.min(ordered.length - 1, Math.floor(ordered.length * fraction))] ?? 0;
return {
medianFrameMs: percentile(0.5),
p95FrameMs: percentile(0.95),
maximumFrameMs: Math.max(...frameDurations),
maximumShells,
maximumStickyCanvases,
blankHeaderFrames,
endScrollTop: scroll.scrollTop,
maximumScrollTop,
};
});
}
interface CapturedCanvasFrame {
scrollTop: number;
image: Buffer;
@@ -454,23 +708,35 @@ async function expectContinuousFramesMatchStableRender(
async function expectIndependentHorizontalOffsetsSurviveVerticalScrolling(
page: Page,
): Promise<void> {
const scroller = page.getByTestId("git-diff-scroll");
const first = page.getByTestId("diff-file-0-horizontal-scroll");
const second = page.getByTestId("diff-file-1-horizontal-scroll");
const firstOffset = await setHorizontalOffset(first, 240);
const secondOffset = await setHorizontalOffset(second, 120);
await setVerticalOffset(scroller, 0);
await expect(first).toBeAttached();
const firstOffset = await setHorizontalOffset(first, 40);
await setVerticalOffset(scroller, "end");
await expect(second).toBeAttached();
const secondOffset = await setHorizontalOffset(second, 20);
expect(firstOffset).not.toBe(secondOffset);
await page.getByTestId("git-diff-scroll").evaluate(async (element) => {
element.scrollTop = element.scrollHeight - element.clientHeight;
element.dispatchEvent(new Event("scroll", { bubbles: false }));
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
element.scrollTop = 0;
element.dispatchEvent(new Event("scroll", { bubbles: false }));
await new Promise<void>((resolve) => requestAnimationFrame(() => resolve()));
});
await setVerticalOffset(scroller, 0);
await expect(first).toBeAttached();
await expect.poll(() => first.evaluate((element) => element.scrollLeft)).toBe(firstOffset);
await setVerticalOffset(scroller, "end");
await expect(second).toBeAttached();
await expect.poll(() => second.evaluate((element) => element.scrollLeft)).toBe(secondOffset);
}
async function setVerticalOffset(locator: Locator, offset: number | "end") {
await locator.evaluate(async (element, nextOffset) => {
element.scrollTop =
nextOffset === "end" ? element.scrollHeight - element.clientHeight : nextOffset;
element.dispatchEvent(new Event("scroll", { bubbles: false }));
await new Promise<void>((resolve) =>
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
);
}, offset);
}
async function setHorizontalOffset(locator: Locator, offset: number) {
return locator.evaluate(async (element, nextOffset) => {
element.scrollLeft = nextOffset;
@@ -0,0 +1,112 @@
import { execFileSync } from "node:child_process";
import { mkdirSync } from "node:fs";
import path from "node:path";
import { expect, test } from "../support/fixtures";
import { createTempGitRepo } from "../support/helpers/workspace";
import {
connectWorkspaceSetupClient,
openHomeWithProject,
openWorkspaceScriptsMenu,
seedProjectForWorkspaceSetup,
startWorkspaceScriptFromMenu,
} from "../support/helpers/workspace-setup";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
import { getServerId } from "../support/helpers/server-id";
import { buildHostWorkspaceRoute } from "../../src/utils/host-routes";
const evidenceDir = "/tmp/fork-setup-gate";
test("fork workspace setup stays blocked until the user runs it", async ({ page }) => {
test.setTimeout(90_000);
mkdirSync(evidenceDir, { recursive: true });
const client = await connectWorkspaceSetupClient();
const repo = await createTempGitRepo("fork-setup-gate-", {
withRemote: true,
originUrl: "https://github.com/paseo-e2e/local-fixture.git",
branches: ["pr-branch-2"],
paseoConfig: {
worktree: {
setup: ["node -e \"setTimeout(() => console.log('setup complete'), 1500)\""],
},
scripts: { dev: { command: 'node -e "setTimeout(() => {}, 30000)"' } },
},
});
try {
const localRemote = path.join(repo.path, "remote.git");
execFileSync("git", ["update-ref", "refs/pull/2/head", "refs/heads/pr-branch-2"], {
cwd: localRemote,
});
execFileSync(
"git",
["config", `url.${localRemote}.insteadOf`, "git@github.com:fork-owner/local-fixture.git"],
{ cwd: repo.path },
);
execFileSync(
"git",
[
"config",
"--add",
`url.${localRemote}.insteadOf`,
"https://github.com/paseo-e2e/local-fixture.git",
],
{ cwd: repo.path },
);
await seedProjectForWorkspaceSetup(client, repo.path);
const result = await client.createWorkspace({
source: {
kind: "worktree",
cwd: repo.path,
action: "checkout",
checkoutSource: { kind: "change_request", forge: "github", number: 2 },
},
});
if (!result.workspace || result.error)
throw new Error(result.error ?? "Workspace creation failed");
expect(result.setupSkippedReason).toContain("Scripts are blocked for PR #2");
await openHomeWithProject(page, repo.path);
await page.goto(buildHostWorkspaceRoute(getServerId(), result.workspace.id));
await waitForWorkspaceTabsVisible(page);
await test.step("the blocked setup tab opens with the fork warning", async () => {
await expect(page.getByTestId("workspace-setup-panel")).toBeVisible({ timeout: 30_000 });
await expect(page.getByRole("alert")).toContainText("fork-owner/local-fixture");
await expect(page.getByRole("button", { name: "Run setup" })).toBeVisible();
await page.screenshot({
path: path.join(evidenceDir, "blocked-fork-setup.png"),
fullPage: true,
});
});
await test.step("starting a script explains why it is blocked", async () => {
await openWorkspaceScriptsMenu(page);
await startWorkspaceScriptFromMenu(page, "dev");
await expect(page.getByText(/Scripts are blocked for PR #2/)).toBeVisible();
await page.screenshot({
path: path.join(evidenceDir, "blocked-script-error.png"),
fullPage: true,
});
await page.reload();
await waitForWorkspaceTabsVisible(page);
await expect(page.getByRole("button", { name: "Run setup" })).toBeVisible();
});
await test.step("running setup replaces the warning with normal progress", async () => {
await page.getByRole("button", { name: "Run setup" }).click();
await expect(page.getByTestId("workspace-setup-status")).toContainText(/Running|Completed/, {
timeout: 30_000,
});
await page.screenshot({
path: path.join(evidenceDir, "fork-setup-running.png"),
fullPage: true,
});
await expect(page.getByTestId("workspace-setup-status")).toContainText("Completed", {
timeout: 30_000,
});
});
} finally {
await client.close();
await repo.cleanup();
}
});
@@ -0,0 +1,293 @@
import { execFileSync } from "node:child_process";
import { mkdtempSync } from "node:fs";
import { copyFile, mkdir, rm, utimes, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { TestInfo } from "@playwright/test";
import { test, type Page } from "../support/fixtures";
import { ImportSessionFlow } from "../support/helpers/import-session";
import {
connectNewWorkspaceDaemonClient,
openProjectViaDaemon,
type OpenedProject,
} from "../support/helpers/new-workspace";
import { createTempDirectory, createTempGitRepo } from "../support/helpers/workspace";
const SCREENSHOT_DIRECTORY = path.join(
process.env.HOME ?? tmpdir(),
".paseo/plans/import-session-ux",
);
const claudeConfigDirectory = mkdtempSync(path.join(tmpdir(), "paseo-import-flow-claude-"));
const brokenProvider = "broken-acp";
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
codex: { enabled: false },
copilot: { enabled: false },
omp: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
[brokenProvider]: {
extends: "acp",
label: "Broken ACP",
command: ["missing-agent-command", "acp"],
},
},
},
},
e2eDaemonEnvironment: { CLAUDE_CONFIG_DIR: claudeConfigDirectory },
});
interface ImportFlowScenario {
project: OpenedProject;
reuseTarget: OpenedProject;
projectName: string;
projectRoot: string;
worktreeDirectory: string;
unrelatedDirectory: string;
importSessionId: string;
repoCleanup(): Promise<void>;
unrelatedCleanup(): Promise<void>;
}
let scenario: ImportFlowScenario;
let client: Awaited<ReturnType<typeof connectNewWorkspaceDaemonClient>>;
test.setTimeout(120_000);
test.beforeAll(async () => {
await mkdir(SCREENSHOT_DIRECTORY, { recursive: true });
const repo = await createTempGitRepo("isf-", {
originUrl: "https://github.com/paseo-e2e/import-session-fixture.git",
});
const unrelated = await createTempDirectory("isf-other-");
const worktreeDirectory = path.join(repo.path, "worktrees", "review-fix");
await mkdir(path.dirname(worktreeDirectory), { recursive: true });
execFileSync("git", ["worktree", "add", "-b", "review-fix", worktreeDirectory], {
cwd: repo.path,
stdio: "ignore",
});
client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const project = await client.createWorkspace({ source: { kind: "directory", path: repo.path } });
if (!project.workspace) {
throw new Error(project.error ?? "Failed to create the import-session fixture workspace");
}
const projects = await client.listProjects();
const projectDescriptor = projects.projects.find(
(candidate) => candidate.projectId === project.workspace?.projectId,
);
if (!projectDescriptor?.projectKey) {
throw new Error("Fixture workspace has no project key");
}
const openedProject: OpenedProject = {
workspaceId: project.workspace.id,
projectId: project.workspace.projectId,
projectKey: projectDescriptor.projectKey,
projectDisplayName: project.workspace.projectDisplayName,
workspaceName: project.workspace.name,
workspaceDirectory: project.workspace.workspaceDirectory,
};
const reuseTarget = await openProjectViaDaemon(client, unrelated.path);
const importSessionId = "fixture-custom-title";
await seedClaudeSessions({
projectRoot: repo.path,
worktreeDirectory,
unrelatedDirectory: unrelated.path,
importSessionId,
});
scenario = {
project: openedProject,
reuseTarget,
projectName: project.workspace.projectDisplayName,
projectRoot: repo.path,
worktreeDirectory,
unrelatedDirectory: unrelated.path,
importSessionId,
repoCleanup: repo.cleanup,
unrelatedCleanup: unrelated.cleanup,
};
});
test.afterAll(async () => {
await client?.removeProject(scenario?.project.projectId).catch(() => undefined);
await client?.removeProject(scenario?.reuseTarget.projectId).catch(() => undefined);
await client?.close().catch(() => undefined);
await scenario?.repoCleanup().catch(() => undefined);
await scenario?.unrelatedCleanup().catch(() => undefined);
await rm(claudeConfigDirectory, { recursive: true, force: true });
});
test("captures the compact import-session journey", async ({ page }, testInfo) => {
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, { width: 390, height: 844 });
await test.step("the mobile sidebar exposes import in its footer", async () => {
await flow.revealMobileEntryPoint();
await capture(page, testInfo, "01-mobile-sidebar-footer.png");
});
await test.step("the host-wide sheet is newest first and fits its provider filter", async () => {
await flow.openGlobally();
await flow.expectScope("Sessions on", false);
await flow.expectRows({
first: [scenario.importSessionId, "fixture-worktree", "fixture-unrelated"],
folders: [
[scenario.importSessionId, scenario.projectName],
["fixture-worktree", `${scenario.projectName} · worktrees/review-fix`],
["fixture-unrelated", scenario.reuseTarget.projectDisplayName],
],
});
await flow.expectProviderError("Broken ACP");
await flow.expectProviderFilterFits(390);
await flow.revealSession("fixture-unrelated");
await capture(page, testInfo, "02-mobile-sheet-unscoped.png");
});
await test.step("search narrows across the fixture corpus", async () => {
await flow.search("invoice");
await capture(page, testInfo, "03-mobile-search-narrowed.png");
});
await test.step("load more grows the result set and then disappears", async () => {
await flow.resetSearch();
await capture(page, testInfo, "04-mobile-load-more-visible.png");
await flow.loadMore();
await capture(page, testInfo, "05-mobile-load-more-complete.png");
});
await test.step("one provider fails inline and Retry settles", async () => {
await flow.retryProvider(brokenProvider, "Broken ACP");
await capture(page, testInfo, "06-mobile-provider-error-retry.png");
});
await test.step("the selected row imports and opens the hydrated transcript", async () => {
await flow.importSession(scenario.importSessionId);
await flow.expectTranscript("Review the invoice migration", "The fixture transcript is ready.");
await capture(page, testInfo, "08-mobile-agent-after-import.png");
});
await test.step("workspace actions start scoped and can widen to the host", async () => {
await flow.openFromWorkspaceHeader();
await capture(page, testInfo, "09-mobile-workspace-scoped.png");
await flow.showAll();
await flow.expectRows({
folders: [["fixture-unrelated", scenario.reuseTarget.projectDisplayName]],
});
await capture(page, testInfo, "10-mobile-workspace-show-all.png");
await flow.importSession("fixture-root-03");
await flow.expectImportedIntoWorkspace(
scenario.reuseTarget.workspaceId,
"Review fixture item 3",
);
});
});
test("captures the desktop import sheet and command-center entry", async ({ page }, testInfo) => {
const flow = new ImportSessionFlow(page);
await flow.openWorkspace(scenario.project.workspaceId, {
width: 1280,
height: 800,
});
await test.step("desktop shows the flat host-wide sheet", async () => {
await flow.openGlobally();
// The compact test may already have imported the newest fixture row, so this
// asserts recency as an ordering between two rows nothing imports.
await flow.expectRows({
before: ["fixture-worktree", "fixture-unrelated"],
folders: [["fixture-worktree", `${scenario.projectName} · worktrees/review-fix`]],
});
await flow.revealSession("fixture-unrelated");
await capture(page, testInfo, "11-desktop-sheet-unscoped.png");
await flow.close();
});
await test.step("import matches the command but not Home", async () => {
await flow.expectCommandCenterMatch();
await capture(page, testInfo, "12-desktop-command-center-import.png");
});
});
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
const outputPath = testInfo.outputPath(name);
await page.screenshot({ path: outputPath, fullPage: true });
await copyFile(outputPath, path.join(SCREENSHOT_DIRECTORY, name));
}
async function seedClaudeSessions(input: {
projectRoot: string;
worktreeDirectory: string;
unrelatedDirectory: string;
importSessionId: string;
}): Promise<void> {
const sessions = [
{
cwd: input.projectRoot,
id: input.importSessionId,
title: "Invoice migration plan",
prompt: "Review the invoice migration",
answer: "The fixture transcript is ready.",
},
{
cwd: input.worktreeDirectory,
id: "fixture-worktree",
title: "Review worktree fix",
prompt: "Check the worktree import flow",
},
{
cwd: input.unrelatedDirectory,
id: "fixture-unrelated",
title: "Unrelated directory notes",
prompt: "Review the unrelated directory",
},
...Array.from({ length: 20 }, (_, index) => ({
cwd: [input.projectRoot, input.worktreeDirectory, input.unrelatedDirectory][index % 3]!,
id: `fixture-root-${String(index + 1).padStart(2, "0")}`,
title: `Root session ${String(index + 1).padStart(2, "0")}`,
prompt: index === 7 ? "Investigate invoice rendering" : `Review fixture item ${index + 1}`,
})),
];
const newest = Date.now() - 60_000;
for (const [index, session] of sessions.entries()) {
const projectDirectory = path.join(
claudeConfigDirectory,
"projects",
session.cwd.replace(/[^a-zA-Z0-9]/g, "-"),
);
await mkdir(projectDirectory, { recursive: true });
const sessionPath = path.join(projectDirectory, `${session.id}.jsonl`);
const records = [
{
type: "user",
uuid: `${session.id}-user`,
message: { role: "user", content: session.prompt },
cwd: session.cwd,
sessionId: session.id,
},
...(session.answer
? [
{
type: "assistant",
uuid: `${session.id}-assistant`,
message: {
role: "assistant",
content: [{ type: "text", text: session.answer }],
},
cwd: session.cwd,
sessionId: session.id,
},
]
: []),
{ type: "custom-title", customTitle: session.title, sessionId: session.id },
];
await writeFile(sessionPath, `${records.map((record) => JSON.stringify(record)).join("\n")}\n`);
const timestamp = new Date(newest - index * 60_000);
await utimes(sessionPath, timestamp, timestamp);
}
}
@@ -0,0 +1,74 @@
import { test } from "../support/fixtures";
import {
closeDiagramFullscreen,
closeDiagramFullscreenFromOutside,
expectCompletedDiagram,
expectFullscreenDiagram,
expectFullscreenDiagramClosed,
openDiagramFullscreen,
requestDiagram,
waitForDiagramTurnToComplete,
zoomAndPanFullscreenDiagram,
} from "../support/helpers/diagram";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const MERMAID_DIAGRAM = [
"```mermaid",
"flowchart LR",
" Start --> Middle",
" Middle --> Review",
" Review --> Ship",
"```",
].join("\n");
test("opens a Mermaid diagram fullscreen and closes it again", async ({ page }) => {
test.setTimeout(120_000);
const agent = await seedMockAgentWorkspace({
repoPrefix: "mermaid-fullscreen-",
title: "Fullscreen Mermaid",
featureValues: {
mockStreamingAssistantResponse: MERMAID_DIAGRAM,
mockStreamingAssistantIntervalMs: 10,
},
});
try {
await test.step("Open the conversation and wait for the rendered diagram", async () => {
await openAgentRoute(page, agent);
await requestDiagram(agent);
await waitForDiagramTurnToComplete(agent);
await expectCompletedDiagram(page, ["Start", "Ship"]);
});
await test.step("The toolbar opens the diagram fullscreen", async () => {
await openDiagramFullscreen(page);
await expectFullscreenDiagram(page, ["Start", "Review", "Ship"]);
});
await test.step("The fullscreen diagram zooms with the wheel and pans by dragging", async () => {
await zoomAndPanFullscreenDiagram(page);
});
await test.step("The close action returns to the conversation", async () => {
await closeDiagramFullscreen(page);
await expectFullscreenDiagramClosed(page);
await expectCompletedDiagram(page, ["Start", "Ship"]);
});
await test.step("Escape closes the fullscreen diagram", async () => {
await openDiagramFullscreen(page);
await expectFullscreenDiagram(page, ["Start", "Ship"]);
await page.keyboard.press("Escape");
await expectFullscreenDiagramClosed(page);
});
await test.step("Clicking outside the diagram closes the fullscreen viewer", async () => {
await openDiagramFullscreen(page);
await expectFullscreenDiagram(page, ["Start", "Ship"]);
await closeDiagramFullscreenFromOutside(page);
await expectFullscreenDiagramClosed(page);
});
} finally {
await agent.cleanup();
}
});
@@ -35,6 +35,7 @@ test("keeps a Mermaid diagram rendered while its message streams, completes, and
page,
}) => {
test.setTimeout(120_000);
let diagramTurnCompleted!: Promise<void>;
const agent = await seedMockAgentWorkspace({
repoPrefix: "mermaid-streaming-",
@@ -48,15 +49,16 @@ test("keeps a Mermaid diagram rendered while its message streams, completes, and
await test.step("Open the conversation and request a diagram", async () => {
await openAgentRoute(page, agent);
await requestDiagram(agent);
diagramTurnCompleted = waitForDiagramTurnToComplete(agent);
});
await test.step("The diagram renders and stays rendered while tokens arrive", async () => {
await expectDiagramWithLabels(page, ["Start", "Middle"]);
await expectDiagramRemainsRenderedWhileStreaming(page);
await expectDiagramRemainsRenderedWhileStreaming(page, diagramTurnCompleted);
});
await test.step("The completed diagram shows the final streamed content", async () => {
await waitForDiagramTurnToComplete(agent);
await diagramTurnCompleted;
await expectCompletedDiagram(page, ["Start", "Done", "Release"]);
});
@@ -27,7 +27,10 @@ test("chooses a metadata model and can return to automatic selection", async ({
}, testInfo) => {
await openMetadataGenerationSettings(page);
await expect(page.getByText("Workspace titles", { exact: false })).toBeVisible();
// The section explains itself through the header's info tooltip, not a paragraph.
await expect(page.getByTestId("metadata-generation-settings-info")).toHaveAccessibleName(
"About Metadata generation",
);
await expect(page.getByRole("button", { name: "Automatic", exact: true })).toHaveAttribute(
"aria-selected",
"true",
@@ -119,7 +119,7 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previousConfig = await client.getDaemonConfig();
await writeFile(path.join(directory, "paseo-plugin.json"), JSON.stringify({ id: PLUGIN_ID }));
await writeFile(path.join(directory, "index.tsx"), PLUGIN_SOURCE);
await writeFile(path.join(directory, "index.client.tsx"), PLUGIN_SOURCE);
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
@@ -121,7 +121,7 @@ test("installs, reloads, recovers, disables, and removes a trusted local plugin"
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
await writeFile(path.join(directory, "paseo-plugin.json"), JSON.stringify({ id: "e2e-plugin" }));
await writeFile(path.join(directory, "index.tsx"), pluginSource("Plugin v1"));
await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v1"));
try {
const catalog = observePluginCatalog(page);
@@ -143,14 +143,14 @@ test("installs, reloads, recovers, disables, and removes a trusted local plugin"
await reloadPlugin(page);
await openContributionFromSettings(page, "Plugin v1", "Plugin v1 cleanup 1");
await writeFile(path.join(directory, "index.tsx"), pluginSource("Plugin v2"));
await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v2"));
await openPluginSettings(page);
await reloadPlugin(page);
await openContributionFromSettings(page, "Plugin v2", "Plugin v2 cleanup 2");
await expect(page.getByRole("button", { name: "Plugin v1", exact: true })).not.toBeVisible();
await writeFile(
path.join(directory, "index.tsx"),
path.join(directory, "index.client.tsx"),
pluginSource("Broken surface", "render exploded"),
);
await openPluginSettings(page);
@@ -159,13 +159,13 @@ test("installs, reloads, recovers, disables, and removes a trusted local plugin"
await openContribution(page, "Healthy surface", "Healthy contribution");
await openContribution(page, "Broken surface", "Plugin failed: render exploded");
await writeFile(path.join(directory, "index.tsx"), pluginSource("Recovered surface"));
await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Recovered surface"));
await reloadActiveContribution(page, client, "Recovered surface cleanup 4");
await expect(
page.getByRole("button", { name: "Broken surface", exact: true }),
).not.toBeVisible();
await writeFile(path.join(directory, "index.tsx"), "export default broken syntax !!!");
await writeFile(path.join(directory, "index.client.tsx"), "export default broken syntax !!!");
await openPluginSettings(page);
await page.getByRole("button", { name: "Reload", exact: true }).click();
await expect(page.getByTestId("plugin-management-feedback")).toContainText("Request failed");
@@ -173,7 +173,7 @@ test("installs, reloads, recovers, disables, and removes a trusted local plugin"
await leavePluginSettings(page);
await expectContributionRemoved(page, "Recovered surface");
await writeFile(path.join(directory, "index.tsx"), pluginSource("Plugin v3"));
await writeFile(path.join(directory, "index.client.tsx"), pluginSource("Plugin v3"));
await openPluginSettings(page);
await page.getByRole("button", { name: "Reload", exact: true }).click();
await expect(page.getByLabel("e2e-plugin running")).toBeVisible();
@@ -54,7 +54,7 @@ test("applies a contributed theme and falls back when its plugin is gone", async
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previousConfig = await client.getDaemonConfig();
await writeFile(path.join(directory, "paseo-plugin.json"), JSON.stringify({ id: PLUGIN_ID }));
await writeFile(path.join(directory, "index.ts"), PLUGIN_SOURCE);
await writeFile(path.join(directory, "index.client.ts"), PLUGIN_SOURCE);
try {
await client.patchDaemonConfig({ pluginsEnabled: true });
@@ -1,4 +1,4 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import type { TestInfo } from "@playwright/test";
@@ -12,10 +12,7 @@ import { buildAgentRoute } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import {
closeMobileAgentSidebar,
expectMobileAgentSidebarHidden,
} from "../support/helpers/sidebar";
import { expectMobileAgentSidebarHidden } from "../support/helpers/sidebar";
import {
switchWorkspaceViaSidebar,
waitForWorkspaceInSidebar,
@@ -29,18 +26,11 @@ function isSettledWorkspaceUrl(url: URL): boolean {
return url.pathname.includes("/workspace/") && !url.searchParams.has("open");
}
function pluginSource(input: { workspaceId: string; agentId: string }): string {
function pluginClientSource(input: { workspaceId: string; agentId: string }): string {
return `import React, { useRef } from "react";
import { Pressable, Text, View } from "react-native";
import { Icon, useAgent, useWorkspace } from "@getpaseo/plugin";
import { defineRpc } from "@getpaseo/plugin/server";
import { z } from "zod";
const recordComposerOpen = defineRpc({
name: "composer.open",
input: z.object({ workspaceId: z.string() }),
output: z.object({ opened: z.boolean() }),
});
import { recordComposerOpen } from "./shared/rpc";
function WorkspacePanel({ workspaceId, host, layout }) {
const workspace = useWorkspace(workspaceId, (value) => ({ id: value.id }));
@@ -114,23 +104,49 @@ function contributeClient(client) {
};
}
export default function contribute(plugin) {
plugin.handle(recordComposerOpen, async ({ workspaceId }, { paseo }) => {
export default function contribute(client) {
client.addSurface("collision", DirectCollisionSurface);
client.addSurface("sidebar-destination", SidebarCollisionSurface);
client.addSidebarItem({ id: "collision", title: "Collision sidebar", icon: "Blocks", surface: "sidebar-destination" });
client.addWorkspacePanel({ id: "workspace", title: "Workspace inspector", icon: "PanelsTopLeft", context: "workspace", Component: WorkspacePanel });
client.addWorkspacePanel({ id: "agent", title: "Agent inspector", icon: "PanelTop", context: "agent", Component: AgentPanel });
client.addCommandCenterItem({ id: "global", title: "Plugin global action", icon: "Blocks", context: "global", onSelect() {} });
client.addCommandCenterItem({ id: "surface", title: "Open direct collision surface", icon: "Blocks", context: "workspace", onSelect({ openSurface }) { openSurface("collision"); } });
client.addCommandCenterItem({ id: "workspace", title: "Open plugin workspace", icon: "PanelsTopLeft", context: "workspace", onSelect({ openPanel }) { openPanel("workspace"); } });
client.addCommandCenterItem({ id: "agent", title: "Open plugin agent", icon: "PanelTop", context: "agent", onSelect({ openPanel }) { openPanel("agent"); } });
return contributeClient(client);
}`;
}
const pluginSharedSource = `import { defineRpc } from "@getpaseo/plugin";
import { z } from "zod";
export const recordComposerOpen = defineRpc({
name: "composer.open",
input: z.object({ workspaceId: z.string() }),
output: z.object({ opened: z.boolean() }),
});`;
const pluginServerSource = `import { recordComposerOpen } from "./shared/rpc";
export default function contribute(server) {
server.handle(recordComposerOpen, async ({ workspaceId }, { paseo }) => {
await paseo.workspaces.ref(workspaceId).setTitle("Opened from composer pill");
return { opened: true };
});
plugin.addSurface("collision", DirectCollisionSurface);
plugin.addSurface("sidebar-destination", SidebarCollisionSurface);
plugin.addSidebarItem({ id: "collision", title: "Collision sidebar", icon: "Blocks", surface: "sidebar-destination" });
plugin.addWorkspacePanel({ id: "workspace", title: "Workspace inspector", icon: "PanelsTopLeft", context: "workspace", Component: WorkspacePanel });
plugin.addWorkspacePanel({ id: "agent", title: "Agent inspector", icon: "PanelTop", context: "agent", Component: AgentPanel });
plugin.addCommandCenterItem({ id: "global", title: "Plugin global action", icon: "Blocks", context: "global", onSelect() {} });
plugin.addCommandCenterItem({ id: "surface", title: "Open direct collision surface", icon: "Blocks", context: "workspace", onSelect({ openSurface }) { openSurface("collision"); } });
plugin.addCommandCenterItem({ id: "workspace", title: "Open plugin workspace", icon: "PanelsTopLeft", context: "workspace", onSelect({ openPanel }) { openPanel("workspace"); } });
plugin.addCommandCenterItem({ id: "agent", title: "Open plugin agent", icon: "PanelTop", context: "agent", onSelect({ openPanel }) { openPanel("agent"); } });
plugin.addClientSide(contributeClient);
return () => {};
}`;
async function writePluginSources(
directory: string,
input: { workspaceId: string; agentId: string },
): Promise<void> {
await mkdir(path.join(directory, "shared"), { recursive: true });
await Promise.all([
writeFile(path.join(directory, "index.client.tsx"), pluginClientSource(input)),
writeFile(path.join(directory, "index.server.ts"), pluginServerSource),
writeFile(path.join(directory, "shared", "rpc.ts"), pluginSharedSource),
]);
}
async function searchCommands(page: Page, query: string) {
@@ -159,7 +175,7 @@ async function runCommand(page: Page, title: string): Promise<void> {
async function openCompactSidebar(page: Page): Promise<void> {
await page.getByRole("button", { name: "Open menu", exact: true }).click();
await expect(page.getByTestId("sidebar-command-center-search")).toBeVisible();
await expect(page.getByTestId("sidebar-search")).toBeVisible();
}
async function capture(page: Page, testInfo: TestInfo, name: string): Promise<void> {
@@ -184,10 +200,10 @@ test.describe("plugin workspace panels and Command Center", () => {
port: secondaryDaemon.port,
});
await writeFile(path.join(directory, "paseo-plugin.json"), JSON.stringify({ id: PLUGIN_ID }));
await writeFile(
path.join(directory, "index.tsx"),
pluginSource({ workspaceId: primary.workspaceId, agentId: "missing-agent" }),
);
await writePluginSources(directory, {
workspaceId: primary.workspaceId,
agentId: "missing-agent",
});
try {
await primaryClient.patchDaemonConfig({ pluginsEnabled: true });
@@ -263,10 +279,10 @@ test.describe("plugin workspace panels and Command Center", () => {
modeId: "load-test",
});
const navigationAgentId = agent.id;
await writeFile(
path.join(directory, "index.tsx"),
pluginSource({ workspaceId: primary.workspaceId, agentId: navigationAgentId }),
);
await writePluginSources(directory, {
workspaceId: primary.workspaceId,
agentId: navigationAgentId,
});
await primaryClient.reloadPlugin(PLUGIN_ID);
await runCommand(page, "Open direct collision surface");
@@ -331,8 +347,9 @@ test.describe("plugin workspace panels and Command Center", () => {
await page.waitForURL(isSettledWorkspaceUrl, { timeout: 60_000 });
await expect(page.getByRole("button", { name: "Open composer review" })).toHaveCount(0);
await openCompactSidebar(page);
// The sidebar's Search row dismisses the compact sidebar on its way to the
// command center, so nothing has to close it after the command runs.
await runCommand(page, "Open plugin agent");
await closeMobileAgentSidebar(page);
await expectMobileAgentSidebarHidden(page);
await expect(page.getByText(`Agent bridge ${agent.id}`)).toBeVisible();
await expect(
@@ -9,6 +9,11 @@ import {
type AgentHandle,
type RewindFlowProvider,
} from "../support/helpers/rewind-flow";
import {
expectNestedProviderSubagentOwnership,
launchNestedProviderSubagentOwnershipScenario,
reopenNestedProviderSession,
} from "../support/helpers/provider-subagents";
import { openSubagentsTrack } from "../support/helpers/subagents";
interface ProviderSubagentCase {
@@ -26,7 +31,7 @@ const cases: ProviderSubagentCase[] = [
provider: "claude",
sentinel: "CLAUDE_CHILD_SENTINEL",
expectedName: "sentinel_child",
providerConfig: { model: "opus" },
providerConfig: { model: "claude-sonnet-5" },
prompt:
'Use Claude Code\'s native Task tool exactly once. Set its subagent_type input to "Explore" and its name input to "sentinel_child". Ask it to reply with exactly CLAUDE_CHILD_SENTINEL and do nothing else. Wait for it, then reply ROOT_DONE. Do not use Paseo tools.',
},
@@ -147,3 +152,23 @@ test.describe("real provider subagent timelines", () => {
});
}
});
test.describe("real Claude nested subagent ownership", () => {
test.setTimeout(600_000);
test("keeps a grandchild and its background notification with their direct owners", async ({
page,
}, testInfo) => {
const cwd = realpathSync(mkdtempSync(path.join(tmpdir(), "paseo-claude-nested-ui-")));
let handle: AgentHandle | undefined;
try {
handle = await launchNestedProviderSubagentOwnershipScenario(page, cwd);
await expectNestedProviderSubagentOwnership(page, testInfo, "live");
await reopenNestedProviderSession(handle);
await expectNestedProviderSubagentOwnership(page, testInfo, "reopened");
} finally {
await cleanupRewindFlow({ handle, cwd });
}
});
});
@@ -69,8 +69,8 @@ test.describe("Same-directory workspaces", () => {
await expectExplorerEntryVisible(page, "SHARED_CHANGE.md");
await openChangesPanel(page);
await expect(
page.getByTestId("git-diff-scroll").getByText("SHARED_CHANGE.md", { exact: true }).first(),
).toBeVisible({ timeout: 30_000 });
page.getByTestId("working-diff-panel").filter({ visible: true }).getByTestId("diff-file-0"),
).toHaveAccessibleName("SHARED_CHANGE.md, +1, -0", { timeout: 30_000 });
// Workspace B (same directory): the SAME directory-backed content is
// visible even though the panel tabs belong to a different workspace.
@@ -79,8 +79,8 @@ test.describe("Same-directory workspaces", () => {
await expectExplorerEntryVisible(page, "SHARED_CHANGE.md");
await openChangesPanel(page);
await expect(
page.getByTestId("git-diff-scroll").getByText("SHARED_CHANGE.md", { exact: true }).first(),
).toBeVisible({ timeout: 30_000 });
page.getByTestId("working-diff-panel").filter({ visible: true }).getByTestId("diff-file-0"),
).toHaveAccessibleName("SHARED_CHANGE.md, +1, -0", { timeout: 30_000 });
} finally {
await seeded.cleanup();
}
@@ -0,0 +1,108 @@
import { expect, test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
expectSidebarItemHidden,
expectSidebarNavSettingsOrder,
expectSidebarNavSettingsRow,
expectSidebarOrder,
expectStoredSidebarNav,
leaveSettings,
moveSidebarNavItemUp,
openSidebarNavSettings,
seedSidebarNavPreferences,
setSidebarNavItemVisible,
} from "../support/helpers/sidebar-nav-settings";
test.describe("Sidebar items in Appearance settings", () => {
test("owner reorders and hides top-level sidebar items", async ({ page }) => {
await gotoAppShell(page);
await test.step("the sidebar starts in the default order", async () => {
await expectSidebarOrder(page, ["new-workspace", "history", "search", "schedules"]);
});
await test.step("the Sidebar section lists every item in the same order", async () => {
await openSidebarNavSettings(page);
// The section explains itself through the header's info tooltip, not a paragraph.
await expect(page.getByTestId("sidebar-nav-section-info")).toHaveAccessibleName(
"About Sidebar",
);
await expectSidebarNavSettingsOrder(page, [
"new-workspace",
"history",
"search",
"schedules",
]);
await expectSidebarNavSettingsRow(page, {
key: "history",
label: "History",
visible: true,
});
// Items with a keyboard shortcut badge it next to their name. Chords render
// with Ctrl off macOS, which is what the browser project runs on.
await expect(
page.getByTestId("sidebar-nav-item-new-workspace").getByText("Ctrl+N", { exact: true }),
).toBeVisible();
});
await test.step("moving Schedules up twice lifts it above History", async () => {
await moveSidebarNavItemUp(page, "schedules");
await expectSidebarNavSettingsOrder(page, [
"new-workspace",
"history",
"schedules",
"search",
]);
await moveSidebarNavItemUp(page, "schedules");
await expectSidebarNavSettingsOrder(page, [
"new-workspace",
"schedules",
"history",
"search",
]);
await leaveSettings(page);
await expectSidebarOrder(page, ["new-workspace", "schedules", "history", "search"]);
});
await test.step("turning History off removes it from the sidebar", async () => {
await openSidebarNavSettings(page);
await setSidebarNavItemVisible(page, "history", false);
await expectStoredSidebarNav(page, [
{ key: "new-workspace", visible: true },
{ key: "schedules", visible: true },
{ key: "history", visible: false },
{ key: "search", visible: true },
]);
await leaveSettings(page);
await expectSidebarItemHidden(page, "history");
await expectSidebarOrder(page, ["new-workspace", "schedules", "search"]);
});
await test.step("the sidebar keeps that shape across a reload", async () => {
await page.reload();
await expectSidebarItemHidden(page, "history");
await expectSidebarOrder(page, ["new-workspace", "schedules", "search"]);
});
});
test("renders no top-level items when every one is turned off", async ({ page }) => {
await seedSidebarNavPreferences(page, [
{ key: "new-workspace", visible: false },
{ key: "history", visible: false },
{ key: "search", visible: false },
{ key: "schedules", visible: false },
]);
await gotoAppShell(page);
// The sidebar itself still renders; only its top-level nav items are gone.
await expect(page.locator('[data-testid="sidebar-settings"]:visible')).toBeVisible({
timeout: 30_000,
});
await expectSidebarItemHidden(page, "new-workspace");
await expectSidebarItemHidden(page, "history");
await expectSidebarItemHidden(page, "search");
await expectSidebarItemHidden(page, "schedules");
});
});
@@ -0,0 +1,77 @@
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { createIdleAgent } from "../support/helpers/archive-tab";
import { seedWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
import { waitForWorkspaceTabsVisible } from "../support/helpers/workspace-tabs";
import { buildHostAgentDetailRoute } from "@/utils/host-routes";
const TITLE_MAX_LENGTH = 80;
function normalizedTitle(title: string): string {
return title.replace(/\s+/g, " ").trim();
}
function expectedTooltipTitle(title: string): string {
const singleLineTitle = normalizedTitle(title);
return singleLineTitle.length <= TITLE_MAX_LENGTH
? singleLineTitle
: `${singleLineTitle.slice(0, TITLE_MAX_LENGTH - 1).trimEnd()}…`;
}
async function openAgent(page: Page, agent: { id: string; workspaceId: string }): Promise<void> {
await page.goto(buildHostAgentDetailRoute(getServerId(), agent.id, agent.workspaceId));
await page.waitForURL(
(url) => url.pathname.includes("/workspace/") && !url.searchParams.has("open"),
{ timeout: 60_000 },
);
await waitForWorkspaceTabsVisible(page);
}
async function openAgentTabTooltip(page: Page, agentId: string, title: string): Promise<Locator> {
await page.getByRole("button", { name: normalizedTitle(title), exact: true }).hover();
const tooltip = page.getByTestId(`workspace-tab-tooltip-agent_${agentId}`);
await expect(tooltip).toBeVisible({ timeout: 10_000 });
return tooltip;
}
async function expectTwoRowAgentSummary(
tooltip: Locator,
input: { title: string; agentId: string },
): Promise<void> {
const title = tooltip.getByText(expectedTooltipTitle(input.title), { exact: true });
const id = tooltip.getByText(input.agentId.slice(0, 7), { exact: true });
const activity = tooltip.getByText(/^(just now|\d+[mhd] ago|[A-Z][a-z]{2} \d{1,2})$/);
await expect(title).toBeVisible();
await expect(id).toBeVisible();
await expect(tooltip.getByText("·", { exact: true })).toBeVisible();
await expect(activity).toBeVisible();
expect((await title.boundingBox())?.y).toBeLessThan((await id.boundingBox())?.y ?? 0);
}
test.describe("Workspace agent tab tooltip", () => {
test("summarizes a multiline agent title above its ID and last activity", async ({ page }) => {
test.setTimeout(120_000);
const workspace = await seedWorkspace({ repoPrefix: "workspace-agent-tooltip-" });
try {
const title = [
"Short first line",
"followed by a much longer continuation that should be joined before the complete title is truncated to a useful tooltip length",
].join("\n");
const agent = await createIdleAgent(workspace.client, {
cwd: workspace.repoPath,
workspaceId: workspace.workspaceId,
title,
});
await openAgent(page, agent);
const tooltip = await openAgentTabTooltip(page, agent.id, title);
await expectTwoRowAgentSummary(tooltip, { title, agentId: agent.id });
} finally {
await workspace.cleanup();
}
});
});
@@ -22,7 +22,7 @@ import {
expectSetupPanel,
openHomeWithProject,
navigateToWorkspaceViaSidebar,
returnHomeFromWorkspace,
leaveWorkspaceViaHistory,
openWorkspaceScriptsMenu,
startWorkspaceScriptFromMenu,
closeWorkspaceScriptsMenu,
@@ -195,7 +195,7 @@ test.describe("Workspace setup streaming", () => {
await expectFailedSetupTabSeededInMainPane(page, workspace.id);
await closeSetupTab(page, workspace.id);
await returnHomeFromWorkspace(page);
await leaveWorkspaceViaHistory(page);
await navigateToWorkspaceViaSidebar(page, workspace.id);
await expectSetupTabNotSeeded(page, workspace.id);
} finally {
@@ -4,7 +4,7 @@ import { expect, type Page } from "@playwright/test";
import { metroTest as test } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import {
createIdleAgent,
createMockIdleAgent,
expectSessionRowArchived,
openSessions,
} from "../support/helpers/archive-tab";
@@ -97,7 +97,7 @@ test.describe("Worktree restore after daemon restart", () => {
createdProjectIds.add(worktree.projectKey);
createdWorktreeDirectories.add(worktree.workspaceDirectory);
const agent = await createIdleAgent(client, {
const agent = await createMockIdleAgent(client, {
cwd: worktree.workspaceDirectory,
workspaceId: worktree.workspaceId,
title: `restart-restore-${randomUUID().slice(0, 8)}`,
+11 -1
View File
@@ -35,6 +35,8 @@ const metroTest = base.extend({
const daemonTest = metroTest.extend<
{ projectOwnership: void },
{
e2eDaemonConfig: Record<string, unknown> | undefined;
e2eDaemonEnvironment: Record<string, string>;
e2eForkProviders: string[];
e2eInjectPaseoTools: boolean;
e2eWorker: void;
@@ -43,9 +45,17 @@ const daemonTest = metroTest.extend<
>({
e2eForkProviders: [[], { scope: "worker", option: true }],
e2eInjectPaseoTools: [false, { scope: "worker", option: true }],
e2eDaemonConfig: [undefined, { scope: "worker", option: true }],
e2eDaemonEnvironment: [{}, { scope: "worker", option: true }],
e2eWorker: [
async ({ e2eForkProviders, e2eInjectPaseoTools }, provide, workerInfo) => {
async (
{ e2eDaemonConfig, e2eDaemonEnvironment, e2eForkProviders, e2eInjectPaseoTools },
provide,
workerInfo,
) => {
const worker = await startE2EWorker(workerInfo.workerIndex, {
daemonConfig: e2eDaemonConfig,
environment: e2eDaemonEnvironment,
forkProviders: e2eForkProviders,
injectPaseoTools: e2eInjectPaseoTools,
});
@@ -58,7 +58,7 @@ export async function observeCommandCenterScroll(page: Page): Promise<void> {
}
export async function openCommandCenterWithKeyboard(page: Page): Promise<Locator> {
await expect(page.getByTestId("sidebar-command-center-search")).toBeVisible({ timeout: 30_000 });
await expect(page.getByTestId("sidebar-search")).toBeVisible({ timeout: 30_000 });
await page.keyboard.press("Meta+K");
const panel = page.getByTestId("command-center-panel");
await expect(panel).toBeVisible({ timeout: 30_000 });
@@ -83,6 +83,7 @@ export async function expectCommandCenterToRemainAtTheTop(page: Page): Promise<v
export async function expectPrimaryCommandCenterActions(panel: Locator): Promise<void> {
const expectedActions = [
{ title: "New workspace", shortcut: "⌘N" },
{ title: "Import session" },
{ title: "History" },
{ title: "Schedules" },
{ title: "Settings", shortcut: "⌘," },
@@ -105,6 +106,9 @@ export async function expectPrimaryCommandCenterActions(panel: Locator): Promise
await input.fill("home");
await expect(panel.getByRole("button").filter({ hasText: "Home" })).toBeVisible();
await expect(panel.getByRole("button").filter({ hasText: "Add project" })).toHaveCount(0);
await input.fill("import");
await expect(panel.getByRole("button").filter({ hasText: "Import session" })).toBeVisible();
await expect(panel.getByRole("button").filter({ hasText: "Home" })).toHaveCount(0);
await input.fill("");
}
@@ -2,7 +2,7 @@ import { expect, type Locator, type Page } from "@playwright/test";
// Opens the command center / global search palette from the sidebar and returns its panel.
export async function openCommandCenter(page: Page): Promise<Locator> {
await page.getByTestId("sidebar-command-center-search").click();
await page.getByTestId("sidebar-search").click();
const panel = page.getByTestId("command-center-panel");
await expect(panel).toBeVisible({ timeout: 30_000 });
return panel;
+109 -7
View File
@@ -25,13 +25,28 @@ export async function expectDiagramWithLabels(
}
}
export async function expectDiagramRemainsRenderedWhileStreaming(page: Page): Promise<void> {
const { diagram, svg } = renderedDiagram(page);
const samples = 80;
for (let sample = 0; sample < samples; sample += 1) {
await expect(diagram).toBeVisible({ timeout: 100 });
await expect(svg).toBeVisible({ timeout: 500 });
await page.waitForTimeout(25);
export async function expectDiagramRemainsRenderedWhileStreaming(
page: Page,
completion: Promise<void>,
): Promise<void> {
const diagram = page.getByRole("img", { name: DIAGRAM_NAME }).last();
let turnCompleted = false;
const completed = completion.then(() => {
turnCompleted = true;
return true;
});
for (;;) {
expect(await diagram.isVisible()).toBe(true);
if (turnCompleted) return completion;
const box = await diagram.boundingBox();
if (turnCompleted) return completion;
expect(box, "the inline diagram should have measurable layout").not.toBeNull();
expect(
box?.height,
"the inline diagram should remain tall enough to read",
).toBeGreaterThanOrEqual(56);
const didComplete = await Promise.race([completed, page.waitForTimeout(16).then(() => false)]);
if (didComplete) return completion;
}
}
@@ -46,3 +61,90 @@ export async function expectCompletedDiagram(page: Page, labels: readonly string
export async function reloadConversation(page: Page): Promise<void> {
await page.reload({ waitUntil: "domcontentloaded" });
}
const FULLSCREEN_VIEWPORT = "mermaid-fullscreen-viewport";
function diagramSvg(page: Page, viewportTestId: string) {
return page
.getByTestId(`${viewportTestId}-canvas`)
.last()
.locator("iframe")
.contentFrame()
.locator("#diagram svg");
}
/**
* The viewport toolbar only reveals itself on hover, so the diagram is hovered first. The
* pointer is parked elsewhere beforehand so the hover transition fires even when a previous
* step left the cursor inside the viewport.
*/
export async function openDiagramFullscreen(page: Page): Promise<void> {
await page.mouse.move(0, 0);
await page.getByTestId("mermaid-viewport-canvas").last().hover();
await page.getByTestId("mermaid-fullscreen").last().click();
}
export async function closeDiagramFullscreen(page: Page): Promise<void> {
await page.getByTestId(`${FULLSCREEN_VIEWPORT}-canvas`).hover();
await page.getByTestId("mermaid-fullscreen-close").click();
}
export async function zoomAndPanFullscreenDiagram(page: Page): Promise<void> {
const canvas = page.getByTestId(`${FULLSCREEN_VIEWPORT}-canvas`);
const svg = diagramSvg(page, FULLSCREEN_VIEWPORT);
const initial = await svg.boundingBox();
expect(initial, "the fullscreen diagram should have measurable layout").not.toBeNull();
await page.mouse.move(initial!.x + initial!.width / 2, initial!.y + initial!.height / 2);
await page.mouse.wheel(0, -100);
const zoomed = await svg.boundingBox();
expect(zoomed, "the zoomed diagram should have measurable layout").not.toBeNull();
expect(zoomed!.width).toBeGreaterThan(initial!.width * 1.1);
const viewport = await canvas.boundingBox();
expect(viewport, "the fullscreen viewport should have measurable layout").not.toBeNull();
await page.mouse.move(viewport!.x + viewport!.width / 2, viewport!.y + viewport!.height / 2);
await page.mouse.down();
await page.mouse.move(
viewport!.x + viewport!.width / 2 - 120,
viewport!.y + viewport!.height / 2,
);
await page.mouse.up();
const panned = await svg.boundingBox();
expect(panned, "the panned diagram should have measurable layout").not.toBeNull();
expect(Math.abs(panned!.x - zoomed!.x)).toBeGreaterThan(100);
}
export async function closeDiagramFullscreenFromOutside(page: Page): Promise<void> {
const canvas = page.getByTestId(`${FULLSCREEN_VIEWPORT}-canvas`);
const viewport = await canvas.boundingBox();
const svg = await diagramSvg(page, FULLSCREEN_VIEWPORT).boundingBox();
expect(viewport, "the fullscreen viewport should have measurable layout").not.toBeNull();
expect(svg, "the fullscreen diagram should have measurable layout").not.toBeNull();
const x = viewport!.x + viewport!.width / 2;
const y =
svg!.y + svg!.height < viewport!.y + viewport!.height - 8
? viewport!.y + viewport!.height - 4
: viewport!.y + 4;
await page.mouse.click(x, y);
}
export async function expectFullscreenDiagram(
page: Page,
labels: readonly string[],
): Promise<void> {
const viewport = page.getByTestId(FULLSCREEN_VIEWPORT);
await expect(viewport).toBeVisible({ timeout: 30_000 });
const svg = diagramSvg(page, FULLSCREEN_VIEWPORT);
await expect(svg).toBeVisible({ timeout: 30_000 });
for (const label of labels) {
await expect(svg).toContainText(label);
}
}
export async function expectFullscreenDiagramClosed(page: Page): Promise<void> {
await expect(page.getByTestId(FULLSCREEN_VIEWPORT)).toHaveCount(0);
}
@@ -34,7 +34,7 @@ async function createRunningMockAgent(
}
async function openCommandCenter(page: Page): Promise<void> {
await page.getByRole("button", { name: "Open command center" }).click();
await page.getByTestId("sidebar-search").click();
}
export class DirectoryBootstrapScenario {
+28 -10
View File
@@ -10,6 +10,13 @@ export interface E2EWorker {
close(): Promise<void>;
}
export interface E2EWorkerOptions {
forkProviders?: string[];
injectPaseoTools?: boolean;
daemonConfig?: Record<string, unknown>;
environment?: Record<string, string>;
}
function resolveOptionalHome(value: string | undefined): string | null {
const trimmed = value?.trim();
if (!trimmed) return null;
@@ -77,31 +84,33 @@ if (origin === fixtureRemote) {
process.exit(0);
}
if (command === "pr list" || command === "pr view") {
const isFork = args.includes("2");
const pr = {
number: 1,
number: isFork ? 2 : 1,
title: "Use pasted PR as start ref",
url: "https://github.com/paseo-e2e/local-fixture/pull/1",
url: "https://github.com/paseo-e2e/local-fixture/pull/" + (isFork ? 2 : 1),
state: "OPEN",
body: null,
labels: [],
baseRefName: "main",
headRefName: "pr-branch-1",
headRefName: isFork ? "pr-branch-2" : "pr-branch-1",
updatedAt: "2026-01-01T00:00:00Z"
};
process.stdout.write(JSON.stringify(command === "pr list" ? [pr] : pr));
process.exit(0);
}
if (command === "api graphql" && args.some((arg) => arg.includes("PullRequestCheckoutTarget"))) {
const isFork = args.some((arg) => arg === "number=2");
process.stdout.write(JSON.stringify({
data: { repository: { pullRequest: {
number: 1,
number: isFork ? 2 : 1,
baseRefName: "main",
headRefName: "pr-branch-1",
isCrossRepository: false,
headRepositoryOwner: { login: "paseo-e2e" },
headRefName: isFork ? "pr-branch-2" : "pr-branch-1",
isCrossRepository: isFork,
headRepositoryOwner: { login: isFork ? "fork-owner" : "paseo-e2e" },
headRepository: {
sshUrl: "git@github.com:paseo-e2e/local-fixture.git",
url: fixtureRemote
sshUrl: isFork ? "git@github.com:fork-owner/local-fixture.git" : "git@github.com:paseo-e2e/local-fixture.git",
url: isFork ? "https://github.com/fork-owner/local-fixture" : fixtureRemote
}
} } }
}));
@@ -156,7 +165,7 @@ async function applyMetadataFork(targetHome: string, providerIds: string[]): Pro
export async function startE2EWorker(
workerIndex: number,
options: { forkProviders?: string[]; injectPaseoTools?: boolean } = {},
options: E2EWorkerOptions = {},
): Promise<E2EWorker> {
const requestedRoot = resolveOptionalHome(process.env.E2E_PASEO_HOME);
const paseoHome = requestedRoot
@@ -169,6 +178,14 @@ export async function startE2EWorker(
try {
await applyMetadataFork(paseoHome, options.forkProviders ?? []);
// Worker-scoped fixture config lets a spec exercise provider discovery without
// reading the developer's provider state or sharing configuration with other specs.
if (options.daemonConfig) {
await writeFile(
path.join(paseoHome, "config.json"),
`${JSON.stringify(options.daemonConfig, null, 2)}\n`,
);
}
if (options.injectPaseoTools) {
await enablePaseoTools(paseoHome);
}
@@ -179,6 +196,7 @@ export async function startE2EWorker(
NODE_ENV: "development",
PATH: `${fakeEditorBin}${path.delimiter}${process.env.PATH ?? ""}`,
PASEO_E2E_EDITOR_RECORD_PATH: editorRecordPath,
...options.environment,
},
});
@@ -0,0 +1,145 @@
import { expect, type Page } from "@playwright/test";
import { buildHostWorkspaceRoute } from "@/utils/host-routes";
import { gotoAppShell } from "./app";
import { openCommandCenter } from "./command-center";
import { getServerId } from "./server-id";
import { expectMobileAgentSidebarVisible, openMobileAgentSidebar } from "./sidebar";
const rowTestId = (id: string) => `import-session-session-claude-${id}`;
const rowFolderTestId = (id: string) => `import-session-row-folder-claude-${id}`;
export class ImportSessionFlow {
constructor(private readonly page: Page) {}
async openWorkspace(workspaceId: string, viewport: { width: number; height: number }) {
await this.page.setViewportSize(viewport);
await gotoAppShell(this.page);
await this.page.goto(buildHostWorkspaceRoute(getServerId(), workspaceId));
await expect(this.page.getByRole("button", { name: "Workspace actions" })).toBeVisible({
timeout: 30_000,
});
}
async revealMobileEntryPoint() {
await openMobileAgentSidebar(this.page);
await expectMobileAgentSidebarVisible(this.page);
const button = this.page.getByTestId("sidebar-import-session");
await expect(button).toHaveAccessibleName("Import session");
await button.hover();
await expect(this.page.getByText("Import session", { exact: true })).toBeVisible();
}
async openGlobally() {
await expect(this.page.getByTestId("sidebar-import-session")).toBeVisible();
await this.page.getByTestId("sidebar-import-session").click();
await this.expectSheetReady();
}
async openFromWorkspaceHeader() {
await this.page.getByRole("button", { name: "Workspace actions" }).click();
await this.page.getByTestId("workspace-header-import-agent").click();
await this.expectScope("This workspace");
await expect(this.page.getByTestId("import-session-show-all")).toBeVisible();
await expect(this.page.getByText("Workspace actions", { exact: true })).not.toBeVisible();
}
async expectScope(text: string, exact = true) {
const scope = this.page.getByTestId("import-session-scope");
if (exact) await expect(scope).toHaveText(text);
else await expect(scope).toContainText(text);
await expect(scope).toBeVisible();
}
async expectRows(input: {
first?: string[];
before?: [string, string];
folders?: Array<[string, string]>;
}) {
const ids = await this.rowIds();
if (input.first) expect(ids.slice(0, input.first.length)).toEqual(input.first.map(rowTestId));
if (input.before) {
expect(ids.indexOf(rowTestId(input.before[0]))).toBeGreaterThanOrEqual(0);
expect(ids.indexOf(rowTestId(input.before[0]))).toBeLessThan(
ids.indexOf(rowTestId(input.before[1])),
);
}
for (const [id, folder] of input.folders ?? []) {
await expect(this.page.getByTestId(rowFolderTestId(id))).toHaveText(folder);
}
}
async expectProviderError(label: string) {
await expect(this.page.getByTestId("import-session-provider-errors")).toContainText(
`Could not load ${label} sessions`,
);
}
async expectProviderFilterFits(width: number) {
await expect(this.page.getByTestId("import-session-scope")).toBeInViewport();
const filter = this.page.getByRole("button", { name: "Filter: All" });
await expect(filter).toBeInViewport();
const bounds = await filter.boundingBox();
expect(bounds?.x ?? width).toBeGreaterThanOrEqual(0);
expect((bounds?.x ?? width) + (bounds?.width ?? 1)).toBeLessThanOrEqual(width);
}
async revealSession(id: string) {
await this.page.getByTestId(rowTestId(id)).scrollIntoViewIfNeeded();
}
async search(query: string) {
await this.page.getByTestId("import-session-search").fill(query);
await expect(this.page.getByText("Invoice migration plan", { exact: true })).toBeVisible();
await expect(this.page.getByText("Root session 01", { exact: true })).toHaveCount(0);
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async resetSearch() {
await this.page.getByTestId("import-session-search").fill("");
await expect(this.page.getByTestId("import-session-load-more")).toBeVisible();
}
async loadMore() {
await this.page.getByTestId("import-session-load-more").click();
await expect(this.page.getByText("Root session 20", { exact: true })).toBeVisible();
await expect(this.page.getByTestId("import-session-load-more")).toHaveCount(0);
}
async retryProvider(provider: string, label: string) {
await this.expectProviderError(label);
await this.page.getByTestId(`import-session-retry-${provider}`).click();
await expect(this.page.getByTestId(`import-session-retry-${provider}`)).toBeEnabled();
await this.expectProviderError(label);
await expect(this.page.getByRole("progressbar")).toHaveCount(0);
}
async importSession(id: string) {
await this.page.getByTestId(rowTestId(id)).click();
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0, {
timeout: 30_000,
});
}
async expectTranscript(userText: string, assistantText: string) {
await expect(this.page.getByTestId("user-message")).toContainText(userText);
await expect(this.page.getByTestId("assistant-message")).toContainText(assistantText);
}
async showAll() {
await this.page.getByTestId("import-session-show-all").click();
await expect(this.page.getByTestId("import-session-scope")).toContainText("Sessions on");
}
async expectImportedIntoWorkspace(workspaceId: string, userText: string) {
await expect(this.page).toHaveURL(buildHostWorkspaceRoute(getServerId(), workspaceId), {
timeout: 30_000,
});
const workspace = this.page.getByTestId(`workspace-deck-entry-${getServerId()}:${workspaceId}`);
await expect(workspace.getByTestId("user-message")).toContainText(userText);
}
async close() {
await this.page.keyboard.press("Escape");
await expect(this.page.getByTestId("import-session-sheet")).toHaveCount(0);
}
async expectCommandCenterMatch() {
const panel = await openCommandCenter(this.page);
await panel.getByTestId("command-center-input").fill("import");
await expect(panel.getByText("Import session", { exact: true })).toBeVisible();
await expect(panel.getByText("Home", { exact: true })).toHaveCount(0);
}
private async expectSheetReady() {
const sheet = this.page.getByTestId("import-session-sheet");
await expect(sheet).toBeVisible({ timeout: 30_000 });
await expect(sheet.getByText("Loading sessions...", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
}
private async rowIds() {
return await this.page
.locator('[data-testid^="import-session-session-claude-"]')
.evaluateAll((nodes) => nodes.map((node) => node.getAttribute("data-testid")));
}
}
@@ -0,0 +1,94 @@
import { expect, type Locator, type Page, type TestInfo } from "@playwright/test";
import { launchAgent, sendMessage, type AgentHandle } from "./rewind-flow";
import { openSubagentsTrack } from "./subagents";
const NESTED_OWNERSHIP_PROMPT =
"You are ROOT_OWNER. Use Claude Code's native Agent tool exactly once, never Paseo tools. " +
"Name the agent direct_owner and give it this complete task: You are DIRECT_OWNER. Use " +
"Claude Code's native Agent tool exactly once. Name that agent nested_owner and give it " +
"this complete task: You are NESTED_OWNER. Use Bash exactly once to run `sleep 2; printf " +
"'NESTED_BACKGROUND_SENTINEL\\n'` with run_in_background true. Wait for the background " +
"command's completion notification. Use TaskOutput with block true to wait for the Bash task and verify exit code 0 and the sentinel output before replying exactly NESTED_DONE. Do not finish while it is running. Wait for nested_owner " +
"to finish, then reply exactly DIRECT_DONE. Wait for direct_owner to finish, then reply " +
"exactly ROOT_DONE.";
export async function launchNestedProviderSubagentOwnershipScenario(
page: Page,
cwd: string,
): Promise<AgentHandle> {
const handle = await launchAgent({
page,
provider: "claude",
cwd,
mode: "full-access",
providerConfig: { model: "claude-sonnet-5" },
});
await sendMessage(handle, NESTED_OWNERSHIP_PROMPT);
await expect(page.getByText("ROOT_DONE", { exact: true }).last()).toBeVisible({
timeout: 120_000,
});
return handle;
}
async function attachScreenshot(page: Page, testInfo: TestInfo, name: string): Promise<void> {
const path = testInfo.outputPath(`${name}.png`);
await page.screenshot({ path });
await testInfo.attach(name, { path, contentType: "image/png" });
}
async function expectOnlySubagent(page: Page, label: RegExp): Promise<Locator> {
const rows = page.locator('[data-testid^="subagents-track-row-"]');
await expect(rows).toHaveCount(1);
const row = page.getByTestId("subagents-track-header-panel").getByRole("button", { name: label });
await expect(row).toBeVisible();
return row;
}
async function selectOnlyRootSubagent(page: Page, label: RegExp): Promise<void> {
await openSubagentsTrack(page);
const row = await expectOnlySubagent(page, label);
await row.click();
}
async function openOwnedSubagents(page: Page, ownerPanel: Locator): Promise<void> {
await ownerPanel.getByTestId("subagents-track-header").click();
await expect(page.getByTestId("subagents-track-header-panel")).toBeVisible();
}
export async function expectNestedProviderSubagentOwnership(
page: Page,
testInfo: TestInfo,
phase: string,
): Promise<void> {
await expect(
page.getByText("Task notification", { exact: true }).filter({ visible: true }),
).toHaveCount(0);
await selectOnlyRootSubagent(page, /^direct_owner\b/);
const directPanel = page.getByTestId("provider-subagent-panel").filter({ visible: true });
await expect(directPanel).toBeVisible();
await openOwnedSubagents(page, directPanel);
const nestedRow = await expectOnlySubagent(page, /^nested_owner\b/);
await attachScreenshot(page, testInfo, `nested-ownership-${phase}-tree`);
await nestedRow.click();
const nestedPanel = page.locator('[data-testid="provider-subagent-panel"]:visible');
await expect(
nestedPanel
.getByRole("button", {
name: /^Task notification Background command .*completed \(exit code 0\)/,
})
.first(),
).toBeVisible();
await expect(nestedPanel).toContainText("NESTED_BACKGROUND_SENTINEL");
await expect(nestedPanel).toContainText("NESTED_DONE");
await attachScreenshot(page, testInfo, `nested-ownership-${phase}-timeline`);
}
export async function reopenNestedProviderSession(handle: AgentHandle): Promise<void> {
await handle.client.refreshAgent(handle.agentId);
await handle.page.reload();
await handle.page.getByTestId(`workspace-tab-agent_${handle.agentId}`).first().click();
await expect(handle.page.getByText("ROOT_DONE", { exact: true }).last()).toBeVisible();
}
@@ -318,9 +318,9 @@ export async function assertFileContains(filePath: string, text: string): Promis
export async function assertComposerIdle(handle: Pick<AgentHandle, "page">): Promise<void> {
await expectComposerEditable(handle.page);
await expect(handle.page.getByRole("button", { name: /stop|cancel/i })).toHaveCount(0, {
timeout: 30_000,
});
await expect(
handle.page.getByRole("button", { name: /^(?:Stop agent|Canceling agent)$/ }),
).toHaveCount(0, { timeout: 30_000 });
await expect(handle.page.getByTestId("turn-working-indicator")).toHaveCount(0, {
timeout: 30_000,
});
@@ -0,0 +1,150 @@
import { expect, type Locator, type Page } from "@playwright/test";
import { openSettings } from "./app";
import { clickSettingsBackToWorkspace, openSettingsSection } from "./settings";
const APP_SETTINGS_KEY = "@paseo:app-settings";
/** Persisted nav key -> the testID the app shell renders that item with. */
const SHELL_ROW_TEST_IDS = {
"new-workspace": "sidebar-global-new-workspace",
history: "sidebar-sessions",
search: "sidebar-search",
schedules: "sidebar-schedules",
} as const;
export type SidebarNavKey = keyof typeof SHELL_ROW_TEST_IDS;
export interface SidebarNavPreference {
key: string;
visible: boolean;
}
function shellRow(page: Page, key: SidebarNavKey): Locator {
// `:visible` rather than a plain testID: the shell keeps a compact copy of the
// sidebar mounted, so the pinned row is the first visible match.
return page.locator(`[data-testid="${SHELL_ROW_TEST_IDS[key]}"]:visible`).first();
}
function settingsRow(page: Page, key: SidebarNavKey): Locator {
return page.getByTestId(`sidebar-nav-item-${key}`);
}
function itemLabel(key: SidebarNavKey): string {
return {
"new-workspace": "New workspace",
history: "History",
search: "Search",
schedules: "Schedules",
}[key];
}
async function rowTop(locator: Locator): Promise<number | null> {
const box = await locator.boundingBox();
return box?.y ?? null;
}
export async function seedSidebarNavPreferences(
page: Page,
preferences: SidebarNavPreference[],
): Promise<void> {
await page.addInitScript(
({ key, sidebarNavItems }) => {
localStorage.setItem(key, JSON.stringify({ sidebarNavItems }));
},
{ key: APP_SETTINGS_KEY, sidebarNavItems: preferences },
);
}
export async function openSidebarNavSettings(page: Page): Promise<void> {
await openSettings(page);
await openSettingsSection(page, "appearance");
await expect(page.getByTestId("sidebar-nav-section")).toBeVisible({ timeout: 30_000 });
}
export async function leaveSettings(page: Page): Promise<void> {
await clickSettingsBackToWorkspace(page);
}
export async function moveSidebarNavItemUp(page: Page, key: SidebarNavKey): Promise<void> {
await settingsRow(page, key).getByRole("button", { name: "Move up", exact: true }).click();
}
export async function setSidebarNavItemVisible(
page: Page,
key: SidebarNavKey,
visible: boolean,
): Promise<void> {
const toggle = settingsRow(page, key).getByRole("switch", {
name: itemLabel(key),
exact: true,
});
await toggle.click();
await expect(toggle).toHaveAttribute("aria-checked", String(visible));
}
export async function expectSidebarNavSettingsRow(
page: Page,
expected: { key: SidebarNavKey; label: string; visible: boolean },
): Promise<void> {
const row = settingsRow(page, expected.key);
await expect(row).toBeVisible();
await expect(row.getByText(expected.label, { exact: true })).toBeVisible();
const toggle = row.getByRole("switch", { name: expected.label, exact: true });
await expect(toggle).toHaveAccessibleName(expected.label);
await expect(toggle).toHaveAttribute("aria-checked", String(expected.visible));
}
export async function expectSidebarNavSettingsOrder(
page: Page,
keys: SidebarNavKey[],
): Promise<void> {
await expectVerticalOrder(keys, (key) => settingsRow(page, key), "sidebar nav settings rows");
}
export async function expectSidebarOrder(page: Page, keys: SidebarNavKey[]): Promise<void> {
await expectVerticalOrder(keys, (key) => shellRow(page, key), "app shell sidebar rows");
}
export async function expectSidebarItemHidden(page: Page, key: SidebarNavKey): Promise<void> {
await expect(page.locator(`[data-testid="${SHELL_ROW_TEST_IDS[key]}"]:visible`)).toHaveCount(0);
}
export async function expectStoredSidebarNav(
page: Page,
expected: SidebarNavPreference[],
): Promise<void> {
await expect
.poll(
() =>
page.evaluate((key) => {
const raw = localStorage.getItem(key);
return raw ? (JSON.parse(raw).sidebarNavItems ?? null) : null;
}, APP_SETTINGS_KEY),
{ timeout: 15_000 },
)
.toEqual(expected);
}
async function expectVerticalOrder(
keys: SidebarNavKey[],
locate: (key: SidebarNavKey) => Locator,
subject: string,
): Promise<void> {
await expect
.poll(
async () => {
const measured = await Promise.all(
keys.map(async (key) => ({ key, top: await rowTop(locate(key)) })),
);
if (
!measured.every(
(entry): entry is { key: SidebarNavKey; top: number } => entry.top !== null,
)
)
return null;
return measured.sort((a, b) => a.top - b.top).map((entry) => entry.key);
},
{ message: `Expected ${subject} in order`, timeout: 15_000 },
)
.toEqual(keys);
}
@@ -163,7 +163,7 @@ class StartupAssertions {
await expect(hostRow).toBeVisible({ timeout: 15_000 });
await expect(hostRow).toContainText(input.label);
await expect(this.page.getByTestId("sidebar-add-project")).toBeVisible();
await expect(this.page.getByTestId("sidebar-home")).toBeVisible();
await expect(this.page.getByTestId("sidebar-import-session")).toBeVisible();
await expect(this.page.getByTestId("sidebar-settings")).toBeVisible();
await expect(this.page.getByTestId("welcome-screen")).toHaveCount(0);
return this;
@@ -276,9 +276,9 @@ export async function navigateToWorkspaceViaSidebar(
});
}
export async function returnHomeFromWorkspace(page: Page): Promise<void> {
await page.getByRole("button", { name: "Home" }).click();
await expect(page).not.toHaveURL(/\/workspace\//, { timeout: 30_000 });
export async function leaveWorkspaceViaHistory(page: Page): Promise<void> {
await page.getByRole("button", { name: "History", exact: true }).click();
await expect(page).toHaveURL(/\/sessions$/, { timeout: 30_000 });
}
export async function openWorkspaceScriptsMenu(page: Page): Promise<void> {
@@ -102,16 +102,16 @@ export async function openChangesTreePanel(page: Page): Promise<void> {
});
}
export async function openChangesPanel(page: Page): Promise<void> {
export async function openChangesPanel(page: Page, timeout = 30_000): Promise<void> {
await openChangesTreePanel(page);
const changedFile = page
.locator('[data-testid^="diff-tree-file-"][data-testid$="-toggle"]')
.filter({ visible: true })
.first();
await expect(changedFile).toBeVisible({ timeout: 30_000 });
await expect(changedFile).toBeVisible({ timeout });
await changedFile.click();
await expect(visibleTestId(page, "working-diff-panel").first()).toBeVisible({
timeout: 30_000,
timeout,
});
}
+6 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.7.0",
"version": "0.7.2",
"private": true,
"main": "index.ts",
"scripts": {
@@ -162,5 +162,10 @@
"vitest": "^4.1.6",
"wrangler": "^4.105.0",
"ws": "^8.20.0"
},
"reanimated": {
"staticFeatureFlags": {
"FORCE_REACT_RENDER_FOR_SETTLED_ANIMATIONS": false
}
}
}
@@ -65,7 +65,6 @@ function timingFor(assistantId: string): Map<string, TurnTiming> {
[
assistantId,
{
startedAt: new Date("2026-08-22T10:00:00.000Z"),
completedAt: new Date("2026-08-22T10:00:02.000Z"),
durationMs: 2_000,
},
@@ -0,0 +1,47 @@
import { useMemo } from "react";
import type { StreamItem } from "@/types/stream";
import type { StreamHistoryRowRevision } from "./strategy";
interface HistoryRowDisplayVariants {
regular?: StreamItem;
compact?: StreamItem;
}
const historyRowDisplayVariants = new WeakMap<StreamItem, HistoryRowDisplayVariants>();
function getHistoryRowDisplayVariant(item: StreamItem, compact: boolean): StreamItem {
let variants = historyRowDisplayVariants.get(item);
if (!variants) {
variants = {};
historyRowDisplayVariants.set(item, variants);
}
const key = compact ? "compact" : "regular";
variants[key] ??= { ...item };
return variants[key];
}
// Item identity is the render signal for history rows: the row boundary in view.tsx bails out
// until its item changes. Every viewport runs its history through this hook so a history host
// whose tool-call group keeps updating from the live head, a group whose expanded state changed,
// or a breakpoint change reaches the row as a fresh identity. Unchanged rows keep their identity,
// which is what limits a live update to the rows it touched.
export function useRevisedHistoryRows(
items: StreamItem[],
revision: StreamHistoryRowRevision | undefined,
): StreamItem[] {
const globalDisplayState = revision?.globalDisplayState ?? false;
const displayStateById = revision?.displayStateById;
const contentById = revision?.contentById;
const globallyRevisedRows = useMemo(
() => items.map((item) => getHistoryRowDisplayVariant(item, globalDisplayState)),
[items, globalDisplayState],
);
const displayStateRevisedRows = useMemo(
() => globallyRevisedRows.map((item) => (displayStateById?.has(item.id) ? { ...item } : item)),
[globallyRevisedRows, displayStateById],
);
return useMemo(
() => displayStateRevisedRows.map((item) => (contentById?.has(item.id) ? { ...item } : item)),
[displayStateRevisedRows, contentById],
);
}
+17 -1
View File
@@ -73,7 +73,6 @@ function thought(id: string, seed: number): Extract<StreamItem, { kind: "thought
function timingFor(...ids: string[]): Map<string, TurnTiming> {
const timing = {
startedAt: timestamp(1),
completedAt: timestamp(9),
durationMs: 8000,
};
@@ -366,6 +365,23 @@ describe("layoutStream", () => {
},
);
it("keeps layout item identity for rows whose layout did not change", () => {
const user = userMessage("u1", 1);
const first = toolCall("tool-1", 2);
const second = toolCall("tool-2", 3);
const before = layoutFor({ platform: "android", tail: [user, first, second] });
const third = toolCall("tool-3", 4);
const after = layoutFor({ platform: "android", tail: [user, first, second, third] });
// A newest-first list shifts every index, but only the rows next to the insertion change.
expect(findLayoutItem(after, user.id)).toBe(findLayoutItem(before, user.id));
expect(findLayoutItem(after, first.id)).toBe(findLayoutItem(before, first.id));
expect(findLayoutItem(after, second.id)).not.toBe(findLayoutItem(before, second.id));
expect(findLayoutItem(after, second.id).isLastInToolSequence).toBe(false);
expect(findLayoutItem(after, third.id).isLastInToolSequence).toBe(true);
});
it("computes tool sequence position from strategy-aware neighbors", () => {
const shell = toolCall("tool-1", 2);
const thinking = thought("thought-1", 3);
+102 -55
View File
@@ -15,8 +15,6 @@ export interface TurnFooterHost {
export interface StreamLayoutItem {
item: StreamItem;
index: number;
items: StreamItem[];
aboveItem: StreamItem | null;
belowItem: StreamItem | null;
gapBelow: number;
@@ -232,60 +230,109 @@ function getSegmentNeighbor(input: {
return null;
}
function layoutSegment(input: LayoutSegmentInput): StreamLayoutItem[] {
return input.items.map((item, index) => {
const aboveItem = getSegmentNeighbor({
strategy: input.strategy,
items: input.items,
index,
relation: "above",
boundaryIndex: input.boundaryIndex,
boundaryItem: input.boundaryAboveItem,
});
const belowItem = getSegmentNeighbor({
strategy: input.strategy,
items: input.items,
index,
relation: "below",
boundaryIndex: input.boundaryIndex,
boundaryItem: input.boundaryBelowItem,
});
const completedFooter = resolveCompletedFooter({
strategy: input.strategy,
items: input.items,
index,
item,
belowItem,
timingByAssistantId: input.timingByAssistantId,
auxiliaryTurnFooter: input.auxiliaryTurnFooter,
boundaryAboveItems: input.boundaryAboveItems,
boundaryAboveIndex: input.boundaryAboveIndex,
});
const assistantSpacing = getAssistantBlockSpacing({
item,
aboveItem,
belowItem,
hasFooterBelow: completedFooter !== null || (input.hasAuxiliaryFooter && belowItem === null),
});
// Last layout emitted for each stream item. A row only rerenders when its layout item identity
// changes, so an item whose render-relevant layout is unchanged must keep its previous object even
// when the surrounding array was rebuilt (a new row shifts every index in a newest-first list).
const previousLayoutItemByStreamItem = new WeakMap<StreamItem, StreamLayoutItem>();
return {
item,
index,
items: input.items,
aboveItem,
belowItem,
gapBelow: completedFooter ? 0 : getGapBetweenStreamItems(item, belowItem),
assistantSpacing,
completedFooter,
toolSequence: getToolSequence({ item, aboveItem, belowItem }),
isFirstInUserGroup: item.kind === "user_message" && aboveItem?.kind !== "user_message",
isLastInUserGroup: item.kind === "user_message" && belowItem?.kind !== "user_message",
isLastInToolSequence:
isToolSequenceItem(item) &&
!(isToolSequenceItem(belowItem) && continuesTurn(item, belowItem)),
frameOrder: input.frameOrder,
phase: input.phase,
};
function areTurnFooterHostsEqual(
left: TurnFooterHost | null,
right: TurnFooterHost | null,
): boolean {
if (left === right) return true;
if (!left || !right) return false;
return (
left.itemId === right.itemId &&
left.timing === right.timing &&
left.startIndex === right.startIndex &&
left.items === right.items
);
}
function areLayoutItemsEquivalent(previous: StreamLayoutItem, next: StreamLayoutItem): boolean {
return (
previous.item === next.item &&
previous.aboveItem === next.aboveItem &&
previous.belowItem === next.belowItem &&
previous.gapBelow === next.gapBelow &&
previous.assistantSpacing === next.assistantSpacing &&
areTurnFooterHostsEqual(previous.completedFooter, next.completedFooter) &&
previous.toolSequence === next.toolSequence &&
previous.isFirstInUserGroup === next.isFirstInUserGroup &&
previous.isLastInUserGroup === next.isLastInUserGroup &&
previous.isLastInToolSequence === next.isLastInToolSequence &&
previous.frameOrder === next.frameOrder &&
previous.phase === next.phase
);
}
function shareLayoutItem(next: StreamLayoutItem): StreamLayoutItem {
const previous = previousLayoutItemByStreamItem.get(next.item);
if (previous && areLayoutItemsEquivalent(previous, next)) {
return previous;
}
previousLayoutItemByStreamItem.set(next.item, next);
return next;
}
function layoutSegment(input: LayoutSegmentInput): StreamLayoutItem[] {
return input.items.map((item, index) => layoutSegmentItem(input, item, index));
}
function layoutSegmentItem(
input: LayoutSegmentInput,
item: StreamItem,
index: number,
): StreamLayoutItem {
const aboveItem = getSegmentNeighbor({
strategy: input.strategy,
items: input.items,
index,
relation: "above",
boundaryIndex: input.boundaryIndex,
boundaryItem: input.boundaryAboveItem,
});
const belowItem = getSegmentNeighbor({
strategy: input.strategy,
items: input.items,
index,
relation: "below",
boundaryIndex: input.boundaryIndex,
boundaryItem: input.boundaryBelowItem,
});
const completedFooter = resolveCompletedFooter({
strategy: input.strategy,
items: input.items,
index,
item,
belowItem,
timingByAssistantId: input.timingByAssistantId,
auxiliaryTurnFooter: input.auxiliaryTurnFooter,
boundaryAboveItems: input.boundaryAboveItems,
boundaryAboveIndex: input.boundaryAboveIndex,
});
const assistantSpacing = getAssistantBlockSpacing({
item,
aboveItem,
belowItem,
hasFooterBelow: completedFooter !== null || (input.hasAuxiliaryFooter && belowItem === null),
});
return shareLayoutItem({
item,
aboveItem,
belowItem,
gapBelow: completedFooter ? 0 : getGapBetweenStreamItems(item, belowItem),
assistantSpacing,
completedFooter,
toolSequence: getToolSequence({ item, aboveItem, belowItem }),
isFirstInUserGroup: item.kind === "user_message" && aboveItem?.kind !== "user_message",
isLastInUserGroup: item.kind === "user_message" && belowItem?.kind !== "user_message",
isLastInToolSequence:
isToolSequenceItem(item) &&
!(isToolSequenceItem(belowItem) && continuesTurn(item, belowItem)),
frameOrder: input.frameOrder,
phase: input.phase,
});
}
+27 -3
View File
@@ -1,5 +1,7 @@
import { describe, expect, it } from "vitest";
import type { StreamItem } from "@/types/stream";
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
import { findMountedWindowStart } from "./history-window";
import { buildAgentStreamRenderModel } from "./model";
function createTimestamp(seed: number): Date {
@@ -69,12 +71,36 @@ describe("buildAgentStreamRenderModel", () => {
expect(model.turnTiming.byAssistantId.has("hidden-a")).toBe(false);
expect(model.turnTiming.byAssistantId.get("visible-a")).toEqual({
startedAt: tail[2]?.timestamp,
completedAt: tail[3]?.timestamp,
durationMs: 1000,
});
});
it("keeps the mounted boundary stable when a transformer filters an earlier item", () => {
const tail = [
userMessage("filtered", 1),
assistantMessage("hidden", 2),
userMessage("visible-u", 3),
assistantMessage("visible-a", 4),
];
const projectedTail = projectPluginTimelineItems(tail, ({ sourceId }) =>
sourceId === "filtered" ? [] : undefined,
);
const historyStart = findMountedWindowStart({ items: projectedTail, minMountedCount: 2 });
const model = buildAgentStreamRenderModel({
isTurnActive: false,
activeTurnStartedAt: null,
tail: projectedTail,
head: [],
platform: "native",
isMobileBreakpoint: false,
historyStart,
});
expect(model.history.map((item) => item.id)).toEqual(["visible-a", "visible-u"]);
});
it("keeps head separate from committed history on desktop web", () => {
const tail: StreamItem[] = [];
for (let index = 0; index < 60; index += 1) {
@@ -176,7 +202,6 @@ describe("buildAgentStreamRenderModel", () => {
expect(model.turnTiming.runningStartedAt).toBe(null);
expect(model.turnTiming.byAssistantId.get("live-a")).toEqual({
startedAt: tail[0]?.timestamp,
completedAt: head[0]?.timestamp,
durationMs: 3000,
});
@@ -196,7 +221,6 @@ describe("buildAgentStreamRenderModel", () => {
expect(model.segments.historyMounted.map((item) => item.id)).toEqual(["a1", "u1"]);
expect(model.turnTiming.byAssistantId.get("a1")).toEqual({
startedAt: tail[0]?.timestamp,
completedAt: tail[1]?.timestamp,
durationMs: 3000,
});
@@ -9,7 +9,6 @@ import {
} from "react";
import {
FlatList,
Keyboard,
Platform,
View,
type LayoutChangeEvent,
@@ -23,6 +22,9 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner";
import type { StreamItem } from "@/types/stream";
import type { Theme } from "@/styles/theme";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useSettledKeyboardShift } from "@/hooks/keyboard-shift-context";
import { resolveStreamKeyboardInset } from "@/hooks/keyboard-shift-policy";
import { useRevisedHistoryRows } from "./history-row-revision";
import { useBottomAnchorController } from "./bottom-anchor-controller";
import { useScrollKeyboardDismiss } from "./scroll-keyboard-dismiss/use-scroll-keyboard-dismiss";
import type { StreamRenderInput, StreamStrategy, StreamViewportHandle } from "./strategy";
@@ -63,24 +65,6 @@ const historyStartSlotStyle: ViewStyle = {
};
const HISTORY_START_SETTLE_FRAMES = 2;
interface HistoryRowDisplayVariants {
regular?: StreamItem;
compact?: StreamItem;
}
const historyRowDisplayVariants = new WeakMap<StreamItem, HistoryRowDisplayVariants>();
function getHistoryRowDisplayVariant(item: StreamItem, compact: boolean): StreamItem {
let variants = historyRowDisplayVariants.get(item);
if (!variants) {
variants = {};
historyRowDisplayVariants.set(item, variants);
}
const key = compact ? "compact" : "regular";
variants[key] ??= { ...item };
return variants[key];
}
function keyExtractor(item: { id: string }): string {
return item.id;
}
@@ -121,6 +105,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
const scrollOffsetYRef = useRef(0);
const isUserScrollActiveRef = useRef(false);
const scrollKeyboardDismiss = useScrollKeyboardDismiss();
const settledKeyboardShift = useSettledKeyboardShift();
const userScrollEndFrameIdRef = useRef<number | null>(null);
const programmaticScrollEventBudgetRef = useRef(0);
const [isNativeViewportSettling, setIsNativeViewportSettling] = useState(false);
@@ -138,27 +123,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
}
return [...segments.historyVirtualized, ...segments.historyMounted];
}, [segments.historyMounted, segments.historyVirtualized]);
// Keep unchanged item identities intact so live updates only rerender rows
// whose projected content or local display state actually changed. A rare
// breakpoint change intentionally refreshes the whole history window.
const globallyRevisedHistoryRows = useMemo(() => {
const globalDisplayState = historyRowRevision?.globalDisplayState ?? false;
return historyItems.map((item) => getHistoryRowDisplayVariant(item, globalDisplayState));
}, [historyItems, historyRowRevision?.globalDisplayState]);
const displayStateHistoryRows = useMemo(
() =>
globallyRevisedHistoryRows.map((item) =>
historyRowRevision?.displayStateById.has(item.id) ? { ...item } : item,
),
[globallyRevisedHistoryRows, historyRowRevision?.displayStateById],
);
const historyRows = useMemo(
() =>
displayStateHistoryRows.map((item) =>
historyRowRevision?.contentById.has(item.id) ? { ...item } : item,
),
[displayStateHistoryRows, historyRowRevision?.contentById],
);
const historyRows = useRevisedHistoryRows(historyItems, historyRowRevision);
const getHistoryStartPaginationInput = useStableEvent((): HistoryStartPaginationInput => {
const metrics = streamViewportMetricsRef.current;
const hasMeasuredViewport =
@@ -310,6 +275,34 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
Platform.OS === "android" && bottomAnchorController.mode === "sticky-bottom"
? undefined
: DEFAULT_MAINTAIN_VISIBLE_CONTENT_POSITION;
const streamKeyboardInset = useMemo(
() =>
resolveStreamKeyboardInset({
platform: Platform.OS === "ios" ? "ios" : "android",
settledShift: settledKeyboardShift,
}),
[settledKeyboardShift],
);
const listContentContainerStyle = useMemo(
() => [
baseListContentContainerStyle,
{ paddingBottom: streamKeyboardInset.contentContainerPaddingBottom },
],
[baseListContentContainerStyle, streamKeyboardInset.contentContainerPaddingBottom],
);
const listInsetProps = useMemo(
() =>
streamKeyboardInset.contentInset
? {
automaticallyAdjustContentInsets: false,
automaticallyAdjustsScrollIndicatorInsets: false,
contentInsetAdjustmentBehavior: "never" as const,
contentInset: streamKeyboardInset.contentInset,
scrollIndicatorInsets: streamKeyboardInset.contentInset,
}
: {},
[streamKeyboardInset.contentInset],
);
useEffect(() => {
streamViewportMetricsRef.current = {
@@ -342,27 +335,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
};
}, [agentId, clearNativeViewportSettling, clearPendingUserScrollEnd, evaluateHistoryStart]);
useEffect(() => {
const keyboardEvents = [
"keyboardWillShow",
"keyboardWillHide",
"keyboardDidShow",
"keyboardDidHide",
"keyboardWillChangeFrame",
"keyboardDidChangeFrame",
] as const;
const subscriptions = keyboardEvents.map((eventName) =>
Keyboard.addListener(eventName, () => {
markNativeViewportSettling();
}),
);
return () => {
for (const subscription of subscriptions) {
subscription.remove();
}
clearNativeViewportSettling();
};
}, [clearNativeViewportSettling, markNativeViewportSettling]);
useEffect(() => () => clearNativeViewportSettling(), [clearNativeViewportSettling]);
useEffect(() => {
bottomAnchorController.prepareForStickyContentChange();
@@ -597,6 +570,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
// data or the live header changes, preserving the row identities above.
return (
<FlatList
{...listInsetProps}
ref={flatListRef}
data={historyRows}
renderItem={renderItem}
@@ -606,7 +580,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
nativeID="agent-chat-scroll-native-virtualized"
ListHeaderComponent={liveHeaderContent ?? undefined}
ListFooterComponent={historyFooterContent ?? undefined}
contentContainerStyle={baseListContentContainerStyle}
contentContainerStyle={listContentContainerStyle}
style={listStyle}
onLayout={handleListLayout}
onScroll={handleScroll}
@@ -252,6 +252,74 @@ describe("createWebStreamStrategy", () => {
expect(renderLiveHeadRow).toHaveBeenCalledTimes(2);
});
it("rerenders only the history row whose content revision changed", () => {
const strategy = createWebStreamStrategy({ isMobileBreakpoint: false });
const viewportRef = React.createRef<StreamViewportHandle>();
const host = userMessage(1);
const other = userMessage(2);
const renderCountById = new Map<string, number>();
const HistoryRow = React.memo(function HistoryRow({ item }: { item: StreamItem }) {
renderCountById.set(item.id, (renderCountById.get(item.id) ?? 0) + 1);
return <div>{item.id}</div>;
});
const renderInput: StreamRenderInput = {
agentId: "agent",
segments: {
historyVirtualized: [],
historyMounted: [host, other],
liveHead: [],
},
boundary: {
hasVirtualizedHistory: false,
hasMountedHistory: true,
hasLiveHead: false,
},
renderers: {
...createRenderers(vi.fn()),
renderHistoryMountedRow: (item) => <HistoryRow item={item} />,
},
listEmptyComponent: null,
viewportRef,
routeBottomAnchorRequest: null,
isAuthoritativeHistoryReady: true,
onNearBottomChange: vi.fn(),
onNearHistoryStart: vi.fn().mockReturnValue(true),
isLoadingOlderHistory: false,
hasOlderHistory: false,
olderHistoryProgressKey: null,
scrollEnabled: true,
listStyle: null,
baseListContentContainerStyle: null,
forwardListContentContainerStyle: null,
};
const unrevised = {
contentById: new Set<string>(),
displayStateById: new Set<string>(),
globalDisplayState: false,
};
container = document.createElement("div");
document.body.appendChild(container);
root = createRoot(container);
act(() => {
root?.render(strategy.render({ ...renderInput, historyRowRevision: unrevised }));
});
expect(renderCountById.get(host.id)).toBe(1);
expect(renderCountById.get(other.id)).toBe(1);
act(() => {
root?.render(
strategy.render({
...renderInput,
historyRowRevision: { ...unrevised, contentById: new Set([host.id]) },
}),
);
});
expect(renderCountById.get(host.id)).toBe(2);
expect(renderCountById.get(other.id)).toBe(1);
});
it("keeps a row mounted when it moves from the live head into mounted history", () => {
const strategy = createWebStreamStrategy({ isMobileBreakpoint: false });
const viewportRef = React.createRef<StreamViewportHandle>();
+12 -1
View File
@@ -20,6 +20,7 @@ import {
shouldAdjustScrollForVirtualRowResize,
} from "./web-virtualization";
import type { StreamRenderInput, StreamStrategy, StreamViewportHandle } from "./strategy";
import { useRevisedHistoryRows } from "./history-row-revision";
import { createStreamStrategy } from "./strategy";
import {
abandonHistoryStartPaginationRequest,
@@ -279,7 +280,8 @@ function isScrollContainerOverscrolledPastBottom(
function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: boolean }) {
const {
segments,
segments: inputSegments,
historyRowRevision,
liveHeadRowRevision,
boundary,
renderers,
@@ -296,6 +298,15 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
scrollEnabled,
isMobileBreakpoint,
} = props;
const historyVirtualized = useRevisedHistoryRows(
inputSegments.historyVirtualized,
historyRowRevision,
);
const historyMounted = useRevisedHistoryRows(inputSegments.historyMounted, historyRowRevision);
const segments = useMemo(
() => ({ ...inputSegments, historyVirtualized, historyMounted }),
[historyMounted, historyVirtualized, inputSegments],
);
const isActive = useRetainedPanelActive();
const isActiveRef = useRef(isActive);
const scrollContainerRef = useRef<HTMLElement | null>(null);
@@ -86,7 +86,13 @@ describe("canonical turn membership", () => {
assistant("heartbeat-2-reply", 6, "turn-3"),
];
expect(completedFooterIds(layoutFor(items, false).layout)).toEqual(["heartbeat-2-reply"]);
const completed = layoutFor(items, false);
expect(completedFooterIds(completed.layout)).toEqual(["heartbeat-2-reply"]);
expect(completed.layout.auxiliaryTurnFooter?.timing).toEqual({
completedAt: at(6),
durationMs: null,
});
});
it.each([
@@ -118,7 +124,6 @@ describe("canonical turn membership", () => {
const completed = layoutFor(completedItems, false);
expect(completedFooterIds(completed.layout)).toEqual(["done"]);
expect(completed.model.turnTiming.byAssistantId.get("done")).toMatchObject({
startedAt: at(1),
completedAt: at(9),
durationMs: 8000,
});
+48 -19
View File
@@ -32,7 +32,7 @@ import {
AssistantMessage,
SpeakMessage,
UserMessage,
ActivityLog,
Notification,
ToolCall,
TodoListCard,
CompactionMarker,
@@ -107,7 +107,8 @@ import type { Theme } from "@/styles/theme";
import { recordRenderProfileReasons } from "@/utils/render-profiler";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { useStreamHistoryWindow } from "./use-stream-history-window";
import { PluginTimelineItemView } from "@/plugins/timeline";
import { PluginTimelineItemView, useInstalledTimelineTransform } from "@/plugins/timeline";
import { projectPluginTimelineItems } from "@/plugins/timeline/projection";
function renderLiveAuxiliaryNode(input: {
pendingPermissions: ReactNode;
@@ -220,6 +221,22 @@ function renderListEmptyComponent(input: {
);
}
// History rows sit inside FlatList cells that rerender on every data change (RN recreates each
// CellRenderer with a fresh ref and, in a newest-first list, a shifted index). This boundary is
// what stops that churn: a row renders again only when its stream item identity, its layout item
// identity, or the renderer itself changes. Item identity is the revision signal the strategy
// already uses (`useRevisedHistoryRows` clones items whose content or display state changed).
const HistoryStreamRow = memo(function HistoryStreamRow({
layoutItem,
renderStreamItem,
}: {
item: StreamItem;
layoutItem: StreamLayoutItem;
renderStreamItem: (layoutItem: StreamLayoutItem) => ReactNode;
}) {
return <>{renderStreamItem(layoutItem)}</>;
});
function renderHistoryStreamItem(input: {
item: StreamItem;
layoutItemById: Map<string, StreamLayoutItem>;
@@ -229,7 +246,13 @@ function renderHistoryStreamItem(input: {
if (!layoutItem) {
return null;
}
return input.renderStreamItem(layoutItem);
return (
<HistoryStreamRow
item={input.item}
layoutItem={layoutItem}
renderStreamItem={input.renderStreamItem}
/>
);
}
function renderLiveHeadStreamItem(input: {
@@ -353,6 +376,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
// Get serverId (fallback to agent's serverId if not provided)
const resolvedServerId = serverId ?? context.serverId ?? "";
const transformTimelineItem = useInstalledTimelineTransform(resolvedServerId);
const client = useSessionStore((state) => state.sessions[resolvedServerId]?.client ?? null);
const sessionStreamHead = useSessionStore((state) =>
@@ -535,6 +559,13 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
toolCallDetailLevel,
],
);
const projectedPlugins = useMemo(
() => ({
tail: projectPluginTimelineItems(projectedToolCalls.tail, transformTimelineItem),
head: projectPluginTimelineItems(projectedToolCalls.head, transformTimelineItem),
}),
[projectedToolCalls.head, projectedToolCalls.tail, transformTimelineItem],
);
const {
start: historyWindowStart,
hasLocalHistory,
@@ -542,7 +573,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
loadOlder,
} = useStreamHistoryWindow({
agentId,
items: projectedToolCalls.tail,
items: projectedPlugins.tail,
loadRemoteOlder,
});
const isLoadingOlder = remoteIsLoadingOlder;
@@ -553,8 +584,8 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
return buildAgentStreamRenderModel({
isTurnActive,
activeTurnStartedAt: effectiveTurnPresentation.startedAt,
tail: projectedToolCalls.tail,
head: projectedToolCalls.head,
tail: projectedPlugins.tail,
head: projectedPlugins.head,
platform: isWeb ? "web" : "native",
isMobileBreakpoint: isMobile,
historyStart: historyWindowStart,
@@ -562,8 +593,8 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
}, [
isMobile,
isTurnActive,
projectedToolCalls.head,
projectedToolCalls.tail,
projectedPlugins.head,
projectedPlugins.tail,
effectiveTurnPresentation.startedAt,
historyWindowStart,
]);
@@ -789,9 +820,14 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
[context.cwd, setInlineDetailsExpanded, handleToolCallOpenFile],
);
// Read through a stable event so live group updates do not change the renderer identity
// every tick; history hosts whose group changed are revised through `historyRowRevision`.
const getToolCallGroup = useStableEvent((hostId: string) =>
projectedToolCalls.groupsByHostId.get(hostId),
);
const renderToolCallItem = useCallback(
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "tool_call" }>) => {
const group = projectedToolCalls.groupsByHostId.get(item.id);
const group = getToolCallGroup(item.id);
if (!group) {
return renderSingleToolCallItem(item, layoutItem.isLastInToolSequence);
}
@@ -818,8 +854,8 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
);
},
[
projectedToolCalls.groupsByHostId,
expandedToolCallGroupIds,
getToolCallGroup,
renderSingleToolCallItem,
setToolCallGroupExpanded,
],
@@ -841,15 +877,8 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
case "tool_call":
return renderToolCallItem(layoutItem, item);
case "activity_log":
return (
<ActivityLog
type={item.activityType}
message={item.message}
timestamp={item.timestamp.getTime()}
metadata={item.metadata}
/>
);
case "notification":
return <Notification level={item.level} message={item.message} />;
case "todo_list":
return <TodoListCard items={item.items} activity={item.activity} />;
@@ -70,7 +70,7 @@ export function estimateStreamItemHeight(item: StreamItem): number {
return COLLAPSED_TOOL_SEQUENCE_ROW_HEIGHT_ESTIMATE;
case "todo_list":
return 144;
case "activity_log":
case "notification":
return 88;
case "compaction":
return 72;
+37 -8
View File
@@ -4,7 +4,13 @@ import { PortalProvider } from "@gorhom/portal";
import { QueryClientProvider } from "@tanstack/react-query";
import * as Linking from "expo-linking";
import * as Notifications from "expo-notifications";
import { Stack, useNavigationContainerRef, usePathname, useRouter } from "expo-router";
import {
Stack,
useGlobalSearchParams,
useNavigationContainerRef,
usePathname,
useRouter,
} from "expo-router";
import {
createContext,
type ReactNode,
@@ -63,7 +69,7 @@ import { HorizontalScrollProvider } from "@/contexts/horizontal-scroll-context";
import { SessionProvider } from "@/contexts/session-context";
import { SidebarCalloutProvider } from "@/contexts/sidebar-callout-context";
import { ToastProvider } from "@/contexts/toast-context";
import { VoiceProvider } from "@/contexts/voice-context";
import { useVoiceOptional, VoiceProvider } from "@/contexts/voice-context";
import {
resolveStartupBlocker,
resolveStartupNavigationReady,
@@ -95,7 +101,7 @@ import { useOpenProject } from "@/hooks/use-open-project";
import { useAppSettings } from "@/hooks/use-settings";
import { useStableEvent } from "@/hooks/use-stable-event";
import { useOpenAgentListGesture } from "@/mobile-panels/gestures";
import { MobilePanelsProvider } from "@/mobile-panels/provider";
import { MobilePanelsProvider, useIsMobilePanelActive } from "@/mobile-panels/provider";
import { I18nProvider } from "@/i18n/provider";
import {
KeyboardActionDispatcherProvider,
@@ -114,7 +120,7 @@ import {
useHosts,
} from "@/runtime/host-runtime";
import { getDaemonStartService } from "@/runtime/daemon-start-service";
import { selectIsAgentListOpen, usePanelStore } from "@/stores/panel-store";
import { usePanelStore } from "@/stores/panel-store";
import { flushDraftPersistStorage } from "@/stores/draft-store";
import { getNextThemePreference } from "@/styles/theme";
import { useSessionStore } from "@/stores/session-store";
@@ -627,10 +633,9 @@ function SidebarChrome({
keyboardShortcutsEnabled: boolean;
}) {
const isCompactLayout = useIsCompactFormFactor();
const isOpen = usePanelStore((state) =>
selectIsAgentListOpen(state, { isCompact: isCompactLayout }),
);
const active = visible && isOpen;
const isMobileActive = useIsMobilePanelActive("agent-list");
const isDesktopOpen = usePanelStore((state) => state.desktop.agentListOpen);
const active = visible && (isCompactLayout ? isMobileActive : isDesktopOpen);
return (
<SidebarModelProvider active={active}>
{mounted ? <LeftSidebar active={active} /> : null}
@@ -668,11 +673,35 @@ function ProvidersWrapper({ children }: { children: ReactNode }) {
<HostSessionManager />
<FaviconStatusSync />
<AppearanceStyleBoundary>{children}</AppearanceStyleBoundary>
<VoiceCallContextSync />
</VoiceProvider>
</AppearanceProvider>
);
}
function VoiceCallContextSync() {
const voice = useVoiceOptional();
const params = useGlobalSearchParams<{
serverId?: string | string[];
workspaceId?: string | string[];
agentId?: string | string[];
}>();
const serverId = Array.isArray(params.serverId) ? params.serverId[0] : params.serverId;
const workspaceId = Array.isArray(params.workspaceId)
? params.workspaceId[0]
: params.workspaceId;
const agentId = Array.isArray(params.agentId) ? params.agentId[0] : params.agentId;
useEffect(() => {
if (!voice?.isVoiceMode || voice.activeServerId !== serverId) return;
void voice
.updateCallContext({ workspaceId: workspaceId ?? null, agentId: agentId ?? null })
.catch((error) => console.warn("[VoiceCall] Failed to update app context", error));
}, [agentId, serverId, voice, workspaceId]);
return null;
}
function DesktopWindowControlsSync() {
const { isLoading } = useAppSettings();
const { theme } = useUnistyles();
@@ -42,6 +42,7 @@ export const ACP_PROVIDER_ICON_SVGS = {
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24">\n <path fill="currentColor" d="M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81"/>\n</svg>\n',
"github-copilot-cli":
'<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">\n<path fill-rule="evenodd" clip-rule="evenodd" d="M7.99816 14.2779C12.0678 14.2779 14.9997 11.6274 14.9997 10.9574V9.3189C14.939 8.77306 14.4165 7.82349 13.6074 7.48636C13.5959 7.42498 13.5859 7.36153 13.5756 7.29542C13.5506 7.13548 13.5231 6.95977 13.4649 6.75954C13.6409 6.31508 13.6873 5.81187 13.6873 5.31135C13.6873 4.54947 13.5757 3.76321 13.0811 3.13712C12.5745 2.4959 11.7737 2.15372 10.6972 2.03411C9.64215 1.91688 8.71828 2.06409 8.12157 2.70342C8.07827 2.74981 8.0345 2.79812 7.99655 2.84746C7.95861 2.79812 7.91805 2.74981 7.87475 2.70342C7.27804 2.06409 6.35416 1.91688 5.29908 2.03411C4.22263 2.15372 3.42181 2.4959 2.91521 3.13712C2.42057 3.76321 2.30905 4.54947 2.30905 5.31135C2.30905 5.81187 2.35539 6.31508 2.53142 6.75954C2.47323 6.95977 2.44574 7.13542 2.42072 7.29536C2.41037 7.3615 2.40044 7.42496 2.38893 7.48636C1.57983 7.82349 1.05728 8.77306 0.996582 9.3189V10.9574C0.996582 11.6274 3.92849 14.2779 7.99816 14.2779ZM10.5523 3.33859C9.63863 3.23707 9.25001 3.41798 9.0811 3.59896C8.90273 3.79007 8.76738 4.19254 8.86971 5.0112C8.94909 5.64627 9.13423 6.08757 9.41018 6.36929C9.67188 6.63645 10.0966 6.8426 10.8435 6.8426C11.6506 6.8426 11.9631 6.66867 12.1051 6.51046C12.2619 6.33577 12.3748 6.00462 12.3748 5.31135C12.3748 4.64141 12.2675 4.22455 12.0513 3.95077C11.8469 3.69214 11.4446 3.43773 10.5523 3.33859ZM6.91639 3.59896C6.74748 3.41798 6.35886 3.23707 5.44518 3.33859C4.55289 3.43773 4.15058 3.69214 3.94624 3.95077C3.72994 4.22455 3.62271 4.64141 3.62271 5.31135C3.62271 6.00462 3.73563 6.33577 3.89239 6.51046C4.03436 6.66867 4.34693 6.8426 5.15396 6.8426C5.90092 6.8426 6.32561 6.63645 6.58731 6.36929C6.86326 6.08757 7.0484 5.64627 7.12778 5.0112C7.23011 4.19254 7.09476 3.79007 6.91639 3.59896ZM7.99818 12.9788C9.99307 12.9788 12.0088 12.0076 12.3748 11.7248V8.00133L12.3546 7.90026C11.9257 8.08369 11.4142 8.1551 10.8435 8.1551C9.84049 8.1551 9.04148 7.86851 8.47257 7.28773C8.28092 7.09208 8.12536 6.87308 7.99978 6.6378C7.8742 6.87308 7.71544 7.09208 7.52378 7.28773C6.95488 7.86851 6.15587 8.1551 5.15283 8.1551C4.58212 8.1551 4.07068 8.08369 3.6418 7.90026L3.62158 8.00133V11.7248C3.98755 12.0076 6.00329 12.9788 7.99818 12.9788Z" fill="currentColor"/>\n<path d="M6.46854 9.0301C6.83097 9.0301 7.12479 9.32391 7.12479 9.68635V10.9988C7.12479 11.3613 6.83097 11.6551 6.46854 11.6551C6.1061 11.6551 5.81229 11.3613 5.81229 10.9988V9.68635C5.81229 9.32391 6.1061 9.0301 6.46854 9.0301Z" fill="currentColor"/>\n<path d="M10.1873 9.68635C10.1873 9.32391 9.89347 9.0301 9.53104 9.0301C9.1686 9.0301 8.87479 9.32391 8.87479 9.68635V10.9988C8.87479 11.3613 9.1686 11.6551 9.53104 11.6551C9.89347 11.6551 10.1873 11.3613 10.1873 10.9988V9.68635Z" fill="currentColor"/>\n</svg>\n',
gjc: '<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="76 62 872 872">\n <path fill="currentColor" d="M284 493C307 423 337 375 377 349C416 318 463 303 512 303C561 303 608 318 647 349C687 375 717 423 740 493C615 454 409 454 284 493Z"/>\n <path fill="none" stroke="currentColor" stroke-width="38" stroke-linecap="round" d="M371 478C355 367 304 260 197 229M653 478C669 367 720 260 827 229"/>\n <path fill="currentColor" d="M98 613C109 510 295 451 512 451C729 451 915 510 926 613C935 681 850 744 759 765L763 717C833 698 883 655 881 613C875 554 711 513 512 513C313 513 149 554 143 613C141 655 191 698 261 717L265 765C174 744 89 681 98 613Z"/>\n <path fill="currentColor" fill-rule="evenodd" d="M356 560H668A94 94 0 0 1 762 654V692A94 94 0 0 1 668 786H356A94 94 0 0 1 262 692V654A94 94 0 0 1 356 560ZM364 586H660A71 71 0 0 1 731 657V689A71 71 0 0 1 660 760H364A71 71 0 0 1 293 689V657A71 71 0 0 1 364 586Z"/>\n <path fill="currentColor" d="M365.5 654H450.5A15.5 15.5 0 0 1 466 669.5A15.5 15.5 0 0 1 450.5 685H365.5A15.5 15.5 0 0 1 350 669.5A15.5 15.5 0 0 1 365.5 654ZM573.5 654H658.5A15.5 15.5 0 0 1 674 669.5A15.5 15.5 0 0 1 658.5 685H573.5A15.5 15.5 0 0 1 558 669.5A15.5 15.5 0 0 1 573.5 654Z"/>\n</svg>\n',
"glm-acp-agent":
'<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="currentColor" fill-rule="evenodd"><title>Z.ai</title><path d="M8.07 1.333L6.618 3.302H.435L1.887 1.333h6.184zM15.503 12.699L14.052 14.667h-6.161l1.449-1.968h6.163zM16 1.333L6.176 14.667H0L9.824 1.333H16z"/></svg>\n',
goose:
@@ -0,0 +1,7 @@
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="76 62 872 872">
<path fill="currentColor" d="M284 493C307 423 337 375 377 349C416 318 463 303 512 303C561 303 608 318 647 349C687 375 717 423 740 493C615 454 409 454 284 493Z"/>
<path fill="none" stroke="currentColor" stroke-width="38" stroke-linecap="round" d="M371 478C355 367 304 260 197 229M653 478C669 367 720 260 827 229"/>
<path fill="currentColor" d="M98 613C109 510 295 451 512 451C729 451 915 510 926 613C935 681 850 744 759 765L763 717C833 698 883 655 881 613C875 554 711 513 512 513C313 513 149 554 143 613C141 655 191 698 261 717L265 765C174 744 89 681 98 613Z"/>
<path fill="currentColor" fill-rule="evenodd" d="M356 560H668A94 94 0 0 1 762 654V692A94 94 0 0 1 668 786H356A94 94 0 0 1 262 692V654A94 94 0 0 1 356 560ZM364 586H660A71 71 0 0 1 731 657V689A71 71 0 0 1 660 760H364A71 71 0 0 1 293 689V657A71 71 0 0 1 364 586Z"/>
<path fill="currentColor" d="M365.5 654H450.5A15.5 15.5 0 0 1 466 669.5A15.5 15.5 0 0 1 450.5 685H365.5A15.5 15.5 0 0 1 350 669.5A15.5 15.5 0 0 1 365.5 654ZM573.5 654H658.5A15.5 15.5 0 0 1 674 669.5A15.5 15.5 0 0 1 658.5 685H573.5A15.5 15.5 0 0 1 558 669.5A15.5 15.5 0 0 1 573.5 654Z"/>
</svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

@@ -96,7 +96,8 @@ export function useAgentControlCommandCenterActions(input: {
provider: controls.provider ?? null,
labels: buildAgentControlContributionLabels(t),
icons: {
provider: (provider) => getCommandCenterIcon(getProviderIcon(provider)),
provider: (provider) =>
getCommandCenterIcon(getProviderIcon(provider, controls.serverId)),
thinking: getCommandCenterIcon(ThinkingIcon),
planMode: getCommandCenterIcon(PlanModeIcon),
mode: (modeId) =>
@@ -8,6 +8,7 @@ import {
FolderPlus,
History,
Home,
Import,
Keyboard,
PanelLeft,
Plus,
@@ -17,6 +18,7 @@ import { withUnistyles } from "react-native-unistyles";
import { getIsElectronRuntime, useIsCompactFormFactor } from "@/constants/layout";
import { useKeyboardShortcutOverrides } from "@/hooks/use-keyboard-shortcut-overrides";
import { useOpenAddProject } from "@/hooks/use-open-add-project";
import { useImportSession } from "@/hooks/use-import-session";
import { useKeyboardActionDispatcher } from "@/keyboard/keyboard-action-dispatcher-context";
import { useKeyboardShortcutsAvailable } from "@/keyboard/availability";
import { resolveShortcutKeysForAction } from "@/keyboard/keyboard-shortcuts";
@@ -52,6 +54,7 @@ const ThemedSettings = withUnistyles(Settings, (theme) => ({
color: theme.colors.foregroundMuted,
}));
const ThemedHome = withUnistyles(Home, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedImport = withUnistyles(Import, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedFolder = withUnistyles(Folder, (theme) => ({ color: theme.colors.foregroundMuted }));
const ThemedCircleDashed = withUnistyles(CircleDashed, (theme) => ({
color: theme.colors.foregroundMuted,
@@ -88,6 +91,10 @@ function HomeIcon({ size }: CommandCenterIconProps) {
return <ThemedHome size={size} strokeWidth={2.2} />;
}
function ImportIcon({ size }: CommandCenterIconProps) {
return <ThemedImport size={size} strokeWidth={2.2} />;
}
function FolderIcon({ size }: CommandCenterIconProps) {
return <ThemedFolder size={size} strokeWidth={2.2} />;
}
@@ -106,6 +113,7 @@ export function CommandCenterRootActions() {
const { overrides } = useKeyboardShortcutOverrides();
const shortcutsAvailable = useKeyboardShortcutsAvailable();
const openAddProject = useOpenAddProject();
const { open: openImportSession, sheet: importSessionSheet } = useImportSession();
const settingsRoute = useMemo<Href>(() => buildSettingsRoute(), []);
const homeRoute = useMemo<Href>(() => buildOpenProjectRoute(), []);
const sessionsRoute = useMemo<Href>(() => buildSessionsRoute(), []);
@@ -166,11 +174,29 @@ export function CommandCenterRootActions() {
},
},
{
id: "home",
id: "import-session",
group: "actions",
groupRank: 0,
rank: 2,
keywords: ["home", "start", "import", "session", "pair", "device", "providers"],
keywords: ["import", "session", "terminal"],
visibility: "always",
run: () => {
clearCommandCenterFocusRestoreElement();
openImportSession();
},
presentation: {
kind: "action",
title: t("importSession.title"),
sectionTitle: t("shell.commandCenter.actions"),
icon: ImportIcon,
},
},
{
id: "home",
group: "actions",
groupRank: 0,
rank: 3,
keywords: ["home", "start", "pair", "device", "providers"],
visibility: "query",
run: () => {
clearCommandCenterFocusRestoreElement();
@@ -187,7 +213,7 @@ export function CommandCenterRootActions() {
id: "history",
group: "actions",
groupRank: 0,
rank: 3,
rank: 4,
keywords: ["history", "sessions", "recent"],
visibility: "always",
run: () => {
@@ -205,7 +231,7 @@ export function CommandCenterRootActions() {
id: "schedules",
group: "actions",
groupRank: 0,
rank: 4,
rank: 5,
keywords: ["schedules", "scheduled", "automation", "recurring"],
visibility: "always",
run: () => {
@@ -223,7 +249,7 @@ export function CommandCenterRootActions() {
id: "settings",
group: "actions",
groupRank: 0,
rank: 5,
rank: 6,
keywords: ["settings", "preferences", "config", "configuration"],
visibility: "always",
run: () => {
@@ -250,7 +276,7 @@ export function CommandCenterRootActions() {
id: "toggle-left-sidebar",
group: "actions",
groupRank: 0,
rank: 7,
rank: 8,
keywords: ["toggle", "sidebar", "left", "panel", "workspaces"],
visibility: "query",
run: () => {
@@ -274,7 +300,7 @@ export function CommandCenterRootActions() {
id: "keyboard-shortcuts",
group: "actions",
groupRank: 0,
rank: 6,
rank: 7,
keywords: ["keyboard", "shortcuts", "keys", "hotkeys"],
visibility: "always",
run: () => setShortcutsDialogOpen(true),
@@ -309,6 +335,7 @@ export function CommandCenterRootActions() {
homeRoute,
keyboardActionDispatcher,
openAddProject,
openImportSession,
overrides,
schedulesRoute,
sessionsRoute,
@@ -322,5 +349,5 @@ export function CommandCenterRootActions() {
]);
useCommandCenterActions({ sourceId: "root", enabled: true, actions });
return null;
return importSessionSheet;
}
@@ -476,7 +476,7 @@ export function AdaptiveModalSheet({
const { t } = useTranslation();
const isMobile = useIsCompactFormFactor();
const insets = useSafeAreaInsets();
const isKeyboardVisible = useKeyboardVisibility();
const isKeyboardVisible = useKeyboardVisibility(visible);
const resolvedSnapPoints = useMemo(() => snapPoints ?? ["65%", "90%"], [snapPoints]);
const compactSafeAreaPadding = useMemo(
() =>
+1 -1
View File
@@ -232,7 +232,7 @@ function SessionRow({
const projectName = agent.projectPlacement?.projectName ?? "";
const branch = agent.projectPlacement?.checkout.currentBranch ?? "";
const workspaceName = agent.projectPlacement?.workspaceName ?? "";
const ProviderIcon = getProviderIcon(agent.provider);
const ProviderIcon = getProviderIcon(agent.provider, agent.serverId);
const pendingPermissionCount = agent.pendingPermissionCount ?? 0;
const rangesFor = useCallback(
(field: AgentSearchMatch["field"]) =>
@@ -2,11 +2,10 @@ import { useCallback, useMemo, useState } from "react";
import { View, Text } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import Animated from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { FOOTER_HEIGHT, MAX_CONTENT_WIDTH } from "@/constants/layout";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { useKeyboardShiftStyle } from "@/hooks/use-keyboard-shift-style";
import { KeyboardTranslateView } from "@/components/keyboard-translate-view";
import { Button } from "@/components/ui/button";
import type { Theme } from "@/styles/theme";
import { toErrorMessage } from "@/utils/error-messages";
@@ -24,11 +23,9 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
const [isUnarchiving, setIsUnarchiving] = useState(false);
const [unarchiveError, setUnarchiveError] = useState<string | null>(null);
const { style: keyboardAnimatedStyle } = useKeyboardShiftStyle({ mode: "translate" });
const containerStyle = useMemo(
() => [styles.container, { paddingBottom: insets.bottom }, keyboardAnimatedStyle],
[insets.bottom, keyboardAnimatedStyle],
() => [styles.container, { paddingBottom: insets.bottom }],
[insets.bottom],
);
const handleUnarchive = useCallback(async () => {
@@ -44,7 +41,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
}, [client, isConnected, isUnarchiving, agentId]);
return (
<Animated.View style={containerStyle}>
<KeyboardTranslateView style={containerStyle}>
<View style={styles.inputAreaContainer}>
<View style={styles.inputAreaContent}>
<View style={styles.calloutStack}>
@@ -67,7 +64,7 @@ export function ArchivedAgentCallout({ serverId, agentId }: ArchivedAgentCallout
</View>
</View>
</View>
</Animated.View>
</KeyboardTranslateView>
);
}
@@ -8,8 +8,9 @@ import {
NativeExplorerSidebarDock,
} from "@/components/compact-explorer-sidebar";
import { useOpenFileExplorerGesture } from "@/mobile-panels/gestures";
import { useIsMobilePanelActive } from "@/mobile-panels/provider";
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
import { selectIsCompactFileExplorerOpen, usePanelStore } from "@/stores/panel-store";
import { usePanelStore } from "@/stores/panel-store";
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import type { WorkspaceTabTarget } from "@/workspace-tabs/model";
import { useWorkspaceCheckoutStatus } from "@/screens/workspace/use-workspace-checkout-status";
@@ -51,7 +52,7 @@ function useActiveCompactExplorerSidebarModel(
): CompactExplorerSidebarHostModel | null {
const selection = useActiveWorkspaceSelection();
const workspace = useWorkspace(selection?.serverId ?? null, selection?.workspaceId ?? null);
const isExplorerOpen = usePanelStore(selectIsCompactFileExplorerOpen);
const isExplorerActive = useIsMobilePanelActive("file-explorer");
const showMobileAgent = usePanelStore((state) => state.showMobileAgent);
const client = useHostRuntimeClient(selection?.serverId ?? "");
const isConnected = useHostRuntimeIsConnected(selection?.serverId ?? "");
@@ -67,32 +68,32 @@ function useActiveCompactExplorerSidebarModel(
const resolvedModel = useMemo(
() =>
resolveCompactExplorerSidebarHostModel({
previous: isExplorerOpen ? retainedModelRef.current : null,
previous: isExplorerActive ? retainedModelRef.current : null,
selection,
workspace,
isGit: checkoutQuery.data?.isGit ?? false,
}),
[checkoutQuery.data?.isGit, isExplorerOpen, selection, workspace],
[checkoutQuery.data?.isGit, isExplorerActive, selection, workspace],
);
useEffect(() => {
if (!selection) {
retainedModelRef.current = null;
if (enabled && isExplorerOpen) {
if (enabled && isExplorerActive) {
showMobileAgent();
}
return;
}
if (!isExplorerOpen) {
if (!isExplorerActive) {
retainedModelRef.current = null;
return;
}
if (resolvedModel) {
retainedModelRef.current = resolvedModel;
}
}, [enabled, isExplorerOpen, resolvedModel, selection, showMobileAgent]);
}, [enabled, isExplorerActive, resolvedModel, selection, showMobileAgent]);
return selection ? (resolvedModel ?? (isExplorerOpen ? retainedModelRef.current : null)) : null;
return selection ? (resolvedModel ?? (isExplorerActive ? retainedModelRef.current : null)) : null;
}
interface CompactExplorerSidebarHostProps {
@@ -14,6 +14,7 @@ import {
type ExplorerTab,
} from "@/stores/panel-store";
import { useCloseFileExplorerGesture } from "@/mobile-panels/gestures";
import { useIsMobilePanelActive } from "@/mobile-panels/provider";
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
import {
HEADER_INNER_HEIGHT,
@@ -81,7 +82,7 @@ export function CompactExplorerSidebar({
}: ExplorerSidebarProps) {
const { theme } = useUnistyles();
const insets = useSafeAreaInsets();
const isOpen = usePanelStore(selectIsCompactFileExplorerOpen);
const isActive = useIsMobilePanelActive("file-explorer");
const showMobileAgent = usePanelStore((state) => state.showMobileAgent);
const { explorerTab, handleTabPress } = useExplorerSidebarSharedState({
serverId,
@@ -99,11 +100,11 @@ export function CompactExplorerSidebar({
(reason: string) => {
logExplorerSidebar("handleClose", {
reason,
isOpen,
isOpen: isActive,
});
showMobileAgent();
},
[isOpen, showMobileAgent],
[isActive, showMobileAgent],
);
const handleHeaderClose = useCallback(() => handleClose("header-close-button"), [handleClose]);
@@ -127,7 +128,7 @@ export function CompactExplorerSidebar({
);
return (
<RetainedPanelActivity active={isOpen}>
<RetainedPanelActivity active={isActive}>
<MobilePanelOverlay
panel="file-explorer"
closeGesture={closeGesture}
@@ -141,7 +142,7 @@ export function CompactExplorerSidebar({
workspaceId={workspaceId}
workspaceRoot={workspaceRoot}
isGit={isGit}
isOpen={isOpen}
isOpen={isActive}
onOpenFile={onOpenFile}
/>
</MobilePanelOverlay>
@@ -461,7 +462,6 @@ function ChangedFilesPane({
workspaceId={workspaceId}
cwd={workspaceRoot}
enabled={isOpen}
modeScope="compact-explorer"
onOpenFile={onOpenFile}
onAddToChat={canAddToChat ? addFile : undefined}
state={changesState}
+1 -9
View File
@@ -1,5 +1,6 @@
import { View, Text } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { formatDiffCount } from "@/git/file-header-presentation";
interface DiffStatProps {
additions: number;
@@ -7,15 +8,6 @@ interface DiffStatProps {
testID?: string;
}
const compactFormatter = new Intl.NumberFormat("en-US", {
notation: "compact",
maximumFractionDigits: 1,
});
export function formatDiffCount(value: number): string {
return compactFormatter.format(value).toLowerCase();
}
export function DiffStat({ additions, deletions, testID }: DiffStatProps) {
return (
<View style={styles.row} testID={testID}>
@@ -4,10 +4,16 @@ import {
aggregateSessionEntries,
ALL_FILTER_VALUE,
buildProviderLabelMap,
collectErroredProviderLabels,
collectProviderErrorRows,
computeEmptyState,
formatDirectoryLabel,
getPromptPreview,
getSessionTitle,
hasMoreSessions,
nextPageLimit,
PER_PROVIDER_LIMIT,
resolveDirectoryLabel,
resolveImportTarget,
resolveProvidersToFetch,
requiresImportSessionsHostUpgrade,
type SessionsQueryResult,
@@ -167,27 +173,176 @@ describe("sumFilteredAlreadyImportedCount", () => {
});
});
describe("collectErroredProviderLabels", () => {
it("returns no labels when no providers are being fetched", () => {
expect(collectErroredProviderLabels(null, [], new Map())).toEqual([]);
describe("collectProviderErrorRows", () => {
it("returns no rows when no providers are being fetched", () => {
expect(collectProviderErrorRows(null, [], new Map())).toEqual([]);
});
it("returns labels for each errored provider, falling back to provider id", () => {
const labels = collectErroredProviderLabels(
it("returns a row for each provider whose request failed", () => {
const rows = collectProviderErrorRows(
["claude", "codex"],
[settled(undefined, { isError: true }), settled({ entries: [] })],
new Map([["claude", "Claude Code"]]),
);
expect(labels).toEqual(["Claude Code"]);
expect(rows).toEqual([{ provider: "claude", label: "Claude Code" }]);
});
it("returns a row for a provider the daemon reported as failed in a good response", () => {
const rows = collectProviderErrorRows(
["codex"],
[
settled({
entries: [],
providerErrors: [{ provider: "codex", message: "timed out" }],
}),
],
new Map([["codex", "Codex"]]),
);
expect(rows).toEqual([{ provider: "codex", label: "Codex" }]);
});
it("uses provider id when the label map has no entry", () => {
const labels = collectErroredProviderLabels(
const rows = collectProviderErrorRows(
["codex"],
[settled(undefined, { isError: true })],
new Map(),
);
expect(labels).toEqual(["codex"]);
expect(rows).toEqual([{ provider: "codex", label: "codex" }]);
});
});
describe("nextPageLimit", () => {
it("grows the per-provider limit one step at a time", () => {
expect(nextPageLimit(PER_PROVIDER_LIMIT)).toBe(45);
expect(nextPageLimit(45)).toBe(90);
expect(nextPageLimit(90)).toBe(200);
});
it("stops at the protocol ceiling", () => {
expect(nextPageLimit(200)).toBe(200);
});
});
describe("hasMoreSessions", () => {
it("reports more when a provider filled the requested page", () => {
expect(hasMoreSessions([settled({ entries: [entry(), entry()] })], 2)).toBe(true);
});
it("reports no more once every provider returned a short page", () => {
expect(hasMoreSessions([settled({ entries: [entry()] })], 2)).toBe(false);
});
it("reports no more at the last page size, however full the page is", () => {
expect(hasMoreSessions([settled({ entries: [entry(), entry()] })], 200)).toBe(false);
});
it("keeps reporting more while the next page replaces placeholder rows", () => {
expect(
hasMoreSessions([settled({ entries: [entry()] }, { isPlaceholderData: true })], 45),
).toBe(true);
});
});
describe("resolveDirectoryLabel", () => {
const projects = [
{ rootPath: "/home/me/paseo", name: "paseo" },
{ rootPath: "/home/me/paseo/packages/app", name: "paseo app" },
];
it("names the project root after the project alone", () => {
expect(resolveDirectoryLabel("/home/me/paseo", projects)).toEqual({ name: "paseo" });
});
it("qualifies a worktree under the project with its path below the root", () => {
expect(
resolveDirectoryLabel("/home/me/paseo/.dev/worktrees/abc/zebra", [projects[0]!]),
).toEqual({ name: "paseo", detail: ".dev/worktrees/abc/zebra" });
});
it("tells two worktrees of the same project apart", () => {
const zebra = resolveDirectoryLabel("/home/me/paseo/.dev/worktrees/abc/zebra", [projects[0]!]);
const otter = resolveDirectoryLabel("/home/me/paseo/.dev/worktrees/def/otter", [projects[0]!]);
expect(zebra).not.toEqual(otter);
expect([zebra.detail, otter.detail]).toEqual([
".dev/worktrees/abc/zebra",
".dev/worktrees/def/otter",
]);
});
it("picks the most specific project root containing the directory", () => {
expect(resolveDirectoryLabel("/home/me/paseo/packages/app/src", projects)).toEqual({
name: "paseo app",
detail: "src",
});
});
it("ignores trailing slashes on both sides", () => {
expect(
resolveDirectoryLabel("/home/me/paseo/", [{ rootPath: "/home/me/paseo/", name: "p" }]),
).toEqual({ name: "p" });
});
it("does not match a project root that is only a string prefix", () => {
expect(resolveDirectoryLabel("/home/me/paseo-fork", projects)).toEqual({
name: "/home/me/paseo-fork",
});
});
it("falls back to the path when no project owns the directory", () => {
expect(resolveDirectoryLabel("/tmp/scratch", projects)).toEqual({ name: "/tmp/scratch" });
});
});
describe("formatDirectoryLabel", () => {
it("shows the project name alone at its root", () => {
expect(formatDirectoryLabel({ name: "paseo" })).toBe("paseo");
});
it("appends the path under the root so worktrees of one project read apart", () => {
expect(formatDirectoryLabel({ name: "paseo", detail: ".dev/worktrees/zebra" })).toBe(
"paseo · .dev/worktrees/zebra",
);
});
});
describe("resolveImportTarget", () => {
it("trusts a scoped listing, whose rows the daemon already matched realpath-aware", () => {
expect(
resolveImportTarget({
entryCwd: "/private/repo/paseo",
workspaceCwd: "/repo/paseo",
workspaceId: "ws-1",
isScopedListing: true,
}),
).toEqual({ workspaceId: "ws-1", crossWorkspace: false });
});
it("keeps the current workspace for a Show-all row in that workspace's directory", () => {
expect(
resolveImportTarget({
entryCwd: "/repo/paseo/",
workspaceCwd: "/repo/paseo",
workspaceId: "ws-1",
isScopedListing: false,
}),
).toEqual({ workspaceId: "ws-1", crossWorkspace: false });
});
it("drops the workspace for a Show-all row from another directory, which the daemon rejects", () => {
expect(
resolveImportTarget({
entryCwd: "/repo/other",
workspaceCwd: "/repo/paseo",
workspaceId: "ws-1",
isScopedListing: false,
}),
).toEqual({ crossWorkspace: true });
});
it("treats a sheet with no workspace as cross-workspace", () => {
expect(resolveImportTarget({ entryCwd: "/repo/paseo", isScopedListing: false })).toEqual({
crossWorkspace: true,
});
});
});
@@ -236,6 +391,7 @@ describe("computeEmptyState", () => {
isQueryingProviders: true,
allQueriesSettled: true,
selectedProvider: ALL_FILTER_VALUE,
hasQuery: false,
aggregatedCount: 0,
visibleCount: 0,
totalAlreadyImportedCount: 0,
@@ -274,6 +430,15 @@ describe("computeEmptyState", () => {
});
});
it("says nothing matched when a query narrowed the list to nothing", () => {
const result = computeEmptyState({
...baseInputs,
hasQuery: true,
totalAlreadyImportedCount: 4,
});
expect(result.emptyStateTitle).toBe("No sessions match your search.");
});
it("shows the already-imported message when imported entries were filtered out", () => {
const result = computeEmptyState({
...baseInputs,
@@ -5,6 +5,18 @@ import { i18n } from "@/i18n/i18next";
export const PER_PROVIDER_LIMIT = 15;
export const ALL_FILTER_VALUE = "__all__";
/**
* Paging grows the per-provider limit instead of carrying an offset. The daemon
* ranks the whole candidate set on every request, so an offset into a previous
* ranking would drift as sessions move; refetching a larger page cannot. 200 is
* the protocol ceiling on `limit`.
*/
const PAGE_LIMITS: readonly number[] = [PER_PROVIDER_LIMIT, 45, 90, 200];
export function nextPageLimit(limit: number): number {
return PAGE_LIMITS.find((candidate) => candidate > limit) ?? limit;
}
export function requiresImportSessionsHostUpgrade(input: {
supportsSnapshot: boolean;
workspaceId?: string | null;
@@ -18,11 +30,13 @@ export interface SessionsQueryResult {
| {
entries: FetchRecentProviderSessionEntry[];
filteredAlreadyImportedCount?: number;
providerErrors?: Array<{ provider: string; message: string }>;
}
| undefined;
isError: boolean;
isLoading: boolean;
isPending: boolean;
isPlaceholderData?: boolean;
}
export function resolveProvidersToFetch(
@@ -81,20 +95,132 @@ export function sumFilteredAlreadyImportedCount(
return total;
}
export function collectErroredProviderLabels(
/**
* A provider that returned a full page may have more behind it. The daemon
* slices to `limit` after dropping already-imported sessions, so a short page is
* the end of that provider's list. Placeholder rows belong to the previous page,
* so the button holds its place instead of blinking out while the next loads.
*/
export function hasMoreSessions(
queries: ReadonlyArray<SessionsQueryResult>,
limit: number,
): boolean {
if (nextPageLimit(limit) === limit) return false;
return queries.some((entryQuery) => {
const count = entryQuery.data?.entries.length ?? 0;
return entryQuery.isPlaceholderData ? count > 0 : count >= limit;
});
}
export interface ProviderErrorRow {
provider: string;
label: string;
}
/**
* One row per provider that could not be listed, whether the request itself
* failed or the daemon reported the provider as failed in an otherwise good
* response. Both mean the same thing to the user, and both retry the same way.
*/
export function collectProviderErrorRows(
providersToFetch: AgentProvider[] | null,
queries: ReadonlyArray<SessionsQueryResult>,
providerLabelById: ReadonlyMap<string, string>,
): string[] {
): ProviderErrorRow[] {
if (providersToFetch === null) return [];
const labels: string[] = [];
for (let index = 0; index < queries.length; index++) {
if (queries[index]?.isError) {
const provider = providersToFetch[index];
labels.push(providerLabelById.get(provider) ?? provider);
}
const rows: ProviderErrorRow[] = [];
for (let index = 0; index < providersToFetch.length; index++) {
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;
rows.push({ provider, label: providerLabelById.get(provider) ?? provider });
}
return labels;
return rows;
}
export interface DirectoryProject {
rootPath: string;
name: string;
}
export interface DirectoryLabel {
/** The owning project's name, or the whole path when no project owns it. */
name: string;
/**
* The directory's path under its project root, absent at the root itself.
* Worktrees of one project all resolve to the same name, so without this the
* sheet would show several identical headings.
*/
detail?: string;
}
function withoutTrailingSlash(path: string): string {
return path.length > 1 ? path.replace(/\/+$/, "") : path;
}
/** The project's name when the app knows the directory, else the directory itself. */
export function resolveDirectoryLabel(
directory: string,
projects: ReadonlyArray<DirectoryProject>,
): DirectoryLabel {
const normalized = withoutTrailingSlash(directory);
let bestRoot: string | null = null;
let bestName: string | null = null;
for (const project of projects) {
const root = withoutTrailingSlash(project.rootPath);
if (!root) continue;
if (bestRoot !== null && root.length <= bestRoot.length) continue;
if (normalized !== root && !normalized.startsWith(`${root}/`)) continue;
bestRoot = root;
bestName = project.name;
}
if (bestRoot === null || bestName === null) {
return { name: normalized };
}
const relative = normalized.slice(bestRoot.length + 1);
return relative ? { name: bestName, detail: relative } : { name: bestName };
}
/** The one-line form a row shows under its prompt preview. */
export function formatDirectoryLabel(label: DirectoryLabel): string {
return label.detail ? `${label.name} · ${label.detail}` : label.name;
}
export interface ImportTarget {
/**
* Omitted unless the row's directory is the scoped workspace's own: the daemon
* rejects an import whose cwd does not match the requested workspace.
*/
workspaceId?: string;
/**
* The agent lands in a workspace other than the one the sheet was opened from,
* so the caller has to open that workspace instead of adding a tab here.
*/
crossWorkspace: boolean;
}
export function resolveImportTarget(input: {
entryCwd: string;
/** The directory the sheet was opened for, absent when it was opened host-wide. */
workspaceCwd?: string | null;
workspaceId?: string | null;
/** The listed rows came from a fetch scoped to `workspaceCwd`. */
isScopedListing: boolean;
}): ImportTarget {
if (!input.workspaceId || !input.workspaceCwd) {
return { crossWorkspace: true };
}
// A scoped listing only holds rows the daemon already matched to this
// workspace's directory with realpaths resolved, which the client cannot do.
// "Show all" drops that guarantee, so each row is compared by path instead.
const belongsToWorkspace =
input.isScopedListing ||
withoutTrailingSlash(input.entryCwd) === withoutTrailingSlash(input.workspaceCwd);
return belongsToWorkspace
? { workspaceId: input.workspaceId, crossWorkspace: false }
: { crossWorkspace: true };
}
export function getSessionTitle(entry: FetchRecentProviderSessionEntry): string {
@@ -123,6 +249,7 @@ export interface EmptyStateInputs {
isQueryingProviders: boolean;
allQueriesSettled: boolean;
selectedProvider: string;
hasQuery: boolean;
aggregatedCount: number;
visibleCount: number;
totalAlreadyImportedCount: number;
@@ -142,6 +269,11 @@ export function computeEmptyState(input: EmptyStateInputs): {
if (!showEmptyState) {
return { showEmptyState, emptyStateTitle: "" };
}
// A query narrowing the list to nothing is a different answer from a host with
// nothing to import, and the recovery is different too.
if (input.hasQuery) {
return { showEmptyState, emptyStateTitle: i18n.t("importSession.empty.noMatches") };
}
const isFilteredEmpty = input.selectedProvider !== ALL_FILTER_VALUE && input.aggregatedCount > 0;
if (isFilteredEmpty) {
const label = input.providerLabelById.get(input.selectedProvider) ?? input.selectedProvider;
@@ -14,12 +14,12 @@ import { ImportSessionSheet } from "@/components/import-session-sheet";
const { theme } = vi.hoisted(() => ({
theme: {
spacing: { 1: 4, 1.5: 6, 2: 8, 3: 12, 4: 16, 6: 24 },
spacing: { 1: 4, 1.5: 6, 2: 8, 2.5: 10, 3: 12, 4: 16, 6: 24, 8: 32 },
borderWidth: { 1: 1 },
borderRadius: { md: 6, lg: 8, full: 9999 },
fontSize: { xs: 11, sm: 13, base: 15 },
fontWeight: { normal: "400", medium: "500", semibold: "600" },
iconSize: { sm: 14, md: 16 },
iconSize: { sm: 14, md: 16, lg: 24 },
opacity: { 50: 0.5 },
colors: {
foreground: "#fff",
@@ -30,6 +30,8 @@ const { theme } = vi.hoisted(() => ({
surface3: "#333",
border: "#444",
borderAccent: "#555",
interactionHighlight: "rgba(255,255,255,0.08)",
palette: { red: { 300: "#f87171" } },
},
},
}));
@@ -75,6 +77,8 @@ vi.mock("lucide-react-native", () => {
Inbox: icon("Inbox"),
Layers: icon("Layers"),
RotateCw: icon("RotateCw"),
Search: icon("Search"),
X: icon("X"),
};
});
@@ -117,6 +121,22 @@ vi.mock("@/components/ui/combobox", () => ({
ComboboxItem: ({ label }: { label: string }) => React.createElement("span", null, label),
}));
interface SheetSearchProps {
onChange: (value: string) => void;
placeholder?: string;
testID?: string;
}
function SheetSearchInput({ search }: { search: SheetSearchProps }) {
const handleChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => search.onChange(event.target.value),
[search],
);
return (
<input data-testid={search.testID} placeholder={search.placeholder} onChange={handleChange} />
);
}
vi.mock("@/components/adaptive-modal-sheet", () => ({
AdaptiveModalSheet: ({
visible,
@@ -125,14 +145,21 @@ vi.mock("@/components/adaptive-modal-sheet", () => ({
testID,
}: {
visible: boolean;
header?: { title: string; actions?: ReactNode };
header?: {
title: string;
subtitle?: ReactNode;
actions?: ReactNode;
search?: { onChange: (value: string) => void; placeholder?: string; testID?: string };
};
children: ReactNode;
testID?: string;
}) =>
visible ? (
<section data-testid={testID}>
<h1>{header?.title}</h1>
{header?.subtitle}
{header?.actions}
{header?.search ? <SheetSearchInput search={header.search} /> : null}
{children}
</section>
) : null,
@@ -163,26 +190,62 @@ vi.mock("@/hooks/use-providers-snapshot", () => ({
}),
}));
const mockHostFeatures = vi.hoisted(() => ({
current: { importSessionSearch: true, importSessionWorkspaceTarget: true } as Record<
string,
boolean
>,
}));
vi.mock("@/runtime/host-features", () => ({
useHostFeature: (_serverId: string | null, feature: string) =>
mockHostFeatures.current[feature] === true,
}));
vi.mock("@/runtime/host-runtime", () => ({
useHosts: () => [{ serverId: "server-1", label: "workbench" }],
}));
const mockHostProjects = vi.hoisted(() => ({
current: [] as Array<{ iconWorkingDir: string; projectName: string }>,
}));
vi.mock("@/projects/host-projects", () => ({
useHostProjects: () => mockHostProjects.current,
}));
interface RenderOptions {
visible?: boolean;
onClose?: () => void;
onImportedAgent?: (agentId: string) => void;
onImported?: (agent: Awaited<ReturnType<DaemonClient["importAgent"]>>) => void;
cwd?: string | null;
workspaceId?: string;
supportsSearch?: boolean;
projects?: Array<{ iconWorkingDir: string; projectName: string }>;
snapshot?: {
entries?: ProviderSnapshotEntry[];
supportsSnapshot?: boolean;
};
}
function renderSheet(
client: Pick<DaemonClient, "fetchRecentProviderSessions" | "importAgent">,
options?: RenderOptions,
) {
function applyHostMocks(options?: RenderOptions) {
mockSnapshot.current = {
entries: options?.snapshot?.entries,
supportsSnapshot: options?.snapshot?.supportsSnapshot ?? false,
};
mockHostFeatures.current = {
importSessionSearch: options?.supportsSearch ?? true,
importSessionWorkspaceTarget: true,
};
mockHostProjects.current = options?.projects ?? [];
}
function renderSheet(
client: Pick<DaemonClient, "fetchRecentProviderSessions" | "importAgent">,
options?: RenderOptions,
) {
applyHostMocks(options);
const queryClient = new QueryClient({
defaultOptions: {
@@ -200,6 +263,7 @@ function renderSheet(
client={client}
serverId="server-1"
cwd={cwd}
workspaceId={options?.workspaceId}
onClose={options?.onClose ?? vi.fn()}
onImportedAgent={options?.onImportedAgent ?? vi.fn()}
onImported={options?.onImported}
@@ -245,6 +309,16 @@ function createImportedAgentSnapshot(id: string): Awaited<ReturnType<DaemonClien
};
}
function createPageOfEntries(count: number): FetchRecentProviderSessionEntry[] {
return Array.from({ length: count }, (_unused, index) =>
createProviderSessionEntry({
providerId: "claude",
providerHandleId: `thread-${index}`,
title: `Session ${index}`,
}),
);
}
function createProviderSessionEntry(
overrides?: Partial<FetchRecentProviderSessionEntry>,
): FetchRecentProviderSessionEntry {
@@ -377,7 +451,8 @@ describe("ImportSessionSheet", () => {
},
);
await screen.findByText("Could not load recent sessions.");
await screen.findByText("Could not load Claude Code sessions");
screen.getByTestId("import-session-retry-claude");
});
it("loads recent provider sessions for the workspace and renders descriptor-owned labels", async () => {
@@ -478,19 +553,34 @@ describe("ImportSessionSheet", () => {
});
it("imports a selected session by provider handle and reports the imported agent", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [
createProviderSessionEntry({
providerId: "claude",
providerLabel: "Claude Code",
cwd: "/repo/paseo-realpath",
const events: string[] = [];
let fetchCount = 0;
const fetchRecentProviderSessions = vi.fn(async () => {
fetchCount += 1;
events.push("fetch");
if (fetchCount > 1) {
return await new Promise<never>(() => {});
}
return {
requestId: "recent-provider-sessions",
entries: [
createProviderSessionEntry({
providerId: "claude",
providerLabel: "Claude Code",
cwd: "/repo/paseo-realpath",
}),
],
};
});
let resolveImport!: (agent: ReturnType<typeof createImportedAgentSnapshot>) => void;
const importAgent = vi.fn(
() =>
new Promise<ReturnType<typeof createImportedAgentSnapshot>>((resolve) => {
resolveImport = resolve;
}),
],
}));
const importAgent = vi.fn(async () => createImportedAgentSnapshot("agent-imported"));
const onClose = vi.fn();
const onImportedAgent = vi.fn();
);
const onClose = vi.fn(() => events.push("close"));
const onImportedAgent = vi.fn(() => events.push("navigate"));
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
@@ -500,21 +590,31 @@ describe("ImportSessionSheet", () => {
{
onClose,
onImportedAgent,
workspaceId: "ws-current",
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
},
);
fireEvent.click(await screen.findByTestId("import-session-session-claude-provider-thread-1"));
const row = await screen.findByTestId("import-session-session-claude-provider-thread-1");
expect(events).toEqual(["fetch"]);
fireEvent.click(row);
await screen.findByText("Importing...");
expect(events).toEqual(["fetch"]);
resolveImport(createImportedAgentSnapshot("agent-imported"));
await waitFor(() => {
expect(importAgent).toHaveBeenCalledWith({
providerId: "claude",
providerHandleId: "provider-thread-1",
cwd: "/repo/paseo-realpath",
workspaceId: "ws-current",
});
expect(events).toEqual(["fetch", "close", "navigate"]);
});
expect(onImportedAgent).toHaveBeenCalledWith("agent-imported");
expect(onClose).toHaveBeenCalledTimes(1);
expect(fetchRecentProviderSessions).toHaveBeenCalledTimes(1);
});
it("shows an import error state without closing when selected session import fails", async () => {
@@ -649,7 +749,7 @@ describe("ImportSessionSheet", () => {
);
await screen.findByText("Session codex");
await screen.findByText("Could not load sessions for Claude Code.");
await screen.findByText("Could not load Claude Code sessions");
});
it("filters the merged list when a provider badge is selected and restores it on All", async () => {
@@ -758,7 +858,7 @@ describe("ImportSessionSheet", () => {
expect(fetchRecentProviderSessions).not.toHaveBeenCalled();
});
it("omits cwd from fetch and renders the session cwd on each row when cwd is unset", async () => {
it("omits cwd from fetch and names each row's folder when cwd is unset", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [
@@ -793,6 +893,9 @@ describe("ImportSessionSheet", () => {
expect.objectContaining({ cwd: expect.anything() }),
);
await screen.findByText("/home/me/work/other-project");
expect(
screen.getByTestId("import-session-row-folder-claude-provider-thread-1").textContent,
).toBe("/home/me/work/other-project");
});
it("uses the session's cwd when importing in cwd-less mode and fires onImported", async () => {
@@ -836,10 +939,344 @@ describe("ImportSessionSheet", () => {
});
expect(onImported).toHaveBeenCalledTimes(1);
expect(onImported).toHaveBeenCalledWith(expect.objectContaining({ id: "agent-imported" }));
expect(onImportedAgent).toHaveBeenCalledWith("agent-imported");
expect(onImportedAgent).not.toHaveBeenCalled();
expect(onClose).toHaveBeenCalledTimes(1);
});
it("names the scope after the host when unscoped and after the workspace when scoped", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [],
}));
const importAgent = vi.fn();
const client = createRecentSessionsClient(fetchRecentProviderSessions, importAgent);
renderSheet(client, {
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
await screen.findByText("Sessions on workbench");
expect(screen.queryByTestId("import-session-show-all")).toBeNull();
cleanup();
renderSheet(client, {
workspaceId: "ws-current",
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
});
await screen.findByText("This workspace");
screen.getByTestId("import-session-show-all");
});
it("lists unscoped rows newest first and names each row's folder", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [
createProviderSessionEntry({
providerId: "claude",
providerHandleId: "newest",
cwd: "/home/me/paseo",
title: "Newest in paseo",
lastActivityAt: "2026-04-30T12:00:00.000Z",
}),
createProviderSessionEntry({
providerId: "claude",
providerHandleId: "elsewhere",
cwd: "/tmp/scratch",
title: "Scratch session",
lastActivityAt: "2026-04-30T11:00:00.000Z",
}),
createProviderSessionEntry({
providerId: "claude",
providerHandleId: "older",
cwd: "/home/me/paseo",
title: "Older in paseo",
lastActivityAt: "2026-04-30T10:00:00.000Z",
}),
createProviderSessionEntry({
providerId: "claude",
providerHandleId: "worktree",
cwd: "/home/me/paseo/.dev/worktrees/zebra",
title: "Worktree session",
lastActivityAt: "2026-04-30T09:00:00.000Z",
}),
],
}));
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
cwd: null,
projects: [{ iconWorkingDir: "/home/me/paseo", projectName: "paseo" }],
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
},
);
await screen.findByTestId("import-session-session-claude-newest");
expect(
screen
.getAllByTestId(/^import-session-session-/)
.map((row) => row.getAttribute("data-testid")),
).toEqual([
"import-session-session-claude-newest",
"import-session-session-claude-elsewhere",
"import-session-session-claude-older",
"import-session-session-claude-worktree",
]);
expect(
screen.getAllByTestId(/^import-session-row-folder-/).map((folder) => folder.textContent),
).toEqual(["paseo", "/tmp/scratch", "paseo", "paseo · .dev/worktrees/zebra"]);
});
it("leaves the folder off every row when the sheet is scoped to one workspace", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [
createProviderSessionEntry({
providerId: "claude",
providerHandleId: "scoped",
cwd: "/repo/paseo",
title: "Scoped session",
}),
],
}));
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
workspaceId: "ws-current",
projects: [{ iconWorkingDir: "/repo/paseo", projectName: "paseo" }],
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
},
);
await screen.findByText("Scoped session");
expect(screen.queryAllByTestId(/^import-session-row-folder-/)).toHaveLength(0);
});
it("sends the debounced search query to every provider", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [],
}));
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
},
);
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalled();
});
fireEvent.change(screen.getByTestId("import-session-search"), {
target: { value: "invoice" },
});
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 15,
query: "invoice",
});
});
});
it("hides the search field when the host cannot search sessions", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [],
}));
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
cwd: null,
supportsSearch: false,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
},
);
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalled();
});
expect(screen.queryByTestId("import-session-search")).toBeNull();
});
it("asks for a larger page when Load more is pressed, and stops offering it on a short page", async () => {
const fetchRecentProviderSessions = vi.fn(async (options: { limit?: number } | undefined) => ({
requestId: "recent-provider-sessions",
entries: createPageOfEntries(options?.limit === 15 ? 15 : 20),
}));
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
cwd: null,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
},
);
fireEvent.click(await screen.findByTestId("import-session-load-more"));
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 45,
});
});
await waitFor(() => {
expect(screen.queryByTestId("import-session-load-more")).toBeNull();
});
});
it("stops the refresh spinner and retries only the failed provider", async () => {
const fetchRecentProviderSessions = vi.fn(
async (options: { providers?: string[] } | undefined) => {
const provider = options?.providers?.[0];
if (provider === "claude") {
throw new Error("claude offline");
}
return {
requestId: `recent-${provider}`,
entries: [
createProviderSessionEntry({
providerId: provider ?? "codex",
providerHandleId: `${provider}-thread`,
title: `Session ${provider}`,
}),
],
};
},
);
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
snapshot: {
supportsSnapshot: true,
entries: [createSnapshotEntry("claude"), createSnapshotEntry("codex")],
},
},
);
await screen.findByText("Session codex");
await screen.findByText("Could not load Claude Code sessions");
await waitFor(() => {
expect(screen.queryByTestId("import-session-loading-spinner")).toBeNull();
});
fetchRecentProviderSessions.mockClear();
fireEvent.click(screen.getByTestId("import-session-retry-claude"));
await waitFor(() => {
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
cwd: "/repo/paseo",
providers: ["claude"],
limit: 15,
});
});
expect(fetchRecentProviderSessions).toHaveBeenCalledTimes(1);
});
it("shows an error row for a provider the daemon reported as failed", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
entries: [createProviderSessionEntry({ providerId: "codex", providerLabel: "Codex" })],
providerErrors: [{ provider: "codex", message: "timed out" }],
}));
const importAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("codex")] },
},
);
await screen.findByText("Could not load Codex sessions");
});
it("imports a foreign-directory row without the current workspace once Show all is on", async () => {
const fetchRecentProviderSessions = vi.fn(async (options: { cwd?: string } | undefined) => ({
requestId: "recent-provider-sessions",
entries: [
createProviderSessionEntry({
providerId: "claude",
providerHandleId: options?.cwd ? "scoped-thread" : "foreign-thread",
cwd: options?.cwd ?? "/home/me/work/other-project",
title: options?.cwd ? "Scoped session" : "Foreign session",
}),
],
}));
const importAgent = vi.fn(async () => createImportedAgentSnapshot("agent-imported"));
const onImported = vi.fn();
const onImportedAgent = vi.fn();
renderSheet(
{ fetchRecentProviderSessions, importAgent } as Pick<
DaemonClient,
"fetchRecentProviderSessions" | "importAgent"
>,
{
workspaceId: "ws-current",
onImported,
onImportedAgent,
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
},
);
await screen.findByText("Scoped session");
fireEvent.click(screen.getByTestId("import-session-show-all"));
await screen.findByText("Foreign session");
expect(fetchRecentProviderSessions).toHaveBeenCalledWith({
providers: ["claude"],
limit: 15,
});
fireEvent.click(screen.getByTestId("import-session-session-claude-foreign-thread"));
await waitFor(() => {
expect(importAgent).toHaveBeenCalledWith({
providerId: "claude",
providerHandleId: "foreign-thread",
cwd: "/home/me/work/other-project",
});
});
expect(onImported).toHaveBeenCalledWith(expect.objectContaining({ id: "agent-imported" }));
expect(onImportedAgent).not.toHaveBeenCalled();
});
it("refetches sessions when the refresh button is clicked", async () => {
const fetchRecentProviderSessions = vi.fn(async () => ({
requestId: "recent-provider-sessions",
@@ -1,6 +1,6 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
import { useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { keepPreviousData, useMutation, useQueries, useQueryClient } from "@tanstack/react-query";
import { useTranslation } from "react-i18next";
import type {
DaemonClient,
@@ -10,22 +10,33 @@ import type { AgentProvider } from "@getpaseo/protocol/agent-types";
import { ChevronDown, Inbox, Layers, RotateCw } from "lucide-react-native";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { Combobox, ComboboxItem, type ComboboxOption } from "@/components/ui/combobox";
import { getProviderIcon } from "@/components/provider-icons";
import { formatTimeAgo } from "@/utils/time";
import { useDebouncedValue } from "@/hooks/use-debounced-value";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useHostProjects } from "@/projects/host-projects";
import { useHostFeature } from "@/runtime/host-features";
import { useHosts } from "@/runtime/host-runtime";
import { i18n } from "@/i18n/i18next";
import {
aggregateSessionEntries,
ALL_FILTER_VALUE,
buildProviderLabelMap,
collectErroredProviderLabels,
collectProviderErrorRows,
computeEmptyState,
type DirectoryProject,
formatDirectoryLabel,
getPromptPreview,
getSessionTitle,
hasMoreSessions,
resolveDirectoryLabel,
nextPageLimit,
PER_PROVIDER_LIMIT,
type ProviderErrorRow,
resolveImportTarget,
resolveProvidersToFetch,
requiresImportSessionsHostUpgrade,
sumFilteredAlreadyImportedCount,
@@ -33,6 +44,8 @@ import {
const IMPORT_SHEET_SNAP_POINTS = ["70%", "92%"];
const DISABLED_ACCESSIBILITY_STATE = { disabled: true };
/** Long enough that a typed word is one request, short enough to feel live. */
const SEARCH_DEBOUNCE_MS = 200;
type RecentProviderSessionsClient = Pick<
DaemonClient,
@@ -48,7 +61,9 @@ interface ImportSessionSheetProps {
cwd?: string | null;
workspaceId?: string | null;
onClose: () => void;
/** The agent belongs to the workspace the sheet was opened from; open it here. */
onImportedAgent?: (agentId: string) => void;
/** The agent belongs to its own workspace; open that workspace and navigate. */
onImported?: (agent: ImportedAgent) => void;
}
@@ -56,27 +71,51 @@ type RecentSessionsResponse = Awaited<
ReturnType<RecentProviderSessionsClient["fetchRecentProviderSessions"]>
>;
type SessionsQueryKey = ReadonlyArray<string | number | null>;
function buildSessionsQueryKey(input: {
cwd: string | null;
query: string;
limit: number;
provider?: string;
}): SessionsQueryKey {
return [
"recent-provider-sessions",
input.cwd,
input.query,
input.limit,
...(input.provider === undefined ? [] : [input.provider]),
];
}
interface SessionsQueryConfig {
queryKey: ReadonlyArray<string | null>;
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;
placeholderData: typeof keepPreviousData;
queryFn: () => Promise<RecentSessionsResponse>;
}
function buildSessionsQueriesConfig(args: {
providersToFetch: AgentProvider[] | null;
sessionsQueryRoot: ReadonlyArray<string | null>;
visible: boolean;
client: RecentProviderSessionsClient | null;
cwd: string | null | undefined;
cwd: string | null;
query: string;
limit: number;
hostDisconnectedMessage?: string;
}): SessionsQueryConfig[] {
const { providersToFetch, sessionsQueryRoot, visible, client, cwd, hostDisconnectedMessage } =
args;
const { providersToFetch, visible, client, cwd, query, limit, hostDisconnectedMessage } = args;
if (providersToFetch === null) return [];
const enabled = visible && Boolean(client);
return providersToFetch.map((provider) => ({
queryKey: [...sessionsQueryRoot, provider],
queryKey: buildSessionsQueryKey({ cwd, query, limit, provider }),
enabled,
retry: false as const,
placeholderData: keepPreviousData,
queryFn: async () => {
if (!client) {
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
@@ -84,7 +123,8 @@ function buildSessionsQueriesConfig(args: {
return await client.fetchRecentProviderSessions({
...(cwd ? { cwd } : {}),
providers: [provider],
limit: PER_PROVIDER_LIMIT,
limit,
...(query ? { query } : {}),
});
},
}));
@@ -96,8 +136,6 @@ interface SheetStatusMessagesProps {
hasNoImportableProviders: boolean;
isLoadingSessions: boolean;
hasRows: boolean;
allQueriesErrored: boolean;
erroredProviderLabels: ReadonlyArray<string>;
importErrored: boolean;
}
@@ -107,8 +145,6 @@ function SheetStatusMessages({
hasNoImportableProviders,
isLoadingSessions,
hasRows,
allQueriesErrored,
erroredProviderLabels,
importErrored,
}: SheetStatusMessagesProps) {
const { theme } = useUnistyles();
@@ -130,16 +166,6 @@ function SheetStatusMessages({
<Text style={styles.statusText}>{t("importSession.status.loading")}</Text>
</View>
) : null}
{allQueriesErrored ? (
<Text style={styles.statusText}>{t("importSession.status.failedAll")}</Text>
) : null}
{!allQueriesErrored && erroredProviderLabels.length > 0 ? (
<Text style={styles.statusText}>
{t("importSession.status.failedProviders", {
providers: erroredProviderLabels.join(", "),
})}
</Text>
) : null}
{importErrored ? (
<Text style={styles.statusText}>{t("importSession.status.failedImport")}</Text>
) : null}
@@ -147,6 +173,48 @@ function SheetStatusMessages({
);
}
function ProviderErrorBanner({
rows,
onRetry,
}: {
rows: ReadonlyArray<ProviderErrorRow>;
onRetry: (provider: string) => void;
}) {
return (
<View style={styles.errorBanner} testID="import-session-provider-errors">
{rows.map((row) => (
<ProviderErrorBannerRow key={row.provider} row={row} onRetry={onRetry} />
))}
</View>
);
}
function ProviderErrorBannerRow({
row,
onRetry,
}: {
row: ProviderErrorRow;
onRetry: (provider: string) => void;
}) {
const { t } = useTranslation();
const handleRetry = useCallback(() => onRetry(row.provider), [onRetry, row.provider]);
return (
<View style={styles.errorRow}>
<Text style={styles.errorText}>
{t("importSession.status.failedProvider", { provider: row.label })}
</Text>
<Button
variant="ghost"
size="xs"
onPress={handleRetry}
testID={`import-session-retry-${row.provider}`}
>
{t("common.actions.retry")}
</Button>
</View>
);
}
function RefreshAction({ isRefreshing, onPress }: { isRefreshing: boolean; onPress: () => void }) {
const { theme } = useUnistyles();
const { t } = useTranslation();
@@ -177,6 +245,38 @@ function RefreshAction({ isRefreshing, onPress }: { isRefreshing: boolean; onPre
);
}
function ScopeSubtitle({
hostLabel,
isScoped,
onShowAll,
}: {
hostLabel: string;
isScoped: boolean;
onShowAll: () => void;
}) {
const { t } = useTranslation();
return (
<View style={styles.subtitleRow}>
<Text style={styles.subtitleText} numberOfLines={1} testID="import-session-scope">
{isScoped
? t("importSession.scope.workspace")
: t("importSession.scope.host", { host: hostLabel })}
</Text>
{isScoped ? (
<Button
variant="ghost"
size="xs"
onPress={onShowAll}
testID="import-session-show-all"
style={styles.subtitleAction}
>
{t("importSession.actions.showAll")}
</Button>
) : null}
</View>
);
}
function SheetEmptyState({ title }: { title: string }) {
const { theme } = useUnistyles();
return (
@@ -190,16 +290,19 @@ function SheetEmptyState({ title }: { title: string }) {
}
function ImportSessionSheetRow({
serverId,
entry,
disabled,
importing,
showCwd,
folder,
onImportSession,
}: {
serverId: string | null;
entry: FetchRecentProviderSessionEntry;
disabled: boolean;
importing: boolean;
showCwd: boolean;
/** The row's directory, shown only when rows can come from more than one. */
folder: string | null;
onImportSession: (entry: FetchRecentProviderSessionEntry) => void;
}) {
const { theme } = useUnistyles();
@@ -207,7 +310,7 @@ function ImportSessionSheetRow({
const title = getSessionTitle(entry);
const promptPreview = getPromptPreview(entry);
const lastActivity = formatTimeAgo(new Date(entry.lastActivityAt));
const ProviderIcon = getProviderIcon(entry.providerId);
const ProviderIcon = getProviderIcon(entry.providerId, serverId);
const accessibilityState = useMemo(
() => (disabled ? DISABLED_ACCESSIBILITY_STATE : undefined),
[disabled],
@@ -248,9 +351,13 @@ function ImportSessionSheetRow({
<Text style={styles.rowPreview} numberOfLines={2}>
{promptPreview}
</Text>
{showCwd && entry.cwd ? (
<Text style={styles.rowCwd} numberOfLines={1}>
{entry.cwd}
{folder ? (
<Text
style={styles.rowFolder}
numberOfLines={1}
testID={`import-session-row-folder-${entry.providerId}-${entry.providerHandleId}`}
>
{folder}
</Text>
) : null}
</View>
@@ -258,6 +365,38 @@ function ImportSessionSheetRow({
);
}
function SessionRows({
serverId,
entries,
disabled,
importingSessionKey,
resolveFolder,
onImportSession,
}: {
serverId: string | null;
entries: ReadonlyArray<FetchRecentProviderSessionEntry>;
disabled: boolean;
importingSessionKey: string | null;
resolveFolder: (entry: FetchRecentProviderSessionEntry) => string | null;
onImportSession: (entry: FetchRecentProviderSessionEntry) => void;
}) {
return (
<View style={styles.list}>
{entries.map((entry) => (
<ImportSessionSheetRow
key={`${entry.providerId}:${entry.providerHandleId}`}
serverId={serverId}
entry={entry}
disabled={disabled}
importing={importingSessionKey === `${entry.providerId}:${entry.providerHandleId}`}
folder={resolveFolder(entry)}
onImportSession={onImportSession}
/>
))}
</View>
);
}
export function ImportSessionSheet({
visible,
client,
@@ -272,8 +411,32 @@ export function ImportSessionSheet({
const queryClient = useQueryClient();
const { theme } = useUnistyles();
// "Show all" widens a workspace-scoped sheet to the whole host. The sheet's own
// `cwd` stays the scope it was opened with, because that is what decides where
// an imported agent lands.
const [isShowingAllDirectories, setIsShowingAllDirectories] = useState(false);
const [searchInput, setSearchInput] = useState("");
const [pageLimit, setPageLimit] = useState(PER_PROVIDER_LIMIT);
const [selectedProvider, setSelectedProvider] = useState<string>(ALL_FILTER_VALUE);
const scopeCwd = isShowingAllDirectories ? null : (cwd ?? null);
const supportsSearch = useHostFeature(serverId, "importSessionSearch");
const query = useDebouncedValue(supportsSearch ? searchInput : "", SEARCH_DEBOUNCE_MS).trim();
useEffect(() => {
if (visible) return;
setIsShowingAllDirectories(false);
setSearchInput("");
}, [visible]);
// A narrower or wider list starts at page one; keeping a grown limit would
// fetch 200 rows for a query that matches three.
useEffect(() => {
setPageLimit(PER_PROVIDER_LIMIT);
}, [query, scopeCwd]);
const { entries: snapshotEntries, supportsSnapshot } = useProvidersSnapshot(serverId, {
cwd,
cwd: scopeCwd,
enabled: visible,
});
const supportsWorkspaceTarget = useHostFeature(serverId, "importSessionWorkspaceTarget");
@@ -293,22 +456,20 @@ export function ImportSessionSheet({
[snapshotEntries],
);
const sessionsQueryRoot = useMemo(
() => ["recent-provider-sessions", cwd ?? null] as const,
[cwd],
);
const sessionsQueryRoot = useMemo(() => ["recent-provider-sessions", scopeCwd], [scopeCwd]);
const queriesConfig = useMemo(
() =>
buildSessionsQueriesConfig({
providersToFetch,
sessionsQueryRoot,
visible,
client,
cwd,
cwd: scopeCwd,
query,
limit: pageLimit,
hostDisconnectedMessage: t("workspace.terminal.hostDisconnected"),
}),
[providersToFetch, sessionsQueryRoot, visible, client, cwd, t],
[providersToFetch, visible, client, scopeCwd, query, pageLimit, t],
);
const queries = useQueries({ queries: queriesConfig });
@@ -320,8 +481,6 @@ export function ImportSessionSheet({
);
const filterProviders = useMemo(() => [...(providersToFetch ?? [])].sort(), [providersToFetch]);
const [selectedProvider, setSelectedProvider] = useState<string>(ALL_FILTER_VALUE);
const [isFilterOpen, setIsFilterOpen] = useState(false);
const filterAnchorRef = useRef<View>(null);
@@ -339,6 +498,27 @@ export function ImportSessionSheet({
return aggregatedEntries.filter((entry) => entry.providerId === selectedProvider);
}, [aggregatedEntries, selectedProvider]);
const projectServerIds = useMemo(() => (serverId ? [serverId] : []), [serverId]);
const hostProjects = useHostProjects(projectServerIds);
const directoryProjects = useMemo<DirectoryProject[]>(
() =>
hostProjects.map((project) => ({
rootPath: project.iconWorkingDir,
name: project.projectName,
})),
[hostProjects],
);
// A scoped sheet only lists one directory, so naming it on every row is noise.
const showRowFolders = scopeCwd === null;
const resolveFolder = useCallback(
(entry: FetchRecentProviderSessionEntry) =>
showRowFolders
? formatDirectoryLabel(resolveDirectoryLabel(entry.cwd, directoryProjects))
: null,
[showRowFolders, directoryProjects],
);
const filterComboboxOptions = useMemo<ComboboxOption[]>(
() => [
{ id: ALL_FILTER_VALUE, label: t("importSession.filters.all") },
@@ -377,11 +557,11 @@ export function ImportSessionSheet({
const map = new Map<string, React.ReactNode>();
map.set(ALL_FILTER_VALUE, <Layers size={14} color={theme.colors.foregroundMuted} />);
for (const provider of filterProviders) {
const ProviderIcon = getProviderIcon(provider);
const ProviderIcon = getProviderIcon(provider, serverId);
map.set(provider, <ProviderIcon size={14} color={theme.colors.foregroundMuted} />);
}
return map;
}, [filterProviders, theme.colors.foregroundMuted]);
}, [filterProviders, serverId, theme.colors.foregroundMuted]);
const renderFilterOption = useCallback(
({
@@ -414,19 +594,31 @@ export function ImportSessionSheet({
if (!entry.cwd) {
throw new Error("Session is missing a working directory");
}
const target = resolveImportTarget({
entryCwd: entry.cwd,
workspaceCwd: cwd,
workspaceId,
isScopedListing: scopeCwd !== null,
});
const agent = await client.importAgent({
providerId: entry.providerId,
providerHandleId: entry.providerHandleId,
cwd: entry.cwd,
...(workspaceId ? { workspaceId } : {}),
...(target.workspaceId ? { workspaceId: target.workspaceId } : {}),
});
return agent;
return { agent, target };
},
onSuccess: async (agent) => {
await queryClient.invalidateQueries({ queryKey: sessionsQueryRoot });
onSuccess: ({ agent, target }) => {
onClose();
onImportedAgent?.(agent.id);
onImported?.(agent);
if (target.crossWorkspace) {
onImported?.(agent);
} else {
onImportedAgent?.(agent.id);
}
void queryClient.invalidateQueries({
queryKey: sessionsQueryRoot,
refetchType: "none",
});
},
});
@@ -442,23 +634,61 @@ export function ImportSessionSheet({
[importMutation],
);
const erroredProviderLabels = useMemo(
() => collectErroredProviderLabels(providersToFetch, queries, providerLabelById),
const providerErrorRows = useMemo(
() => collectProviderErrorRows(providersToFetch, queries, providerLabelById),
[queries, providersToFetch, providerLabelById],
);
const isRefreshing = queries.some((query) => query.isFetching);
// Every query settles, errors included, so this stops turning (#2512).
const isRefreshing = queries.some((providerQuery) => providerQuery.isFetching);
const handleRefresh = useCallback(() => {
void queryClient.invalidateQueries({ queryKey: sessionsQueryRoot });
}, [queryClient, sessionsQueryRoot]);
const handleRetryProvider = useCallback(
(provider: string) => {
void queryClient.refetchQueries({
queryKey: buildSessionsQueryKey({ cwd: scopeCwd, query, limit: pageLimit, provider }),
});
},
[pageLimit, query, queryClient, scopeCwd],
);
const handleShowAll = useCallback(() => setIsShowingAllDirectories(true), []);
const handleLoadMore = useCallback(() => setPageLimit(nextPageLimit), []);
const hosts = useHosts();
const hostLabel = useMemo(
() => hosts.find((host) => host.serverId === serverId)?.label ?? serverId ?? "",
[hosts, serverId],
);
const header = useMemo<SheetHeader>(
() => ({
title: t("importSession.title"),
subtitle: (
<ScopeSubtitle
hostLabel={hostLabel}
isScoped={scopeCwd !== null}
onShowAll={handleShowAll}
/>
),
...(supportsSearch
? {
search: {
onChange: setSearchInput,
placeholder: t("importSession.searchPlaceholder"),
// The compact sheet keeps its content mounted while hidden, so the
// field has to be told to drop the text the state already dropped.
resetKey: visible ? "open" : "closed",
testID: "import-session-search",
},
}
: {}),
actions: <RefreshAction isRefreshing={isRefreshing} onPress={handleRefresh} />,
}),
[isRefreshing, handleRefresh, t],
[handleRefresh, handleShowAll, hostLabel, isRefreshing, scopeCwd, supportsSearch, t, visible],
);
const isSnapshotUnsupported = requiresHostUpgrade;
@@ -467,22 +697,27 @@ export function ImportSessionSheet({
const isQueryingProviders = queries.length > 0;
const isLoadingSessions =
isWaitingForSnapshot ||
(isQueryingProviders && queries.some((query) => query.isLoading || query.isPending));
const allQueriesErrored = isQueryingProviders && queries.every((query) => query.isError);
(isQueryingProviders &&
queries.some((providerQuery) => providerQuery.isLoading || providerQuery.isPending));
const allQueriesErrored =
isQueryingProviders && queries.every((providerQuery) => providerQuery.isError);
const allQueriesSettled =
isQueryingProviders && queries.every((query) => !query.isLoading && !query.isPending);
isQueryingProviders &&
queries.every((providerQuery) => !providerQuery.isLoading && !providerQuery.isPending);
const { showEmptyState, emptyStateTitle } = computeEmptyState({
isLoadingSessions,
allQueriesErrored,
isQueryingProviders,
allQueriesSettled,
selectedProvider,
hasQuery: query.length > 0,
aggregatedCount: aggregatedEntries.length,
visibleCount: visibleEntries.length,
totalAlreadyImportedCount,
providerLabelById,
});
const showFilter = filterProviders.length > 1;
const showLoadMore = hasMoreSessions(queries, pageLimit);
return (
<AdaptiveModalSheet
@@ -506,7 +741,7 @@ export function ImportSessionSheet({
<Layers size={14} color={theme.colors.foregroundMuted} />
) : (
(() => {
const ProviderIcon = getProviderIcon(selectedProvider);
const ProviderIcon = getProviderIcon(selectedProvider, serverId);
return <ProviderIcon size={14} color={theme.colors.foregroundMuted} />;
})()
)}
@@ -536,22 +771,31 @@ export function ImportSessionSheet({
hasNoImportableProviders={hasNoImportableProviders}
isLoadingSessions={isLoadingSessions}
hasRows={visibleEntries.length > 0}
allQueriesErrored={allQueriesErrored}
erroredProviderLabels={erroredProviderLabels}
importErrored={importMutation.isError}
/>
{providerErrorRows.length > 0 ? (
<ProviderErrorBanner rows={providerErrorRows} onRetry={handleRetryProvider} />
) : null}
{visibleEntries.length > 0 ? (
<View style={styles.list}>
{visibleEntries.map((entry) => (
<ImportSessionSheetRow
key={`${entry.providerId}:${entry.providerHandleId}`}
entry={entry}
disabled={importMutation.isPending}
importing={importingSessionKey === `${entry.providerId}:${entry.providerHandleId}`}
showCwd={!cwd}
onImportSession={handleImportSession}
/>
))}
<SessionRows
serverId={serverId}
entries={visibleEntries}
disabled={importMutation.isPending}
importingSessionKey={importingSessionKey}
resolveFolder={resolveFolder}
onImportSession={handleImportSession}
/>
) : null}
{showLoadMore ? (
<View style={styles.footer}>
<Button
variant="ghost"
onPress={handleLoadMore}
disabled={isRefreshing}
testID="import-session-load-more"
>
{t("importSession.actions.loadMore")}
</Button>
</View>
) : null}
{showEmptyState ? <SheetEmptyState title={emptyStateTitle} /> : null}
@@ -560,6 +804,21 @@ export function ImportSessionSheet({
}
const styles = StyleSheet.create((theme) => ({
subtitleRow: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
minWidth: 0,
},
subtitleText: {
flexShrink: 1,
minWidth: 0,
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
subtitleAction: {
marginHorizontal: -theme.spacing[2],
},
filterTriggerWrap: {
paddingBottom: theme.spacing[2],
},
@@ -568,6 +827,7 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[1.5],
alignSelf: "flex-start",
maxWidth: "100%",
paddingVertical: theme.spacing[1.5],
paddingHorizontal: theme.spacing[3],
borderRadius: theme.borderRadius.md,
@@ -582,6 +842,8 @@ const styles = StyleSheet.create((theme) => ({
backgroundColor: theme.colors.surface3,
},
filterTriggerText: {
flexShrink: 1,
minWidth: 0,
color: theme.colors.foreground,
fontSize: theme.fontSize.base,
fontWeight: theme.fontWeight.medium,
@@ -589,6 +851,10 @@ const styles = StyleSheet.create((theme) => ({
list: {
gap: theme.spacing[1],
},
footer: {
paddingTop: theme.spacing[2],
alignItems: "center",
},
row: {
flexDirection: "row",
alignItems: "flex-start",
@@ -636,7 +902,7 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.base,
lineHeight: 20,
},
rowCwd: {
rowFolder: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
},
@@ -650,6 +916,26 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.base,
},
errorBanner: {
marginBottom: theme.spacing[2],
borderWidth: theme.borderWidth[1],
borderColor: theme.colors.border,
borderRadius: theme.borderRadius.lg,
paddingVertical: theme.spacing[1],
paddingHorizontal: theme.spacing[3],
},
errorRow: {
flexDirection: "row",
alignItems: "center",
justifyContent: "space-between",
gap: theme.spacing[2],
},
errorText: {
flexShrink: 1,
minWidth: 0,
color: theme.colors.palette.red[300],
fontSize: theme.fontSize.sm,
},
emptyState: {
alignItems: "center",
justifyContent: "center",
@@ -1,21 +1,15 @@
import type { ReactNode } from "react";
import type { ViewProps } from "react-native";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { useKeyboardShift } from "@/hooks/keyboard-shift-context";
import { KeyboardTranslateView } from "@/components/keyboard-translate-view";
interface KeyboardDockProps extends ViewProps {
children: ReactNode;
}
export function KeyboardDock({ children, style, ...props }: KeyboardDockProps) {
const { shift } = useKeyboardShift();
const keyboardPaddingStyle = useAnimatedStyle(() => ({
paddingBottom: shift.value,
}));
return (
<Animated.View style={[style, keyboardPaddingStyle]} {...props}>
<KeyboardTranslateView style={style} {...props}>
{children}
</Animated.View>
</KeyboardTranslateView>
);
}
@@ -0,0 +1,27 @@
import type { ReactNode } from "react";
import type { ViewProps } from "react-native";
import Animated, { useAnimatedStyle } from "react-native-reanimated";
import { useKeyboardShift } from "@/hooks/keyboard-shift-context";
interface KeyboardTranslateViewProps extends ViewProps {
children: ReactNode;
enabled?: boolean;
}
export function KeyboardTranslateView({
children,
enabled = true,
style,
...props
}: KeyboardTranslateViewProps) {
const { shift } = useKeyboardShift();
const keyboardStyle = useAnimatedStyle(() => ({
transform: [{ translateY: enabled ? -shift.value : 0 }],
}));
return (
<Animated.View style={[style, keyboardStyle]} {...props}>
{children}
</Animated.View>
);
}
@@ -0,0 +1,33 @@
import { useMemo, type ReactNode } from "react";
import { Animated, type ViewProps } from "react-native";
import { useKeyboardAnimation } from "react-native-keyboard-controller";
import { useSafeAreaInsets } from "react-native-safe-area-context";
interface KeyboardTranslateViewProps extends ViewProps {
children: ReactNode;
enabled?: boolean;
}
export function KeyboardTranslateView({
children,
enabled = true,
style,
...props
}: KeyboardTranslateViewProps) {
const insets = useSafeAreaInsets();
const { height, progress } = useKeyboardAnimation();
const translateY = useMemo(
() => Animated.add(height, Animated.multiply(progress, insets.bottom)),
[height, insets.bottom, progress],
);
const keyboardStyle = useMemo(
() => ({ transform: [{ translateY: enabled ? translateY : 0 }] }),
[enabled, translateY],
);
return (
<Animated.View style={[style, keyboardStyle]} {...props}>
{children}
</Animated.View>
);
}
@@ -0,0 +1,15 @@
import type { ReactNode } from "react";
import { View, type ViewProps } from "react-native";
interface KeyboardTranslateViewProps extends ViewProps {
children: ReactNode;
enabled?: boolean;
}
export function KeyboardTranslateView({
children,
enabled: _enabled,
...props
}: KeyboardTranslateViewProps) {
return <View {...props}>{children}</View>;
}
+149 -272
View File
@@ -1,12 +1,9 @@
import { router, usePathname } from "expo-router";
import { router, useGlobalSearchParams } from "expo-router";
import {
CalendarClock,
AudioLines,
FolderPlus,
GitBranch,
History,
Home,
Plus,
Search,
Import,
Server,
Settings,
X,
@@ -33,17 +30,16 @@ import {
SIDEBAR_RESIZE_FAIL_OFFSET,
} from "@/components/sidebar-resize-handle-layout";
import { HostPicker } from "@/components/hosts/host-picker";
import { SidebarHeaderRow } from "@/components/sidebar/sidebar-header-row";
import { SidebarDisplayPreferencesMenu } from "@/components/sidebar/display-preferences/menu";
import { SidebarNavRows } from "@/components/sidebar/sidebar-nav-rows";
import { SidebarHelpMenu } from "@/components/sidebar/sidebar-help-menu";
import { SidebarResizeHandle } from "@/components/sidebar-resize-handle";
import { Shortcut } from "@/components/ui/shortcut";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { HEADER_INNER_HEIGHT, useIsCompactFormFactor } from "@/constants/layout";
import { useOpenAddProject } from "@/hooks/use-open-add-project";
import { useImportSession } from "@/hooks/use-import-session";
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { canCreateWorktreeForProjectKind } from "@/projects/host-projects";
import { useHostFeature } from "@/runtime/host-features";
import {
type SidebarProjectEntry,
type SidebarWorkspaceEntry,
@@ -54,29 +50,23 @@ import { RetainedPanelActivity } from "@/components/retained-panel";
import type { SidebarWorkspaceGroup } from "@/components/sidebar/sidebar-labels";
import type { SidebarProjectIconTarget } from "@/utils/sidebar-project-row-model";
import { type SidebarGroupMode, useSidebarViewStore } from "@/stores/sidebar-view-store";
import { useKeyboardShortcutsStore } from "@/stores/keyboard-shortcuts-store";
import { useHosts } from "@/runtime/host-runtime";
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
import { useWorkspace } from "@/stores/session-store-hooks";
import { useHostRuntimeIsConnected, useHosts } from "@/runtime/host-runtime";
import { useVoiceOptional } from "@/contexts/voice-context";
import { useToast } from "@/contexts/toast-context";
import { usePanelStore } from "@/stores/panel-store";
import { useOwnsWindowChromeCorner, WindowChromeSafeArea } from "@/utils/desktop-window";
import { useCloseAgentListGesture } from "@/mobile-panels/gestures";
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
import { useIsMobilePanelPresented } from "@/mobile-panels/provider";
import {
buildOpenProjectRoute,
buildNewWorkspaceRoute,
buildSchedulesRoute,
buildSessionsRoute,
buildSettingsAddHostRoute,
buildSettingsRoute,
} from "@/utils/host-routes";
import { buildSettingsAddHostRoute, buildSettingsRoute } from "@/utils/host-routes";
import { openHostOverview } from "@/navigation/settings-navigation";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { SidebarAgentListSkeleton } from "./sidebar-agent-list-skeleton";
import { SidebarCalloutSlot } from "./sidebar-callout-slot";
import { SidebarWorkspaceList } from "./sidebar-workspace-list";
import { PluginSidebarItems } from "@/plugins";
import { VoiceCallSurface } from "./voice-call-surface";
import {
useActiveWorkspaceSelection,
useLastWorkspaceSelection,
} from "@/stores/navigation-active-workspace-store";
type SidebarTheme = ReturnType<typeof useUnistyles>["theme"];
@@ -100,39 +90,32 @@ interface SidebarSharedProps {
toggleProjectCollapsed: (projectViewKey: string) => void;
handleRefresh: () => void;
handleOpenProject: () => void;
handleHome: () => void;
handleImportSession: () => void;
handleSettings: () => void;
labels: SidebarLabels;
newWorkspaceKeys: ShortcutKey[][] | null;
handleAddHost: () => void;
handleOpenHostSettings: (serverId: string) => void;
}
interface SidebarLabels {
addProject: string;
newWorkspace: string;
hosts: string;
home: string;
importSession: string;
settings: string;
searchHosts: string;
sessions: string;
schedules: string;
closeSidebar: string;
}
interface MobileSidebarProps extends SidebarSharedProps {
active: boolean;
insetsTop: number;
insetsBottom: number;
closeSidebar: () => void;
handleViewMoreNavigate: () => void;
handleViewSchedulesNavigate: () => void;
}
interface DesktopSidebarProps extends SidebarSharedProps {
insetsTop: number;
active: boolean;
handleViewMore: () => void;
handleViewSchedules: () => void;
}
export const LeftSidebar = memo(function LeftSidebar({ active }: { active: boolean }) {
@@ -174,6 +157,7 @@ export const LeftSidebar = memo(function LeftSidebar({ active }: { active: boole
}, [isRevalidating, isManualRefresh]);
const openProjectPicker = useOpenAddProject();
const { open: openImportSession, sheet: importSessionSheet } = useImportSession();
const handleOpenProjectMobile = useCallback(() => {
showMobileAgent();
@@ -214,34 +198,18 @@ export const LeftSidebar = memo(function LeftSidebar({ active }: { active: boole
openHostOverview(serverId);
}, []);
const handleHomeMobile = useCallback(() => {
const handleImportSessionMobile = useCallback(() => {
showMobileAgent();
router.push(buildOpenProjectRoute());
}, [showMobileAgent]);
openImportSession();
}, [openImportSession, showMobileAgent]);
const handleHomeDesktop = useCallback(() => {
router.push(buildOpenProjectRoute());
}, []);
const handleViewMoreNavigate = useCallback(() => {
router.push(buildSessionsRoute());
}, []);
const handleViewSchedulesNavigate = useCallback(() => {
router.push(buildSchedulesRoute());
}, []);
const newWorkspaceKeys = useShortcutKeys("new-workspace");
const labels = useMemo(
(): SidebarLabels => ({
addProject: t("sidebar.actions.addProject"),
newWorkspace: t("sidebar.actions.newWorkspace"),
hosts: t("sidebar.actions.hosts"),
home: t("sidebar.actions.home"),
importSession: t("importSession.title"),
settings: t("sidebar.actions.settings"),
searchHosts: t("sidebar.host.searchPlaceholder"),
sessions: t("sidebar.sections.sessions"),
schedules: t("sidebar.sections.schedules"),
closeSidebar: t("sidebar.actions.closeSidebar"),
}),
[t],
@@ -265,44 +233,46 @@ export const LeftSidebar = memo(function LeftSidebar({ active }: { active: boole
toggleProjectCollapsed,
handleRefresh,
labels,
newWorkspaceKeys,
};
if (isCompactLayout) {
return (
<RetainedPanelActivity active={active}>
<MobileSidebar
{...sharedProps}
insetsTop={insets.top}
insetsBottom={insets.bottom}
closeSidebar={showMobileAgent}
handleOpenProject={handleOpenProjectMobile}
handleHome={handleHomeMobile}
handleSettings={handleSettingsMobile}
handleAddHost={handleAddHostMobile}
handleOpenHostSettings={handleOpenHostSettingsMobile}
handleViewMoreNavigate={handleViewMoreNavigate}
handleViewSchedulesNavigate={handleViewSchedulesNavigate}
/>
</RetainedPanelActivity>
<>
<RetainedPanelActivity active={active}>
<MobileSidebar
{...sharedProps}
active={active}
insetsTop={insets.top}
insetsBottom={insets.bottom}
closeSidebar={showMobileAgent}
handleOpenProject={handleOpenProjectMobile}
handleImportSession={handleImportSessionMobile}
handleSettings={handleSettingsMobile}
handleAddHost={handleAddHostMobile}
handleOpenHostSettings={handleOpenHostSettingsMobile}
/>
</RetainedPanelActivity>
{importSessionSheet}
</>
);
}
return (
<RetainedPanelActivity active={active}>
<DesktopSidebar
{...sharedProps}
insetsTop={insets.top}
active={active}
handleOpenProject={handleOpenProjectDesktop}
handleHome={handleHomeDesktop}
handleSettings={handleSettingsDesktop}
handleAddHost={handleAddHostDesktop}
handleOpenHostSettings={handleOpenHostSettingsDesktop}
handleViewMore={handleViewMoreNavigate}
handleViewSchedules={handleViewSchedulesNavigate}
/>
</RetainedPanelActivity>
<>
<RetainedPanelActivity active={active}>
<DesktopSidebar
{...sharedProps}
insetsTop={insets.top}
active={active}
handleOpenProject={handleOpenProjectDesktop}
handleImportSession={openImportSession}
handleSettings={handleSettingsDesktop}
handleAddHost={handleAddHostDesktop}
handleOpenHostSettings={handleOpenHostSettingsDesktop}
/>
</RetainedPanelActivity>
{importSessionSheet}
</>
);
});
@@ -313,6 +283,7 @@ function sidebarHostOptionTestID(serverId: string): string {
function FooterIconButton({
buttonRef,
onPress,
disabled = false,
testID,
label,
icon: Icon,
@@ -321,6 +292,7 @@ function FooterIconButton({
theme,
}: {
onPress: () => void;
disabled?: boolean;
testID: string;
label: string;
icon: typeof FolderPlus;
@@ -334,19 +306,20 @@ function FooterIconButton({
<TooltipTrigger asChild>
<Pressable
ref={buttonRef}
style={styles.footerIconButton}
testID={testID}
nativeID={testID}
collapsable={false}
accessible
accessibilityLabel={label}
accessibilityRole="button"
disabled={disabled}
onPress={onPress}
style={[styles.footerIconButton, disabled && styles.footerIconButtonDisabled]}
>
{({ hovered }) => (
<Icon
size={iconSize ?? theme.iconSize.md}
color={hovered ? theme.colors.foreground : theme.colors.foregroundMuted}
color={hovered && !disabled ? theme.colors.foreground : theme.colors.foregroundMuted}
/>
)}
</Pressable>
@@ -358,6 +331,68 @@ function FooterIconButton({
);
}
function firstSearchParam(value: string | string[] | undefined): string | null {
return Array.isArray(value) ? (value[0] ?? null) : (value ?? null);
}
function SidebarVoiceChatButton({ theme }: { theme: SidebarTheme }) {
const { t } = useTranslation();
const toast = useToast();
const voice = useVoiceOptional();
const activeWorkspace = useActiveWorkspaceSelection();
const lastWorkspace = useLastWorkspaceSelection();
const workspace = activeWorkspace ?? lastWorkspace;
const params = useGlobalSearchParams<{
serverId?: string | string[];
workspaceId?: string | string[];
agentId?: string | string[];
}>();
const isConnected = useHostRuntimeIsConnected(workspace?.serverId ?? "");
const isActiveRoute =
workspace?.serverId === firstSearchParam(params.serverId) &&
workspace?.workspaceId === firstSearchParam(params.workspaceId);
const agentId = isActiveRoute ? firstSearchParam(params.agentId) : null;
const disabled = !voice || voice.isVoiceSwitching;
const handlePress = useCallback(() => {
if (!voice || disabled) return;
if (!workspace) {
toast.error("Open a workspace before starting voice chat.");
return;
}
if (!isConnected) {
toast.error("Connect to the host before starting voice chat.");
return;
}
void voice
.startCall(workspace.serverId, { workspaceId: workspace.workspaceId, agentId })
.catch((error) => {
console.error("[Sidebar] Failed to start voice chat", error);
toast.error(error instanceof Error ? error.message : "Unable to start voice chat");
});
}, [agentId, disabled, isConnected, toast, voice, workspace]);
if (voice?.isVoiceMode) return null;
return (
<FooterIconButton
onPress={handlePress}
disabled={disabled}
testID="sidebar-voice-chat"
label={t("composer.voice.voiceMode")}
icon={AudioLines}
theme={theme}
/>
);
}
function VoiceWorkspaceListClearance() {
const voice = useVoiceOptional();
return voice?.isVoiceMode ? <View style={styles.voiceWorkspaceListClearance} /> : null;
}
const voiceWorkspaceListClearance = <VoiceWorkspaceListClearance />;
function footerAddProjectButtonStyle({
hovered,
}: PressableStateCallbackType & { hovered?: boolean }) {
@@ -486,65 +521,10 @@ function IconTooltipContent({
);
}
const SidebarNewWorkspaceHeaderRow = memo(function SidebarNewWorkspaceHeaderRow({
label,
testID,
variant,
shortcutKeys,
onBeforeNavigate,
}: {
label: string;
testID: string;
variant: "header" | "compact";
shortcutKeys: ShortcutKey[][] | null;
onBeforeNavigate?: () => void;
}) {
const activeWorkspaceSelection = useActiveWorkspaceSelection();
const activeWorkspaceServerId = activeWorkspaceSelection?.serverId ?? null;
const activeWorkspaceId = activeWorkspaceSelection?.workspaceId ?? null;
const activeWorkspace = useWorkspace(activeWorkspaceServerId, activeWorkspaceId);
const supportsWorkspaceMultiplicity = useHostFeature(
activeWorkspaceServerId,
"workspaceMultiplicity",
);
const canUseActiveWorkspaceContext = Boolean(
activeWorkspace &&
(supportsWorkspaceMultiplicity || canCreateWorktreeForProjectKind(activeWorkspace.projectKind)),
);
const handlePress = useCallback(() => {
onBeforeNavigate?.();
router.push(
activeWorkspaceServerId
? buildNewWorkspaceRoute(
activeWorkspace && canUseActiveWorkspaceContext
? {
serverId: activeWorkspaceServerId,
sourceDirectory: activeWorkspace.projectRootPath,
projectId: activeWorkspace.projectId,
}
: { serverId: activeWorkspaceServerId },
)
: buildNewWorkspaceRoute(),
);
}, [activeWorkspace, activeWorkspaceServerId, canUseActiveWorkspaceContext, onBeforeNavigate]);
return (
<SidebarHeaderRow
icon={Plus}
label={label}
onPress={handlePress}
testID={testID}
variant={variant}
shortcutKeys={shortcutKeys}
/>
);
});
function SidebarFooter({
theme,
handleOpenProject,
handleHome,
handleImportSession,
handleSettings,
labels,
handleAddHost,
@@ -552,12 +532,12 @@ function SidebarFooter({
}: {
theme: SidebarTheme;
handleOpenProject: () => void;
handleHome: () => void;
handleImportSession: () => void;
handleSettings: () => void;
labels: {
addProject: string;
hosts: string;
home: string;
importSession: string;
settings: string;
searchHosts: string;
};
@@ -583,12 +563,13 @@ function SidebarFooter({
onOpenHostSettings={handleOpenHostSettings}
/>
<FooterIconButton
onPress={handleHome}
testID="sidebar-home"
label={labels.home}
icon={Home}
onPress={handleImportSession}
testID="sidebar-import-session"
label={labels.importSession}
icon={Import}
theme={theme}
/>
<SidebarVoiceChatButton theme={theme} />
<SidebarHelpMenu />
<FooterIconButton
onPress={handleSettings}
@@ -604,6 +585,7 @@ function SidebarFooter({
}
function MobileSidebar({
active,
theme,
workspaceGroups,
projectIconTargets,
@@ -620,9 +602,8 @@ function MobileSidebar({
shortcutIndexByWorkspaceKey,
toggleProjectCollapsed,
handleRefresh,
newWorkspaceKeys,
handleOpenProject,
handleHome,
handleImportSession,
handleSettings,
labels,
handleAddHost,
@@ -630,25 +611,9 @@ function MobileSidebar({
insetsTop,
insetsBottom,
closeSidebar,
handleViewMoreNavigate,
handleViewSchedulesNavigate,
}: MobileSidebarProps) {
const pathname = usePathname();
const hasActiveHostFilter = useSidebarViewStore((state) => state.hostFilters.length > 0);
const isSessionsActive = pathname.includes("/sessions");
const isSchedulesActive = pathname.includes("/schedules");
const { gesture: closeGesture, gestureRef: closeGestureRef } = useCloseAgentListGesture();
const dragGestureHostPresented = useIsMobilePanelPresented("agent-list");
const handleViewMore = useCallback(() => {
closeSidebar();
handleViewMoreNavigate();
}, [closeSidebar, handleViewMoreNavigate]);
const handleViewSchedules = useCallback(() => {
closeSidebar();
handleViewSchedulesNavigate();
}, [closeSidebar, handleViewSchedulesNavigate]);
const handleWorkspacePress = useCallback(() => {
closeSidebar();
@@ -671,32 +636,7 @@ function MobileSidebar({
>
<View style={styles.sidebarContent} pointerEvents="auto">
<WindowChromeSafeArea placement="below" />
<View style={styles.sidebarHeaderGroup}>
<SidebarNewWorkspaceHeaderRow
label={labels.newWorkspace}
testID="sidebar-global-new-workspace"
variant="compact"
shortcutKeys={newWorkspaceKeys}
onBeforeNavigate={closeSidebar}
/>
<SidebarHeaderRow
icon={History}
label={labels.sessions}
onPress={handleViewMore}
isActive={isSessionsActive}
testID="sidebar-sessions"
variant="compact"
/>
<SidebarHeaderRow
icon={CalendarClock}
label={labels.schedules}
onPress={handleViewSchedules}
isActive={isSchedulesActive}
testID="sidebar-schedules"
variant="compact"
/>
<PluginSidebarItems onBeforeNavigate={closeSidebar} />
</View>
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
<WindowChromeSafeArea placement="inline" style={styles.mobileCloseButtonRow}>
<Pressable
style={styles.mobileCloseButton}
@@ -736,16 +676,19 @@ function MobileSidebar({
onRefresh={handleRefresh}
onWorkspacePress={handleWorkspacePress}
onAddProject={handleOpenProject}
onImportSession={handleImportSession}
listFooterComponent={voiceWorkspaceListClearance}
parentGestureRef={closeGestureRef}
dragGestureHostPresented={dragGestureHostPresented}
dragGestureHostActive={active}
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<VoiceCallSurface />
<SidebarFooter
theme={theme}
handleOpenProject={handleOpenProject}
handleHome={handleHome}
handleImportSession={handleImportSession}
handleSettings={handleSettings}
labels={labels}
handleAddHost={handleAddHost}
@@ -773,23 +716,17 @@ function DesktopSidebar({
shortcutIndexByWorkspaceKey,
toggleProjectCollapsed,
handleRefresh,
newWorkspaceKeys,
handleOpenProject,
handleHome,
handleImportSession,
handleSettings,
labels,
handleAddHost,
handleOpenHostSettings,
insetsTop,
active,
handleViewMore,
handleViewSchedules,
}: DesktopSidebarProps) {
const ownsTopLeft = useOwnsWindowChromeCorner("top-left");
const pathname = usePathname();
const hasActiveHostFilter = useSidebarViewStore((state) => state.hostFilters.length > 0);
const isSessionsActive = pathname.includes("/sessions");
const isSchedulesActive = pathname.includes("/schedules");
const sidebarWidth = usePanelStore((state) => state.sidebarWidth);
const setSidebarWidth = usePanelStore((state) => state.setSidebarWidth);
const { width: viewportWidth } = useWindowDimensions();
@@ -897,31 +834,7 @@ function DesktopSidebar({
) : (
<TitlebarDragRegion />
)}
<View style={sidebarHeaderGroupStyle}>
<SidebarNewWorkspaceHeaderRow
label={labels.newWorkspace}
testID="sidebar-global-new-workspace"
variant="compact"
shortcutKeys={newWorkspaceKeys}
/>
<SidebarHeaderRow
icon={History}
label={labels.sessions}
onPress={handleViewMore}
isActive={isSessionsActive}
testID="sidebar-sessions"
variant="compact"
/>
<SidebarHeaderRow
icon={CalendarClock}
label={labels.schedules}
onPress={handleViewSchedules}
isActive={isSchedulesActive}
testID="sidebar-schedules"
variant="compact"
/>
<PluginSidebarItems />
</View>
<SidebarNavRows style={sidebarHeaderGroupStyle} />
</View>
{isInitialLoad && !hasActiveHostFilter ? (
@@ -942,16 +855,19 @@ function DesktopSidebar({
isRefreshing={isManualRefresh && isRevalidating}
onRefresh={handleRefresh}
onAddProject={handleOpenProject}
onImportSession={handleImportSession}
listFooterComponent={voiceWorkspaceListClearance}
listHeaderComponent={workspacesSectionHeaderElement}
/>
)}
<SidebarCalloutSlot />
<VoiceCallSurface />
<SidebarFooter
theme={theme}
handleOpenProject={handleOpenProject}
handleHome={handleHome}
handleImportSession={handleImportSession}
handleSettings={handleSettings}
labels={labels}
handleAddHost={handleAddHost}
@@ -970,45 +886,10 @@ function DesktopSidebar({
}
function WorkspacesSectionHeader() {
const { theme } = useUnistyles();
const setCommandCenterOpen = useKeyboardShortcutsStore((state) => state.setCommandCenterOpen);
const commandCenterKeys = useShortcutKeys("toggle-command-center");
const handleSearchPress = useCallback(() => setCommandCenterOpen(true), [setCommandCenterOpen]);
const searchButtonStyle = useCallback(
({ hovered = false, pressed }: PressableStateCallbackType & { hovered?: boolean }) => [
styles.workspacesHeaderIconButton,
(hovered || pressed) && styles.workspacesHeaderIconButtonHovered,
],
[],
);
return (
<View style={styles.workspacesSectionHeader}>
<Text style={styles.workspacesSectionTitle}>Workspaces</Text>
<View style={styles.workspacesSectionActions}>
<Tooltip delayDuration={300}>
<TooltipTrigger asChild>
<Pressable
accessibilityRole="button"
accessibilityLabel="Open command center"
testID="sidebar-command-center-search"
style={searchButtonStyle}
onPress={handleSearchPress}
>
{({ hovered, pressed }) => (
<Search
size={14}
color={
hovered || pressed ? theme.colors.foreground : theme.colors.foregroundMuted
}
/>
)}
</Pressable>
</TooltipTrigger>
<TooltipContent side="bottom" align="center" offset={8}>
<IconTooltipContent label="Search" shortcutKeys={commandCenterKeys} />
</TooltipContent>
</Tooltip>
<Tooltip delayDuration={300}>
<TooltipTrigger asChild>
<View>
@@ -1074,16 +955,6 @@ const styles = StyleSheet.create((theme) => ({
alignItems: "center",
gap: theme.spacing[1],
},
workspacesHeaderIconButton: {
width: 28,
height: 28,
alignItems: "center",
justifyContent: "center",
borderRadius: theme.borderRadius.md,
},
workspacesHeaderIconButtonHovered: {
backgroundColor: theme.colors.surfaceSidebarHover,
},
sidebarContent: {
flex: 1,
minHeight: 0,
@@ -1190,6 +1061,12 @@ const styles = StyleSheet.create((theme) => ({
paddingVertical: theme.spacing[1],
paddingHorizontal: theme.spacing[1],
},
footerIconButtonDisabled: {
opacity: theme.opacity[50],
},
voiceWorkspaceListClearance: {
height: theme.spacing[12],
},
tooltipRow: {
flexDirection: "row",
alignItems: "center",
@@ -54,6 +54,11 @@ const html = `<!doctype html>
margin: 0;
padding: 0;
background: transparent;
height: 100%;
}
/* The host sizes this frame to the diagram, so the diagram fills the frame. */
#diagram {
height: 100%;
}
#diagram svg {
display: block;
@@ -0,0 +1,140 @@
import { useCallback, useEffect, useMemo, useRef } from "react";
import { Modal, View } from "react-native";
import { X } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet } from "react-native-unistyles";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { ZoomableViewport } from "@/components/zoomable-viewport";
import { SPACING } from "@/styles/theme";
import { WindowChromeRootRegion } from "@/utils/desktop-window";
import { MermaidIframeRuntime, type MermaidRenderedMessage } from "./iframe-runtime.web";
import type { DiagramColorScheme } from "./render-model";
import { useMermaidRenderModel } from "./use-render-model";
interface MermaidFullscreenViewerProps {
source: string;
colorScheme: DiagramColorScheme;
onClose: () => void;
}
// The diagram is already in the render cache, so the viewport knows its size before the
// fullscreen iframe has re-rendered it.
const FALLBACK_SIZE = { width: 240, height: 240 };
const VIEWER_FIT = { padding: SPACING[6] };
export function MermaidFullscreenViewer({
source,
colorScheme,
onClose,
}: MermaidFullscreenViewerProps) {
const { t } = useTranslation();
const insets = useSafeAreaInsets();
const { state, request, rendered, renderFailed } = useMermaidRenderModel({
source,
phase: "complete",
colorScheme,
});
const handleRendered = useCallback(
(message: MermaidRenderedMessage) => {
rendered({
revision: message.revision,
source: message.source,
colorScheme: message.colorScheme,
dimensions: { height: message.height, width: message.width },
});
},
[rendered],
);
useEffect(() => {
function handleKeydown(event: KeyboardEvent): void {
if (event.key === "Escape") onClose();
}
window.addEventListener("keydown", handleKeydown);
return () => window.removeEventListener("keydown", handleKeydown);
}, [onClose]);
// The Modal focus trap walks descendants and focuses the first one that takes it. Focus the
// content layer ourselves (this effect runs after the trap's) so keystrokes stay in this
// document instead of disappearing into a focused diagram iframe.
const contentLayerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
contentLayerRef.current?.focus();
}, []);
const visible = state.visible;
const contentSize = useMemo(
() => (visible ? { width: visible.width, height: visible.height } : FALLBACK_SIZE),
[visible],
);
const actions = useMemo(
() => [
{
icon: X,
label: t("common.actions.close"),
onPress: onClose,
testID: "mermaid-fullscreen-close",
},
],
[onClose, t],
);
const contentLayerStyle = useMemo(
() => [
styles.contentLayer,
{
paddingTop: insets.top,
paddingRight: insets.right,
paddingBottom: insets.bottom,
paddingLeft: insets.left,
},
],
[insets.bottom, insets.left, insets.right, insets.top],
);
return (
<Modal transparent animationType="fade" statusBarTranslucent visible onRequestClose={onClose}>
<WindowChromeRootRegion corners="both">
<View style={styles.root}>
<View style={styles.backdrop} />
<View style={contentLayerStyle}>
{/* biome-ignore lint/a11y/noNoninteractiveTabindex: focus holder for the Escape shortcut */}
<div ref={contentLayerRef} style={focusLayerDomStyle} tabIndex={-1}>
<ZoomableViewport
accessibilityLabel={t("message.diagram.diagram")}
actions={actions}
contentSize={contentSize}
fit={VIEWER_FIT}
minScale={1}
onPressOutsideContent={onClose}
style={styles.viewport}
testID="mermaid-fullscreen-viewport"
wheelActivation="always"
>
<MermaidIframeRuntime
request={request}
onRendered={handleRendered}
onRenderFailed={renderFailed}
/>
</ZoomableViewport>
</div>
</View>
</View>
</WindowChromeRootRegion>
</Modal>
);
}
const focusLayerDomStyle: React.CSSProperties = {
display: "flex",
flexDirection: "column",
height: "100%",
minHeight: 0,
outline: "none",
};
const styles = StyleSheet.create((theme) => ({
root: { flex: 1, minHeight: 0, minWidth: 0 },
backdrop: { position: "absolute", inset: 0, backgroundColor: theme.colors.surface0 },
contentLayer: { position: "absolute", inset: 0 },
viewport: { flex: 1 },
}));
@@ -1,104 +1,17 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useCallback, useMemo, useState } from "react";
import { Pressable, View, type TextStyle, type ViewStyle } from "react-native";
import { Code, Workflow } from "lucide-react-native";
import { Code, Maximize2, Workflow } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import { ZoomableViewport } from "@/components/zoomable-viewport";
import type { Theme } from "@/styles/theme";
import type { MarkdownFenceRendererProps } from "../types";
import type { MermaidRenderRequest } from "./render-model";
import { mermaidRuntimeHtml } from "./runtime/html.gen";
import { parseMermaidRuntimeMessage, type MermaidRuntimeRenderMessage } from "./runtime/messages";
import { MermaidRuntimeRequestDriver } from "./runtime/request-driver";
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
import { MermaidIframeRuntime, type MermaidRenderedMessage } from "./iframe-runtime.web";
import { useMermaidRenderModel } from "./use-render-model";
import { getDiagramBoxStyle } from "./presentation";
interface MermaidIframeRuntimeProps {
request: MermaidRenderRequest | null;
height: React.CSSProperties["height"];
onRendered: (message: {
revision: number;
source: string;
colorScheme: "light" | "dark";
height: number;
width: number;
}) => void;
onRenderFailed: (revision: number) => void;
}
function MermaidIframeRuntime({
request,
height,
onRendered,
onRenderFailed,
}: MermaidIframeRuntimeProps) {
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const driverRef = useRef<MermaidRuntimeRequestDriver | null>(null);
driverRef.current ??= new MermaidRuntimeRequestDriver();
const iframeStyle = useMemo<React.CSSProperties>(
() => ({
display: "block",
width: "100%",
height,
border: 0,
pointerEvents: "none",
background: "transparent",
}),
[height],
);
const sendRequest = useCallback((current: MermaidRenderRequest | null) => {
const target = iframeRef.current?.contentWindow;
if (!current || !target) return;
const message: MermaidRuntimeRenderMessage = {
type: "render",
revision: current.revision,
source: current.source,
colorScheme: current.colorScheme,
interactive: false,
};
target.postMessage(message, "*");
}, []);
useEffect(() => {
sendRequest(driverRef.current?.update(request) ?? null);
}, [request, sendRequest]);
useEffect(() => {
function receiveMessage(event: MessageEvent): void {
if (event.source !== iframeRef.current?.contentWindow) return;
const message = parseMermaidRuntimeMessage(event.data);
if (!message) return;
if (message.type === "bridgeReady") {
sendRequest(driverRef.current?.ready() ?? null);
return;
}
if (message.type === "renderError") {
onRenderFailed(message.revision);
sendRequest(driverRef.current?.settled(message.revision, false) ?? null);
return;
}
onRendered(message);
sendRequest(driverRef.current?.settled(message.revision, true) ?? null);
}
window.addEventListener("message", receiveMessage);
return () => window.removeEventListener("message", receiveMessage);
}, [onRenderFailed, onRendered, sendRequest]);
return (
<iframe
ref={iframeRef}
title=""
aria-hidden
sandbox="allow-scripts"
srcDoc={mermaidRuntimeHtml}
tabIndex={-1}
style={iframeStyle}
/>
);
}
interface MermaidFenceHostImplProps extends MarkdownFenceRendererProps {
colorScheme?: "light" | "dark";
}
@@ -118,16 +31,13 @@ function MermaidFenceHostImpl({
});
const [hasRuntimeContent, setHasRuntimeContent] = useState(false);
const [showSource, setShowSource] = useState(false);
const [isFullscreen, setIsFullscreen] = useState(false);
const showSourcePress = useCallback(() => setShowSource(true), []);
const showDiagramPress = useCallback(() => setShowSource(false), []);
const openFullscreen = useCallback(() => setIsFullscreen(true), []);
const closeFullscreen = useCallback(() => setIsFullscreen(false), []);
const handleRendered = useCallback(
(message: {
revision: number;
source: string;
colorScheme: "light" | "dark";
height: number;
width: number;
}) => {
(message: MermaidRenderedMessage) => {
setHasRuntimeContent(true);
rendered({
revision: message.revision,
@@ -149,8 +59,14 @@ function MermaidFenceHostImpl({
label: t("message.diagram.viewSource"),
onPress: showSourcePress,
},
{
icon: Maximize2,
label: t("message.diagram.fullscreen"),
onPress: openFullscreen,
testID: "mermaid-fullscreen",
},
],
[showSourcePress, t],
[openFullscreen, showSourcePress, t],
);
const sourceView = useMemo(() => {
const { marginTop, marginBottom, marginVertical, ...sourceTextStyle } = textStyle;
@@ -162,7 +78,11 @@ function MermaidFenceHostImpl({
return { container: [margins, sourceContainerStyle], text };
}, [textStyle]);
const diagramStyle = useMemo(
() => [getDiagramBoxStyle(textStyle), containerStyle, { height: runtimeHeight }],
() => [
getDiagramBoxStyle(textStyle),
containerStyle,
{ height: runtimeHeight, minHeight: MIN_DIAGRAM_BOX_HEIGHT },
],
[runtimeHeight, textStyle],
);
const diagramSize = useMemo(
@@ -212,18 +132,40 @@ function MermaidFenceHostImpl({
>
<MermaidIframeRuntime
request={request}
height="100%"
onRendered={handleRendered}
onRenderFailed={renderFailed}
/>
</ZoomableViewport>
{isFullscreen && visible ? (
<MermaidFullscreenViewer
source={visible.source}
colorScheme={visible.colorScheme}
onClose={closeFullscreen}
/>
) : null}
</>
);
}
const MEASURING_SIZE = { width: 240, height: 240 };
/**
* The toolbar overlays the top of the box (8px offset + 32px compact buttons) and the box clips
* with `overflow: hidden`, so a shorter box leaves the buttons half-clipped and unclickable.
*/
const MIN_DIAGRAM_BOX_HEIGHT = 56;
const sourceContainerStyle: ViewStyle = { position: "relative" };
const containerStyle: ViewStyle = { overflow: "hidden", position: "relative" };
/**
* The viewport's own root is `flex: 1`, so as a flex item it has `flex-basis: 0%` and that basis
* replaces the height below. In the markdown column there is no free space to grow into, so the
* box collapses and the diagram is scaled down to fit a couple of pixels. Size it from the height.
*/
const containerStyle: ViewStyle = {
flexBasis: "auto",
flexGrow: 0,
flexShrink: 0,
overflow: "hidden",
position: "relative",
};
const measuringStyle: ViewStyle = {
position: "absolute",
left: 0,
@@ -0,0 +1,92 @@
import { useCallback, useEffect, useRef } from "react";
import type { DiagramColorScheme, MermaidRenderRequest } from "./render-model";
import { mermaidRuntimeHtml } from "./runtime/html.gen";
import { parseMermaidRuntimeMessage, type MermaidRuntimeRenderMessage } from "./runtime/messages";
import { MermaidRuntimeRequestDriver } from "./runtime/request-driver";
export interface MermaidRenderedMessage {
revision: number;
source: string;
colorScheme: DiagramColorScheme;
height: number;
width: number;
}
interface MermaidIframeRuntimeProps {
request: MermaidRenderRequest | null;
onRendered: (message: MermaidRenderedMessage) => void;
onRenderFailed: (revision: number) => void;
}
/** Sandboxed Mermaid renderer. Sizing and gestures belong to the surrounding viewport. */
export function MermaidIframeRuntime({
request,
onRendered,
onRenderFailed,
}: MermaidIframeRuntimeProps) {
const iframeRef = useRef<HTMLIFrameElement | null>(null);
const driverRef = useRef<MermaidRuntimeRequestDriver | null>(null);
driverRef.current ??= new MermaidRuntimeRequestDriver();
const sendRequest = useCallback((current: MermaidRenderRequest | null) => {
const target = iframeRef.current?.contentWindow;
if (!current || !target) return;
const message: MermaidRuntimeRenderMessage = {
type: "render",
revision: current.revision,
source: current.source,
colorScheme: current.colorScheme,
interactive: false,
};
target.postMessage(message, "*");
}, []);
useEffect(() => {
sendRequest(driverRef.current?.update(request) ?? null);
}, [request, sendRequest]);
useEffect(() => {
function receiveMessage(event: MessageEvent): void {
if (event.source !== iframeRef.current?.contentWindow) return;
const message = parseMermaidRuntimeMessage(event.data);
if (!message) return;
if (message.type === "bridgeReady") {
sendRequest(driverRef.current?.ready() ?? null);
return;
}
if (message.type === "renderError") {
onRenderFailed(message.revision);
sendRequest(driverRef.current?.settled(message.revision, false) ?? null);
return;
}
onRendered(message);
sendRequest(driverRef.current?.settled(message.revision, true) ?? null);
}
window.addEventListener("message", receiveMessage);
return () => window.removeEventListener("message", receiveMessage);
}, [onRenderFailed, onRendered, sendRequest]);
// `inert` (not just tabIndex) because the Modal focus trap focuses descendants
// programmatically; a focused iframe swallows every keystroke, including Escape.
return (
<iframe
ref={iframeRef}
title=""
aria-hidden
inert
sandbox="allow-scripts"
srcDoc={mermaidRuntimeHtml}
tabIndex={-1}
style={iframeStyle}
/>
);
}
const iframeStyle: React.CSSProperties = {
display: "block",
width: "100%",
height: "100%",
border: 0,
pointerEvents: "none",
background: "transparent",
};
@@ -59,6 +59,41 @@ let pendingRender: MermaidRuntimeRenderMessage | null = null;
let isRendering = false;
let isDrainScheduled = false;
interface DiagramSize {
height: number;
width: number;
}
/**
* Mermaid emits `width="100%"` with an inline `max-width` in pixels, so the diagram renders at
* its natural width and never fills a larger box. The host sizes this frame, so let the diagram
* follow the frame in both directions instead.
*/
function stretchToFrame(svg: SVGSVGElement): void {
svg.style.maxWidth = "100%";
svg.style.maxHeight = "100%";
svg.style.width = "100%";
svg.style.height = "100%";
}
/**
* The reported size is the host's content size, and the host feeds it back as this frame's size.
* Measuring the rendered box would make that a loop: every re-render lands in a frame the last
* measurement shrank by the container's padding, so a streaming diagram ratchets down to nothing.
* The viewBox is the diagram's own size and doesn't move.
*/
function measureDiagram(host: HTMLElement, svg: SVGSVGElement | null): DiagramSize {
const viewBox = svg?.viewBox.baseVal;
if (viewBox && viewBox.width > 0 && viewBox.height > 0) {
return { height: Math.ceil(viewBox.height), width: Math.ceil(viewBox.width) };
}
const rect = svg?.getBoundingClientRect();
return {
height: Math.ceil(rect?.height ?? host.scrollHeight),
width: Math.ceil(rect?.width ?? host.scrollWidth),
};
}
async function render(message: MermaidRuntimeRenderMessage): Promise<void> {
try {
initializeMermaid(message.colorScheme);
@@ -72,14 +107,18 @@ async function render(message: MermaidRuntimeRenderMessage): Promise<void> {
return;
}
host.innerHTML = svg;
const rect = host.querySelector("svg")?.getBoundingClientRect();
const element = host.querySelector("svg");
if (element) {
stretchToFrame(element);
}
const size = measureDiagram(host, element);
sendToHost({
type: "rendered",
revision: message.revision,
source: message.source,
colorScheme: message.colorScheme,
height: Math.ceil(rect?.height ?? host.scrollHeight),
width: Math.ceil(rect?.width ?? host.scrollWidth),
height: size.height,
width: size.width,
});
} catch {
if (message.revision === latestRevision) {
File diff suppressed because one or more lines are too long

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