Compare commits

..
Author SHA1 Message Date
paseo-ai[bot] c539fc1dc6 fix: update lockfile signatures and Nix hash [skip ci] 2026-11-27 18:48:51 +00:00
Mohamed Boudra 1c053e207e feat(desktop): new butterfly app icons on desktop and mobile (#11091)
* feat(desktop): draw the app icons from the new butterfly mark

The desktop and mobile icons still carried the old butterfly, and each
was a hand-exported file. They now come from one script that renders
them from the canonical mark in assets/brand, so a change to the mark
reaches every icon.

The icons are flat. Each platform masks and lights its own icons, and
artwork that arrives already lit ends up lit twice. The lit versions
are kept in assets/brand/app-icons and nothing uses them.

The packaged Mac app now takes its icon from an Icon Composer document
instead of the .icns, so macOS draws the tile, the margin, the lighting
and the dark, tinted and clear variants itself. electron-builder
compiles the document with actool, which needs Xcode 26 or later. The
Nix build has no Xcode and keeps the .icns, and so does the DMG volume
icon, because the .icns actool derives stops at 256 px.

macOS draws a dev build's Dock icon and an .icns exactly as supplied.
Their tile is now 824 of 1024 px with continuous corners, measured from
the icon macOS 27 draws for the document. The old production tile was
88% of the canvas and looked oversized next to other Dock icons.

* test(desktop): put the tunnel heartbeat test on a fake clock

The test ran a 25 ms heartbeat against a 65 ms timeout on the real
clock. A heartbeat tick closes the wire instead of pinging once the
timeout has passed, so when the first tick landed late on a slow
Windows runner the wire closed with no ping sent, and the assertion
that a ping went out failed.

With a fake clock the ticks land at 25, 50 and 75 ms every time: two
pings, then the heartbeat close.
2026-11-28 01:38:26 +07:00
Mohamed Boudra 14734843fd chore(release): reconcile v0.18.1 (#11102) 2026-11-28 01:32:34 +07:00
10a71e6904 Keep a streamed reply whole when a steering message arrives mid-stream (#5267)
* fix(server): keep a streamed assistant message whole across a steer

Steering an agent mid-stream records the user message at the next
timeline seq, between two chunks of the assistant message that is still
streaming. The projection merged assistant chunks only when they were
adjacent, so the interposed user row split one provider message into two
timeline rows at whatever character had arrived, often mid-word.

An assistant message that carries a provider message id now has a
timeline identity, like a tool call does, so its chunks collapse into one
item wherever they land. Chunks without a message id keep the existing
adjacency merge.

* test(server): synchronize the steer regression test on timeline state

Replace the fixed sleeps with polling assertions, and run the coalescer
with a zero window so every chunk flushes on its leading edge.

* fix(server): merge a steered message only across user rows

The identity merge joined every chunk of one provider message into its
first row, whatever rows were recorded between them. Text a provider
wrote after a tool call moved above the tool call, and seeded rows lost
the turn stats on the merged reply.

A chunk now continues the assistant message right before it, or, when
it carries a provider message id, the assistant row before a run of
user rows recorded mid-stream. Any other row in between keeps the
provider's order. The merge carries the stats from the later chunk.

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

* fix(app): keep streamed replies whole across steering messages

---------

Co-authored-by: paseo-bot <paseo-bot@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 17:42:54 +00:00
Mohamed Boudra 4810eb2d74 fix(app): keep Command Center result order stable while typing (#11085)
Command Center scored contributions and workspaces with right-edge text-match tiers (TIER_EXACT and TIER_WHOLE_WORD), so rows flipped mid-word whenever a shorter word or title finished on the latest keystroke (for example, typing renam then e flipped Rename workspace and Rename, and typing to jumped Pin to top above Toggle Explorer sidebar). Because CommandCenterInteraction resets active selection to index 0 on every keystroke, Enter executed the wrong action.

Score Command Center matches by left-edge rank only (field start, word start, inside word, scattered) and rank workspaces within the same MatchClass by recency directly instead of raw sub-tiers. Also label the active tab rename action with the existing Rename agent / Rename terminal keys instead of bare Rename.
2026-11-27 23:29:24 +07:00
paseo-bot[bot]andClaude Opus 5.5 79a32f40c6 fix(pi): queue a prompt while Pi runs a turn it started itself (#11077)
Pi starts runs on its own, for example for an extension message or a
background result, and reports them only at agent_start. A prompt sent
in that window had no streamingBehavior, so Pi rejected it with
"Agent is already processing" and the message was lost.

Send prompts with streamingBehavior followUp. Pi queues the prompt into
its running turn, and ignores the option when it is idle.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:14:07 +00:00
a997246655 fix(opencode): clear v2 approvals that OpenCode dropped (#11061)
OpenCode v2 removes a pending approval without a `permission.replied`
event when the tool call that asked is interrupted, and answers a later
reply to it with HTTP 404. Paseo kept its copy, so the card stayed and
every answer failed. A message sent while the card was open failed the
same way, because clearing the card threw the 404.

Reconciling a session now drops approvals OpenCode no longer lists, and
a 404 reply resolves the approval instead of failing.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: rhettjay <67493409+rhettjay@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 16:00:29 +00:00
Mohamed Boudra 3b8fd4ab3d fix(gitlab): load fork MR pipeline jobs from the pipeline project (#11074)
glab ci get --merge-request fetches the MR from the target repository, reads
head_pipeline.id, and then requests that pipeline from the target repository
instead of head_pipeline.project_id. For fork merge requests whose pipeline runs
in the fork project, GitLab returns 404 Not Found on every PR status poll and
PR-pane pipeline drill-down.

Query the GitLab REST API directly via glab api using head_pipeline.project_id
(falling back to target_project_id, the MR project path, or :fullpath) for both
fetchPipelineChecks and getCheckDetails, matching how gitlab-change-requests.ts
already resolves fork pipelines.
2026-11-27 22:46:07 +07:00
paseo-bot[bot]andClaude Opus 5.5 9416336d73 Reopen an ACP agent whose process exited while it was idle (#11047)
* Reopen an ACP agent whose process exited while it was idle

When a generic ACP agent's process exits between turns, for example after
an external kill -9, every later message failed with "ACP agent
disconnected" until someone reloaded the agent by hand.

startTurn now reports a dead connection as a stale provider session when
the provider can reopen sessions (session/load or session resume). The
prompt path already reloads a stale session from persistence on a new
process and retries the message, as it does for plugin sessions. A
provider that cannot reopen a session keeps the current error, because a
reload would close the agent without a way back.

The exit handler also logs an unexpected exit, with the pid, the exit
code or signal, and whether a turn was running. Before, an exit while
idle left no line in the daemon log.

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

* Wait for the daemon to see the ACP exit in the recovery test

On Windows the test saw the killed process gone before the daemon read
the closed pipes, so the next message started a turn on the dead
connection. The test now waits for the daemon's exit warning, and checks
the disconnect text without the signal, which Windows reports as an exit
code.

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

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:52:24 +00:00
Matt CowgerandMatt Cowger 5715467245 fix(omp): preserve tool call intent in metadata (#10727)
Carry OMP tool-call `intent` strings in `ToolCallBase.metadata.intent` across live updates (`running`, `completed`, `failed`, `canceled`) and replayed session history, reusing the existing tool-call `metadata` path through the daemon, app stream, replica cache, and client timeline plugins without changing the shared protocol.

Replay reads only string `content.intent` values (ignoring non-string values and never deriving intent from a tool argument named `i`). Updates `docs/plugins.md` and `public-docs/plugins/reference.md`, and retries Windows temp-dir cleanup in `forge-cli-command.test.ts`.

Fixes #10730

Co-authored-by: Matt Cowger <matt@cowger.us>
2026-11-27 21:41:16 +07:00
paseo-bot[bot]andClaude Opus 5.5 8e8b383f4c Let idle cleanup unload an OpenCode chat while another session runs (#11039)
The v2 runtime safety check vetoed collection whenever any session on
the server was active. The shared server stays up after its last lease
goes, so that veto kept every idle chat resident while one unrelated
session worked. Another session's execution now vetoes only when
releasing the lease would stop the server; the chat's own session and
its descendants still veto as before.

Fixes #10305

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:23:13 +00:00
Mohamed Boudra 1fd744795d Add host-wide instructions for metadata generation (#11064)
* feat(settings): add host-wide instructions for metadata generation

Add a single host-level agents.metadataGeneration.instructions field instead of a language-only switch or per-artifact host overrides. It applies across workspace titles, worktree branch names, commit messages, and pull request drafts alongside Paseo's default styles, while letting per-project paseo.json overrides take precedence on conflict.

Gate the UI field on server_info.features.metadataGenerationInstructions so older daemons that drop the field on patch do not show a no-op editor, and split MutableMetadataGenerationConfigPatchSchema without a default providers array so patching instructions never wipes configured providers.

* fix(server): read host metadata instructions through structured-generation config helper
2026-11-27 20:51:24 +07:00
paseo-bot[bot]andClaude Opus 5.5 bec63111f1 test(cli): let lifecycle test daemons bind their own ports (#11054)
The lifecycle tests reserved a free port, released it, and later started
a daemon on it. Another process could bind the port in between, and the
daemon then exited with EADDRINUSE. That failed "raw log following" on
main. Tests that need no fixed port now configure 127.0.0.1:0, so the
daemon allocates the port itself and publishes it.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 12:31:09 +00:00
Mohamed Boudra dbba977ab8 fix(app): eliminate first-open jank in starting ref popover (#11042)
Opening the Starting ref popover in New Workspace for the first time jumped in two steps: the query was disabled until open, buildPickerOptionData rendered a lone [main] row in a 132px frame, and when branch suggestions arrived the popover grew to 400px while pushing main down below newer branches.

Lock the desktop popover height to 400px (and clamp fixed minHeight to availableHeight in buildDesktopFrameStyle so short viewports do not overflow), warm default branch suggestions and forge wording while the trigger is visible on the focused screen, retain same-project results while filtering, and show the searching state instead of a premature single-row placeholder on cold opens.
2026-11-27 19:22:41 +07:00
Mohamed Boudra 29179ba27f fix(server): clear finished terminals when marking a workspace read (#11040)
A terminal that goes from working to idle records finished attention, and the
workspace status rolls it up as attention. The workspace clear-attention
handler only cleared agents, so a workspace kept green by a terminal stayed
green after Mark as read, with no agent inside showing why.

Terminals are matched by the workspace they belong to, not by cwd: a terminal
can run in a different directory than its workspace. Needs-input attention is
left alone, matching how agent permission prompts are handled.
2026-11-27 19:18:37 +07:00
Mohamed Boudra dcdd327cdf fix(app): show composer autocomplete after closing overlays and hide it while submitting (#11041)
* fix(app): restore composer autocomplete after closing web overlays

Closing a web overlay such as the New Workspace branch picker runs useOverlayRegistration's teardown inside a useLayoutEffect cleanup. React 19 runs layout effect cleanups during the mutation commit phase while its DOM event system is disabled, so calling target.focus() synchronously drops focusin. React's SelectEventPlugin then keeps activeElement unset and skips onSelect/onSelectionChange, leaving the composer cursor stuck at 0 so slash and @ autocomplete never open until another event refocuses the textarea.

Defer focus restoration in addWebOverlay via queueMicrotask so focus runs after React finishes its mutation commit, guarded so a newer overlay opened in the same commit is not stolen from. Also hide ComposerAutocompleteBinding while isComposerLocked is true so autocomplete cannot appear over a submitting composer.

* fix(app): preserve focus claimed during overlay close and guard missing DOM

Skip deferred overlay focus restoration when the closing commit moves focus to a new element (such as an autofocused inline input mounted by a menu action like file explorer Rename, New file, or New folder). Also guard typeof document and typeof HTMLElement in the deferred focus-restore helpers so Node unit tests that tear down DOM stubs before microtasks run do not throw.

* fix(app): restore overlay focus during layout phase before passive effects

Deferring focus restoration to a microtask when active flipped true -> false ran after passive useEffect hooks updated, which let HoverCard's focusin listener re-enable and reopen the workspace hover card when closing a sidebar context menu.

Split registration/deactivation from unmount cleanup in useOverlayRegistration so active: true -> false restores focus synchronously inside the layout effect (after React re-enables DOM events and before passive effects run), reserving queueMicrotask for unmount-while-active where no layout setup runs. Also detach the overlay entry before clearing scopeRef so the departing scope is preserved.
2026-11-27 19:18:24 +07:00
Mohamed Boudra 91613f516d Preserve in-flight iOS App Store reviews and add EAS review queue controls (#11044)
* feat(release): preserve in-flight iOS reviews and add EAS review queue controls

Release builds previously passed reject_if_possible: true to fastlane deliver, which cancelled any in-flight Apple review whenever a quick desktop or daemon patch shipped.

submit_review now checks App Store Connect for active in-flight iOS versions and ReviewSubmissions before submitting. When a review is already in flight and REPLACE_IN_REVIEW is not true, it leaves the active review untouched, logs a machine-scannable IOS_REVIEW_SKIPPED line naming both versions, and exits 0 so Release Mobile stays green while still uploading the new binary to TestFlight.

When replace_in_review=true is explicitly requested, submit_review validates the replacement TestFlight build first and cancels the active ReviewSubmission before calling deliver, avoiding fastlane 2.241.1's verify_version-before-reject_version_if_possible ordering race. Added on-demand EAS workflows and Fastlane lanes to inspect live App Store Connect review status and cancel an in-flight review with an expected_version safety guard.

* fix(release): clear stale UNRESOLVED_ISSUES submissions and re-check review queue after build wait

When Apple rejects an earlier version, fastlane 2.241.1's Deliver::SubmitForReview#create_review_submission fails if the prior ReviewSubmission stays in UNRESOLVED_ISSUES.

Instead of passing reject_if_possible: true on the default path (which could cancel a newly-submitted WAITING_FOR_REVIEW/IN_REVIEW review that arrived during build processing), submit_review now re-checks find_blocking_review after TestFlight processing completes and clears only UNRESOLVED_ISSUES submissions before invoking deliver with reject_if_possible: false.
2026-11-27 18:40:23 +07:00
31aa498a5b fix(app): clear the iOS status bar on wide browser layouts, including the Mermaid viewer (#9970)
* fix(app): clear the iOS status bar on wide browser layouts

In an iOS Home Screen web app at a wide (non-compact) layout there is no
compact header to absorb the top safe-area inset, so the top rows sat
under the status bar and could not be tapped (#9524). The window surface
now consumes the top inset on the web when the layout is not compact;
native window chrome keeps its own top band.

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

* fix(app): keep the Mermaid fullscreen controls below the status bar

The fullscreen Mermaid viewer is a Modal that covers the whole window,
but it padded its content with the insets of the chat message that
opened it. On wide web layouts the layout surface now spends the top
inset itself and hands its children top 0, so the viewer's zoom and
close buttons moved under the iOS status bar.

Wrap the viewer in WindowSafeArea, as the attachment lightbox does, so
it reads the window's insets.

Co-authored-by: Matt Abar <mattaabar@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): keep the overlay left sidebar below the status bar on wide browser layouts

The wide layout surface now pads the status bar itself and hands its
content a top inset of 0. The overlay sidebar is absolutely positioned
against the surface, over that padding, so it starts at the window's top
edge and needs the window's top inset. The docked sidebar keeps reading
the inset the surface leaves its content.

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

* fix(app): keep the autocomplete popover below the status bar from a wide layout surface

The popover clamped its height with the composer's top inset, which a wide
browser layout surface now sets to 0. The root portal host the popover can
render into sits outside that surface, against the window's top edge, so
the popover's top went under the status bar. The frame now reads the inset
where it renders, inside the portal host: the root host gets the window's
inset, and the workspace host, inside the surface, keeps 0.

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

* docs: state that the wide web layout surface owns the top inset

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

---------

Co-authored-by: Matt Abar <mattaabar@gmail.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 11:25:08 +00:00
paseo-bot[bot]andAndrii Panasiuk 8037d79330 Deliver Android agent notifications promptly during Doze (#8501)
* fix(server): send push notifications at high priority so Android delivers them on time

* test(push): cover urgent notifications without global stubs

Keep the push transport explicit so the priority regression exercises every batch without replacing global fetch. Production callers retain the native transport by default.

Co-authored-by: Andrii Panasiuk <andrew.panassiouk@gmail.com>

* refactor(push): name notification sender dependencies

Use an options object for the logger, token revocation callback, and HTTP transport while retaining native fetch by default.

---------

Co-authored-by: Andrii Panasiuk <andrew.panassiouk@gmail.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 10:59:07 +00:00
Mohamed Boudra 8c002cc750 Parallelize post-approval release shipping (#11033)
* docs(release): parallelize post-approval release shipping

Every tag-triggered GitHub Actions workflow and EAS workflow builds from the checked-out tag commit with local workspace packages, so tag builds do not depend on public npm publication. Update release:ship and release:ship:beta to push the tag before publishing npm, and document the parallel ship fan-out and sync gates in docs/release.md.

* docs(release): document npm publish recovery after tag push
2026-11-27 17:41:46 +07:00
237cfe91f1 Show enterprise spending usage for Claude and Codex (#8976)
* fix(usage): report enterprise spending limits

* fix(usage): complete enterprise spending percentages

Derive missing remaining percentages so CLI spending output matches the Usage card. Preserve explicitly reported percentages and cover missing currency and absent rolling windows.

Co-authored-by: Matt Cowger <matt@cowger.us>
Co-authored-by: JasprW <wang@jaspr.me>

---------

Co-authored-by: Matt Cowger <matt@cowger.us>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: JasprW <wang@jaspr.me>
2026-11-27 10:22:03 +00:00
paseo-ai[bot] d4fd6dcafd fix: update lockfile signatures and Nix hash [skip ci] 2026-11-27 10:13:16 +00:00
Mohamed Boudra 518e58cd63 chore(release): reconcile v0.18.0 (#11030) 2026-11-27 17:04:04 +07:00
paseo-bot[bot]andbenthecarman 82dcf7821e fix(usage): load Kimi usage for global logins (#8505)
* Find Kimi usage for logins to kimi.ai

The Kimi CLI keeps one credential slot per deployment. A login to the
global (kimi.ai) deployment writes its token to
credentials/kimi-code-env-<hash>.json and talks to api.kimi.ai, but the
usage source only read credentials/kimi-code.json and only called
api.kimi.com. Users signed in through kimi.ai saw no Kimi usage, or a
"Login expired. Sign in again." message when an old kimi-code.json from
an earlier login was still on disk.

Discovery now checks the slots of both official deployments and picks
the one with the latest expiry, which is the slot the CLI keeps
refreshing. The usage request goes to the API of that deployment.

Kimi access tokens last 15 minutes, so a CLI token is often expired
while the user is still signed in. Report those with refreshedBy so the
Usage page says to run kimi instead of asking for a new sign-in.

* fix(usage): preserve the selected Kimi credential home

Compare deployment credentials within each home so a newer legacy-home
login cannot override KIMI_CODE_HOME. Cover the expired-default plus live
global workflow through discovery and usage fetching.

Co-authored-by: benthecarman <benthecarman@live.com>

---------

Co-authored-by: benthecarman <benthecarman@live.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 09:50:43 +00:00
Mohamed Boudra 5d003d9613 test(cli): report version from fake ACP provider helper (#11032)
antigravity-provider status() now runs --version and requires >= 1.5.1 (#10992). Without a --version handler, supervisor-acp.cjs exited with empty stdout on the version probe and broke 23-daemon-sigint-supervisor.test.ts at createAgent().
2026-11-27 16:36:42 +07:00
paseo-bot[bot]andpeanut_hzm 9868ebc11c fix(usage): discover the GLM Agent login for its Usage card (#8376)
* fix(usage): follow the CLIs' current auth locations for MiniMax and Z.ai

The usage sources look for credentials where the CLIs used to keep them, so
their plan quota never appears in Settings → Usage.

MiniMax Code (`mcode`) moved its OAuth login to
`~/.minimax/auth/<buildEnv>/<region>/<clientId>/auth.json`, with the token
inside a `records` map and the region in a sibling `auth-state.json`. The
source still looked in `~/.mmx/` for the older `access_token` shape. It also
called `/v1/token_plan/remains`, which the agent backend answers with
`status_code 1004` ("Please carry the API secret key in the 'Authorization'
field"); the coding-plan endpoint the CLI itself uses is
`/v1/api/openplatform/coding_plan/remains`.

Z.ai's `glm-acp-agent` reads `Z_AI_API_KEY` and persists it to
`~/.config/glm-acp-agent/credentials.json` as `z_ai_api_key`. The source
looked for `ZAI_API_KEY` and `GLM_API_KEY` only, and never read the
credentials file.

Both keep their existing lookups working, so a configured environment
variable or the older `~/.mmx/` layout still resolves.

* fix(usage): narrow credential discovery repair to the verified GLM path

Keep the independently reproduced GLM discovery fix and isolate its file test from inherited XDG_CONFIG_HOME. Leave MiniMax quota routing for separate verification before changing existing API-key requests.

Co-authored-by: peanut_hzm <peanut_hzm@163.com>

* test(usage): isolate the legacy login locator from inherited credentials

---------

Co-authored-by: peanut_hzm <peanut_hzm@163.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 09:21:16 +00:00
965e28e3d6 feat(highlight): add diff/patch and zero-dependency legacy-mode syntax highlighting (#11026)
* feat(highlight): highlight diff and patch fences and files

Register CodeMirror's legacy diff mode for .diff and .patch files and diff/patch code fences, mapping inserted/deleted tokens to diffAddition/diffDeletion roles and stripping legacy trailing-whitespace error prefixes so CodeMirror emits no unknown-tag warnings.

Co-authored-by: Hyacinthe Malaspina <malaspina.hyacinthe@gmail.com>

* feat(highlight): add Ruby syntax highlighting

Register @codemirror/legacy-modes ruby via StreamLanguage for rb, rbw, rake,
gemspec, ru, jbuilder, podspec and thor, plus extensionless Ruby files
(Gemfile, Rakefile, Guardfile, Capfile, Podfile, Vagrantfile, ...).

* feat(highlight): add Kotlin syntax highlighting for .kt/.kts files

Kotlin files previously rendered as plain text in diffs, the read-only
source panel, and the editor because the extension map in
@getpaseo/highlight had no entry for kt/kts. Register the kotlin stream
parser from @codemirror/legacy-modes/mode/clike, the same package already
used for Swift and Dart.

* test(highlight): assert Kotlin token styles in highlightCode

Follow-up to review feedback: the parsers tests only checked that
kt/kts are registered. Add a Kotlin case to the highlightCode suite,
mirroring the Swift and Dart cases, asserting keyword ('class', 'val'),
type ('String'), and string token styles. Fails on main without the
parser registration, passes with it.

* feat(highlight): add TOML syntax highlighting

* feat(highlight): add remaining legacy-mode languages and fence aliases

Register SQL, Lua, Protobuf, PowerShell, Groovy/Gradle, Scala, CMake (including CMakeLists.txt), Properties/INI, R, Perl, and LaTeX/TeX from @codemirror/legacy-modes, and add fence alias parity (including shell, ruby, kotlin, powershell/pwsh, protobuf, perl, and latex) in HighlightedCodeBlock.

Co-authored-by: Maxime Conan <maximeconan@MacBook-Pro-de-Maxime.local>

* fix(highlight): unify diff token colors and support binary diff frames

Append diffAddition and diffDeletion to DIFF_HIGHLIGHT_STYLES so Changes panel binary diff frames preserve diff colors for .diff/.patch files while older clients safely decode unknown indices as null. Unify syntaxTokenStyles onto theme.colors.syntax and tune light syntax theme diff colors to >=4.0:1 contrast on code surfaces.

---------

Co-authored-by: Hyacinthe Malaspina <malaspina.hyacinthe@gmail.com>
Co-authored-by: Karol Bąk <kukicola@gmail.com>
Co-authored-by: Anton Prokhorov <anton.prokhorov@jetbrains.com>
Co-authored-by: chandlerok <chandleroking@gmail.com>
Co-authored-by: Maxime Conan <maximeconan@MacBook-Pro-de-Maxime.local>
2026-11-27 15:31:57 +07:00
Mohamed Boudra 690f6970c3 fix(app): focus composer when dropping attachments (#11022)
Workspace file drops already called focusInput(), but raster image drops went directly to addImages() and generic file drops only uploaded without focusing. Focus the composer when dropped images attach and as soon as dropped files are accepted for upload, so users can type right away without waiting for uploads to finish.
2026-11-27 14:33:30 +07:00
paseo-bot[bot] bcb0097344 test(terminal): accept socket-overflow output that arrives after the replay (#11016)
The PTY child finishing its write does not mean the worker has parsed those
bytes. On Windows, ConPTY renders before the worker reads, so the reconnect
snapshot can be cut before the last marker; that marker then reaches the
viewer as live output. Wait for it across the replay and the live output
that follows the replay end.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 06:59:00 +00:00
Mohamed Boudra 9eab3b278f Stop client plugins from crashing iOS when importing react-native (#11011)
* fix(plugins): prevent iOS PushNotificationIOS crash when plugins import react-native

Filter unsupported throwing getters (PushNotificationIOS, AsyncStorage, ImagePickerIOS, ProgressViewIOS, DatePickerIOS, Slider) and raw default from the react-native runtime exposed to client plugins, while preserving lazy property descriptors on safe exports.

Also replace eager Hermes CommonJS interop evaluation (value: from[key]) with per-key lazy getter closures (get: ((k) => () => from[k])(key)) in the server plugin compiler so namespace imports no longer evaluate unrelated host module getters.

Closes #10978

* fix(plugins): allowlist safe react-native exports for client plugins

Replace the react-native denylist in evaluate.ts with an explicit allowlist of cross-platform UI, layout, and animation exports (PLUGIN_REACT_NATIVE_EXPORTS) while preserving lazy property descriptors.

Add a wiring test verifying require('react-native') returns the allowlisted runtime object rather than the raw ReactNative namespace, plus a contract test verifying every allowlisted key exists as a non-deprecated, non-throwing getter in react-native/index.js.

* fix(plugins): retain SafeAreaView and InteractionManager in react-native allowlist

Keep SafeAreaView and InteractionManager in PLUGIN_REACT_NATIVE_EXPORTS so existing published plugins that import them from react-native (e.g. SafeAreaView insets and InteractionManager.runAfterInteractions) keep working on iOS, Android, and web. Both exports are safe cross-platform getters on iOS and react-native-web and remain lazy under the compiler's per-key getter interop.

Also harden the react-native/index.js getter contract test to assert the parser matched getters and that PushNotificationIOS stays excluded.

* fix(plugins): omit only PushNotificationIOS and default from plugin react-native runtime

Replace the 46-key react-native allowlist with copying all own enumerable descriptors from Object.keys(source) lazily while skipping only PushNotificationIOS and default. An audit of published plugins showed 14 plugins rely on react-native exports outside the allowlist (TurboModuleRegistry, NativeModules, UIManager, DeviceEventEmitter, AppRegistry, Clipboard, Settings, and RN-web render).

Keep the lazy per-key Hermes interop fix in compiler-build.ts, the require('react-native') wiring test, and the react-native/index.js enumerable getter contract test.
2026-11-27 13:49:51 +07:00
Mohamed Boudra fcfcdf156a Make ACP catalog probing respectful and clean up Antigravity ACP hygiene (#10992)
* feat(acp): make ACP catalog probing respectful and clean up Antigravity ACP hygiene

* fix(acp): address Windows CI failures and paseo-bot review findings

* refactor(acp): remove manual catalog mode and use on_demand for Antigravity

* fix(server): share Windows WinGet candidate resolution when findExecutable skips probing

* test(server): compare Windows PATHEXT casing case-insensitively in executable-resolution test
2026-11-27 13:29:55 +07:00
391 changed files with 13470 additions and 23134 deletions
+1
View File
@@ -15,6 +15,7 @@
"*.lock",
"**/*.gen.ts",
"**/*.gen.tsx",
"**/*.icon/**",
"packages/react-native-enriched-markdown/**"
]
}
+44
View File
@@ -1,5 +1,49 @@
# Changelog
## 0.18.1 - 2026-11-27
- **Host metadata instructions:** Set host-wide instructions once to guide language, tone, and formatting for generated workspace titles, branch names, commit messages, and pull requests. ([#11064](https://github.com/getpaseo/paseo/pull/11064))
- **Enterprise spending usage:** Usage now shows Claude extra-usage spending and Codex individual spending limits with reset times. ([#8976](https://github.com/getpaseo/paseo/pull/8976) by [@mcowger](https://github.com/mcowger), [@JasprW](https://github.com/JasprW))
### Fixed
- Fixed Android agent push notifications arriving minutes late during Doze ([#8501](https://github.com/getpaseo/paseo/pull/8501) by [@truelecter](https://github.com/truelecter))
- Fixed Command Center results reordering mid-word while typing ([#11085](https://github.com/getpaseo/paseo/pull/11085))
- Fixed composer slash and `@` autocomplete stopping after closing a web overlay or opening while a prompt submits ([#11041](https://github.com/getpaseo/paseo/pull/11041))
- Fixed the Starting ref popover in New Workspace jumping in height and shifting rows on first open ([#11042](https://github.com/getpaseo/paseo/pull/11042))
- Fixed the iOS Home Screen web app status bar overlapping focus-mode tabs, the overlay sidebar, and the Mermaid fullscreen viewer on wide layouts ([#9970](https://github.com/getpaseo/paseo/pull/9970) by [@mywaffles](https://github.com/mywaffles))
- Fixed Mark as read on a workspace not clearing finished terminal attention ([#11040](https://github.com/getpaseo/paseo/pull/11040))
- Fixed GitLab merge request checks and pipeline details failing with 404 when the pipeline runs in a fork project ([#11074](https://github.com/getpaseo/paseo/pull/11074))
- Fixed messages sent while Pi runs a turn it started itself failing instead of queuing ([#11077](https://github.com/getpaseo/paseo/pull/11077))
- Fixed OpenCode v2 tool approvals staying stuck after OpenCode already dropped the request ([#11061](https://github.com/getpaseo/paseo/pull/11061) by [@rhettjay](https://github.com/rhettjay))
- Fixed idle cleanup keeping OpenCode v2 chats in memory while another session runs on the shared server ([#11039](https://github.com/getpaseo/paseo/pull/11039))
- Fixed idle ACP agents failing permanently after their process exits instead of reopening on the next message ([#11047](https://github.com/getpaseo/paseo/pull/11047))
- Fixed Kimi usage failing or showing an expired login for global `kimi.ai` accounts ([#8505](https://github.com/getpaseo/paseo/pull/8505) by [@benthecarman](https://github.com/benthecarman))
- Fixed the Z.ai Usage card missing when GLM Agent is signed in via `Z_AI_API_KEY` or its credentials file ([#8376](https://github.com/getpaseo/paseo/pull/8376) by [@Peanut-HZM](https://github.com/Peanut-HZM))
### Plugins
- Added OMP tool-call intent to `item.metadata.intent` for timeline plugins ([#10727](https://github.com/getpaseo/paseo/pull/10727) by [@mcowger](https://github.com/mcowger))
## 0.18.0 - 2026-11-27
- **Remote workspace browser proxy:** Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote `localhost` servers open directly in Paseo. ([#10944](https://github.com/getpaseo/paseo/pull/10944) by [@airon-assustadus](https://github.com/airon-assustadus))
- **Per-device notification preferences:** Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps. ([#10888](https://github.com/getpaseo/paseo/pull/10888))
- **Agent profile system prompts:** Save an optional system prompt on an agent profile to apply it to new agents started from that profile. ([#10996](https://github.com/getpaseo/paseo/pull/10996))
- **More syntax highlighting:** Syntax highlighting now covers diff and patch files along with Ruby, Kotlin, TOML, SQL, Lua, Protobuf, PowerShell, Groovy, Gradle, Scala, CMake, Properties, INI, R, Perl, and LaTeX. ([#11026](https://github.com/getpaseo/paseo/pull/11026) by [@hmalaspina](https://github.com/hmalaspina), [@kukicola](https://github.com/kukicola), [@MaximeConan](https://github.com/MaximeConan), [@singleton11](https://github.com/singleton11), [@chandlerok](https://github.com/chandlerok))
### Changed
- Changed ACP providers to cache model catalogs across daemon restarts instead of probing in the background, and cleaned up Antigravity ACP flags and metadata. Requires [Antigravity CLI 1.5.1 or later](https://paseo.sh/docs/supported-providers/antigravity) ([#10992](https://github.com/getpaseo/paseo/pull/10992))
### Fixed
- Fixed Paseo iOS crashing shortly after connecting when an enabled client plugin imports `react-native` ([#11011](https://github.com/getpaseo/paseo/pull/11011))
- Fixed OpenCode v2 agents staying stuck in running after Stop when stream events were missed or chat history was large ([#10955](https://github.com/getpaseo/paseo/pull/10955))
- Fixed steering a Pi agent during a run it started on its own aborting the run instead of steering it ([#10977](https://github.com/getpaseo/paseo/pull/10977) by [@viiqswim](https://github.com/viiqswim))
- Fixed creating a workspace from a pull request in a fork clone checking out the fork's pull request with the same number ([#10987](https://github.com/getpaseo/paseo/pull/10987))
- Fixed dropping images or files onto the composer leaving the input unfocused ([#11022](https://github.com/getpaseo/paseo/pull/11022))
## 0.17.6 - 2026-11-27
### Improved
+44
View File
@@ -1,5 +1,49 @@
# Changelog
## 0.18.1 - 2026-11-27
- **主机元数据指令**:设置一次主机级指令,即可统一控制自动生成的工作区标题、分支名、提交信息和 PR 的语言、语气与格式。([#11064](https://github.com/getpaseo/paseo/pull/11064))
- **企业消费用量**:使用情况现已显示 Claude 额外消费用量以及 Codex 个人消费限额和重置时间。([#8976](https://github.com/getpaseo/paseo/pull/8976),贡献者:[@mcowger](https://github.com/mcowger), [@JasprW](https://github.com/JasprW))
### 修复
- 修复 Android 在 Doze 休眠模式下 Agent 推送通知延迟数分钟送达的问题 ([#8501](https://github.com/getpaseo/paseo/pull/8501),贡献者:[@truelecter](https://github.com/truelecter))
- 修复在命令中心输入时结果顺序在单词输入中途跳动的问题 ([#11085](https://github.com/getpaseo/paseo/pull/11085))
- 修复关闭网页浮层后 Composer 的斜杠与 `@` 自动补全失效,以及提交提示词时自动补全弹出的问题 ([#11041](https://github.com/getpaseo/paseo/pull/11041))
- 修复在“新建工作区”中首次打开“起始 ref”浮层时高度跳动和行位偏移的问题 ([#11042](https://github.com/getpaseo/paseo/pull/11042))
- 修复宽屏布局下 iOS 主屏幕网页应用的状态栏遮挡专注模式标签栏、覆盖侧边栏和 Mermaid 全屏查看器的问题 ([#9970](https://github.com/getpaseo/paseo/pull/9970),贡献者:[@mywaffles](https://github.com/mywaffles))
- 修复将工作区标记为已读时未清除已完成终端提醒的问题 ([#11040](https://github.com/getpaseo/paseo/pull/11040))
- 修复 GitLab 合并请求的流水线运行在 fork 项目中时,检查状态和流水线详情返回 404 的问题 ([#11074](https://github.com/getpaseo/paseo/pull/11074))
- 修复 Pi 运行其自行启动的轮次时发送的消息直接失败而不是排队的问题 ([#11077](https://github.com/getpaseo/paseo/pull/11077))
- 修复 OpenCode v2 已丢弃工具审批请求后,审批卡片仍一直卡住的问题 ([#11061](https://github.com/getpaseo/paseo/pull/11061),贡献者:[@rhettjay](https://github.com/rhettjay))
- 修复共享服务器上运行其他会话时,空闲清理不会卸载闲置 OpenCode v2 对话的问题 ([#11039](https://github.com/getpaseo/paseo/pull/11039))
- 修复空闲 ACP Agent 的进程意外退出后永久失败,而不是在下一条消息时重新打开会话的问题 ([#11047](https://github.com/getpaseo/paseo/pull/11047))
- 修复使用全局 `kimi.ai` 账号登录时 Kimi 用量加载失败或显示登录已过期的问题 ([#8505](https://github.com/getpaseo/paseo/pull/8505),贡献者:[@benthecarman](https://github.com/benthecarman))
- 修复通过 `Z_AI_API_KEY` 或凭据文件登录 GLM Agent 时缺少 Z.ai 使用情况卡片的问题 ([#8376](https://github.com/getpaseo/paseo/pull/8376),贡献者:[@Peanut-HZM](https://github.com/Peanut-HZM))
### 插件
- 为时间线插件在 `item.metadata.intent` 中新增 OMP 工具调用意图 ([#10727](https://github.com/getpaseo/paseo/pull/10727),贡献者:[@mcowger](https://github.com/mcowger))
## 0.18.0 - 2026-11-27
- **远程工作区浏览器代理**:远程工作区中的桌面端浏览器标签页现在会通过该工作区的 daemon 转发流量,远程 `localhost` 服务可以直接在 Paseo 中打开。([#10944](https://github.com/getpaseo/paseo/pull/10944),贡献者:[@airon-assustadus](https://github.com/airon-assustadus))
- **按设备配置通知偏好**:每台设备都可以分别选择哪些 Agent、终端和插件事件发送通知,插件现在也可以发送通知并处理点击。([#10888](https://github.com/getpaseo/paseo/pull/10888))
- **智能体配置文件系统提示词**:在智能体配置文件中保存可选的系统提示词,以便在通过该配置启动新 Agent 时应用。([#10996](https://github.com/getpaseo/paseo/pull/10996))
- **更多语法高亮语言**:语法高亮现已支持 diff 和 patch 文件,以及 Ruby、Kotlin、TOML、SQL、Lua、Protobuf、PowerShell、Groovy、Gradle、Scala、CMake、Properties、INI、R、Perl 和 LaTeX。([#11026](https://github.com/getpaseo/paseo/pull/11026),贡献者:[@hmalaspina](https://github.com/hmalaspina), [@kukicola](https://github.com/kukicola), [@MaximeConan](https://github.com/MaximeConan), [@singleton11](https://github.com/singleton11), [@chandlerok](https://github.com/chandlerok))
### 变更
- ACP Provider 现在会在 daemon 重启间将已发现的模型目录缓存到磁盘,不再在后台轮询,同时清理了多余的 Antigravity ACP 参数和元数据。需要 [Antigravity CLI 1.5.1 或更高版本](https://paseo.sh/zh-CN/docs/supported-providers/antigravity) ([#10992](https://github.com/getpaseo/paseo/pull/10992))
### 修复
- 修复已启用的客户端插件导入 `react-native` 时,Paseo iOS 在连接后不久崩溃的问题 ([#11011](https://github.com/getpaseo/paseo/pull/11011))
- 修复流事件丢失或对话历史较大时,OpenCode v2 Agent 在点击停止后仍停留在运行中的问题 ([#10955](https://github.com/getpaseo/paseo/pull/10955))
- 修复在 Pi Agent 运行其自行启动的轮次时发送引导消息会中止该轮次而不是引导它的问题 ([#10977](https://github.com/getpaseo/paseo/pull/10977),贡献者:[@viiqswim](https://github.com/viiqswim))
- 修复在 fork 克隆中根据 PR 创建工作区时,检出到 fork 中同编号 PR 的问题 ([#10987](https://github.com/getpaseo/paseo/pull/10987))
- 修复向 Composer 拖放图片或文件后输入框未获得焦点的问题 ([#11022](https://github.com/getpaseo/paseo/pull/11022))
## 0.17.6 - 2026-11-27
### 改进
-1
View File
@@ -55,7 +55,6 @@ At the start of non-trivial work, list `docs/` and skim anything relevant to the
| [docs/permissions.md](docs/permissions.md) | Semantic daemon permissions, principals, credentials, pairing invitations, and Hub authority |
| [docs/terminal-performance.md](docs/terminal-performance.md) | Terminal latency pipeline, coalescing/backpressure invariants, benchmark + perf spec usage |
| [docs/terminal-rendering.md](docs/terminal-rendering.md) | Native terminal view: xterm owns the grid, cluster placement, emoji widths, mixed-direction limits, render regression |
| [docs/timeline-sync.md](docs/timeline-sync.md) | Owned agent history, rewind retirements, live stream vs authoritative fetch, paged catch-up, client replica |
| [docs/agent-stream-performance.md](docs/agent-stream-performance.md) | Assistant text pipeline — coalescing window, paced reveal, why arrival lumps are smoothed at render |
| [docs/agent-stream-disclosure.md](docs/agent-stream-disclosure.md) | Expand/collapse in the chat timeline — hold contract, native anchor sequence, frame spacing, render-window cost |
| [docs/markdown-renderer.md](docs/markdown-renderer.md) | Shared Markdown engine, the vendored library fork, native selection, links, images and library constraints |
+27 -1
View File
@@ -1,6 +1,6 @@
# Brand assets
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets that will replace the existing icons across the app, desktop client, website, docs, and Hub in follow-up work.
Canonical marks, lockups, and wordmark font for **Paseo** and **Paseo Hub**. These are the source assets for the icons across the app, desktop client, website, docs, and Hub.
## Brand architecture
@@ -37,6 +37,10 @@ All lockups (`lockups/*.svg`) share a `144`-unit height (`140`-unit flower ink h
```text
assets/brand/
build.mjs Regenerates all marks and lockups
build-app-icons.mjs Regenerates the desktop and mobile app icons
app-icons/
paseo-lit.png
paseo-dev-lit.png
fonts/
PlusJakartaSans-SemiBold.ttf
OFL.txt
@@ -61,3 +65,25 @@ assets/brand/
```sh
node assets/brand/build.mjs
```
## App icons
`build-app-icons.mjs` renders every desktop and mobile app icon from `marks/paseo-white.svg`: the white butterfly on a black tile, and a blueprint tile for desktop development builds. Regenerate them after changing the butterfly:
```sh
node assets/brand/build-app-icons.mjs
```
The icons that ship are flat. Each platform masks and lights its own icons, so lit artwork ends up lit twice. `app-icons/` keeps a lit version of the two desktop icons, a baked approximation of macOS Liquid Glass. Nothing uses them.
The packaged Mac app takes its icon from `packages/desktop/assets/icon.icon`, an Icon Composer document the script also writes. macOS draws Liquid Glass on it and derives the dark, tinted, and clear variants. electron-builder compiles the document with `actool`, so packaging the Mac app needs Xcode 26 or later. The Nix build has no Xcode and uses `icon.icns`.
To see what macOS draws from the document without packaging the app, export it with Icon Composer's command line tool on a Mac:
```sh
"/Applications/Xcode.app/Contents/Applications/Icon Composer.app/Contents/Executables/ictool" \
packages/desktop/assets/icon.icon --export-image --output-file icon.png \
--platform macOS --rendition Default --width 1024 --height 1024 --scale 1
```
`--rendition` also takes `Dark`, `TintedLight`, `TintedDark`, `ClearLight`, and `ClearDark`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 212 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 109 KiB

+464
View File
@@ -0,0 +1,464 @@
// Generates every Paseo app icon from the canonical butterfly mark.
//
// node assets/brand/build-app-icons.mjs
//
// The artwork is the white butterfly on a black tile. A desktop development build gets the same
// tile drawn as a blueprint, so it is never mistaken for an installed app.
//
// The icons that ship are flat. Each platform masks and lights its own icons, and artwork that
// arrives already lit ends up lit twice. The lit finish is a baked approximation of the Liquid
// Glass material macOS draws for Icon Composer icons. It is written to app-icons/ so it stays
// available, and nothing consumes it.
//
// A packaged Mac app gets its icon from the Icon Composer document in the desktop assets, which
// macOS masks and lights itself. macOS draws a dev build's Dock icon and an .icns exactly as
// supplied, so those carry the system's tile in the artwork. Its geometry is measured from the icon
// macOS 27 draws for that document: the tile covers 824 of the 1024 canvas pixels and its corners
// are continuous curves with a radius of 26.4% of the tile.
//
// sharp is not a declared dependency. It resolves from the workspace root, the way opentype.js
// does for build.mjs.
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import sharp from "sharp";
const brandDir = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(brandDir, "../..");
const brandMarkPath = path.join(brandDir, "marks/paseo-white.svg");
const CANVAS = 1024;
const MACOS_TILE_ON_CANVAS = 824 / CANVAS;
// Windows and Linux have no icon grid, and a tile with the macOS margin looks small next to their
// other icons.
const WINDOWS_LINUX_TILE_ON_CANVAS = 928 / CANVAS;
// Artwork is drawn in the brand mark's own 700-unit box, which the tile fills.
const TILE = 700;
const TILE_RADIUS = 185;
const MARK_INK = 527;
// Scaled down, the mark keeps clear of the tile's corners and covers as much of the tile as the
// glyphs in Apple's icons do.
const MARK_SCALE = 0.9;
const MARK_INK_ON_TILE = (MARK_INK * MARK_SCALE) / TILE;
// Android shows the middle 72 of an adaptive icon's 108 units.
const ANDROID_ADAPTIVE_VISIBLE = 72 / 108;
const NOTIFICATION_MARK_INK = 0.75;
// Apple's continuous corner. Each pair is a distance back along the incoming edge and a distance
// along the outgoing edge, in units of the corner radius.
const CORNER_SEGMENTS = [
["C", [1.08849296, 0], [0.86840694, 0], [0.66993427, 0.065496]],
["L", [0.63149399, 0.074911]],
["C", [0.37282392, 0.16905899], [0.16905899, 0.37282392], [0.074911, 0.63149399]],
["L", [0.065496, 0.66993427]],
["C", [0, 0.86840694], [0, 1.08849296], [0, 1.52866483]],
];
const CORNER_START = [1.52866483, 0];
function continuousSquarePath(inset) {
const near = inset;
const far = TILE - inset;
const radius = TILE_RADIUS - inset;
const corners = [
{ at: [far, near], incoming: [1, 0], outgoing: [0, 1] },
{ at: [far, far], incoming: [0, 1], outgoing: [-1, 0] },
{ at: [near, far], incoming: [-1, 0], outgoing: [0, -1] },
{ at: [near, near], incoming: [0, -1], outgoing: [1, 0] },
];
const commands = corners.map(({ at, incoming, outgoing }, cornerIndex) => {
const point = ([back, along]) =>
[0, 1]
.map((axis) => at[axis] - incoming[axis] * back * radius + outgoing[axis] * along * radius)
.map((value) => Number(value.toFixed(2)))
.join(" ");
const segments = CORNER_SEGMENTS.map(
([command, ...points]) => `${command}${points.map(point).join(" ")}`,
);
return `${cornerIndex === 0 ? "M" : "L"}${point(CORNER_START)}${segments.join("")}`;
});
return `${commands.join("")}Z`;
}
const TILE_SHAPE = `<path d="${continuousSquarePath(0)}" />`;
const FILL_TILE = `<rect width="${TILE}" height="${TILE}" fill="url(#surface)" />`;
const PRODUCTION = {
flat: {
defs: `<linearGradient id="surface"><stop stop-color="#000000" /></linearGradient>`,
surface: FILL_TILE,
},
lit: {
defs: `
<linearGradient id="surface" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#202022" />
<stop offset="1" stop-color="#0E0E10" />
</linearGradient>`,
surface: FILL_TILE,
tileEdge: { color: "#000000", opacity: 0.75 },
markEdge: { color: "#4A5568", opacity: 0.45 },
markShadow: { color: "#000000", opacity: 0.5 },
},
};
const GRID_DIVISIONS = 8;
const GRID_MAJOR_EVERY = 2;
const OUTLINE_INSET = 28;
function gridLines(isIncluded) {
const step = TILE / GRID_DIVISIONS;
const segments = [];
for (let index = 1; index < GRID_DIVISIONS; index += 1) {
if (!isIncluded(index)) continue;
const at = index * step;
segments.push(`M${at} 0V${TILE}`, `M0 ${at}H${TILE}`);
}
return segments.join("");
}
const isMajorLine = (index) => index % GRID_MAJOR_EVERY === 0;
const BLUEPRINT_SHEET = {
defs: `
<linearGradient id="surface" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#05C2FE" />
<stop offset="0.5" stop-color="#0191FD" />
<stop offset="1" stop-color="#026CFA" />
</linearGradient>`,
surface: `
${FILL_TILE}
<g fill="none" stroke="#FFFFFF">
<path d="${gridLines((index) => !isMajorLine(index))}" stroke-opacity="0.16" stroke-width="1.5" />
<path d="${gridLines(isMajorLine)}" stroke-opacity="0.34" stroke-width="2" />
<circle cx="${TILE / 2}" cy="${TILE / 2}" r="${TILE / 2 - OUTLINE_INSET}" stroke-opacity="0.45" stroke-width="2" stroke-dasharray="10 8" />
<path d="${continuousSquarePath(OUTLINE_INSET)}" stroke-opacity="0.34" stroke-width="2" />
</g>`,
};
const BLUEPRINT = {
flat: BLUEPRINT_SHEET,
lit: {
...BLUEPRINT_SHEET,
tileEdge: { color: "#0034B4", opacity: 0.55 },
markEdge: { color: "#1E5FD0", opacity: 0.5 },
markShadow: { color: "#00308F", opacity: 0.4 },
},
};
// The lit finish, tuned against Apple's own renders. The light comes from straight above: a
// layer's upward-facing edge gets a bright highlight, its downward-facing edge a fainter one, and
// its side edges darken.
//
// An edge highlight is the part of the layer that a vertically shifted copy does not cover. A
// vertical blur of the shifted copy makes the highlight brightest at the edge and absent on
// vertical edges. A wider, round blur of the same band dims it where the edge turns away from
// the light, which is what keeps the tile's corners quieter than its top.
function glassFilter({ id, edge, edgeWidth, lightWidth, upperLight, lowerLight, shadow }) {
const light = (name, direction, opacity) => `
<feOffset in="SourceAlpha" dy="${direction * lightWidth}" />
<feGaussianBlur stdDeviation="0 ${lightWidth}" result="${name}Shifted" />
<feComposite in="SourceAlpha" in2="${name}Shifted" operator="out" result="${name}Edge" />
<feOffset in="SourceAlpha" dy="${direction * lightWidth * 2}" result="${name}Far" />
<feComposite in="SourceAlpha" in2="${name}Far" operator="out" />
<feGaussianBlur stdDeviation="${lightWidth * 3}" />
<feComponentTransfer><feFuncA type="gamma" exponent="3" amplitude="65" /></feComponentTransfer>
<feComposite in2="${name}Edge" operator="arithmetic" k1="1" result="${name}Shape" />
<feFlood flood-color="#FFFFFF" flood-opacity="${opacity}" />
<feComposite in2="${name}Shape" operator="in" result="${name}" />`;
const dropShadow = shadow
? `
<feGaussianBlur in="SourceAlpha" stdDeviation="${shadow.blur}" />
<feOffset dy="${shadow.offset}" result="shadowShape" />
<feFlood flood-color="${shadow.color}" flood-opacity="${shadow.opacity}" />
<feComposite in2="shadowShape" operator="in" result="shadow" />`
: "";
return `
<filter id="${id}" x="-20%" y="-20%" width="140%" height="140%" color-interpolation-filters="sRGB">${dropShadow}
<feMorphology in="SourceAlpha" operator="erode" radius="${edgeWidth * 0.6}" />
<feGaussianBlur stdDeviation="${edgeWidth}" result="core" />
<feFlood flood-color="${edge.color}" flood-opacity="${edge.opacity}" />
<feComposite in2="core" operator="out" />
<feComposite in2="SourceAlpha" operator="in" result="edge" />
${light("upper", 1, upperLight)}
${light("lower", -1, lowerLight)}
<feMerge>
${shadow ? '<feMergeNode in="shadow" />' : ""}
<feMergeNode in="SourceGraphic" />
<feMergeNode in="edge" />
<feMergeNode in="upper" />
<feMergeNode in="lower" />
</feMerge>
</filter>`;
}
function litDefs({ tileEdge, markEdge, markShadow }) {
const markBody = `
<linearGradient id="markBody" x1="0" y1="0" x2="0" y2="1">
<stop offset="0" stop-color="#FFFFFF" />
<stop offset="0.4" stop-color="#FFFFFF" />
<stop offset="1" stop-color="#D9DFE9" />
</linearGradient>`;
const tileGlass = glassFilter({
id: "tileGlass",
edge: tileEdge,
edgeWidth: 3,
lightWidth: 3.6,
upperLight: 0.82,
lowerLight: 0.45,
});
const markGlass = glassFilter({
id: "markGlass",
edge: markEdge,
edgeWidth: 1.2,
lightWidth: 1.6,
upperLight: 1,
lowerLight: 0.6,
shadow: { ...markShadow, blur: 9, offset: 8 },
});
return `${markBody}${tileGlass}${markGlass}`;
}
function brandMark(stroke) {
const svg = readFileSync(brandMarkPath, "utf8");
const outline = svg.match(/\bd="([^"]+)"/);
const strokeWidth = svg.match(/\bstroke-width="([^"]+)"/);
if (!outline || !strokeWidth) {
throw new Error(`No stroked mark path in ${brandMarkPath}`);
}
// The path carries its own `fill="none"`: Icon Composer ignores the one on the <svg> element and
// draws a hairline from the end of the stroke back to its start.
return `<path d="${outline[1]}" fill="none" stroke="${stroke}" stroke-width="${strokeWidth[1]}" stroke-linecap="round" stroke-linejoin="round" />`;
}
function scaledAboutCentre(scale, content) {
const centre = TILE / 2;
return `<g transform="translate(${centre} ${centre}) scale(${scale}) translate(${-centre} ${-centre})">${content}</g>`;
}
// A square canvas with the 700-unit artwork box centred on it and covering `boxOnCanvas` of its
// width.
function canvasSvg(boxOnCanvas, content) {
const canvasUnits = TILE / boxOnCanvas;
const origin = (TILE - canvasUnits) / 2;
return [
`<svg width="${CANVAS}" height="${CANVAS}" viewBox="${origin} ${origin} ${canvasUnits} ${canvasUnits}" fill="none" xmlns="http://www.w3.org/2000/svg">`,
content,
"</svg>",
].join("\n");
}
// The tile with the mark on it. A masked tile has the continuous corners cut into the artwork. A
// square tile is for platforms that apply their own mask.
function tileIconSvg({ artwork, finish, tileOnCanvas, corners }) {
const look = artwork[finish];
const isLit = finish === "lit";
const filtered = (id, content) => (isLit ? `<g filter="url(#${id})">${content}</g>` : content);
const tile =
corners === "continuous" ? `<g clip-path="url(#tile)">${look.surface}</g>` : look.surface;
const mark = scaledAboutCentre(MARK_SCALE, brandMark(isLit ? "url(#markBody)" : "#FFFFFF"));
return canvasSvg(
tileOnCanvas,
[
`<defs><clipPath id="tile">${TILE_SHAPE}</clipPath>${look.defs}${isLit ? litDefs(look) : ""}</defs>`,
filtered("tileGlass", tile),
filtered("markGlass", mark),
].join("\n"),
);
}
// The white mark alone on a transparent canvas, its ink covering `inkOnCanvas` of the width.
function markOnlySvg(inkOnCanvas) {
return canvasSvg((inkOnCanvas * TILE) / MARK_INK, brandMark("#FFFFFF"));
}
function rasterizer(svg) {
const source = Buffer.from(svg);
const sized = (size) => sharp(source).resize(size, size);
return {
png: (size) => sized(size).png({ compressionLevel: 9 }).toBuffer(),
opaquePng: (size) => sized(size).removeAlpha().png({ compressionLevel: 9 }).toBuffer(),
rgba: (size) => sized(size).ensureAlpha().raw().toBuffer(),
};
}
// ICO: a directory of PNG-encoded entries. A size byte of 0 means 256.
function encodeIco(entries) {
const header = Buffer.alloc(6);
header.writeUInt16LE(1, 2);
header.writeUInt16LE(entries.length, 4);
let offset = header.length + entries.length * 16;
const directory = entries.map(({ size, png }) => {
const entry = Buffer.alloc(16);
entry.writeUInt8(size % 256, 0);
entry.writeUInt8(size % 256, 1);
entry.writeUInt16LE(1, 4);
entry.writeUInt16LE(32, 6);
entry.writeUInt32LE(png.length, 8);
entry.writeUInt32LE(offset, 12);
offset += png.length;
return entry;
});
return Buffer.concat([header, ...directory, ...entries.map((entry) => entry.png)]);
}
function icnsElement(type, data) {
const header = Buffer.alloc(8);
header.write(type, 0, "latin1");
header.writeUInt32BE(header.length + data.length, 4);
return Buffer.concat([header, data]);
}
// The 16 and 32 pixel ICNS slots predate PNG: three run-length-encoded colour planes plus a
// separate 8-bit alpha mask. A control byte below 128 copies the next (byte + 1) values, so
// literal-only chunks are a valid encoding.
function icnsLegacyElements(colorType, maskType, rgba) {
const pixels = rgba.length / 4;
const chunks = [];
for (let channel = 0; channel < 3; channel += 1) {
for (let start = 0; start < pixels; start += 128) {
const length = Math.min(128, pixels - start);
const chunk = Buffer.alloc(length + 1);
chunk[0] = length - 1;
for (let index = 0; index < length; index += 1) {
chunk[index + 1] = rgba[(start + index) * 4 + channel];
}
chunks.push(chunk);
}
}
const mask = Buffer.alloc(pixels);
for (let index = 0; index < pixels; index += 1) {
mask[index] = rgba[index * 4 + 3];
}
return [icnsElement(colorType, Buffer.concat(chunks)), icnsElement(maskType, mask)];
}
async function encodeIcns(icon) {
const pngSlots = [
["ic07", 128],
["ic08", 256],
["ic09", 512],
["ic10", 1024],
["ic11", 32],
["ic12", 64],
["ic13", 256],
["ic14", 512],
];
const elements = [
...icnsLegacyElements("is32", "s8mk", await icon.rgba(16)),
...icnsLegacyElements("il32", "l8mk", await icon.rgba(32)),
];
for (const [type, size] of pngSlots) {
elements.push(icnsElement(type, await icon.png(size)));
}
const body = Buffer.concat(elements);
const header = Buffer.alloc(8);
header.write("icns", 0, "latin1");
header.writeUInt32BE(header.length + body.length, 4);
return Buffer.concat([header, body]);
}
// The Icon Composer document macOS 26 and later build the app icon from. The canvas is the whole
// tile: macOS adds the mask, the margin, and the lighting. The mark stays opaque so it reads as
// solid white on the black tile.
function iconComposerFiles() {
const layer = "butterfly.svg";
const document = {
fill: { solid: "srgb:0.00000,0.00000,0.00000,1.00000" },
groups: [
{
layers: [{ "image-name": layer, name: "butterfly" }],
shadow: { kind: "neutral", opacity: 0.5 },
translucency: { enabled: false, value: 0.5 },
},
],
"supported-platforms": { squares: ["macOS"] },
};
return [
["icon.json", `${JSON.stringify(document, null, 2)}\n`],
[`Assets/${layer}`, `${markOnlySvg(MARK_INK_ON_TILE)}\n`],
];
}
function write(file, data) {
const target = path.join(repoRoot, file);
mkdirSync(path.dirname(target), { recursive: true });
writeFileSync(target, data);
}
function desktopIcon(artwork, finish, tileOnCanvas) {
return rasterizer(tileIconSvg({ artwork, finish, tileOnCanvas, corners: "continuous" }));
}
async function buildDesktopIcons() {
const production = desktopIcon(PRODUCTION, "flat", WINDOWS_LINUX_TILE_ON_CANVAS);
const assets = "packages/desktop/assets";
const pngFiles = [
["icon.png", 512],
["32x32.png", 32],
["64x64.png", 64],
["128x128.png", 128],
["128x128@2x.png", 256],
];
for (const [file, size] of pngFiles) {
write(`${assets}/${file}`, await production.png(size));
}
const icoEntries = [];
for (const size of [32, 16, 24, 48, 64, 256]) {
icoEntries.push({ size, png: await production.png(size) });
}
write(`${assets}/icon.ico`, encodeIco(icoEntries));
write(
`${assets}/icon.icns`,
await encodeIcns(desktopIcon(PRODUCTION, "flat", MACOS_TILE_ON_CANVAS)),
);
for (const [file, content] of iconComposerFiles()) {
write(`${assets}/icon.icon/${file}`, content);
}
write(
`${assets}/icon-dev.png`,
await desktopIcon(BLUEPRINT, "flat", MACOS_TILE_ON_CANVAS).png(CANVAS),
);
}
async function buildMobileIcons() {
const flat = (corners) =>
rasterizer(tileIconSvg({ artwork: PRODUCTION, finish: "flat", tileOnCanvas: 1, corners }));
// iOS masks these itself, and Expo flattens any transparency in the app icon onto white.
const square = flat("square");
// Shown as supplied, so the corners are part of the artwork.
const masked = flat("continuous");
const adaptiveForeground = rasterizer(markOnlySvg(ANDROID_ADAPTIVE_VISIBLE * MARK_INK_ON_TILE));
const notification = rasterizer(markOnlySvg(NOTIFICATION_MARK_INK));
write("packages/app/assets/images/icon.png", await square.opaquePng(1024));
write("packages/app/public/apple-touch-icon.png", await square.opaquePng(180));
write(
"packages/app/assets/images/android-icon-foreground.png",
await adaptiveForeground.png(1024),
);
write("packages/app/assets/images/notification-icon.png", await notification.png(96));
write("packages/app/assets/images/splash-icon.png", await masked.png(1024));
write("packages/app/public/pwa-icon-192.png", await masked.png(192));
write("packages/app/public/pwa-icon-512.png", await masked.png(512));
write("fastlane/metadata/android/en-US/images/icon.png", await masked.png(512));
}
async function buildLitIcons() {
for (const [file, artwork] of [
["paseo-lit.png", PRODUCTION],
["paseo-dev-lit.png", BLUEPRINT],
]) {
const icon = desktopIcon(artwork, "lit", MACOS_TILE_ON_CANVAS);
write(`assets/brand/app-icons/${file}`, await icon.png(CANVAS));
}
}
await buildDesktopIcons();
await buildMobileIcons();
await buildLitIcons();
+6 -7
View File
@@ -39,8 +39,8 @@ An unarchived agent may be `closed` without being deleted or archived. Closing r
processes and subscriptions while retaining its Paseo identity, persistence handle, timeline,
workspace, labels, title, usage, attention, timestamps, and parent relationship. Opening or prompting
the agent runs through `ensureAgentLoaded()`, which resumes the durable provider session under the
same Paseo agent ID. Resume does not read provider history when the agent already has a timeline;
see [owned history](timeline-sync.md#owned-history).
same Paseo agent ID. Provider history is not appended again when the canonical timeline is already
primed.
Reload releases the old runtime before resuming its durable session: an idle provider process can
still own an exclusive writer. A close failure retains that runtime for cleanup and blocks the
@@ -80,7 +80,9 @@ Provider checks follow the signals their runtimes expose:
- Codex queries background terminals for loaded threads, including native children, and protects
pending provider requests. App servers without the terminal-list RPC stay resident.
- OpenCode checks active executions and descendants. V1 checks PTYs; v2 also checks shell and
inbox inventories. The shared server remains leased while a session vetoes collection.
inbox inventories. The shared server remains leased while a session vetoes collection. V2 lets
another session's execution veto only when releasing the lease would stop the server; the shared
server stays up after its last lease goes.
- Pi checks streaming, compaction, pending replies, and adapter-owned operations. Known native
subagent signals also protect their parent through the daemon's subagent store.
- OMP additionally requires `get_state.isSettled: true` and `hasPendingAsyncWork: false`.
@@ -268,8 +270,7 @@ lifecycle is separate from public workspace visibility and is not a public creat
Archive is a **soft delete**: the agent record stays on disk with `archivedAt` set, the runtime is closed, and the agent disappears from active lists. Archive is **global** — it lives on the server and propagates to every connected client.
Archive sets `archivedAt`, invokes the provider's native archive hook, and cascades to managed
children. The timeline and the provider children stay, so an archived chat reads them without its
provider; deleting the agent removes them.
children.
`create_agent_request` can opt an agent into `autoArchive`. In that mode the daemon archives the agent after the first terminal turn event (`turn_completed`, `turn_failed`, or `turn_canceled`). When the agent owns an isolated workspace, auto-archive archives that workspace too; the managed worktree is removed when its final workspace reference is gone.
@@ -365,8 +366,6 @@ Workspace status is an aggregate activity signal computed **per `workspaceId`**.
Running provider-native subagents contribute `running` to the workspace owned by their parent agent. Their completed, failed, and canceled states stay in the parent's subagents track.
Only the parent's current runtime makes a provider child running. A child's stored status is the last report about it, and that report can come from provider history or from a runtime an earlier daemon ran, so a stored `running` child does not make the workspace running or keep the parent's runtime alive. It counts again once the live session reports it running. Closing a runtime cancels the children that runtime reported running; children it never reported keep their stored status.
A finished or failed workspace can be marked unread after it has been reviewed. The daemon restores
attention on its newest eligible workspace-root agent, `error` for an agent whose lifecycle is
`error` and `finished` otherwise, without sending a new notification. Opening a workspace restores
+1 -3
View File
@@ -94,7 +94,6 @@ workspace for a directory clears it. The store lives in memory and resets on dae
| `server/directory-sync/` | Daemon-global latest-state sequences for projects, workspaces, and agents |
| `server/workspace-labels/` | Host-local label catalog, assignment mutations, and explicit subscriptions |
| `server/agent/agent-manager.ts` | Agent lifecycle state machine, timeline tracking, subscriber management |
| `server/agent/timeline/` | Owned agent history, provider children, rewind retirements, behind a backend |
| `server/agent/agent-storage.ts` | File-backed JSON persistence at `$PASEO_HOME/agents/` |
| `server/agent/tools/` | Transport-neutral catalog for workspaces, agents, permissions, and automation |
| `server/agent/mcp-server.ts` | Thin MCP adapter that registers the Paseo tool catalog with the MCP SDK |
@@ -403,7 +402,7 @@ initializing → idle ⇄ running
client-side dedup; the default fetch page is 200 items.
- Timeline row `timestamp` values are canonical daemon-owned timestamps. Providers may supply original replay timestamps, but clients must not guess timestamp trust or hide time UI based on local clock heuristics.
- Events stream to connected clients in real time; correctness is backed by authoritative timeline fetches and paged-to-completion catch-up.
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. That storage path is derived from `cwd`, not from workspace id. Timeline rows persist in the daemon database, `$PASEO_HOME/paseo.db`. They are the transcript authority after the first import of provider history. See [owned history](timeline-sync.md#owned-history).
- Agent state persists to `$PASEO_HOME/agents/{cwd-with-dashes}/{agent-id}.json`. Timeline rows are runtime memory; provider history is the durable transcript authority and resumed agents rebuild from it. That storage path is derived from `cwd`, not from workspace id.
## Right-sidebar boundary: directory-backed vs workspace-owned
@@ -479,7 +478,6 @@ Providers that can accept native tool definitions should set `supportsNativePase
```
$PASEO_HOME/
├── agents/{cwd-with-dashes}/{agent-id}.json # Agent record
├── paseo.db # Daemon database (SQLite): agent timelines
├── projects/projects.json # Project registry
├── projects/workspaces.json # Workspace registry
├── projects/icons/ # Custom project icon images
+4 -43
View File
@@ -34,7 +34,7 @@ Workspace archive runs lifecycle teardown from the exact `cwd` but removes only
`worktreeRoot` after its last active reference disappears. Worktree recovery recreates that backing
checkout from `mainRepoRoot`, then restores the relative path from `worktreeRoot` to `cwd`.
Paseo persists most stores as JSON files, and agent timelines in the [daemon database](#daemon-database). JSON data is validated at runtime with Zod schemas. Most JSON stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. JSON stores have no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
Paseo uses **file-based JSON persistence** instead of a traditional database. All data is validated at runtime with Zod schemas. Most stores write atomically (write to temp file, then rename); a few still use plain `writeFile` — see each section. There is no schema-versioning/migration framework — schemas rely on optional fields with defaults for forward compatibility, with a small amount of inline normalization in `persisted-config.ts` for legacy provider/speech entries.
All server-side stores live under `$PASEO_HOME` (defaults to `~/.paseo`).
@@ -53,7 +53,6 @@ $PASEO_HOME/
├── daemon-keypair.json # E2EE keypair for relay (mode 0600)
├── paseo.pid # Daemon PID lock file
├── local-credential # Per-run local client credential (mode 0600)
├── paseo.db # Daemon database (SQLite, with -wal and -shm files)
├── daemon.log # Default log file (path configurable)
├── agents/
│ └── {sanitized-cwd}/
@@ -182,45 +181,6 @@ Terminal activity contributes to the workspace status bucket **per `workspaceId`
---
## Daemon database
`$PASEO_HOME/paseo.db` is one SQLite file that the daemon opens at startup with `node:sqlite`
(`packages/server/src/server/database/`). Agent timelines are its only store today. Each store is a
`SchemaModule`: its own table-name prefix and an append-only list of migrations.
- **Migrations.** Startup runs every module's pending migrations in one transaction, so a failed
migration leaves the file as it was. `schema_versions` records each module's version and
`min_reader_version`. Mark a migration `breaking` when an older daemon cannot read the result,
for example a dropped or renamed column. An older daemon then refuses to start with
`DatabaseSchemaTooNewError`. Additive migrations leave older daemons working, and they ignore
modules they do not know. This matters because the app and the daemon update separately, and a
user can run an older daemon on the same `$PASEO_HOME`.
- **Failure.** A file that SQLite cannot open stops the daemon with `DatabaseOpenError`, which
names the path. The daemon does not delete or recreate the file.
- **Access.** The file holds every prompt and reply, so the daemon sets it and its `-wal` and `-shm`
files to mode `0600` on every open. SQLite gives the WAL files it creates the mode of the database
file.
- **Durability.** The database uses WAL with `synchronous = NORMAL`. A power loss can drop the
last commits but does not corrupt the file.
- **Checkpoints.** A checkpoint syncs the file to disk and takes up to 100 ms. SQLite's
auto-checkpoint runs it on the committing thread, which stalled the event loop during streaming.
The daemon turns it off and checkpoints from a worker thread with its own connection. If the
worker exits, the daemon turns auto-checkpoint back on.
- **Transactions.** `write` and `read` callbacks are synchronous, so a transaction never spans an
`await` and transactions never interleave.
- **Node.** `node:sqlite` needs Node 22.16 or later. Node 22 prints an experimental warning once,
when the daemon opens the database.
### Agent timelines
`AgentTimeline` owns each agent's history, and its SQLite backend stores the projected rows, the
source ranges, retirements, the open rewind, and provider children in `timeline_*` tables. The text
of a streamed assistant or reasoning message is stored as one chunk per source event, beside its
row, so a chunk never rewrites the message. An earlier file store rewrote the whole transcript on
every update. See [owned history](timeline-sync.md#owned-history).
---
## 2. Daemon Configuration
**Path:** `$PASEO_HOME/config.json`
@@ -280,7 +240,8 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
// `extends` (one of the built-ins or `"acp"`) and `label`. See `provider-launch-config.ts`.
providers: Record<providerId, ProviderOverride>,
metadataGeneration: {
providers: [{ provider, model?, thinkingOptionId? }]
providers: [{ provider, model?, thinkingOptionId? }],
instructions?: string
}
},
pluginsEnabled: boolean,
@@ -359,7 +320,7 @@ Paseo tools; otherwise the provider policy applies. Provider and global policy a
session is created, resumed, imported, or reloaded, so configuration changes affect the next
session rather than an already-running one.
`agents.metadataGeneration.providers` selects the models for daemon-side metadata tasks: commit messages, PR text, branch names, and generated titles. An empty list is Automatic; a non-empty list is Manual and only those models are tried. See [public-docs/metadata-generation.md](../public-docs/metadata-generation.md#how-a-model-is-chosen).
`agents.metadataGeneration.providers` selects the models for daemon-side metadata tasks: commit messages, PR text, branch names, and generated titles. An empty list is Automatic; a non-empty list is Manual and only those models are tried. `agents.metadataGeneration.instructions` adds host-wide guidance to every metadata generation prompt alongside the built-in or per-project style. See [public-docs/metadata-generation.md](../public-docs/metadata-generation.md#how-a-model-is-chosen).
### Git process limits
+1 -1
View File
@@ -177,7 +177,7 @@ Electron window controls are top-corner obstructions, not a compact-layout condi
Windows and Linux controls are fixed window chrome, outside scrolling header content. A tab rail that reaches them ends at their obstruction and shows the shared overflow fade. On macOS, the Explorer toggle occupies a fixed top-right window slot so opening and closing Explorer does not move the pointer target.
Each window edge has one safe-area owner. `WindowLayoutProvider` publishes the bottom inset that every surface reads through `useSafeAreaInsets()`: on iOS 27.1 and later it is UIKit's bottom-bar clearance, which refines the rectangular home-indicator inset to the screen's corners, and elsewhere the system inset. Surfaces apply that value once and never stack their own spacing under it; `WindowLayoutSurface` owns the horizontal insets the same way.
Each window edge has one safe-area owner. `WindowLayoutProvider` publishes the bottom inset that every surface reads through `useSafeAreaInsets()`: on iOS 27.1 and later it is UIKit's bottom-bar clearance, which refines the rectangular home-indicator inset to the screen's corners, and elsewhere the system inset. Surfaces apply that value once and never stack their own spacing under it; `WindowLayoutSurface` owns the horizontal insets the same way, and on wide web layouts it also owns the top inset: it pads the status bar of an iOS Home Screen web app once and gives its content a top inset of 0. Content inside the surface that draws against the window instead of the padded content reads the window's insets; see Gotcha 8 in `docs/floating-panels.md`.
A new list+detail feature copies the settings shell. A new workspace-shaped feature copies the workspace shell. Inventing a third shape happens in design review, not in a PR.
+16 -5
View File
@@ -459,10 +459,15 @@ Wrapping providers _around_ the modal does nothing. They land on the wrong side.
## Gotcha 8 — Read safe-area insets where the overlay draws
A compact sheet tab's body (`SheetBottomInset` in `adaptive-modal-sheet.tsx`) pads the bottom
inset and gives its content a bottom inset of 0, so the composer dock sits the same in a sheet as
in a tab. An overlay opened from that content and calling `useSafeAreaInsets()` at its call site
gets that 0 and draws over the navigation bar.
Two containers spend an inset and give their content 0 for that edge:
- A compact sheet tab's body (`SheetBottomInset` in `adaptive-modal-sheet.tsx`) pads the bottom
inset, so the composer dock sits the same in a sheet as in a tab.
- `WindowLayoutSurface` on a wide web layout pads the top inset, the status bar of an iOS Home
Screen web app (`docs/design.md`, section 9).
An overlay opened from that content and calling `useSafeAreaInsets()` at its call site gets that 0
and draws over the navigation bar or under the status bar. Read the inset where the overlay draws:
- A Gorhom sheet reads the inset inside its children, which render in the app's sheet host. See
`SheetVisibleFrame` (used by `CompactSheetBody` and `ComboboxSheetFrame`) and `MenuSheetScrollView`.
@@ -470,7 +475,13 @@ gets that 0 and draws over the navigation bar.
`WindowSafeArea` from `@/window-layout` and read the inset below that. It provides the insets of
the whole window, published by `WindowLayoutProvider`. Do not put a `SafeAreaProvider` inside the
modal: on Android it measures the dialog window, whose bottom inset reads 24, then 0, then 24
again over the first frames, and everything padded by it jumps. See `attachment-lightbox.tsx`.
again over the first frames, and everything padded by it jumps. See `attachment-lightbox.tsx`
and the Mermaid fullscreen viewer.
- A panel in a `FloatingPanelPortalHost` reads `useSafeAreaInsets()` inside the portal, where it
resolves at the host's position (Gotcha 2): the root host sits outside the layout surface and
gets the window's inset, a workspace host inside it gets 0. See the autocomplete `PopoverFrame`.
- An absolutely positioned view that covers the surface's padding, such as the overlay left
sidebar, reads the window's insets with `useWindowSafeAreaInsets()`.
## Recipe for a new anchored panel
+4
View File
@@ -972,6 +972,10 @@ reply text once, forks at its message, and shows its duration and stats. Read th
`getAssistantReply` (`packages/app/src/types/stream.ts`) instead of checking `kind ===
"assistant_message"`.
A provider-only fact about a tool call goes in the item's `metadata`, which transformers already
receive. Do not add a shared tool-call field for it. OMP's intent string is
[`metadata.intent`](../public-docs/plugins/reference.md#timeline-items).
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.
+3
View File
@@ -340,6 +340,9 @@ See the [public usage source reference](../public-docs/plugins/reference.md#usag
contract, account and window identity, provider-derived period names, login fallback, and
read-only credential rules. Usage adapters own the interpretation of provider fields; the app
renders their names and resolves pins without provider-specific duration guesses.
Claude's OAuth usage endpoint is undocumented. Extra-usage amounts are reported in minor currency
units and displayed only for USD; the balance contract does not represent other currencies.
Codex individual spending limits provide percentages, not dollar amounts.
---
+109 -71
View File
@@ -4,29 +4,41 @@ All workspaces share one version and release together.
## Two steps
A release has exactly two steps. The agent does the first, the user authorizes the second.
A release has two steps. The agent runs Preparation before approval, and the user authorizes Ship.
**Preparation** (reversible — agent does this on the release branch):
### Preparation
- resolve the [release base](#release-base-and-source) and get the [release inventory](#release-inventory) approved when one applies
- classify the diff from the previous stable to the release source as patch or minor, then show the
target version and rationale to the user
- draft `CHANGELOG.md` and `CHANGELOG.zh-CN.md`, show the draft to the user, and wait for review
- run the pre-release sanity check (stable only) and surface findings to the user
- commit the approved changelog and any requested ACP update, run format, lint, and typecheck, then
run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag
- push the `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` branch and confirm its `CI` and
`Desktop Packages` runs pass (never wait on `main` CI)
- run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
Preparation is reversible and runs on the release branch before the user authorizes shipping.
**Go-ahead** (user says "go ahead"):
1. Resolve the [release base](#release-base-and-source) and get the [release inventory](#release-inventory) approved when one applies.
2. Classify the diff from the previous stable release to the release source as patch or minor, then show the target version and rationale to the user.
3. Draft `CHANGELOG.md` and `CHANGELOG.zh-CN.md`, show the draft to the user, and wait for approval.
4. Run the [pre-release sanity check](#pre-release-sanity-check) for stable releases, and report any findings to the user.
5. Commit the approved changelog and any requested ACP update, then run `npm run format`, `npm run lint`, and `npm run typecheck`.
6. Run `npm run release:prep:<mode>` to create the `chore(release): cut <version>` commit without a tag.
7. Push `release/vX.Y.Z` or `release/vX.Y.Z-beta.N` and wait for `CI` and `Desktop Packages` on that branch to pass (never wait on `main` CI).
8. Run the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit.
- run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta), which publishes npm
with retry and registry visibility checks, advances the `beta` dist-tag on stable when newer, and
pushes the tag on the already-verified commit
- create the release heartbeat immediately and babysit it to completion
- open the [reconcile `main`](#reconcile-main) PR right away so its CI runs in parallel with release
builds, then delete the remote release branch once the PR merges
### Ship
Ship starts after the user says "go ahead". All tag-triggered GitHub Actions workflows and EAS workflows build from the checked-out tag commit with local workspace packages, so none of them install `@getpaseo/*` from the public npm registry.
1. Run `npm run release:push` first to verify the clean release branch and push `vX.Y.Z` or `vX.Y.Z-beta.N`. Pushing the tag takes a few seconds and starts `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and (for stable tags) `Deploy App` on GitHub Actions, plus `Release Mobile` (stable) or `Release iOS Beta` (beta) on EAS. (`Deploy Website` runs later on the `release: published` event when `Desktop Release` publishes the stable GitHub Release.)
2. Run `npm run release:publish` (stable) or `npm run release:publish:beta` (beta) in parallel with the remote builds. `scripts/publish-release-packages.mjs` publishes the seven `@getpaseo/*` packages in dependency waves and polls npm visibility between packages to avoid `E409` or `E404` propagation races.
3. Open the [reconcile `main`](#reconcile-main) PR from `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N` right after `npm run release:push` finishes, so its CI run overlaps with npm publication and the release builds.
4. Create the release heartbeat immediately with `create_heartbeat` to track every ship step to completion.
### Sync gates
Wait until every gate below passes before deleting the remote release branch or reporting the release as shipped:
- All seven `@getpaseo/*` npm packages are visible on `latest` (stable) or `beta` (beta), and on stable the `beta` dist-tag points to the shipped version unless an active newer beta exists.
- All tag-triggered GitHub Actions workflows are green (`Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` for stable), and `Deploy Website` ran after stable publication.
- The GitHub Release is published and non-draft (marked prerelease for beta) with the synced changelog body, all macOS, Linux, and Windows assets, the Android APK asset, and all three channel manifests (`latest-mac.yml`, `latest-linux.yml`, `latest.yml` for stable; `beta-mac.yml`, `beta-linux.yml`, `beta.yml` for beta).
- The matching EAS workflow is green (`Release Mobile` with all six build, distribution, screenshot, and review-submission jobs for stable; `Release iOS Beta` for beta).
- The reconcile PR is merged into `main`.
Once all sync gates pass, delete the remote release branch (`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`), delete the heartbeat, and report the release as shipped.
Rules that apply to both steps:
@@ -110,18 +122,20 @@ An explicit user instruction can select another base.
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
6. After go-ahead, run `npm run release:ship` (stable) or `npm run release:ship:beta` (beta). This
publishes to npm and pushes the `v*` tag on the already-verified commit. Because the release
branch is already pushed at `HEAD`, no second CI run starts and only the tag release workflows
run.
7. Start [Reconcile `main`](#reconcile-main) immediately so its PR checks overlap with desktop and
EAS builds.
6. After go-ahead, push the tag first with `npm run release:push` so remote builds start right away.
Because the release branch is already pushed at `HEAD`, no second branch CI run starts, and only
the tag release workflows run.
7. Immediately in parallel after `npm run release:push` finishes: publish npm packages with
`npm run release:publish` (stable) or `npm run release:publish:beta` (beta), start
[Reconcile `main`](#reconcile-main) so its PR checks overlap with desktop and EAS builds, and
create the release heartbeat. (`npm run release:ship` and `npm run release:ship:beta` also run
`release:push` before `release:publish`, so tag builds never wait behind npm.)
When promoting or branching from a tag created before `release:prep:*`, `release:ship`, and the
`release/**` workflow triggers existed (for example `v0.17.0-beta.1`), either cherry-pick the
release-tooling commit onto the release branch (leaving product code unchanged) or follow the
older tag's scripts (`version:all:*`, manual `gh workflow run ci.yml --ref <branch>`,
`release:publish`, and `release:push`) until the next tag carries the new tooling.
`release:push`, and `release:publish`) until the next tag carries the new tooling.
A stable hotfix can take the version a patch beta line would promote to, such as `0.13.3`
shipping while `0.13.3-beta.2` soaks. Never republish or reuse a shipped version. Continue the line
@@ -130,7 +144,7 @@ computes that from a prerelease, so run `npm run release:check`, bump with
`npm version 0.13.4-beta.1 --include-workspace-root --no-git-tag-version && git commit -m "chore(release): cut 0.13.4-beta.1"`,
push the release branch for `CI` and `Desktop Packages`, and complete the
[pre-release dependency checks](#pre-release-dependency-checks) before shipping with
`npm run release:ship:beta`.
`npm run release:push` and `npm run release:publish:beta` (or `npm run release:ship:beta`).
Record the tested beta tag as its source so its soak still counts for the unchanged content.
## Release inventory
@@ -159,8 +173,7 @@ For a promotion, every item defaults to defer.
## Reconcile main
Right after the tag push (in parallel with desktop and EAS builds), open a PR into `main` from a
fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`:
Right after `npm run release:push` pushes the tag (in parallel with npm publication and all desktop, APK, Docker, and EAS builds), open a PR into `main` from a fresh branch off `origin/main` named `reconcile/vX.Y.Z` or `reconcile/vX.Y.Z-beta.N`. Reconcile reads only the tagged git commit, so it does not wait for npm or any release build:
```bash
git fetch origin --tags
@@ -180,10 +193,10 @@ hunks from the release base:
- Leaves unshipped work on `main` untouched and makes no claims about unshipped work in the
changelog entry.
Commit, open the PR into `main`, and merge once its checks pass. After the reconcile PR merges and
the release completes, delete the remote release branch (`git push origin --delete release/vX.Y.Z`
or `release/vX.Y.Z-beta.N`). The tag is the record of shipped source; Paseo maintains no release
track besides `main`.
Commit, open the PR into `main`, and merge once its checks pass. Delete the remote release branch
(`git push origin --delete release/vX.Y.Z` or `release/vX.Y.Z-beta.N`) only after the reconcile PR
merges and every [sync gate](#sync-gates) passes. The tag is the record of shipped source, and
Paseo maintains no release track besides `main`.
## ACP catalog updates
@@ -240,24 +253,30 @@ npm run release:prep:minor
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead and green release-branch checks: publish npm and push the tag.
npm run release:ship
# 3. After go-ahead and green release-branch checks: push the tag first to start builds.
npm run release:push
# 4. Run these in parallel immediately after step 3:
npm run release:publish
# Also open the reconcile/vX.Y.Z PR into main and create the release heartbeat.
# (`npm run release:ship` runs `release:push` before `release:publish` if used standalone.)
```
`release:ship` runs `scripts/publish-release-packages.mjs` and `scripts/push-current-release-tag.mjs`:
`scripts/push-current-release-tag.mjs` refuses non-`release/*` branches, checks that `HEAD` matches `origin/release/*`, tags `HEAD` with `vX.Y.Z`, and pushes the tag. Because `HEAD` is already on the pushed release branch, no second branch CI run starts.
- Publishes all seven `@getpaseo/*` packages in dependency order, skips versions already on npm,
retries transient 429/5xx/network errors, and waits until each version is visible on npm before
continuing.
- Checks `npm view @getpaseo/cli dist-tags` and moves npm's `beta` dist-tag to the new stable
version across all seven packages whenever the stable version is newer than `beta` (leaving
`beta` untouched during a stable hotfix on an older line).
- Refuses non-`release/*` branches, tags `HEAD` with `vX.Y.Z`, and pushes the tag. Because `HEAD`
is already on the release branch, no second CI run starts.
`scripts/publish-release-packages.mjs` publishes the seven `@getpaseo/*` packages in dependency-wave order:
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`.
1. Wave 1: `@getpaseo/highlight`, `@getpaseo/relay`, and `@getpaseo/protocol` (no `@getpaseo/*` dependencies).
2. Wave 2: `@getpaseo/client` (depends on `@getpaseo/protocol` and `@getpaseo/relay`).
3. Wave 3: `@getpaseo/plugin` (depends on `@getpaseo/client` and `@getpaseo/protocol`).
4. Wave 4: `@getpaseo/server` (depends on `@getpaseo/client`, `@getpaseo/highlight`, `@getpaseo/plugin`, `@getpaseo/protocol`, and `@getpaseo/relay`).
5. Wave 5: `@getpaseo/cli` (depends on `@getpaseo/client`, `@getpaseo/protocol`, and `@getpaseo/server`).
Verify `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
After each `npm publish`, the script polls `npm view` (up to 12 checks, 5 seconds apart) until the published version is visible on npm before moving to the next package. Waiting for registry visibility prevents dependent publishes and manual retries from hitting `E409` conflicts or `E404` propagation lag. On stable releases, the script also checks `npm view @getpaseo/cli dist-tags` and moves npm's `beta` dist-tag to the new stable version across all seven packages whenever the stable version is newer than `beta` (leaving `beta` untouched during a stable hotfix on an older line).
The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Release Notes Sync`, and `Deploy App` (`app.paseo.sh`, stable tags only) on GitHub Actions. `Desktop Release` and `Release Notes Sync` create the GitHub Release as a draft while builds and release-note sync run. `Deploy Website` triggers later on `release: published` when `Desktop Release` publishes the non-draft stable GitHub Release. EAS picks up the same tag through the EAS GitHub app and starts `Release Mobile` (iOS and Android store builds) in parallel, with no mobile-release workflow under `.github/workflows`. None of these workflows install `@getpaseo/*` from the public npm registry because all of them build from the checked-out tag commit and workspace packages.
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
@@ -276,8 +295,10 @@ npm run version:all:minor
git push -u origin HEAD # Trigger CI + Desktop Packages on release/vX.Y.Z
# Wait for CI and Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:push # Create tag vX.Y.Z on HEAD and push (starts release builds)
# In parallel right after release:push:
npm run release:publish # Publish to npm (idempotent, with propagation + beta dist-tag sync)
npm run release:push # Create tag vX.Y.Z on HEAD and push (triggers release workflows)
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat.
```
## Beta flow
@@ -294,15 +315,19 @@ npm run release:prep:beta:next # Cut X.Y.Z-beta.2, beta.3, ...
git push -u origin HEAD
# Complete the pre-release dependency checks on this commit.
# 3. After go-ahead:
npm run release:ship:beta
# 3. After go-ahead: push the tag first, then run npm publish, reconcile, and heartbeat in parallel:
npm run release:push
npm run release:publish:beta
# (Or run `npm run release:ship:beta` in one shell while opening reconcile/vX.Y.Z-beta.N.)
# Later, after soak, promote on release/vX.Y.Z:
npm run release:prep:promote
git push -u origin HEAD
# Wait for CI + Desktop Packages and complete the pre-release dependency checks.
# After go-ahead:
npm run release:ship
npm run release:push
npm run release:publish
# Open reconcile/vX.Y.Z PR into main and create the release heartbeat in parallel.
```
- Beta tags are published GitHub prereleases like `v0.1.41-beta.1`
@@ -489,7 +514,7 @@ macOS 13 maps to Darwin 22. The two values use different version domains; do not
iOS and Android store builds are not in `.github/workflows`. They are triggered by the EAS GitHub app the moment the `v*` tag is pushed:
- **Android (Play Store)** — EAS builds with profile `production` and auto-submits to the Play Store via `eas submit` (EAS-managed credentials). A Fastlane lane then replaces the store screenshots.
- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane uploads the store screenshots and submits that same build for App Store review.
- **iOS (TestFlight + App Store)** — EAS builds with profile `production`, uploads once through a `testflight` job, distributes the build to the `Paseo Beta` external group with Beta App Review submission, and a Fastlane lane uploads the store screenshots and submits that same build for App Store review. When an earlier iOS version is already in Apple's review or release queue (`WAITING_FOR_REVIEW`, `IN_REVIEW`, `PENDING_APPLE_RELEASE`, `PENDING_DEVELOPER_RELEASE`, `PROCESSING_FOR_DISTRIBUTION`, `WAITING_FOR_EXPORT_COMPLIANCE`, or `ACCEPTED`), `submit_review` leaves it untouched, logs `IOS_REVIEW_SKIPPED` with the in-review version and the waiting TestFlight build, and exits `0` so `Release Mobile` stays green.
- **Android APK (GitHub Release asset)** — separate, via `.github/workflows/android-apk-release.yml`. This is the only Android-related workflow that lives in this repo.
EAS uses the local app version source. `packages/app/app.config.js` derives the native version from the package version. Android `versionCode` is `major * 1_000_000 + minor * 1_000 + patch`. iOS reserves 1,000 build slots per app version: beta `N` uses slot `N`, and stable uses slot `999`. For example, `0.2.6-beta.2` appears in App Store Connect as version `0.2.6` build `2006002`; stable uses build `2006999`. Rebuilding the same tag produces the same native build number; if a store has already accepted a binary and you need a different binary, cut the next beta or patch instead of relying on EAS remote auto-increment.
@@ -535,11 +560,22 @@ npx eas build:view <build-id>
# and submit_ios_for_review.
npx eas workflow:view <workflow-run-id> --json
# Read failed submit/review job logs.
# Read submit/review job logs (also check for IOS_REVIEW_SKIPPED on green runs).
npx eas workflow:logs <workflow-job-id> --all-steps --non-interactive
# Stream logs for a build.
npx eas build:view <build-id> --json | jq '.logFiles[]'
# Check live App Store Connect review state + top 5 recent iOS TestFlight builds.
npx eas workflow:run ios-review-status.yml
# Submit a waiting TestFlight build once the review slot is free (default replace_in_review=false skips if still active).
npx eas workflow:run resubmit-ios-review.yml
# Or force-replace an in-flight review for an urgent iOS hotfix:
npx eas workflow:run resubmit-ios-review.yml -F app_version=0.18.1 -F app_build_version=18001999 -F replace_in_review=true
# Cancel an active in-flight iOS App Store review (pass expected_version to guard against version drift).
npx eas workflow:run cancel-ios-review.yml -F expected_version=0.18.0
```
A build's `gitCommitHash` must match the release tag commit. `status` walks through `NEW` → `IN_QUEUE` → `IN_PROGRESS` → `FINISHED` (or `ERRORED`/`CANCELED`). The EAS workflow run's `gitCommitHash` and `trigger` must also match the release tag.
@@ -555,15 +591,14 @@ For the `Release Mobile` EAS workflow, these jobs must pass:
- `submit_android` — Android binary submitted to the Play Store
- `upload_android_screenshots` — Google Play screenshots replaced from the repo
Do not treat `build_ios: SUCCESS` or `distribute_ios: SUCCESS` as a completed iOS release. `submit_ios_for_review: FAILURE` means the iOS release is blocked even if the build is visible in TestFlight.
Do not treat `build_ios: SUCCESS` or `distribute_ios: SUCCESS` as a completed iOS release. `submit_ios_for_review: FAILURE` means the iOS release is blocked even if the build is visible in TestFlight. Even when `submit_ios_for_review` passes, inspect its log with `npx eas workflow:logs <workflow-job-id> --all-steps --non-interactive` for `IOS_REVIEW_SKIPPED`. If App Store submission was skipped because an earlier version is already in flight, explicitly notify the maintainer with both the in-review version/state and the waiting TestFlight version/build so they can either let the current review finish and run `npx eas workflow:run resubmit-ios-review.yml` later, or replace it with `replace_in_review=true`.
To confirm the submission landed, inspect the EAS workflow with `npx eas workflow:view <workflow-run-id> --json`. App Store Connect (review state for the matching version/build) and the Play Console track are the final ground truth.
## Release completion and heartbeat
A release is **in progress** after npm publication and tag push. Report it as
**shipped** only after every applicable build, publication, asset, manifest, and
store submission passes the completion checklist.
A release is in progress once the tag is pushed. Report it as shipped only after every applicable
[sync gate](#sync-gates) and completion checklist item passes.
Immediately after every beta, stable, or promotion tag push, create a heartbeat
that resumes the release in the current conversation. Create it automatically
@@ -572,9 +607,10 @@ the completion checklist or finds a failure that needs new user authority.
Each heartbeat checks the release tag commit, `CI` and `Desktop Packages` for the release branch,
every tag-triggered GitHub Actions run (`Desktop Release`, `Android APK Release`, `Docker`,
`Release Notes Sync`), npm dist-tags, the GitHub Release body and assets, desktop updater
manifests, the published Docker image, the applicable EAS workflow, the reconcile PR, and remote
release branch cleanup. Inspect the GitHub Release itself and confirm that the macOS, Linux,
`Release Notes Sync`, and `Deploy App` for stable), `Deploy Website` after stable release
publication, npm dist-tags, the GitHub Release body and assets, desktop updater manifests, the
published Docker image, the applicable EAS workflow, the reconcile PR, and remote release branch
cleanup. Inspect the GitHub Release itself and confirm that the macOS, Linux,
Windows, and Android APK assets are present along with the channel manifests
(`latest-mac.yml`, `latest-linux.yml`, and `latest.yml` for stable;
`beta-mac.yml`, `beta-linux.yml`, and `beta.yml` for beta).
@@ -597,7 +633,7 @@ Pattern:
"timezone": "UTC",
"maxRuns": 120,
"expiresIn": "24h",
"prompt": "Resume the vX.Y.Z release babysit for commit <sha>. Check npm tags; CI and Desktop Packages on release/vX.Y.Z; every tag-triggered GitHub Actions run; the published GitHub Release body, expected desktop/APK assets, and channel manifests; the Docker image; the matching EAS workflow; and the reconcile PR into main. Completion requires every applicable checklist item. For stable, require build_ios, distribute_ios (Paseo Beta external distribution and Beta App Review submission), submit_ios_for_review, build_android, and submit_android to succeed. For beta, require the beta TestFlight distribution and Beta App Review path. If work is pending, wait for the next heartbeat. If a failure can be retried safely for the same version, follow the failed-release procedure; otherwise report the blocker. When every applicable completion-checklist item passes and the reconcile PR is merged, delete origin/release/vX.Y.Z, delete THIS heartbeat, report shipped, and stop.",
"prompt": "Resume the vX.Y.Z release babysit for commit <sha>. Check npm tags; CI and Desktop Packages on release/vX.Y.Z; every tag-triggered GitHub Actions run (Desktop Release, Android APK Release, Docker, Release Notes Sync, and Deploy App on stable) plus Deploy Website after release publish; the published GitHub Release body, expected desktop/APK assets, and channel manifests; the Docker image; the matching EAS workflow; and the reconcile PR into main. Completion requires every applicable checklist item. For stable, require build_ios, distribute_ios (Paseo Beta external distribution and Beta App Review submission), submit_ios_for_review, build_android, submit_android, and upload_android_screenshots to succeed, and inspect the submit_ios_for_review log for IOS_REVIEW_SKIPPED (if skipped, explicitly report both the in-review version and the waiting TestFlight build to the maintainer). For beta, require the beta TestFlight distribution and Beta App Review path. If work is pending, wait for the next heartbeat. If a failure can be retried safely for the same version, follow the failed-release procedure; otherwise report the blocker. When every applicable completion-checklist item passes and the reconcile PR is merged, delete origin/release/vX.Y.Z, delete THIS heartbeat, report shipped, and stop.",
}
```
@@ -622,6 +658,8 @@ The GitHub Release body is populated automatically by the `Release Notes Sync` w
**NEVER bump the version to fix a build problem.** New versions are reserved for meaningful product changes (features, fixes, improvements). Build/CI failures are fixed on the current version.
If `npm run release:publish` or `npm run release:publish:beta` fails after `npm run release:push` pushed the tag, fix the npm authentication, OTP, or local build issue and rerun the publish command on the same commit. Do not move or force-push the `v*` tag, because `scripts/publish-release-packages.mjs` skips packages already visible on npm and resumes from the remaining packages.
**Do not rely on `workflow_dispatch` for tagged code fixes.** The `workflow_dispatch` trigger runs the workflow file from the default branch but checks out the code at the tag ref (`ref: ${{ inputs.tag }}`). That means fixes committed to `main` won't change the tagged source tree being built. `workflow_dispatch` only helps when the fix lives in the workflow file itself.
For Docker-only retries, **do not push or force-push a `v*` release tag**.
@@ -706,9 +744,7 @@ intentionally unavailable to desktop updater clients.
- The npm `version` lifecycle regenerates F-Droid changelog files from `CHANGELOG.md` for stable releases only (`npm run fdroid:changelogs`) and stages them, so the release commit and tag carry them. Betas are a no-op. A stable run **aborts the release** if `CHANGELOG.md` has no entry for the version being cut — commit the changelog entry first. See [docs/android.md](android.md) for why these files are generated per ABI.
- `release:prepare` refreshes workspace `node_modules` links to prevent stale types.
- `npm run dev:desktop` and `npm run build:desktop` target the Electron desktop package in `packages/desktop`.
- `release:publish` and `release:publish:beta` run `scripts/publish-release-packages.mjs`: if a run
fails partway through, re-running skips versions already published on npm, retries transient
registry errors, and waits for each version to become visible on npm before continuing.
- `release:publish` and `release:publish:beta` run `scripts/publish-release-packages.mjs`. They publish the seven `@getpaseo/*` packages in dependency waves, skip versions already visible on npm, retry transient registry errors, and poll `npm view` between packages so dependents do not hit `E409` or `E404` propagation lag. `release:ship` and `release:ship:beta` run `release:push` before `release:publish` or `release:publish:beta`.
- The website uses GitHub's latest published release API for download links, so published beta prereleases do not replace the stable download target.
## Changelog format
@@ -969,8 +1005,8 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] The diff from the previous stable to the resolved release source is classified as patch or minor, with the target version and rationale approved
- [ ] `npm run release:prep:beta:patch`, `release:prep:beta:minor`, or `release:prep:beta:next` created the version commit on `release/vX.Y.Z-beta.N` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:ship:beta` published npm and pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run
- [ ] npm shows the version under the `beta` dist-tag, not `latest`
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z-beta.N` tag without triggering a second CI run, while `npm run release:publish:beta`, the `reconcile/vX.Y.Z-beta.N` PR, and the release heartbeat started in parallel
- [ ] All seven `@getpaseo/*` npm packages show the version under the `beta` dist-tag, not `latest`
- [ ] The GitHub prerelease was published only after the three beta manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] 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`
@@ -978,7 +1014,7 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] GitHub `Docker` workflow is green and the versioned beta image is published without moving `latest`
- [ ] GitHub `Release Notes Sync` mirrored the beta entry into the prerelease body
- [ ] EAS `Release iOS Beta` completed its build, TestFlight distribution, external beta group, and Beta App Review path
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main`, and `origin/release/vX.Y.Z-beta.N` was deleted
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries and version into `main` and merged before cleanup, and `origin/release/vX.Y.Z-beta.N` was deleted after all sync gates passed
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
### Stable release (or promotion)
@@ -988,13 +1024,13 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] The release base and changes match the [release base table](#release-base-and-source) and any approved [inventory](#release-inventory)
- [ ] A promotion ships the tested beta's product content after its soak, unless the user explicitly overrode either default
- [ ] Every PR in the release range has been opened, and its full description and every linked issue have been read before drafting the changelog
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes — not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
- [ ] Update `CHANGELOG.md` with user-facing release notes (features, fixes, not refactors). Promotion renames the series' `## X.Y.Z-beta.N` entry to `## X.Y.Z - YYYY-MM-DD` and re-checks it covers the full release. Commit the matching [`CHANGELOG.zh-CN.md` entry](#changelog-translations) with it
- [ ] Verify the changelog heading follows strict `## X.Y.Z - YYYY-MM-DD` format
- [ ] Ensure local format, lint, and typecheck pass and the working tree is clean before running `release:prep:*`
- [ ] `npm run release:prep:patch`, `release:prep:minor`, or `release:prep:promote` created the version commit on `release/vX.Y.Z` without a tag, and the pushed branch passed `CI` and `Desktop Packages` before shipping (never relying on `main` CI)
- [ ] Complete the [pre-release dependency checks](#pre-release-dependency-checks) on the release commit
- [ ] After go-ahead, `npm run release:ship` published npm, updated dist-tags, and pushed the `vX.Y.Z` tag without triggering a second CI run
- [ ] `latest` resolves to the new stable, and `beta` resolves to it too unless an active newer beta holds `beta`
- [ ] After go-ahead, `npm run release:push` pushed the `vX.Y.Z` tag without triggering a second CI run, while `npm run release:publish`, the `reconcile/vX.Y.Z` PR, and the release heartbeat started in parallel
- [ ] All seven `@getpaseo/*` npm packages show `latest` at the new stable, and `beta` at the new stable too unless an active newer beta holds `beta`
- [ ] The GitHub Release was published only after the three stable manifests were uploaded, and it has the changelog body and every expected macOS, Linux, Windows, and Android APK asset
- [ ] GitHub `Desktop Release` workflow for the `v*` tag is green
- [ ] The GitHub Release contains `latest-mac.yml`, `latest-linux.yml`, and `latest.yml`
@@ -1002,11 +1038,13 @@ Every entry covers `previous stable release → release source`: first beta, lat
- [ ] 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
- [ ] GitHub `Deploy App` workflow for the same tag is green, and `Deploy Website` succeeded after the release published
- [ ] EAS `Release Mobile` workflow for the same tag is green
- [ ] EAS iOS `build_ios` completes for the same tag
- [ ] EAS iOS `distribute_ios` succeeds, uploading the binary once, distributing it to `Paseo Beta`, and submitting it for Beta App Review
- [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review
- [ ] EAS iOS `submit_ios_for_review` succeeds, putting the build into App Store review (or its log was checked for `IOS_REVIEW_SKIPPED` and the maintainer was notified with both the in-review version and the waiting TestFlight build)
- [ ] EAS Android `build_android` completes for the same tag
- [ ] EAS Android `submit_android` succeeds, putting the build on its Play Store track
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries, F-Droid changelogs, and version into `main`, and `origin/release/vX.Y.Z` was deleted
- [ ] EAS Android `upload_android_screenshots` succeeds for the same tag
- [ ] The [reconcile PR](#reconcile-main) brought the shipped changelog entries, F-Droid changelogs, and version into `main` and merged before cleanup, and `origin/release/vX.Y.Z` was deleted after all sync gates passed
- [ ] The release heartbeat was created after the tag push and deleted only after every item above passed
+1 -1
View File
@@ -30,7 +30,7 @@ Terminal directory snapshots (`terminalsChanged`) and workspace contribution cha
Each `onChange` delivers both the new snapshot and the `previous` one (`{ state, changedAt }`). The transition flows unchanged up through `TerminalSession.onActivityChange` (as `{ activity, previous }`), the worker protocol's `terminalActivityChange` event, and the manager-level `subscribeTerminalActivity(listener)` stream (`{ terminalId, name, cwd, activity, previous }`).
The daemon consumes these transitions, not snapshots. When a transition moves from `working` to `idle`, the tracker records finished attention, so the terminal shows the same green finished dot as an idle agent that needs review. The websocket layer also fires a "Terminal finished" attention notification. A terminal that exits while still working emits no turn-end notification.
The daemon consumes these transitions, not snapshots. When a transition moves from `working` to `idle`, the tracker records finished attention, so the terminal shows the same green finished dot as an idle agent that needs review. Focusing the terminal tab or using Mark as read on its owning workspace clears finished attention. Mark as read leaves needs-input attention alone, the same way it leaves an agent's pending permission. The websocket layer also fires a "Terminal finished" attention notification. A terminal that exits while still working emits no turn-end notification.
Terminal list visibility is `workspaceId`-scoped: a terminal belongs to the workspace that created it, and same-`cwd` sibling workspaces do not see it in their terminal lists. Terminal status routing starts from that owning workspace, uses the owning workspace's `cwd`, then fans the status bucket out to every active workspace with the same `cwd`.
+11 -68
View File
@@ -5,9 +5,15 @@ Agent chat delivery has two paths:
1. **Live stream** — `agent_stream` WebSocket messages for immediacy. These may be delta-shaped lifecycle updates.
2. **Authoritative history** — `fetch_agent_timeline_request` for correctness. This always returns full projected timeline items, never lifecycle deltas.
Pagination bounds each read, not total resident history. Streaming overhead must remain
proportional to the retained transcript. Cumulative text snapshots must be released after their
deltas have been consumed.
The daemon retains projected items in memory. Each source event advances the stream sequence,
then replaces the previous tool state or merges into the current text item. Intermediate payloads
are never retained for history or catch-up. Provider history is the durable transcript authority
and rebuilds the projection when an agent resumes.
Pagination bounds each read, not total resident history. Active and idle agents retain their
projected transcript; archive releases it and later history reads rebuild it from the provider.
Streaming overhead must remain proportional to the retained transcript. Cumulative text snapshots
must be released after their deltas have been consumed.
The invariants are:
@@ -26,50 +32,6 @@ bounded item is used for runtime timeline rows and live stream events. Provider
applies the same rule so reopening an agent cannot restore an oversized payload. Fetches apply it
again to assistant and reasoning rows the projection merges from many chunks.
## Owned history
The daemon owns each agent's history in `AgentTimeline`
(`packages/server/src/server/agent/timeline/`): one ordered history per agent, with each provider
child's descriptor and history in a child scope of the same agent. Each source event advances the
stream sequence, then replaces the previous tool state or merges into the current text item.
Intermediate payloads are never retained for history or catch-up.
History is append-only: rewind, import, reload and archive never delete or rewrite a row. Only
deleting the agent, or a provider removing one of its own children, deletes history.
- **Rewind** retires a range of rows. They leave the conversation and stay stored, in the same
epoch. See [Rewind retires rows](#rewind-retires-rows).
- **Provider history** is imported only into an agent that has no history. After that, resume
does not read it. Reload agent and Unarchive require the provider history to start with the
same prompt IDs and text in order. They then append whole new turns, starting at the next
prompt. Existing replies, including partial replies, stay as recorded. If the prompts differ,
for example because the provider stored expanded attachment text, the chat stays unchanged and
Paseo reports a mismatch. A provider child Paseo already holds, listed or retired, is never imported again.
- **Archive and reload** keep the history and the provider children. An archived chat reads them
without its provider. Opening a stored agent that has no provider session to resume starts its
first session on the same history.
- **Delete** removes the agent's history and every child's, retired ones included, before the
agent record. If the history cannot be removed, the request fails and the agent stays listed. The
user can keep using it and delete it again.
`epoch` is the stored history's identity, minted once when the history is created.
`AgentTimeline` serializes every operation of one agent, child scopes included, and keeps its
state in an `AgentTimelineBackend`: the sequence, the rows and retirements, prompt identities, the
open rewind, and the children. The backend contract suite is `agent-timeline.test.ts`, run over
`TIMELINE_CONTRACT_BACKENDS` in `timeline/testing.ts`. The daemon uses the SQLite backend in the
[daemon database](data-model.md#daemon-database). History, retirements, the open rewind, and
provider children survive a daemon restart in the same epoch, so clients keep their cursors. A
closed or archived agent holds no history in memory. Each fetch reads the page from the database
and starts no provider. An internal agent, such as the one that writes a commit message, keeps its
history in a memory backend instead, so it leaves nothing on disk. The memory backend also serves
tests.
An open rewind is stored with the history. Resuming an agent whose history holds one settles it
before the agent takes prompts: a recorded provider cut is committed, and an unknown outcome is
judged from the resumed provider history. When that history proves nothing, the rewind stays open
and the agent refuses prompts with the unknown-outcome error.
## Presence is not delivery
Client heartbeat reports presence:
@@ -211,7 +173,7 @@ or retry backoff. This cannot keep a mobile socket alive after the operating sys
bookkeeping without replacing timeline arrays, preserving an upward-scrolled viewport.
- When the page overlaps or is adjacent to the local end cursor, only projected items newer than
that cursor are applied. Already-covered rows are not replayed.
- A true middle gap or epoch change atomically replaces stale canonical history with the
- A true middle gap, epoch change, or rewind atomically replaces stale canonical history with the
latest tail. The replacement reconciles positioned live rows beyond its coverage and unresolved
local submissions; it never retains two discontiguous canonical ranges.
@@ -224,24 +186,6 @@ history replay. The pending approval UI can hide that tool from presentation, bu
must retain its position. Creating a new history card on rejection places it after the prompt that
rejected it; changing steer-event ordering would also put new assistant output before that prompt.
## Rewind retires rows
A conversation rewind commits a retirement `{ seq, retireFromSeq }`: active rows anchored in
`[retireFromSeq, seq)` leave the conversation, and `seq` is the retirement's own position in the
sequence. The provider children spawned by retired tool calls, and their descendants, are retired
in the same commit. They leave the listing, keep their history, and drop late provider events.
Clients learn of a retirement live through `agent.timeline.rewind`, and on pages through
`retirements`, which lists the retirements whose `seq` lies inside the page's span. The client
drops the rows it holds in that range; rows without a timeline position are unechoed local sends
and stay. Retired ranges and the retirement's `seq` count as covered, so forward cursors advance
through them. Tail, before and prompt-jump pages are served from active rows, so one served before
a retirement the client already applied is stale and is refetched (`viewed-timeline-sync.ts`).
Clients without `timeline_rewind_operations` cannot drop retired rows. For them the session derives
a wire epoch that changes with each retirement, so they take the destructive replacement they
always took on rewind. The shim is tagged `COMPAT(timelineRewindOperations)`.
## Provider child history
Child transcripts use the same projected-page reconciliation as the main conversation. The client
@@ -419,7 +363,7 @@ the draft-create handoff is the one boundary that also permits the legacy canoni
arrived first. Generic reducers and consumers do not reimplement message identity matching.
Ordinary bootstrap, same-epoch reset, and catch-up replacement preserve unmatched locally submitted
rows because a provider may never echo them. A known epoch change replaces history and
rows because a provider may never echo them. A known epoch change or rewind replaces history and
drops acknowledged local rows omitted by the new canonical epoch; every transaction not yet
acknowledged by the provider, and no other local row, crosses that destructive boundary. A cold
reset without an existing epoch is destructive because the client has no continuity anchor.
@@ -435,7 +379,6 @@ canonical assistant prefix, it stays in the head lane. No row may be returned in
## Relevant code
- Server owned history: `packages/server/src/server/agent/timeline/`
- Server live stream forwarding: `packages/server/src/server/session.ts`
- App sync planning: `packages/app/src/timeline/timeline-sync-plan.ts`
- App viewed-agent synchronization: `packages/app/src/timeline/viewed-timeline-sync.ts`
@@ -0,0 +1,4 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,4 @@
- Remote workspace browser proxy: Desktop browser tabs in remote workspaces now route through the workspace daemon, so remote localhost servers open directly in Paseo.
- Per-device notification preferences: Each device can choose which agent, terminal, and plugin events send notifications, and plugins can send notifications and handle taps.
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,8 @@
- Host metadata instructions: Set host-wide instructions once to guide language, tone, and formatting for generated workspace titles, branch names, commit messages, and pull requests.
- Enterprise spending usage: Usage now shows Claude extra-usage spending and Codex individual spending limits with reset times.
Fixed
- Fixed Android agent push notifications arriving minutes late during Doze
- Fixed Command Center results reordering mid-word while typing
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,8 @@
- Host metadata instructions: Set host-wide instructions once to guide language, tone, and formatting for generated workspace titles, branch names, commit messages, and pull requests.
- Enterprise spending usage: Usage now shows Claude extra-usage spending and Codex individual spending limits with reset times.
Fixed
- Fixed Android agent push notifications arriving minutes late during Doze
- Fixed Command Center results reordering mid-word while typing
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,8 @@
- Host metadata instructions: Set host-wide instructions once to guide language, tone, and formatting for generated workspace titles, branch names, commit messages, and pull requests.
- Enterprise spending usage: Usage now shows Claude extra-usage spending and Codex individual spending limits with reset times.
Fixed
- Fixed Android agent push notifications arriving minutes late during Doze
- Fixed Command Center results reordering mid-word while typing
Full notes: https://paseo.sh/changelog
@@ -0,0 +1,8 @@
- Host metadata instructions: Set host-wide instructions once to guide language, tone, and formatting for generated workspace titles, branch names, commit messages, and pull requests.
- Enterprise spending usage: Usage now shows Claude extra-usage spending and Codex individual spending limits with reset times.
Fixed
- Fixed Android agent push notifications arriving minutes late during Doze
- Fixed Command Center results reordering mid-word while typing
Full notes: https://paseo.sh/changelog
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

+4 -1
View File
@@ -128,6 +128,8 @@ buildNpmPackage {
cd packages/desktop
# The Nix output is not a distributable DMG, so leave it unsigned and
# disable the hardened runtime that requires a matching signature.
# Compiling the Icon Composer document needs Xcode, which the build
# does not have, so use the prebuilt icns.
CSC_IDENTITY_AUTO_DISCOVERY=false \
npm exec --offline -- electron-builder \
--config electron-builder.yml \
@@ -138,7 +140,8 @@ buildNpmPackage {
--config.buildVersion=${lib.escapeShellArg buildVersion} \
--config.mac.identity=null \
--config.mac.hardenedRuntime=false \
--config.mac.notarize=false
--config.mac.notarize=false \
--config.mac.icon=assets/icon.icns
)
''}
+1 -1
View File
@@ -1 +1 @@
sha256-kzMT9+KlfYhaEa643XUTzxOA4Y8+zdpdXEs2QguED7w=
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
+30 -49
View File
@@ -1,12 +1,12 @@
{
"name": "paseo",
"version": "0.17.6",
"version": "0.18.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "paseo",
"version": "0.17.6",
"version": "0.18.1",
"hasInstallScript": true,
"license": "Apache-2.0",
"workspaces": [
@@ -45,9 +45,6 @@
"react-dom": "19.2.3",
"typescript": "^5.9.3",
"ws": "^8.20.0"
},
"engines": {
"node": ">=22.16.0"
}
},
"node_modules/@0no-co/graphql.web": {
@@ -37544,7 +37541,7 @@
},
"packages/app": {
"name": "@getpaseo/app",
"version": "0.17.6",
"version": "0.18.1",
"dependencies": {
"@codemirror/commands": "6.10.4",
"@codemirror/language": "6.12.4",
@@ -39697,13 +39694,13 @@
},
"packages/cli": {
"name": "@getpaseo/cli",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"@clack/prompts": "^1.0.0",
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/server": "0.17.6",
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/server": "0.18.1",
"chalk": "^5.3.0",
"commander": "^12.0.0",
"mime-types": "^2.1.35",
@@ -39722,9 +39719,6 @@
"typescript": "^5.2.2",
"vitest": "^4.1.6",
"zx": "^8.8.5"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/cli/node_modules/@vitest/expect": {
@@ -39953,11 +39947,11 @@
},
"packages/client": {
"name": "@getpaseo/client",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/relay": "0.18.1",
"ws": "^8.20.0",
"zod": "^4.4.3"
},
@@ -39969,7 +39963,7 @@
},
"packages/desktop": {
"name": "@getpaseo/desktop",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"@getpaseo/cli": "*",
@@ -40212,7 +40206,7 @@
},
"packages/expo-two-way-audio": {
"name": "@getpaseo/expo-two-way-audio",
"version": "0.17.6",
"version": "0.18.1",
"license": "MIT",
"devDependencies": {
"@types/jest": "^29.5.14",
@@ -40258,7 +40252,7 @@
},
"packages/highlight": {
"name": "@getpaseo/highlight",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"@codemirror/language": "6.12.4",
@@ -40288,7 +40282,7 @@
},
"packages/plugin": {
"name": "@getpaseo/plugin",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^1.4.0",
@@ -40296,8 +40290,8 @@
"use-sync-external-store": "^1.6.0"
},
"devDependencies": {
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@types/node": "^20.9.0",
"@types/react": "~19.2.0",
"react": "19.2.3",
@@ -40307,8 +40301,8 @@
"zod": "^4.4.3"
},
"peerDependencies": {
"@getpaseo/client": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/client": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"react": ">=19.1.0 <20",
"react-native": ">=0.81.5",
"zod": "^4.4.3"
@@ -40330,7 +40324,7 @@
},
"packages/protocol": {
"name": "@getpaseo/protocol",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"semver": "^7.8.5",
@@ -40357,7 +40351,7 @@
}
},
"packages/react-native-enriched-markdown": {
"version": "0.17.6",
"version": "0.18.1",
"hasInstallScript": true,
"license": "MIT",
"peerDependencies": {
@@ -40373,7 +40367,7 @@
},
"packages/relay": {
"name": "@getpaseo/relay",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"@noble/ciphers": "^2.4.0",
@@ -40595,17 +40589,17 @@
},
"packages/server": {
"name": "@getpaseo/server",
"version": "0.17.6",
"version": "0.18.1",
"license": "Apache-2.0",
"dependencies": {
"@agentclientprotocol/sdk": "^0.17.1",
"@anthropic-ai/claude-agent-sdk": "0.3.326",
"@anthropic-ai/sdk": "^0.104.2",
"@getpaseo/client": "0.17.6",
"@getpaseo/highlight": "0.17.6",
"@getpaseo/plugin": "0.17.6",
"@getpaseo/protocol": "0.17.6",
"@getpaseo/relay": "0.17.6",
"@getpaseo/client": "0.18.1",
"@getpaseo/highlight": "0.18.1",
"@getpaseo/plugin": "0.18.1",
"@getpaseo/protocol": "0.18.1",
"@getpaseo/relay": "0.18.1",
"@isaacs/ttlcache": "^2.1.4",
"@modelcontextprotocol/node": "2.1.2",
"@modelcontextprotocol/sdk": "1.29.0",
@@ -40653,7 +40647,7 @@
"@playwright/test": "^1.56.1",
"@types/express": "^4.17.20",
"@types/markdown-it": "^14.2.0",
"@types/node": "^22.16.0",
"@types/node": "^20.9.0",
"@types/qrcode": "^1.5.6",
"@types/uuid": "^9.0.7",
"@types/ws": "^8.5.8",
@@ -40661,9 +40655,6 @@
"cross-env": "^10.1.0",
"tsx": "^4.6.0",
"vitest": "^4.1.6"
},
"engines": {
"node": ">=22.16.0"
}
},
"packages/server/node_modules/@esbuild/aix-ppc64": {
@@ -41111,16 +41102,6 @@
"@types/mdurl": "^2"
}
},
"packages/server/node_modules/@types/node": {
"version": "22.20.5",
"resolved": "https://registry.npmjs.org/@types/node/-/node-22.20.5.tgz",
"integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~6.21.0"
}
},
"packages/server/node_modules/@vitest/expect": {
"version": "4.1.6",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.6.tgz",
@@ -41569,7 +41550,7 @@
},
"packages/website": {
"name": "@getpaseo/website",
"version": "0.17.6",
"version": "0.18.1",
"dependencies": {
"@cloudflare/vite-plugin": "^1.29.1",
"@cloudflare/workers-types": "^4.20260317.1",
@@ -43180,7 +43161,7 @@
},
"plugins": {
"name": "@getpaseo/builtin-plugins",
"version": "0.17.6",
"version": "0.18.1",
"dependencies": {
"@getpaseo/plugin": "*",
"zod": "^4.4.3"
+3 -6
View File
@@ -1,6 +1,6 @@
{
"name": "paseo",
"version": "0.17.6",
"version": "0.18.1",
"private": true,
"description": "Paseo: voice-controlled development environment for local AI coding agents",
"keywords": [
@@ -124,8 +124,8 @@
"release:publish": "node scripts/publish-release-packages.mjs",
"release:publish:beta": "node scripts/publish-release-packages.mjs --beta",
"release:push": "node scripts/push-current-release-tag.mjs",
"release:ship": "node scripts/push-current-release-tag.mjs --check && npm run release:publish && npm run release:push",
"release:ship:beta": "node scripts/push-current-release-tag.mjs --check && npm run release:publish:beta && npm run release:push",
"release:ship": "npm run release:push && npm run release:publish",
"release:ship:beta": "npm run release:push && npm run release:publish:beta",
"release:reconcile": "node scripts/reconcile-release.mjs"
},
"devDependencies": {
@@ -169,8 +169,5 @@
"tiny-async-pool": {
"semver@^5": "5.7.2"
}
},
"engines": {
"node": ">=22.16.0"
}
}
@@ -0,0 +1,27 @@
name: Cancel iOS App Store review
# Cancel an active in-flight iOS App Store review submission on App Store
# Connect. Pass expected_version to abort safely if Apple has already moved on
# to a different version.
on:
workflow_dispatch:
inputs:
expected_version:
type: string
required: false
description: "Expected marketing version currently in review, e.g. 0.18.0. Fails without cancelling if the active submission is for a different version."
jobs:
cancel_ios_review:
name: Cancel iOS App Store review
environment: production
runs_on: macos-medium
steps:
- uses: eas/checkout
- name: Install fastlane
run: bundle install
- name: Cancel review
run: |
export EXPECTED_VERSION="${{ inputs.expected_version }}"
bundle exec fastlane ios cancel_review
@@ -0,0 +1,20 @@
name: Check iOS App Store review status
# Inspect live App Store Connect state for sh.paseo: the live App Store
# version, any active or pending App Store versions, active review submissions,
# and the five most recently uploaded iOS TestFlight builds.
on:
workflow_dispatch: {}
jobs:
check_ios_review_status:
name: Check iOS App Store review status
environment: production
runs_on: macos-medium
steps:
- uses: eas/checkout
- name: Install fastlane
run: bundle install
- name: Check review status
run: bundle exec fastlane ios review_status
@@ -69,4 +69,5 @@ jobs:
run: |
export APP_VERSION="${{ needs.build_ios.outputs.app_version }}"
export APP_BUILD_VERSION="${{ needs.build_ios.outputs.app_build_version }}"
export REPLACE_IN_REVIEW="false"
bundle exec fastlane ios submit_review
@@ -1,9 +1,11 @@
name: Resubmit iOS for App Store review
# Standalone re-trigger for the App Store review submission step. The iOS
# binary is already uploaded to TestFlight via the EAS GitHub app's tag-push
# build; this workflow just runs the fastlane submit_review lane against the
# latest TestFlight build, without rebuilding or re-uploading.
# Standalone trigger for the App Store review submission step. The iOS binary
# is already uploaded to TestFlight via the EAS GitHub app's tag-push build;
# this workflow runs fastlane ios submit_review without rebuilding or
# re-uploading. By default (replace_in_review=false) it skips cleanly if
# another App Store review is already in flight; pass replace_in_review=true
# to cancel an in-flight review and submit an urgent replacement.
on:
workflow_dispatch:
@@ -16,6 +18,11 @@ on:
type: string
required: false
description: "CFBundleVersion to resubmit, e.g. 2. Only used when app_version is set."
replace_in_review:
type: boolean
required: false
default: false
description: "Cancel an in-flight App Store review and submit this build instead. Leave false to skip safely while another review is active."
jobs:
submit_ios_for_review:
@@ -30,4 +37,5 @@ jobs:
run: |
export APP_VERSION="${{ inputs.app_version }}"
export APP_BUILD_VERSION="${{ inputs.app_build_version }}"
export REPLACE_IN_REVIEW="${{ inputs.replace_in_review }}"
bundle exec fastlane ios submit_review
Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 62 KiB

After

Width:  |  Height:  |  Size: 31 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

After

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

After

Width:  |  Height:  |  Size: 43 KiB

@@ -13,13 +13,6 @@ import {
import { expectNearBottom, scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
import { holdRewindCompletion } from "../support/helpers/agent-timeline-gate";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
import {
closeWorkspaceAgentTab,
fetchAgentArchivedAt,
primeAdditionalPage,
resetSeededPageState,
} from "../support/helpers/archive-tab";
async function completeSubmittedTurn(
page: Page,
@@ -55,102 +48,26 @@ async function expectTurnCompletesNormally(
await expectAgentIdle(page);
}
async function openAgentOnAnotherClient(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await primeAdditionalPage(page);
await resetSeededPageState(page);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
}
/** The prompts the chat shows, in order, each exactly once. */
async function expectPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect(messages).toHaveCount(prompts.length);
await expect(messages).toContainText(prompts);
}
async function reloadAgentFromTabMenu(page: Page, agentId: string): Promise<void> {
const tabId = `workspace-tab-agent_${agentId}`;
await page.getByTestId(tabId).filter({ visible: true }).first().click({ button: "right" });
await page.getByTestId(`workspace-tab-context-agent_${agentId}-reload-agent`).click();
}
async function archiveAgentByClosingTab(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
): Promise<void> {
await closeWorkspaceAgentTab(page, agent.agentId);
await expect.poll(() => fetchAgentArchivedAt(agent.client, agent.agentId)).not.toBeNull();
}
async function unarchiveAgent(page: Page): Promise<void> {
await page.getByRole("button", { name: "Unarchive", exact: true }).click();
await expect(page.getByText("This agent is archived", { exact: true })).toHaveCount(0, {
timeout: 30_000,
});
}
async function expectToast(page: Page, message: string): Promise<void> {
await expect(page.getByTestId("app-toast-message")).toHaveText(message, { timeout: 30_000 });
}
// The mock provider's resumed session holds no history, so it never matches what Paseo shows.
const UNSYNCED_RELOAD =
"Reloaded agent, but the provider's history doesn't match this chat, so it wasn't synced";
/** The prompts of the whole conversation, after scrolling up through its older pages. */
async function expectConversationPrompts(page: Page, prompts: string[]): Promise<void> {
const messages = page.getByTestId("user-message");
await expect
.poll(async () => {
await userScrollsTimelineToHistoryStart(page);
return await messages.count();
})
.toBe(prompts.length);
await expect(messages).toContainText(prompts);
}
// A row React remounts loses this attribute; one that stays mounted keeps it.
async function markMounted(row: Locator): Promise<void> {
await row.evaluate((element) => element.setAttribute("data-e2e-mounted", "before-rewind"));
}
async function expectStillMounted(row: Locator): Promise<void> {
await expect(row).toHaveAttribute("data-e2e-mounted", "before-rewind");
}
test.describe("Agent message rewind", () => {
test("rewinds a prompt in place on every open client and keeps a human draft", async ({
test("rewinds a submitted prompt without replaying history and preserves a human draft", async ({
page,
}) => {
test.setTimeout(150_000);
test.setTimeout(90_000);
const retainedPrompt = "Keep this completed turn after rewind.";
const rewoundPrompt = "Remove this completed turn after rewind.";
const nextPrompt = "Continue after the rewind.";
const preservedDraft = "Keep this human draft after rewind.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-roundtrip-",
title: "Message rewind roundtrip",
model: "ten-second-stream",
});
const otherClient = await page.context().newPage();
try {
const rewindCompletion = await holdRewindCompletion(page, agent.agentId);
await openAgentRoute(page, agent);
await expectComposerVisible(page);
const retainedMessage = await completeSubmittedTurn(page, agent, retainedPrompt);
await completeSubmittedTurn(page, agent, retainedPrompt);
const userMessage = await completeSubmittedTurn(page, agent, rewoundPrompt);
await test.step("a second client opens the same chat", async () => {
await openAgentOnAnotherClient(otherClient, agent);
await expectPrompts(otherClient, [retainedPrompt, rewoundPrompt]);
});
await markMounted(retainedMessage);
await scrollChatAwayFromBottom(page, {
deltaY: -900,
minDistanceFromBottom: 300,
@@ -159,92 +76,19 @@ test.describe("Agent message rewind", () => {
await blurComposerInput(page);
rewindCompletion.clearTimelineStreamCount();
await test.step("the rewind stays pending until the daemon answers", async () => {
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
});
const rewind = rewindConversation(page, userMessage, rewoundPrompt);
await rewindCompletion.waitForDelayedResponse();
await expect(page.getByTestId("rewind-menu-conversation")).toBeDisabled();
expect(rewindCompletion.timelineStreamCount()).toBe(0);
rewindCompletion.release();
await rewind;
await test.step("the rewound turn leaves without reloading the chat", async () => {
await expectPrompts(page, [retainedPrompt]);
await expectStillMounted(retainedMessage);
expect(rewindCompletion.timelineFetchCount()).toBe(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
await expectPrompts(otherClient, [retainedPrompt]);
});
await test.step("the next prompt appears once on both clients", async () => {
await completeSubmittedTurn(otherClient, agent, nextPrompt);
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
await expectPrompts(page, [retainedPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the rewound conversation", async () => {
await otherClient.reload();
await expectPrompts(otherClient, [retainedPrompt, nextPrompt]);
});
} finally {
await otherClient.close();
await agent.cleanup();
}
});
test("keeps the rewound conversation through Reload agent, archive and unarchive", async ({
page,
}) => {
test.setTimeout(150_000);
const keptPrompt = "Keep this turn through reload and archive.";
const rewoundPrompt = "Rewind this turn before reloading.";
const nextPrompt = "Continue after the rewind, then reload.";
const agent = await seedMockAgentWorkspace({
repoPrefix: "message-rewind-reload-archive-",
title: "Message rewind reload archive",
model: "ten-second-stream",
});
try {
await openAgentRoute(page, agent);
await expectComposerVisible(page);
await completeSubmittedTurn(page, agent, keptPrompt);
const rewound = await completeSubmittedTurn(page, agent, rewoundPrompt);
await rewindConversation(page, rewound, rewoundPrompt);
await expectPrompts(page, [keptPrompt]);
await completeSubmittedTurn(page, agent, nextPrompt);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await test.step("Reload agent keeps the chat and says the provider's history was not synced", async () => {
await reloadAgentFromTabMenu(page, agent.agentId);
await expectToast(page, UNSYNCED_RELOAD);
await expectPrompts(page, [keptPrompt, nextPrompt]);
await expectComposerVisible(page);
});
await test.step("the archived chat shows the rewound conversation", async () => {
await archiveAgentByClosingTab(page, agent);
await openAgentRoute(page, agent);
await expect(page.getByText("This agent is archived", { exact: true })).toBeVisible({
timeout: 30_000,
});
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("unarchiving keeps the rewound conversation", async () => {
await unarchiveAgent(page);
await expectToast(page, UNSYNCED_RELOAD);
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await test.step("a reconnecting client loads the same conversation", async () => {
await page.reload();
await expectComposerVisible(page);
await expectConversationPrompts(page, [keptPrompt, nextPrompt]);
});
await expect(page.getByTestId("user-message").filter({ hasText: rewoundPrompt })).toHaveCount(
0,
);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectNearBottom(page);
} finally {
await agent.cleanup();
}
@@ -45,26 +45,6 @@ const PROFILE = {
const PROFILE_SUMMARY = "Mock Load Test · One minute stream · Approval test";
// Isolate this suite to the sole mock provider so it tests single-provider picker
// behavior deterministically regardless of which CLIs are installed on the host.
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
claude: { enabled: false },
codex: { enabled: false },
copilot: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
omp: { enabled: false },
antigravity: { enabled: false },
hoplite: { enabled: false },
},
},
},
});
test.describe("Agent profiles in the model picker", () => {
test("an empty host still exposes agent profile settings from the picker", async ({ page }) => {
const seed = await seedAgentProfiles([]);
@@ -89,8 +69,8 @@ test.describe("Agent profiles in the model picker", () => {
page,
}) => {
const seed = await seedAgentProfiles([PROFILE]);
// With only the mock provider enabled on this host, the picker opens
// directly into its models and shows its pinned profile.
// A live agent is one provider's process, so the profile has to name that
// same provider or the picker will not offer it at all.
const workspace = await seedMockAgentWorkspace({
repoPrefix: "agent-profiles-picker-",
title: "Agent profiles picker",
@@ -2,6 +2,7 @@ import type { Locator } from "@playwright/test";
import { test, expect, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { daemonWsRoutePattern } from "../support/helpers/daemon-port";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
@@ -142,6 +143,38 @@ test.describe("Command center workspace management", () => {
}
});
test("keeps Rename workspace ahead of Rename agent across renam and rename", async ({ page }) => {
const workspace = await seedMockAgentWorkspace({
repoPrefix: "cc-rename-order-",
title: "Command center rename order",
model: "five-minute-stream",
});
try {
await openAgentRoute(page, workspace);
const panel = await openCommandCenter(page);
const searchInput = panel.getByTestId("command-center-input");
const renameWorkspace = action(panel, "Rename workspace");
const renameAgent = action(panel, "Rename agent");
for (const query of ["renam", "rename"]) {
await searchInput.fill(query);
await expect(renameWorkspace).toBeVisible({ timeout: 15_000 });
await expect(renameAgent).toBeVisible({ timeout: 15_000 });
const workspaceTop = (await renameWorkspace.boundingBox())?.y ?? Number.NaN;
const agentTop = (await renameAgent.boundingBox())?.y ?? Number.NaN;
expect(workspaceTop, query).toBeLessThan(agentTop);
}
await page.keyboard.press("Enter");
await expect(page.getByTestId("workspace-rename-modal-global-input")).toBeFocused({
timeout: 15_000,
});
} finally {
await workspace.cleanup();
}
});
test("copies the workspace path and confirms with a toast", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "cc-copy-path-" });
@@ -12,9 +12,12 @@ import {
openImageLightbox,
closeImageLightbox,
pressInterruptShortcut,
blurComposerInput,
expectComposerDraft,
expectComposerDisabled,
expectComposerEditable,
expectComposerFocused,
expectComposerNotFocused,
expectAttachButtonDisabled,
fillComposerDraft,
dropFileOnComposer,
@@ -175,8 +178,19 @@ test.describe("Composer attachments", () => {
await test.step("remove the image and attach a dropped file", async () => {
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_JSON);
await expectAttachmentPill(page, "composer-file-attachment-pill");
await expectComposerFocused(page);
});
await test.step("dropping an image focuses the composer", async () => {
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_IMAGE);
await expectAttachmentPill(page, "composer-image-attachment-pill");
await expectComposerFocused(page);
});
});
@@ -198,9 +212,12 @@ test.describe("Composer attachments", () => {
projectDisplayName: workspace.projectDisplayName,
});
await blurComposerInput(page);
await expectComposerNotFocused(page);
await dropFileOnComposer(page, TEST_JSON);
await expectAttachmentPill(page, "composer-file-attachment-pill");
await expectComposerFocused(page);
} finally {
await workspace.cleanup();
}
@@ -12,14 +12,25 @@ import {
import { expectWorkspaceTabVisible, openSessions } from "../support/helpers/archive-tab";
import { daemonWsRoutePattern } from "../support/helpers/daemon-port";
import { getServerId } from "../support/helpers/server-id";
import { switchWorkspaceViaSidebar } from "../support/helpers/workspace-ui";
import {
switchWorkspaceViaSidebar,
waitForSidebarHydration,
} from "../support/helpers/workspace-ui";
import {
closeMobileAgentSidebar,
expectMobileAgentSidebarHidden,
expectMobileAgentSidebarVisible,
openMobileAgentSidebar,
} from "../support/helpers/sidebar";
import { expectNewWorkspaceProjectSelected } from "../support/helpers/new-workspace";
import {
expectNewWorkspaceProjectSelected,
openGlobalNewWorkspaceComposer,
openStartingRefPicker,
selectBranchInPicker,
selectWorkspaceIsolation,
} from "../support/helpers/new-workspace";
import { gotoAppShell } from "../support/helpers/app";
import { seedWorkspace } from "../support/helpers/seed-client";
const TEST_COMMANDS = [
{
@@ -119,11 +130,18 @@ const TEST_COMMANDS_REPLY: ListCommandsReply = { commands: TEST_COMMANDS, error:
async function installListCommandsStub(
page: Page,
reply: () => ListCommandsReply | Promise<ListCommandsReply> = () => TEST_COMMANDS_REPLY,
options?: {
onClientMessage?: (message: string | Buffer, forward: () => void) => void;
},
): Promise<void> {
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
if (options?.onClientMessage) {
options.onClientMessage(message, () => server.send(message));
return;
}
server.send(message);
});
@@ -169,6 +187,24 @@ async function installListCommandsStub(
});
}
async function holdWorkspaceCreateWithCommandsStub(page: Page): Promise<{ release: () => void }> {
let release: (() => void) | null = null;
await installListCommandsStub(page, undefined, {
onClientMessage(message, forward) {
if (typeof message === "string" && message.includes('"workspace.create.request"')) {
release = forward;
return;
}
forward();
},
});
return {
release: () => {
release?.();
},
};
}
function createHeldReply(): {
reply: () => Promise<ListCommandsReply>;
release: () => void;
@@ -450,6 +486,44 @@ test.describe("Composer autocomplete", () => {
}
});
test("shows autocomplete after closing the New Workspace branch picker and hides it while submitting", async ({
page,
}) => {
const heldCreate = await holdWorkspaceCreateWithCommandsStub(page);
const seeded = await seedWorkspace({ repoPrefix: "autocomplete-branch-picker-" });
try {
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openGlobalNewWorkspaceComposer(page);
const input = composerLocator(page);
await expect(input).toBeEditable({ timeout: 30_000 });
await selectWorkspaceIsolation(page, "worktree");
await expect(page.getByTestId("new-workspace-ref-picker-trigger")).toBeVisible({
timeout: 30_000,
});
await openStartingRefPicker(page);
await selectBranchInPicker(page, "main");
await expect(input).toBeFocused();
await page.keyboard.type("/h");
const popover = page.getByTestId("composer-autocomplete-popover");
await expect(popover.getByText("/help", { exact: true }).first()).toBeVisible({
timeout: 30_000,
});
// Submitting while locked hides the autocomplete popover instead of leaving it over loading.
await page.getByTestId("workspace-create-submit").click();
await expect(input).not.toBeEditable({ timeout: 10_000 });
await expect(popover).toHaveCount(0);
} finally {
heldCreate.release();
await seeded.cleanup();
}
});
test("keeps New workspace off the running-agent command list before a project is chosen", async ({
page,
}) => {
@@ -0,0 +1,235 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import {
openFileExplorer,
openFileFromExplorer,
expectFileTabOpen,
} from "../support/helpers/file-explorer";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const APP_SETTINGS_KEY = "@paseo:app-settings";
const DIFF_FIXTURE = [
"Here is a diff block:",
"",
"```diff",
"diff --git a/src/greet.ts b/src/greet.ts",
"--- a/src/greet.ts",
"+++ b/src/greet.ts",
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
" const prefix = 'Hello';",
"- return `${prefix}, ${name}`;",
"+ const trimmed = name.trim();",
"+ return `${prefix}, ${trimmed}!`;",
"```",
"",
"And a patch block:",
"",
"```patch",
"--- a/README.md",
"+++ b/README.md",
"@@ -1,2 +1,2 @@",
" # Paseo",
"-Old description",
"+New description",
"```",
"",
"Plus Ruby, Kotlin, TOML, and SQL:",
"",
"```ruby",
"class Greeter",
' def hi(name) = "Hello #{name}"',
"end",
"```",
"",
"```kotlin",
'val message: String = "Kotlin ready"',
"```",
"",
"```toml",
"[server]",
'host = "localhost"',
"```",
"",
"```sql",
"SELECT id, name FROM users WHERE active = TRUE;",
"```",
].join("\n");
const FILE_DIFF_CONTENT = [
"diff --git a/app.py b/app.py",
"index 1111111..2222222 100644",
"--- a/app.py",
"+++ b/app.py",
"@@ -1,3 +1,3 @@ def greet():",
" print('hello')",
"-old_value = 1",
"+new_value = 2",
].join("\n");
async function saveScreenshot(page: Page, name: string): Promise<void> {
const dir = process.env.PASEO_QA_SCREENSHOT_DIR;
if (!dir) return;
await mkdir(dir, { recursive: true });
await page.screenshot({ path: path.join(dir, name), fullPage: true });
}
function assistantMessages(page: Page) {
return page.locator("[data-message-id]").filter({ has: page.getByTestId("assistant-message") });
}
test.describe("diff and patch syntax highlighting", () => {
for (const theme of ["dark", "light"] as const) {
test(`highlights diff and patch fences in chat (${theme} theme)`, async ({ page }) => {
await page.addInitScript(
({ key, mode }) => {
localStorage.setItem(key, JSON.stringify({ theme: mode }));
},
{ key: APP_SETTINGS_KEY, mode: theme },
);
const agent = await seedMockAgentWorkspace({
repoPrefix: `diff-chat-${theme}-`,
title: `Diff highlight (${theme})`,
initialPrompt: "Show me the diff and patch.",
featureValues: { mockAssistantResponse: DIFF_FIXTURE },
});
try {
await agent.client.waitForAgentUpsert(
agent.agentId,
(snapshot) => snapshot.status === "idle",
30_000,
);
await openAgentRoute(page, agent);
const message = assistantMessages(page);
const expectedColors =
theme === "dark"
? {
addition: "rgb(152, 195, 121)",
deletion: "rgb(224, 108, 117)",
meta: "rgb(92, 99, 112)",
}
: {
addition: "rgb(52, 130, 51)",
deletion: "rgb(214, 59, 47)",
meta: "rgb(160, 161, 167)",
};
const diffAdd = message.getByText("+ const trimmed = name.trim();", { exact: true });
const diffDel = message.getByText("- return `${prefix}, ${name}`;", { exact: true });
const diffMeta = message.getByText(
"@@ -1,3 +1,4 @@ export function greet(name: string) {",
{
exact: true,
},
);
const patchAdd = message.getByText("+New description", { exact: true });
const patchDel = message.getByText("-Old description", { exact: true });
await expect(diffAdd).toBeVisible({ timeout: 30_000 });
await expect(diffAdd).toHaveCSS("color", expectedColors.addition);
await expect(diffDel).toHaveCSS("color", expectedColors.deletion);
await expect(diffMeta).toHaveCSS("color", expectedColors.meta);
await expect(patchAdd).toHaveCSS("color", expectedColors.addition);
await expect(patchDel).toHaveCSS("color", expectedColors.deletion);
const rubyDef = message.getByText("def", { exact: true });
const kotlinVal = message.getByText("val", { exact: true });
const tomlHost = message.getByText("host", { exact: true });
const sqlSelect = message.getByText("SELECT", { exact: true });
const expectedKeyword = theme === "dark" ? "rgb(198, 120, 221)" : "rgb(166, 38, 164)";
const expectedProperty = theme === "dark" ? "rgb(209, 154, 102)" : "rgb(152, 104, 1)";
await expect(rubyDef).toHaveCSS("color", expectedKeyword);
await expect(kotlinVal).toHaveCSS("color", expectedKeyword);
await expect(tomlHost).toHaveCSS("color", expectedProperty);
await expect(sqlSelect).toHaveCSS("color", expectedKeyword);
await saveScreenshot(page, `chat-diff-patch-${theme}.png`);
} finally {
await agent.cleanup();
}
});
}
test("highlights a .diff file in the Files viewer", async ({ page, withWorkspace }) => {
await page.addInitScript(
({ key }) => {
localStorage.setItem(key, JSON.stringify({ theme: "dark" }));
},
{ key: APP_SETTINGS_KEY },
);
const workspace = await withWorkspace({ prefix: "diff-file-viewer-" });
await writeFile(path.join(workspace.repoPath, "changes.diff"), FILE_DIFF_CONTENT);
await workspace.navigateTo();
await openFileExplorer(page);
await openFileFromExplorer(page, "changes.diff");
await expectFileTabOpen(page, "changes.diff");
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
await expect(editor).toBeVisible({ timeout: 30_000 });
const addLine = editor
.locator(".cm-line", { hasText: "+new_value = 2" })
.locator("span")
.first();
const delLine = editor
.locator(".cm-line", { hasText: "-old_value = 1" })
.locator("span")
.first();
const metaLine = editor
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
.locator("span")
.first();
await expect(addLine).toHaveCSS("color", "rgb(152, 195, 121)");
await expect(delLine).toHaveCSS("color", "rgb(224, 108, 117)");
await expect(metaLine).toHaveCSS("color", "rgb(92, 99, 112)");
await saveScreenshot(page, "files-viewer-diff-dark.png");
});
test("highlights a .patch file in the Files viewer (light theme)", async ({
page,
withWorkspace,
}) => {
await page.addInitScript(
({ key }) => {
localStorage.setItem(key, JSON.stringify({ theme: "light" }));
},
{ key: APP_SETTINGS_KEY },
);
const workspace = await withWorkspace({ prefix: "patch-file-viewer-" });
await writeFile(path.join(workspace.repoPath, "fix.patch"), FILE_DIFF_CONTENT);
await workspace.navigateTo();
await openFileExplorer(page);
await openFileFromExplorer(page, "fix.patch");
await expectFileTabOpen(page, "fix.patch");
const editor = page.getByTestId("file-source-editor").filter({ visible: true });
await expect(editor).toBeVisible({ timeout: 30_000 });
const addLine = editor
.locator(".cm-line", { hasText: "+new_value = 2" })
.locator("span")
.first();
const delLine = editor
.locator(".cm-line", { hasText: "-old_value = 1" })
.locator("span")
.first();
const metaLine = editor
.locator(".cm-line", { hasText: "@@ -1,3 +1,3 @@ def greet():" })
.locator("span")
.first();
await expect(addLine).toHaveCSS("color", "rgb(52, 130, 51)");
await expect(delLine).toHaveCSS("color", "rgb(214, 59, 47)");
await expect(metaLine).toHaveCSS("color", "rgb(160, 161, 167)");
await saveScreenshot(page, "files-viewer-patch-light.png");
});
});
@@ -111,3 +111,102 @@ test("replaces only the first configured metadata model", async ({ page }) => {
}
}
});
test("saves and clears host-wide metadata instructions without overwriting providers", async ({
page,
}, testInfo) => {
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previousConfig = await client.getDaemonConfig();
try {
await client.patchDaemonConfig({
metadataGeneration: {
providers: [{ provider: "mock", model: "ten-second-stream" }],
instructions: "",
},
});
await openMetadataGenerationSettings(page);
const instructionsRow = page.getByTestId("metadata-generation-instructions-row");
await expect(instructionsRow).toBeVisible();
await page.screenshot({
path: testInfo.outputPath("metadata-instructions-tucked-empty.png"),
fullPage: true,
});
await instructionsRow.click();
const instructionsSheet = page.getByTestId("metadata-generation-instructions-sheet");
const instructionsInput = page.getByTestId("metadata-generation-instructions-input");
const saveButton = page.getByTestId("metadata-generation-instructions-save");
await expect(instructionsSheet).toBeVisible();
await expect(saveButton).toBeDisabled();
await page.screenshot({
path: testInfo.outputPath("metadata-instructions-sheet-empty.png"),
fullPage: true,
animations: "disabled",
});
await instructionsInput.fill("Write in Simplified Chinese. Do not use em dashes.");
await expect(saveButton).toBeEnabled();
await saveButton.click();
await expect(instructionsSheet).toHaveCount(0);
await expect
.poll(async () => (await client.getDaemonConfig()).config.metadataGeneration)
.toEqual({
providers: [{ provider: "mock", model: "ten-second-stream" }],
instructions: "Write in Simplified Chinese. Do not use em dashes.",
});
await page.reload();
await expect(
page
.getByTestId("metadata-generation-instructions-row")
.getByText("Write in Simplified Chinese. Do not use em dashes."),
).toBeVisible();
await page.screenshot({
path: testInfo.outputPath("metadata-instructions-tucked-saved.png"),
fullPage: true,
});
// Verify compact layout keeps the tucked row and bottom sheet clean.
await page.setViewportSize({ width: 390, height: 844 });
await expect(page.getByTestId("metadata-generation-instructions-row")).toBeVisible();
await page.screenshot({
path: testInfo.outputPath("metadata-instructions-compact-row.png"),
fullPage: true,
});
await page.getByTestId("metadata-generation-instructions-row").click();
await expect(page.getByTestId("metadata-generation-instructions-input")).toHaveValue(
"Write in Simplified Chinese. Do not use em dashes.",
);
await page.screenshot({
path: testInfo.outputPath("metadata-instructions-compact-sheet.png"),
fullPage: true,
});
await page.getByTestId("metadata-generation-instructions-input").fill("");
await expect(page.getByTestId("metadata-generation-instructions-save")).toBeEnabled();
await page.getByTestId("metadata-generation-instructions-save").click();
await expect(page.getByTestId("metadata-generation-instructions-sheet")).toHaveCount(0);
await expect
.poll(async () => (await client.getDaemonConfig()).config.metadataGeneration)
.toEqual({
providers: [{ provider: "mock", model: "ten-second-stream" }],
});
} finally {
try {
await client.patchDaemonConfig({
metadataGeneration: {
providers: previousConfig.config.metadataGeneration.providers,
instructions: previousConfig.config.metadataGeneration.instructions ?? "",
},
});
} finally {
await client.close().catch(() => undefined);
}
}
});
@@ -6,6 +6,7 @@ import {
openStartingRefPicker,
selectBranchInPicker,
selectWorkspaceIsolation,
watchBrowserBranchSuggestions,
} from "../support/helpers/new-workspace";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
import { getServerId } from "../support/helpers/server-id";
@@ -16,6 +17,21 @@ const LONG_HOST_NAME =
"development-macbook-pro.local-connected-through-a-very-long-private-hostname";
const LONG_BRANCH_NAME =
"feat/app/add-amoled-theme-with-a-very-long-pull-request-and-branch-description";
const MANY_BRANCHES = Array.from(
{ length: 12 },
(_, index) => `feat/branch-${String(index + 1).padStart(2, "0")}`,
);
interface PopoverFrameSample {
t: number;
opacity: number;
top: number;
left: number;
width: number;
height: number;
rowCount: number;
mainTop: number | null;
}
function measureControlRightEdges(controls: HTMLElement[]) {
const measurements: Array<{ label: string | null; right: number }> = [];
@@ -26,13 +42,69 @@ function measureControlRightEdges(controls: HTMLElement[]) {
return measurements;
}
async function startPopoverFrameSampler(page: import("@playwright/test").Page): Promise<void> {
await page.evaluate(() => {
const win = window as unknown as {
__popoverFrames?: PopoverFrameSample[];
__popoverSamplerStop?: () => void;
};
const samples: PopoverFrameSample[] = [];
const start = performance.now();
let stopped = false;
let rafId = 0;
const tick = () => {
if (stopped) return;
const el = document.querySelector<HTMLElement>('[data-testid="combobox-desktop-container"]');
if (el) {
const style = getComputedStyle(el);
const opacity = Number.parseFloat(style.opacity || "1");
const rect = el.getBoundingClientRect();
const rows = el.querySelectorAll("[data-combobox-option-index]");
const mainEl = el.querySelector<HTMLElement>(
'[data-testid="new-workspace-ref-picker-branch-main"]',
);
samples.push({
t: Math.round(performance.now() - start),
opacity,
top: Math.round(rect.top),
left: Math.round(rect.left),
width: Math.round(rect.width),
height: Math.round(rect.height),
rowCount: rows.length,
mainTop: mainEl ? Math.round(mainEl.getBoundingClientRect().top) : null,
});
}
rafId = requestAnimationFrame(tick);
};
rafId = requestAnimationFrame(tick);
win.__popoverFrames = samples;
win.__popoverSamplerStop = () => {
stopped = true;
cancelAnimationFrame(rafId);
};
});
}
async function stopPopoverFrameSampler(
page: import("@playwright/test").Page,
): Promise<PopoverFrameSample[]> {
return page.evaluate(() => {
const win = window as unknown as {
__popoverFrames?: PopoverFrameSample[];
__popoverSamplerStop?: () => void;
};
win.__popoverSamplerStop?.();
return win.__popoverFrames ?? [];
});
}
test.describe("New workspace metadata row layout", () => {
let workspace: SeededWorkspace;
test.beforeEach(async () => {
workspace = await seedWorkspace({
repoPrefix: "new-workspace-layout-",
repo: { branches: [LONG_BRANCH_NAME] },
repo: { branches: [LONG_BRANCH_NAME, ...MANY_BRANCHES] },
});
});
@@ -84,4 +156,110 @@ test.describe("New workspace metadata row layout", () => {
).toBeLessThanOrEqual(composerRightRail + 1);
}
});
test("starting ref popover holds height and row positions on a cold first open", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 900 });
const branchWatch = await watchBrowserBranchSuggestions(page, { hold: true });
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectWorkspaceIsolation(page, "worktree");
await startPopoverFrameSampler(page);
await openStartingRefPicker(page);
const popover = page.getByTestId("combobox-desktop-container");
await expect(popover).toBeVisible({ timeout: 10_000 });
await branchWatch.waitForResponse();
// Give the loading state several frames to paint before releasing the branch list.
await page.waitForTimeout(120);
const loadingBox = await popover.boundingBox();
expect(loadingBox).not.toBeNull();
branchWatch.release();
await expect(page.getByTestId("new-workspace-ref-picker-branch-feat/branch-12")).toBeVisible({
timeout: 10_000,
});
await page.waitForTimeout(80);
const settledBox = await popover.boundingBox();
expect(settledBox).not.toBeNull();
const samples = await stopPopoverFrameSampler(page);
const visibleSamples = samples.filter((s) => s.opacity > 0.9);
expect(visibleSamples.length).toBeGreaterThan(0);
const heights = visibleSamples.map((s) => s.height);
const tops = visibleSamples.map((s) => s.top);
const mainTops = visibleSamples
.map((s) => s.mainTop)
.filter((value): value is number => value !== null);
expect(
Math.max(...heights) - Math.min(...heights),
`popover height shifted across visible frames: ${JSON.stringify(visibleSamples)}`,
).toBeLessThanOrEqual(1);
expect(
Math.max(...tops) - Math.min(...tops),
`popover top shifted across visible frames: ${JSON.stringify(visibleSamples)}`,
).toBeLessThanOrEqual(1);
expect(
mainTops.length > 0 ? Math.max(...mainTops) - Math.min(...mainTops) : 0,
`main row jumped vertically across visible frames: ${JSON.stringify(visibleSamples)}`,
).toBeLessThanOrEqual(1);
// Switching to Pull requests keeps the same frame height.
await page.getByTestId("new-workspace-ref-picker-tab-pull-requests").click();
await page.waitForTimeout(80);
const prBox = await popover.boundingBox();
expect(prBox).not.toBeNull();
expect(Math.abs(prBox!.height - settledBox!.height)).toBeLessThanOrEqual(1);
});
test("starting ref popover prefetches branches before the first click and clamps to short viewports", async ({
page,
}) => {
await page.setViewportSize({ width: 1280, height: 900 });
const branchWatch = await watchBrowserBranchSuggestions(page, { hold: false });
await gotoAppShell(page);
await waitForSidebarHydration(page);
await openNewWorkspaceComposer(page, {
projectKey: workspace.projectKey,
projectDisplayName: workspace.projectDisplayName,
});
await selectWorkspaceIsolation(page, "worktree");
// Branches must prefetch before the user ever clicks the trigger.
await branchWatch.waitForResponse();
await page.waitForTimeout(100);
await startPopoverFrameSampler(page);
await openStartingRefPicker(page);
await expect(page.getByTestId("new-workspace-ref-picker-branch-feat/branch-12")).toBeVisible({
timeout: 10_000,
});
await page.waitForTimeout(80);
const samples = await stopPopoverFrameSampler(page);
const firstVisible = samples.find((s) => s.opacity > 0.9);
expect(firstVisible).toBeDefined();
expect(firstVisible!.rowCount).toBeGreaterThan(5);
// Close and verify short viewport clamping keeps the popover inside the window.
await page.keyboard.press("Escape");
await page.setViewportSize({ width: 1280, height: 500 });
await openStartingRefPicker(page);
const popover = page.getByTestId("combobox-desktop-container");
await expect(popover).toBeVisible({ timeout: 10_000 });
await page.waitForTimeout(100);
const shortBox = await popover.boundingBox();
expect(shortBox).not.toBeNull();
expect(shortBox!.y + shortBox!.height).toBeLessThanOrEqual(500);
});
});
@@ -1,559 +0,0 @@
import { mkdir } from "node:fs/promises";
import path from "node:path";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { expectAgentIdle, expectAgentReadyToInterrupt } from "../support/helpers/agent-stream";
import {
drillIntoProvider,
expectComposerMode,
expectComposerModel,
openModelPicker,
selectModelRow,
} from "../support/helpers/agent-profiles";
import { expectWorkspaceAgentConfiguration } from "../support/helpers/command-center-agent-controls";
import {
expectComposerVisible,
expectQueuedMessageButton,
submitMessage,
submitMessageWithButton,
} from "../support/helpers/composer";
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
import { userScrollsTimelineToHistoryStart } from "../support/helpers/timeline-pagination";
const DIRECT_PROVIDER = {
id: "direct-example",
label: "Direct provider example",
pluginId: "provider-direct-example",
modelId: "example-1",
modelLabel: "Example 1",
modeLabel: "Build",
} as const;
// Disable external CLIs so the E2E host deterministically exposes only Mock +
// the installed Direct provider plugin on both developer machines and CI.
test.use({
e2eDaemonConfig: {
version: 1,
agents: {
providers: {
claude: { enabled: false },
codex: { enabled: false },
copilot: { enabled: false },
opencode: { enabled: false },
pi: { enabled: false },
omp: { enabled: false },
antigravity: { enabled: false },
hoplite: { enabled: false },
},
},
},
});
interface PluginInstallDaemonClient {
connect(): Promise<void>;
close(): Promise<void>;
getDaemonConfig(): Promise<{ config: { pluginsEnabled?: boolean } }>;
patchDaemonConfig(config: { pluginsEnabled?: boolean }): Promise<unknown>;
installDirectoryPlugin(directory: string): Promise<unknown>;
removePlugin(pluginId: string): Promise<void>;
getProvidersSnapshot(): Promise<{
entries: Array<{ provider: string; available?: boolean }>;
}>;
}
async function hasDirectProvider(client: PluginInstallDaemonClient): Promise<boolean> {
const snapshot = await client.getProvidersSnapshot();
return snapshot.entries.some((entry) => entry.provider === DIRECT_PROVIDER.id);
}
async function expectSwitchMarkerCountAfterScroll(page: Page, expected: number): Promise<void> {
await expect
.poll(
async () => {
await userScrollsTimelineToHistoryStart(page);
return await page.getByTestId("provider-switch-marker").count();
},
{ timeout: 30_000 },
)
.toBe(expected);
}
async function captureQaScreenshot(page: Page, fileName: string): Promise<void> {
const dir = process.env.PASEO_QA_SCREENSHOT_DIR?.trim();
if (!dir) return;
await mkdir(dir, { recursive: true });
await page.screenshot({ path: path.join(dir, fileName), fullPage: false });
}
async function expectNoHorizontalOverflow(page: Page): Promise<void> {
const overflow = await page.evaluate(() => {
const doc = document.documentElement;
return Math.ceil(doc.scrollWidth - doc.clientWidth);
});
expect(overflow).toBeLessThanOrEqual(1);
}
async function startSwitchOrderGuard(page: Page): Promise<void> {
await page.evaluate(() => {
const violations: string[] = [];
let stopped = false;
const step = () => {
const msgs = Array.from(document.querySelectorAll('[data-testid="user-message"]'));
const markers = Array.from(
document.querySelectorAll('[data-testid="provider-switch-marker"]'),
);
const banner = document.querySelector('[data-testid="staged-provider-switch-banner"]');
if (msgs.length >= 2) {
const secondMsg = msgs[msgs.length - 1];
const lastMarker = markers[markers.length - 1];
if (!lastMarker) {
violations.push("user-message painted without switch marker");
} else {
const msgRect = secondMsg.getBoundingClientRect();
const markerRect = lastMarker.getBoundingClientRect();
if (markerRect.top > msgRect.top) {
violations.push(
`switch marker painted below user-message (${Math.round(markerRect.top)} > ${Math.round(msgRect.top)})`,
);
}
}
if (banner && banner.getBoundingClientRect().height > 0) {
violations.push("staged-provider-switch-banner stayed visible after submit");
}
}
if (!stopped) requestAnimationFrame(step);
};
requestAnimationFrame(step);
(window as unknown as { __stopSwitchOrderGuard?: () => string[] }).__stopSwitchOrderGuard =
() => {
stopped = true;
return violations;
};
});
}
async function stopSwitchOrderGuard(page: Page): Promise<string[]> {
return await page.evaluate(
() =>
(
window as unknown as { __stopSwitchOrderGuard?: () => string[] }
).__stopSwitchOrderGuard?.() ?? [],
);
}
async function completeMockTurn(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
prompt: string,
): Promise<Locator> {
await submitMessage(page, prompt);
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(userMessage).toBeVisible({ timeout: 30_000 });
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finish.status).toBe("idle");
await expectAgentIdle(page);
await expect(userMessage).toHaveAttribute("aria-busy", "false");
return userMessage;
}
async function completeDirectTurn(
page: Page,
agent: Awaited<ReturnType<typeof seedMockAgentWorkspace>>,
prompt: string,
options?: { useSendButton?: boolean },
): Promise<Locator> {
if (options?.useSendButton) {
await submitMessageWithButton(page, prompt);
} else {
await submitMessage(page, prompt);
}
const userMessage = page.getByTestId("user-message").filter({ hasText: prompt });
await expect(userMessage).toBeVisible({ timeout: 30_000 });
const finish = await agent.client.waitForFinish(agent.agentId, 30_000);
expect(finish.status).toBe("idle");
await expectAgentIdle(page);
await expect(userMessage).toHaveAttribute("aria-busy", "false");
return userMessage;
}
async function stageProviderDesktop(
page: Page,
providerId: string,
modelId: string,
): Promise<void> {
await openModelPicker(page);
const picker = page.getByTestId("combobox-desktop-container");
const backButton = picker.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await drillIntoProvider(page, providerId);
await selectModelRow(page, { provider: providerId, modelId });
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
}
async function stageDirectProviderDesktop(page: Page): Promise<void> {
await stageProviderDesktop(page, DIRECT_PROVIDER.id, DIRECT_PROVIDER.modelId);
}
async function stageDirectProviderCompact(page: Page): Promise<void> {
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
await expect(page.getByTestId("agent-controls-model")).toBeVisible({ timeout: 30_000 });
await page.getByTestId("agent-controls-model").click();
const browserSheet = page.getByTestId("agent-controls-model-browser-sheet");
const browserViewport = page.getByTestId("agent-controls-model-browser-viewport");
await expect(browserViewport).toBeVisible({ timeout: 30_000 });
const backButton = browserSheet.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await browserViewport.getByTestId(`model-provider-${DIRECT_PROVIDER.id}`).click();
await browserViewport
.getByTestId(`model-row-${DIRECT_PROVIDER.id}-${DIRECT_PROVIDER.modelId}`)
.click();
await expect(browserViewport).toHaveCount(0, { timeout: 30_000 });
// Dismiss the outer agent-controls sheet so the composer and banner are ready to submit.
await page.getByRole("button", { name: "Close", exact: true }).last().click();
await expect(page.getByTestId("agent-controls-model")).toHaveCount(0, { timeout: 30_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toBeVisible({ timeout: 30_000 });
}
async function rewindConversation(page: Page, userMessage: Locator, prompt: string): Promise<void> {
await userMessage.getByText(prompt, { exact: true }).hover();
await userMessage.getByRole("button", { name: "Rewind to this message", exact: true }).click();
await page.getByRole("menuitem", { name: "Rewind conversation", exact: true }).click();
}
test.describe.serial("Provider switching in chat", () => {
let pluginClient: PluginInstallDaemonClient;
let pluginFixture: Awaited<ReturnType<typeof copyPluginExample>>;
let previousPluginsEnabled: boolean | undefined;
test.beforeAll(async () => {
pluginClient = await connectDaemonClient<PluginInstallDaemonClient>({
clientIdPrefix: "provider-switching-e2e",
});
pluginFixture = await copyPluginExample("provider-direct");
previousPluginsEnabled = (await pluginClient.getDaemonConfig()).config.pluginsEnabled;
await pluginClient.patchDaemonConfig({ pluginsEnabled: true });
await pluginClient.installDirectoryPlugin(pluginFixture.directory);
await expect.poll(() => hasDirectProvider(pluginClient), { timeout: 30_000 }).toBe(true);
});
test.afterAll(async () => {
await pluginClient?.removePlugin(DIRECT_PROVIDER.pluginId).catch(() => undefined);
await pluginClient
?.patchDaemonConfig({ pluginsEnabled: previousPluginsEnabled })
.catch(() => undefined);
await pluginClient?.close().catch(() => undefined);
await pluginFixture?.cleanup().catch(() => undefined);
});
test("stages, cancels, switches providers, inspects marker, scopes rewind, and survives reload", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const preSwitchPrompt = "First prompt on Mock before switching.";
const postSwitchPrompt = "Follow up on Direct provider after switching.";
const postRewindPrompt = "Continue on Direct provider after rewinding.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-desktop-",
title: "Provider switch desktop",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await expectComposerMode(page, "Load test");
const initialUrl = page.url();
await completeMockTurn(page, workspace, preSwitchPrompt);
await test.step("staging updates only draft state and Cancel restores the live provider", async () => {
await stageDirectProviderDesktop(page);
await expectComposerModel(page, DIRECT_PROVIDER.modelLabel);
await expectComposerMode(page, DIRECT_PROVIDER.modeLabel);
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText(
DIRECT_PROVIDER.label,
);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "e2e-fast-stream",
modeId: "load-test",
});
// Editing a staged provider option must keep all staged option controls visible.
const conciseToggle = page.getByRole("button", { name: /Concise responses/i }).first();
const voiceSelect = page.getByRole("button", { name: /Voice/i }).first();
await expect(conciseToggle).toBeVisible();
await expect(voiceSelect).toBeVisible();
await conciseToggle.click();
await expect(conciseToggle).toBeVisible();
await expect(voiceSelect).toBeVisible();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-staged-switch.png");
await page.getByTestId("cancel-staged-provider-switch").click();
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectComposerMode(page, "Load test");
// Returning to the live provider by choosing a different model clears the staged switch
// and applies the newly chosen model directly to the live provider.
await stageDirectProviderDesktop(page);
await openModelPicker(page);
const picker = page.getByTestId("combobox-desktop-container");
const backButton = picker.getByTestId("sheet-header-back");
if (await backButton.isVisible()) {
await backButton.click();
}
await drillIntoProvider(page, "mock");
await selectModelRow(page, { provider: "mock", modelId: "one-minute-stream" });
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectComposerModel(page, "One minute stream");
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "one-minute-stream",
modeId: "load-test",
});
});
await test.step("submitting commits the switch in place with clean user display text and inspectable marker", async () => {
await stageDirectProviderDesktop(page);
await startSwitchOrderGuard(page);
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt);
expect(await stopSwitchOrderGuard(page)).toEqual([]);
expect(page.url()).toBe(initialUrl);
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
// Clean display text: handoff summary must never leak into the visible user bubble.
await expect(switchedMessage).toContainText(postSwitchPrompt);
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
// Direct provider echoes its prompt, proving bounded pre-switch context was attached.
const directReply = page
.getByTestId("assistant-message")
.filter({ hasText: "Echo:" })
.last();
await expect(directReply).toContainText(preSwitchPrompt);
await expect(directReply).toContainText(postSwitchPrompt);
// Switch marker is visible and expands to show context handoff details.
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
await marker.getByTestId("provider-switch-marker-toggle").click();
const details = marker.getByTestId("provider-switch-marker-details");
await expect(details).toBeVisible();
await expect(details).toContainText("Mock");
await expect(details).toContainText(DIRECT_PROVIDER.label);
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "desktop-switched-expanded.png");
await marker.getByTestId("provider-switch-marker-toggle").click();
await expect(details).toHaveCount(0);
});
await test.step("switching back to Mock enforces segment-scoped rewind and preserves pre-switch turns", async () => {
const backToMockPrompt = "Switch back to Mock for segment-scoped rewind.";
await stageProviderDesktop(page, "mock", "ten-second-stream");
await expect(page.getByTestId("staged-provider-switch-banner")).toContainText("Mock");
const backToMockMessage = await completeMockTurn(page, workspace, backToMockPrompt);
await expect(backToMockMessage).not.toContainText("<chat-history-summary>");
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2, {
timeout: 30_000,
});
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Pre-switch prompts from earlier segments must not expose rewind even though Mock supports it.
const preSwitchMessage = page
.getByTestId("user-message")
.filter({ hasText: preSwitchPrompt });
await preSwitchMessage.scrollIntoViewIfNeeded();
await preSwitchMessage.getByText(preSwitchPrompt, { exact: true }).hover();
await expect(
preSwitchMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
const directMessage = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await directMessage.scrollIntoViewIfNeeded();
await directMessage.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
directMessage.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
// Post-switch prompt on Mock CAN rewind without retiring earlier segments or markers.
await backToMockMessage.scrollIntoViewIfNeeded();
await rewindConversation(page, backToMockMessage, backToMockPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: backToMockPrompt }),
).toHaveCount(0, { timeout: 30_000 });
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postSwitchPrompt }),
).toBeVisible();
await expect(page.getByTestId("provider-switch-marker")).toHaveCount(2);
// Continuing in the now-empty active segment completes cleanly.
const retriedMessage = await completeMockTurn(page, workspace, postRewindPrompt);
await expect(retriedMessage).not.toContainText("<chat-history-summary>");
});
await test.step("reload preserves the switched provider, markers, and rewind boundary", async () => {
await page.reload();
await expectComposerVisible(page);
await expectComposerModel(page, "Ten second stream");
await expectSwitchMarkerCountAfterScroll(page, 2);
const reloadedDirect = page
.getByTestId("user-message")
.filter({ hasText: postSwitchPrompt });
await expect(reloadedDirect).toBeVisible();
await expect(
page.getByTestId("user-message").filter({ hasText: postRewindPrompt }),
).toBeVisible();
await reloadedDirect.scrollIntoViewIfNeeded();
await reloadedDirect.getByText(postSwitchPrompt, { exact: true }).hover();
await expect(
reloadedDirect.getByRole("button", { name: "Rewind to this message", exact: true }),
).toHaveCount(0);
});
} finally {
await workspace.cleanup();
}
});
test("stages a switch mid-turn, queues the prompt, and switches cleanly between turns", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 1280, height: 800 });
const runningPrompt = "Run a ten-second mock turn first.";
const queuedPrompt = "Queued handoff prompt for Direct provider.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-midturn-",
title: "Provider switch midturn",
model: "ten-second-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessage(page, runningPrompt);
await expectAgentReadyToInterrupt(page);
// Stage Direct provider while Mock is actively streaming.
await stageDirectProviderDesktop(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: "mock",
model: "ten-second-stream",
modeId: "load-test",
});
// Submitting queues the prompt instead of racing the live turn.
await submitMessage(page, queuedPrompt);
await expectQueuedMessageButton(page);
// Once the mock turn completes, the queue drains and commits the switch.
await expect(page.getByTestId("provider-switch-marker")).toBeVisible({ timeout: 45_000 });
await expect(page.getByTestId("staged-provider-switch-banner")).toHaveCount(0, {
timeout: 30_000,
});
await expect(
page.getByTestId("assistant-message").filter({ hasText: queuedPrompt }).last(),
).toBeVisible({ timeout: 30_000 });
await expectAgentIdle(page);
await expectWorkspaceAgentConfiguration(workspace, {
id: workspace.agentId,
provider: DIRECT_PROVIDER.id,
model: DIRECT_PROVIDER.modelId,
modeId: "build",
});
} finally {
await workspace.cleanup();
}
});
test("switches providers cleanly on a compact viewport with zero horizontal overflow", async ({
page,
}) => {
test.setTimeout(150_000);
await page.setViewportSize({ width: 390, height: 844 });
const preSwitchPrompt = "Compact turn on Mock.";
const postSwitchPrompt = "Compact handoff on Direct.";
const workspace = await seedMockAgentWorkspace({
repoPrefix: "provider-switch-compact-",
title: "Provider switch compact",
model: "e2e-fast-stream",
modeId: "load-test",
});
try {
await openAgentRoute(page, workspace);
await expectComposerVisible(page);
await submitMessageWithButton(page, preSwitchPrompt);
await expect(
page.getByTestId("user-message").filter({ hasText: preSwitchPrompt }),
).toBeVisible({ timeout: 30_000 });
const firstFinish = await workspace.client.waitForFinish(workspace.agentId, 30_000);
expect(firstFinish.status).toBe("idle");
await expectAgentIdle(page);
await stageDirectProviderCompact(page);
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-staged-switch.png");
const switchedMessage = await completeDirectTurn(page, workspace, postSwitchPrompt, {
useSendButton: true,
});
await expect(switchedMessage).not.toContainText("<chat-history-summary>");
const marker = page.getByTestId("provider-switch-marker");
await expect(marker).toBeVisible({ timeout: 30_000 });
await marker.scrollIntoViewIfNeeded();
const toggle = marker.getByTestId("provider-switch-marker-toggle");
const toggleBox = await toggle.boundingBox();
expect(toggleBox).not.toBeNull();
expect((toggleBox?.x ?? 0) + (toggleBox?.width ?? 0)).toBeLessThanOrEqual(390);
await toggle.click();
await expect(marker.getByTestId("provider-switch-marker-details")).toBeVisible();
await marker.scrollIntoViewIfNeeded();
await expectNoHorizontalOverflow(page);
await captureQaScreenshot(page, "compact-switched-expanded.png");
} finally {
await workspace.cleanup();
}
});
});
@@ -235,7 +235,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 0);
await expectUserMessageCount(page, 1);
await expectComposerDraft(page, firstPrompt);
await expectComposerFocused(page);
@@ -243,7 +243,7 @@ test.describe("Rewind sheet", () => {
await expectUserMessageVisible(page, replacementPrompt);
await expect(userMessage(page, secondPrompt)).toHaveCount(0);
await expect(page.getByText("Cycle 1", { exact: true })).toHaveCount(0);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 2);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -254,19 +254,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, "");
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
const preservedDraft = "Keep this human draft after rewind.";
await fillComposerDraft(page, preservedDraft);
await composerLocator(page).evaluate((element) => element.blur());
await userMessage(page, replacementPrompt).hover();
await page.getByTestId("rewind-menu-trigger").last().click();
await expect(page.getByTestId("rewind-menu-content")).toBeVisible();
await selectRewindOption(page, "Rewind files");
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, preservedDraft);
await expectComposerNotFocused(page);
await expectUserMessageCount(page, 1);
await expectUserMessageCount(page, 2);
await fillComposerDraft(page, "");
await composerLocator(page).evaluate((element) => element.blur());
@@ -277,7 +265,7 @@ test.describe("Rewind sheet", () => {
await expect(page.getByTestId("rewind-menu-content")).toHaveCount(0);
await expectComposerDraft(page, replacementPrompt);
await expectComposerFocused(page);
await expectUserMessageCount(page, 0);
await expectUserMessageCount(page, 1);
} finally {
await session.cleanup();
}
@@ -31,8 +31,6 @@ export interface RewindCompletionGate {
clearTimelineStreamCount(): void;
release(): void;
timelineStreamCount(): number;
/** Timeline reads this page sent since the last clear. */
timelineFetchCount(): number;
waitForDelayedResponse(): Promise<void>;
}
@@ -188,20 +186,12 @@ export async function holdDaemonHydration(page: Page): Promise<DaemonHydrationGa
};
}
// The rewind response and the timeline change it causes; the change removes the rewound row too.
const REWIND_COMPLETION_MESSAGES = new Set([
"agent.rewind.response",
"agent.timeline.rewind",
"agent.timeline.replacement",
]);
export async function holdRewindCompletion(
page: Page,
agentId: string,
): Promise<RewindCompletionGate> {
let released = false;
let timelineStreamCount = 0;
let timelineFetchCount = 0;
const delayedForwards: Array<() => void> = [];
let resolveDelayedResponse: (() => void) | null = null;
const delayedResponse = new Promise<void>((resolve) => {
@@ -210,16 +200,7 @@ export async function holdRewindCompletion(
await page.routeWebSocket(daemonWsRoutePattern(), (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
if (
sessionMessage?.type === "fetch_agent_timeline_request" &&
sessionMessage.agentId === agentId
) {
timelineFetchCount += 1;
}
server.send(message);
});
ws.onMessage((message) => server.send(message));
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const payload = sessionMessage ? getPayload(sessionMessage) : null;
@@ -235,11 +216,11 @@ export async function holdRewindCompletion(
}
if (
!released &&
sessionMessage &&
REWIND_COMPLETION_MESSAGES.has(String(sessionMessage.type)) &&
(sessionMessage?.type === "agent.rewind.response" ||
sessionMessage?.type === "agent.timeline.replacement") &&
payload?.agentId === agentId
) {
// The rewind also signals completion and removes the rewound row/menu.
// The replacement also signals completion and removes the rewound row/menu.
// Hold it with the response so the pending-state assertion observes a pending rewind.
delayedForwards.push(() => ws.send(message));
if (sessionMessage.type === "agent.rewind.response") resolveDelayedResponse?.();
@@ -252,7 +233,6 @@ export async function holdRewindCompletion(
return {
clearTimelineStreamCount() {
timelineStreamCount = 0;
timelineFetchCount = 0;
},
release() {
released = true;
@@ -261,7 +241,6 @@ export async function holdRewindCompletion(
}
},
timelineStreamCount: () => timelineStreamCount,
timelineFetchCount: () => timelineFetchCount,
waitForDelayedResponse: () => delayedResponse,
};
}
@@ -739,6 +739,70 @@ export async function delayBrowserWorkspaceCreatedResponse(
};
}
export interface BranchSuggestionsControl {
release(): void;
waitForRequest(): Promise<void>;
waitForResponse(): Promise<void>;
}
/**
* Intercepts `branch_suggestions_request` / `branch_suggestions_response` frames over the daemon
* WebSocket. Pass `hold: true` to keep responses queued until `release()` is called, or `hold: false`
* to observe prefetched responses without delaying them.
*/
export async function watchBrowserBranchSuggestions(
page: Page,
options: { hold: boolean },
): Promise<BranchSuggestionsControl> {
const frames = await loadSessionMessageReaders();
const daemonPortPattern = daemonWsRoutePattern();
const delayedForwards: Array<() => void> = [];
let releaseRequested = !options.hold;
let resolveRequest: (() => void) | null = null;
let resolveResponse: (() => void) | null = null;
const requestSeen = new Promise<void>((resolve) => {
resolveRequest = resolve;
});
const responseSeen = new Promise<void>((resolve) => {
resolveResponse = resolve;
});
await page.routeWebSocket(daemonPortPattern, (ws) => {
const server = ws.connectToServer();
ws.onMessage((message) => {
const sessionMessage = frames.client(message);
if (sessionMessage?.type === "branch_suggestions_request") {
resolveRequest?.();
}
server.send(message);
});
server.onMessage((message) => {
const sessionMessage = frames.server(message);
if (sessionMessage?.type === "branch_suggestions_response") {
resolveResponse?.();
if (!releaseRequested) {
delayedForwards.push(() => ws.send(message));
return;
}
}
ws.send(message);
});
});
return {
release() {
releaseRequested = true;
for (const forward of delayedForwards.splice(0)) {
forward();
}
},
waitForRequest: () => requestSeen,
waitForResponse: () => responseSeen,
};
}
type WorkspaceEntry = Awaited<
ReturnType<NewWorkspaceDaemonClient["fetchWorkspaces"]>
>["entries"][number];
+65 -81
View File
@@ -1,5 +1,6 @@
require "fileutils"
require "tmpdir"
require_relative "ios_review"
default_platform(:ios)
@@ -42,8 +43,20 @@ def stage_google_play_screenshots
root
end
def connect_ios_review_client
client = IosReview::SpaceshipClient.new
client.authenticate!(
key_id: ENV.fetch("ASC_KEY_ID"),
issuer_id: ENV.fetch("ASC_ISSUER_ID"),
key_filepath: ENV.fetch("ASC_KEY_P8"),
)
app = client.find_app(APP_IDENTIFIER)
UI.user_error!("Could not find app #{APP_IDENTIFIER} on App Store Connect") if app.nil?
[client, app]
end
platform :ios do
desc "Submit the latest TestFlight build to App Store Review"
desc "Submit the latest TestFlight build to App Store Review (non-destructive by default)"
lane :submit_review do
api_key = app_store_connect_api_key(
key_id: ENV.fetch("ASC_KEY_ID"),
@@ -51,89 +64,60 @@ platform :ios do
key_filepath: ENV.fetch("ASC_KEY_P8"),
)
require "spaceship"
Spaceship::ConnectAPI.token = Spaceship::ConnectAPI::Token.create(
key_id: ENV.fetch("ASC_KEY_ID"),
issuer_id: ENV.fetch("ASC_ISSUER_ID"),
filepath: ENV.fetch("ASC_KEY_P8"),
client, app = connect_ios_review_client
IosReview.submit_review(
client: client,
app: app,
ui: UI,
target_version: ENV["APP_VERSION"],
target_build: ENV["APP_BUILD_VERSION"],
replace_in_review: IosReview.parse_bool(ENV["REPLACE_IN_REVIEW"]),
deliver_runner: lambda do |app_version:, build_number:, reject_if_possible:|
deliver(
api_key: api_key,
app_identifier: APP_IDENTIFIER,
app_version: app_version,
build_number: build_number.to_s,
submit_for_review: true,
automatic_release: true,
reject_if_possible: reject_if_possible,
release_notes: {
"en-US" => "Bug fixes and improvements.",
},
force: true,
skip_binary_upload: true,
screenshots_path: stage_app_store_screenshots,
overwrite_screenshots: true,
precheck_include_in_app_purchases: false,
submission_information: {
add_id_info_uses_idfa: false,
export_compliance_uses_encryption: false,
},
)
end,
)
app = Spaceship::ConnectAPI::App.find(APP_IDENTIFIER)
UI.user_error!("Could not find app #{APP_IDENTIFIER} on App Store Connect") if app.nil?
end
# The release workflow forwards the marketing version and CFBundleVersion of
# the binary it just built. Use them to identify the exact build, since
# CFBundleVersion is not unique across marketing versions in this project
# (the production profile resets it per app_version). The resubmit workflow
# leaves these unset and falls back to "most recently uploaded iOS build".
target_version = ENV["APP_VERSION"].to_s.strip
target_build = ENV["APP_BUILD_VERSION"].to_s.strip
target_version = nil if target_version.empty?
target_build = nil if target_build.empty?
if target_version
UI.message("Targeting App Store version #{target_version}#{target_build ? " build #{target_build}" : ""} from workflow input")
else
UI.message("No APP_VERSION provided; selecting the most recently uploaded iOS build")
end
valid_build = nil
deadline = Time.now + (30 * 60)
loop do
builds = Spaceship::ConnectAPI::Build.all(
app_id: app.id,
sort: "-uploadedDate",
limit: 100,
).select { |b| b.pre_release_version&.platform == "IOS" }
builds = builds.select { |b| b.pre_release_version&.version == target_version } if target_version
builds = builds.select { |b| b.version == target_build } if target_build
build = builds.first
if build.nil?
UI.user_error!("Timed out waiting for build to appear on App Store Connect.") if Time.now > deadline
UI.message("No matching iOS build visible on App Store Connect yet; waiting...")
sleep(30)
next
end
state = build.processing_state
UI.message("Build #{build.pre_release_version.version} (#{build.version}) processing state: #{state || 'unknown'}")
if state == "VALID"
valid_build = build
break
end
if state == "INVALID" || state == "FAILED"
UI.user_error!("Build #{build.version} failed App Store processing (state: #{state}).")
end
if Time.now > deadline
UI.user_error!("Timed out waiting for build #{build.version} to finish processing on App Store Connect.")
end
sleep(30)
end
app_version = valid_build.pre_release_version.version
build_number = valid_build.version
UI.message("Submitting build #{build_number} as App Store version #{app_version} for review")
deliver(
api_key: api_key,
desc "Print live App Store version, active/pending versions, review submissions, and recent TestFlight builds"
lane :review_status do
client, app = connect_ios_review_client
IosReview.review_status(
client: client,
app: app,
ui: UI,
app_identifier: APP_IDENTIFIER,
app_version: app_version,
build_number: build_number.to_s,
submit_for_review: true,
automatic_release: true,
reject_if_possible: true,
release_notes: {
"en-US" => "Bug fixes and improvements.",
},
force: true,
skip_binary_upload: true,
screenshots_path: stage_app_store_screenshots,
overwrite_screenshots: true,
precheck_include_in_app_purchases: false,
submission_information: {
add_id_info_uses_idfa: false,
export_compliance_uses_encryption: false,
},
)
end
desc "Cancel the active in-flight iOS App Store review submission"
lane :cancel_review do
client, app = connect_ios_review_client
IosReview.cancel_review(
client: client,
app: app,
ui: UI,
expected_version: ENV["EXPECTED_VERSION"],
)
end
end
+635
View File
@@ -0,0 +1,635 @@
# frozen_string_literal: true
module IosReview
PLATFORM_IOS = "IOS"
# Valid App Store Connect API v1 filter[appVersionState] values (fastlane 2.241.1
# Spaceship::ConnectAPI::AppStoreVersion::AppVersionState) that block a new
# App Store review submission.
BLOCKING_API_VERSION_STATES = %w[
WAITING_FOR_REVIEW
IN_REVIEW
PENDING_DEVELOPER_RELEASE
PENDING_APPLE_RELEASE
PROCESSING_FOR_DISTRIBUTION
WAITING_FOR_EXPORT_COMPLIANCE
ACCEPTED
].freeze
# In-memory check also recognizes the deprecated AppStoreState alias
# PROCESSING_FOR_APP_STORE (never sent in filter[appVersionState]).
BLOCKING_VERSION_STATES = (BLOCKING_API_VERSION_STATES + %w[
PROCESSING_FOR_APP_STORE
]).freeze
# Valid filter[appVersionState] values shown in review_status under active/pending versions.
ACTIVE_API_VERSION_STATES = (BLOCKING_API_VERSION_STATES + %w[
PREPARE_FOR_SUBMISSION
READY_FOR_REVIEW
DEVELOPER_REJECTED
REJECTED
METADATA_REJECTED
INVALID_BINARY
]).freeze
# ReviewSubmission states representing an active submission already in Apple's queue
# (or mid-cancellation). UNRESOLVED_ISSUES is intentionally excluded here so a
# rejected version's free slot is not treated as an in-flight review; stale
# UNRESOLVED_ISSUES submissions are cleared separately right before deliver runs.
IN_FLIGHT_SUBMISSION_STATES = %w[
WAITING_FOR_REVIEW
IN_REVIEW
CANCELING
].freeze
UNRESOLVED_SUBMISSION_STATES = %w[
UNRESOLVED_ISSUES
].freeze
# ReviewSubmission states that can be cancelled via ReviewSubmission#cancel_submission
# (or waited on if already CANCELING).
CANCELLABLE_SUBMISSION_STATES = %w[
WAITING_FOR_REVIEW
IN_REVIEW
UNRESOLVED_ISSUES
CANCELING
].freeze
STATUS_SUBMISSION_STATES = %w[
WAITING_FOR_REVIEW
IN_REVIEW
UNRESOLVED_ISSUES
CANCELING
READY_FOR_REVIEW
].freeze
DEFAULT_BUILD_TIMEOUT_SECONDS = 30 * 60
DEFAULT_BUILD_POLL_INTERVAL = 30
DEFAULT_CANCEL_TIMEOUT_SECONDS = 5 * 60
DEFAULT_CANCEL_POLL_INTERVAL = 15
# Thin adapter around Spaceship::ConnectAPI (fastlane 2.241.1).
# Injected into IosReview operations so all workflow logic is unit-testable
# against in-memory fakes without requiring live ASC credentials.
class SpaceshipClient
def authenticate!(key_id:, issuer_id:, key_filepath:)
require "spaceship"
Spaceship::ConnectAPI.token = Spaceship::ConnectAPI::Token.create(
key_id: key_id,
issuer_id: issuer_id,
filepath: key_filepath,
)
end
def find_app(bundle_id)
Spaceship::ConnectAPI::App.find(bundle_id)
end
def live_version(app)
app.get_live_app_store_version(platform: PLATFORM_IOS, includes: "build")
end
def ios_versions(app, states:)
app.get_app_store_versions(
filter: {
platform: PLATFORM_IOS,
appVersionState: states.join(","),
},
includes: "build",
)
end
def get_app_store_version(app_store_version_id)
Spaceship::ConnectAPI::AppStoreVersion.get(
app_store_version_id: app_store_version_id,
includes: "build",
)
end
def review_submissions(app, states:)
app.get_review_submissions(
filter: {
platform: PLATFORM_IOS,
state: states.join(","),
},
includes: "appStoreVersionForReview",
)
end
def get_review_submission(review_submission_id)
Spaceship::ConnectAPI::ReviewSubmission.get(
review_submission_id: review_submission_id,
includes: "appStoreVersionForReview",
)
end
def cancel_review_submission(submission)
submission.cancel_submission
end
def find_ios_builds(app, version: nil, build_number: nil)
if version.nil? && build_number.nil?
return recent_ios_builds(app, limit: 25)
end
Spaceship::ConnectAPI::Build.all(
app_id: app.id,
version: version,
build_number: build_number,
platform: PLATFORM_IOS,
sort: "-uploadedDate",
limit: 100,
)
end
def recent_ios_builds(app, limit: 5)
fetch_limit = [limit * 4, 25].max
builds = Spaceship::ConnectAPI.get_builds(
filter: { app: app.id },
includes: "preReleaseVersion",
sort: "-uploadedDate",
limit: fetch_limit,
).to_models
builds.select { |b| b.pre_release_version&.platform == PLATFORM_IOS }.first(limit)
end
end
module_function
def parse_bool(value)
value.to_s.strip.casecmp("true").zero?
end
def normalize_optional_string(value)
str = value.to_s.strip
str.empty? ? nil : str
end
def version_state(version)
return nil if version.nil?
state = version.respond_to?(:app_version_state) ? version.app_version_state : nil
state = nil if state.to_s.strip.empty?
return state unless state.nil?
fallback = version.respond_to?(:app_store_state) ? version.app_store_state : nil
fallback.to_s.strip.empty? ? nil : fallback
end
def blocking_version_state?(state)
BLOCKING_VERSION_STATES.include?(state.to_s)
end
def sort_versions_descending(versions)
versions.sort_by do |version|
begin
Gem::Version.new(version.version_string.to_s)
rescue ArgumentError
Gem::Version.new("0")
end
end.reverse
end
def find_blocking_review(client:, app:)
versions = client.ios_versions(app, states: BLOCKING_API_VERSION_STATES)
.select { |v| blocking_version_state?(version_state(v)) }
if !versions.empty?
version = sort_versions_descending(versions).first
return {
source: :app_store_version,
version: version.version_string,
state: version_state(version),
build: version.respond_to?(:build) ? version.build&.version : nil,
version_record: version,
}
end
submissions = client.review_submissions(app, states: IN_FLIGHT_SUBMISSION_STATES)
.select { |s| IN_FLIGHT_SUBMISSION_STATES.include?(s.state.to_s) }
if !submissions.empty?
submission = submissions.first
assoc_version = submission.respond_to?(:app_store_version_for_review) ? submission.app_store_version_for_review : nil
return {
source: :review_submission,
version: assoc_version&.version_string || "unknown",
state: submission.state,
build: assoc_version&.respond_to?(:build) ? assoc_version.build&.version : nil,
submission: submission,
version_record: assoc_version,
}
end
nil
end
def wait_for_valid_build(
client:,
app:,
target_version:,
target_build:,
ui:,
timeout_seconds: DEFAULT_BUILD_TIMEOUT_SECONDS,
poll_interval: DEFAULT_BUILD_POLL_INTERVAL,
sleep_fn: Kernel.method(:sleep),
clock: Time.method(:now)
)
if target_version
ui.message("Targeting App Store version #{target_version}#{target_build ? " build #{target_build}" : ""} from workflow input")
else
ui.message("No APP_VERSION provided; selecting the most recently uploaded iOS build")
end
deadline = clock.call + timeout_seconds
loop do
builds = client.find_ios_builds(app, version: target_version, build_number: target_build)
.select { |b| b.pre_release_version&.platform == PLATFORM_IOS }
builds = builds.select { |b| b.pre_release_version&.version == target_version } if target_version
builds = builds.select { |b| b.version.to_s == target_build.to_s } if target_build
build = builds.first
if build.nil?
if clock.call >= deadline
ui.user_error!("Timed out waiting for build to appear on App Store Connect.")
end
ui.message("No matching iOS build visible on App Store Connect yet; waiting...")
sleep_fn.call(poll_interval)
next
end
state = build.processing_state
ui.message("Build #{build.pre_release_version.version} (#{build.version}) processing state: #{state || 'unknown'}")
return build if state == "VALID"
if state == "INVALID" || state == "FAILED"
ui.user_error!("Build #{build.version} failed App Store processing (state: #{state}).")
end
if clock.call >= deadline
ui.user_error!("Timed out waiting for build #{build.version} to finish processing on App Store Connect.")
end
sleep_fn.call(poll_interval)
end
end
def resolve_waiting_build_summary(client:, app:, target_version:, target_build:)
return [target_version, target_build] if target_version && target_build
builds = client.find_ios_builds(app, version: target_version, build_number: target_build)
.select { |b| b.pre_release_version&.platform == PLATFORM_IOS }
builds = builds.select { |b| b.pre_release_version&.version == target_version } if target_version
builds = builds.select { |b| b.version.to_s == target_build.to_s } if target_build
latest = builds.first
[
target_version || latest&.pre_release_version&.version || "unknown",
target_build || latest&.version&.to_s || "unknown",
]
end
def submit_review(
client:,
app:,
ui:,
deliver_runner:,
target_version: nil,
target_build: nil,
replace_in_review: false,
build_timeout_seconds: DEFAULT_BUILD_TIMEOUT_SECONDS,
build_poll_interval: DEFAULT_BUILD_POLL_INTERVAL,
cancel_timeout_seconds: DEFAULT_CANCEL_TIMEOUT_SECONDS,
cancel_poll_interval: DEFAULT_CANCEL_POLL_INTERVAL,
sleep_fn: Kernel.method(:sleep),
clock: Time.method(:now)
)
target_version = normalize_optional_string(target_version)
target_build = normalize_optional_string(target_build)
blocking = find_blocking_review(client: client, app: app)
if blocking && !replace_in_review
return emit_skipped_result(
client: client,
app: app,
ui: ui,
blocking: blocking,
target_version: target_version,
target_build: target_build,
)
end
valid_build = wait_for_valid_build(
client: client,
app: app,
target_version: target_version,
target_build: target_build,
ui: ui,
timeout_seconds: build_timeout_seconds,
poll_interval: build_poll_interval,
sleep_fn: sleep_fn,
clock: clock,
)
app_version = valid_build.pre_release_version.version
build_number = valid_build.version.to_s
if replace_in_review
cancel_result = cancel_review(
client: client,
app: app,
ui: ui,
expected_version: nil,
timeout_seconds: cancel_timeout_seconds,
poll_interval: cancel_poll_interval,
sleep_fn: sleep_fn,
clock: clock,
)
if cancel_result[:status] == :canceled
ui.message("Proceeding to submit replacement build #{build_number} as App Store version #{app_version}")
end
else
# Re-check after waiting for TestFlight processing so a review submitted
# in the meantime is never disturbed.
post_wait_blocking = find_blocking_review(client: client, app: app)
if post_wait_blocking
return emit_skipped_result(
client: client,
app: app,
ui: ui,
blocking: post_wait_blocking,
target_version: app_version,
target_build: build_number,
)
end
# Fastlane's Deliver::SubmitForReview#create_review_submission fails if a
# prior rejected ReviewSubmission remains in UNRESOLVED_ISSUES. Clear only
# UNRESOLVED_ISSUES submissions here while keeping reject_if_possible: false
# so an in-flight WAITING_FOR_REVIEW or IN_REVIEW submission is never cancelled.
clear_unresolved_issues_submissions(
client: client,
app: app,
ui: ui,
timeout_seconds: cancel_timeout_seconds,
poll_interval: cancel_poll_interval,
sleep_fn: sleep_fn,
clock: clock,
)
end
ui.message("Submitting build #{build_number} as App Store version #{app_version} for review (reject_if_possible=#{replace_in_review})")
deliver_runner.call(
app_version: app_version,
build_number: build_number,
reject_if_possible: replace_in_review,
)
{
status: :submitted,
app_version: app_version,
build_number: build_number,
reject_if_possible: replace_in_review,
}
end
def emit_skipped_result(client:, app:, ui:, blocking:, target_version:, target_build:)
waiting_version, waiting_build = resolve_waiting_build_summary(
client: client,
app: app,
target_version: target_version,
target_build: target_build,
)
summary = "IOS_REVIEW_SKIPPED in_review_version=#{blocking[:version]} in_review_state=#{blocking[:state]} waiting_version=#{waiting_version} waiting_build=#{waiting_build}"
ui.important(summary)
ui.message(
"Leaving iOS App Store version #{blocking[:version]} (#{blocking[:state]}) untouched. " \
"TestFlight build #{waiting_version} (#{waiting_build}) is ready to submit later via " \
"resubmit-ios-review.yml (or with replace_in_review=true to replace the in-flight review).",
)
{
status: :skipped,
summary: summary,
in_review_version: blocking[:version],
in_review_state: blocking[:state],
waiting_version: waiting_version,
waiting_build: waiting_build,
}
end
def clear_unresolved_issues_submissions(
client:,
app:,
ui:,
timeout_seconds: DEFAULT_CANCEL_TIMEOUT_SECONDS,
poll_interval: DEFAULT_CANCEL_POLL_INTERVAL,
sleep_fn: Kernel.method(:sleep),
clock: Time.method(:now)
)
stale_submissions = client.review_submissions(app, states: UNRESOLVED_SUBMISSION_STATES)
.select { |s| UNRESOLVED_SUBMISSION_STATES.include?(s.state.to_s) }
stale_submissions.each do |submission|
assoc_version = submission.respond_to?(:app_store_version_for_review) ? submission.app_store_version_for_review : nil
ui.message(
"Clearing stale rejected review submission #{submission.id} " \
"(version #{assoc_version&.version_string || 'unknown'}, state: #{submission.state}) before submitting...",
)
client.cancel_review_submission(submission)
wait_for_submission_cancellation(
client: client,
submission: submission,
assoc_version: assoc_version,
ui: ui,
timeout_seconds: timeout_seconds,
poll_interval: poll_interval,
sleep_fn: sleep_fn,
clock: clock,
)
end
end
def wait_for_submission_cancellation(
client:,
submission:,
assoc_version:,
ui:,
timeout_seconds:,
poll_interval:,
sleep_fn:,
clock:
)
deadline = clock.call + timeout_seconds
final_submission_state = submission.state
final_version_state = version_state(assoc_version)
loop do
refreshed = client.get_review_submission(submission.id)
final_submission_state = refreshed ? refreshed.state : "COMPLETE"
submission_done = refreshed.nil? || !CANCELLABLE_SUBMISSION_STATES.include?(refreshed.state.to_s)
version_done = true
if assoc_version&.id
refreshed_version = client.get_app_store_version(assoc_version.id)
final_version_state = version_state(refreshed_version) || final_version_state
version_done = !%w[WAITING_FOR_REVIEW IN_REVIEW].include?(final_version_state.to_s)
end
return [final_submission_state, final_version_state] if submission_done && version_done
if clock.call >= deadline
ui.user_error!(
"Timed out waiting for iOS review submission #{submission.id} cancellation to complete " \
"(submission_state=#{final_submission_state}, version_state=#{final_version_state || 'unknown'}).",
)
end
ui.message("Waiting for cancellation to take effect (submission=#{final_submission_state}, version=#{final_version_state || 'unknown'})...")
sleep_fn.call(poll_interval)
end
end
def cancel_review(
client:,
app:,
ui:,
expected_version: nil,
timeout_seconds: DEFAULT_CANCEL_TIMEOUT_SECONDS,
poll_interval: DEFAULT_CANCEL_POLL_INTERVAL,
sleep_fn: Kernel.method(:sleep),
clock: Time.method(:now)
)
expected_version = normalize_optional_string(expected_version)
submissions = client.review_submissions(app, states: CANCELLABLE_SUBMISSION_STATES)
.select { |s| CANCELLABLE_SUBMISSION_STATES.include?(s.state.to_s) }
blocking_versions = client.ios_versions(app, states: BLOCKING_API_VERSION_STATES)
.select { |v| blocking_version_state?(version_state(v)) }
if submissions.empty?
non_cancellable = sort_versions_descending(blocking_versions).first
if non_cancellable
state = version_state(non_cancellable)
ui.user_error!(
"Cannot cancel iOS App Store version #{non_cancellable.version_string} (state: #{state}): " \
"no cancellable review submission is in progress on App Store Connect.",
)
end
suffix = expected_version ? " expected_version=#{expected_version}" : ""
summary = "IOS_REVIEW_CANCEL_NOOP reason=no_active_review#{suffix}"
ui.message(summary)
ui.message("No iOS App Store review submission is currently in flight.")
return { status: :noop, summary: summary }
end
submission = submissions.first
assoc_version = submission.respond_to?(:app_store_version_for_review) ? submission.app_store_version_for_review : nil
if assoc_version.nil?
assoc_version = sort_versions_descending(blocking_versions).find do |v|
%w[WAITING_FOR_REVIEW IN_REVIEW].include?(version_state(v))
end
end
active_version = assoc_version&.version_string
if expected_version && active_version != expected_version
ui.user_error!(
"Refusing to cancel iOS review: expected version #{expected_version}, " \
"but active review submission #{submission.id} is for version #{active_version || 'unknown'} (state: #{submission.state}).",
)
end
if submission.state == "CANCELING"
ui.message("Review submission #{submission.id} (version #{active_version || 'unknown'}) is already CANCELING; waiting for completion...")
else
ui.message("Cancelling iOS review submission #{submission.id} for version #{active_version || 'unknown'} (state: #{submission.state})...")
client.cancel_review_submission(submission)
end
final_submission_state, final_version_state = wait_for_submission_cancellation(
client: client,
submission: submission,
assoc_version: assoc_version,
ui: ui,
timeout_seconds: timeout_seconds,
poll_interval: poll_interval,
sleep_fn: sleep_fn,
clock: clock,
)
summary = "IOS_REVIEW_CANCELED version=#{active_version || 'unknown'} submission_id=#{submission.id} submission_state=#{final_submission_state} version_state=#{final_version_state || 'unknown'}"
ui.success(summary)
{
status: :canceled,
summary: summary,
version: active_version,
submission_id: submission.id,
submission_state: final_submission_state,
version_state: final_version_state,
}
end
def review_status(client:, app:, ui:, app_identifier: "sh.paseo", recent_build_limit: 5)
live = client.live_version(app)
active_versions = sort_versions_descending(
client.ios_versions(app, states: ACTIVE_API_VERSION_STATES),
)
active_submissions = client.review_submissions(app, states: STATUS_SUBMISSION_STATES)
recent_builds = client.recent_ios_builds(app, limit: recent_build_limit)
lines = ["=== iOS App Store Review Status (#{app_identifier}) ==="]
lines << "Live App Store version:"
if live
lines << format_version_line(live)
else
lines << " (none)"
end
lines << "Active / pending App Store versions:"
if active_versions.empty?
lines << " (none)"
else
active_versions.each { |v| lines << format_version_line(v) }
end
lines << "Active review submissions:"
if active_submissions.empty?
lines << " (none)"
else
active_submissions.each do |s|
assoc = s.respond_to?(:app_store_version_for_review) ? s.app_store_version_for_review : nil
submitted = s.respond_to?(:submitted_date) && s.submitted_date ? s.submitted_date : "none"
lines << " id=#{s.id} | version=#{assoc&.version_string || 'unknown'} | state=#{s.state} | submitted_date=#{submitted}"
end
end
lines << "Recent iOS TestFlight builds (top #{recent_build_limit}):"
if recent_builds.empty?
lines << " (none)"
else
recent_builds.each_with_index do |b, idx|
ver = b.pre_release_version&.version || "unknown"
lines << " #{idx + 1}. version=#{ver} | build=#{b.version} | processing_state=#{b.processing_state || 'unknown'} | uploaded_date=#{b.uploaded_date || 'unknown'}"
end
end
report = lines.join("\n")
ui.message(report)
{
live_version: live,
active_versions: active_versions,
active_submissions: active_submissions,
recent_builds: recent_builds,
report: report,
}
end
def format_version_line(version)
state = version_state(version) || "unknown"
build_number = version.respond_to?(:build) ? version.build&.version : nil
" version=#{version.version_string} | state=#{state} | build=#{build_number || 'none'}"
end
end
+595
View File
@@ -0,0 +1,595 @@
# frozen_string_literal: true
require "minitest/autorun"
require_relative "ios_review"
class IosReviewTest < Minitest::Test
FakeApp = Struct.new(:id, :bundle_id, keyword_init: true)
FakePreReleaseVersion = Struct.new(:version, :platform, keyword_init: true)
FakeBuild = Struct.new(:version, :processing_state, :uploaded_date, :pre_release_version, keyword_init: true)
FakeAppStoreVersion = Struct.new(:id, :version_string, :app_version_state, :app_store_state, :build, keyword_init: true)
FakeReviewSubmission = Struct.new(:id, :state, :submitted_date, :app_store_version_for_review, keyword_init: true)
class FakeUserError < StandardError; end
class FakeUI
attr_reader :messages, :importants, :successes
def initialize
@messages = []
@importants = []
@successes = []
end
def message(text)
@messages << text
end
def important(text)
@importants << text
end
def success(text)
@successes << text
end
def user_error!(text)
raise FakeUserError, text
end
end
class FakeClock
attr_reader :now
def initialize(start = 1_000)
@now = start
end
def call
@now
end
def advance(seconds)
@now += seconds
end
end
# In-memory fake matching the SpaceshipClient surface.
class FakeClient
attr_accessor :live_version_record, :versions, :submissions, :builds
attr_reader :canceled_submission_ids, :queried_version_state_filters, :queried_submission_state_filters
def initialize(
live_version_record: nil,
versions: [],
submissions: [],
builds: [],
submission_poll_states: nil,
version_poll_states: nil
)
@live_version_record = live_version_record
@versions = versions
@submissions = submissions
@builds = builds
@submission_poll_states = submission_poll_states || {}
@version_poll_states = version_poll_states || {}
@canceled_submission_ids = []
@queried_version_state_filters = []
@queried_submission_state_filters = []
end
def live_version(_app)
@live_version_record
end
def ios_versions(_app, states:)
@queried_version_state_filters << states
@versions.select do |v|
state = IosReview.version_state(v)
states.include?(state) || (state == "PROCESSING_FOR_APP_STORE" && states.include?("PROCESSING_FOR_DISTRIBUTION"))
end
end
def get_app_store_version(app_store_version_id)
version = @versions.find { |v| v.id == app_store_version_id }
return nil if version.nil?
queue = @version_poll_states[app_store_version_id]
if queue && !queue.empty?
next_state = queue.shift
version.app_version_state = next_state
end
version
end
def review_submissions(_app, states:)
@queried_submission_state_filters << states
@submissions.select { |s| states.include?(s.state) }
end
def get_review_submission(review_submission_id)
submission = @submissions.find { |s| s.id == review_submission_id }
return nil if submission.nil?
queue = @submission_poll_states[review_submission_id]
if queue && !queue.empty?
submission.state = queue.shift
end
submission
end
def cancel_review_submission(submission)
@canceled_submission_ids << submission.id
submission.state = "CANCELING"
submission
end
def find_ios_builds(_app, version: nil, build_number: nil)
result = @builds.select { |b| b.pre_release_version&.platform == "IOS" }
result = result.select { |b| b.pre_release_version&.version == version } if version
result = result.select { |b| b.version.to_s == build_number.to_s } if build_number
result
end
def recent_ios_builds(_app, limit: 5)
@builds.select { |b| b.pre_release_version&.platform == "IOS" }.first(limit)
end
end
def setup
@app = FakeApp.new(id: "app-1", bundle_id: "sh.paseo")
@ui = FakeUI.new
@clock = FakeClock.new
@sleep_fn = lambda { |seconds| @clock.advance(seconds) }
end
def make_build(version, build_number, processing_state: "VALID", uploaded_date: "2026-11-27T10:00:00Z", platform: "IOS")
FakeBuild.new(
version: build_number,
processing_state: processing_state,
uploaded_date: uploaded_date,
pre_release_version: FakePreReleaseVersion.new(version: version, platform: platform),
)
end
def test_submit_review_skips_when_blocking_version_is_in_flight_by_default
blocking_states = %w[
WAITING_FOR_REVIEW
IN_REVIEW
PENDING_DEVELOPER_RELEASE
PENDING_APPLE_RELEASE
PROCESSING_FOR_DISTRIBUTION
PROCESSING_FOR_APP_STORE
WAITING_FOR_EXPORT_COMPLIANCE
ACCEPTED
]
blocking_states.each do |state|
ui = FakeUI.new
in_flight = if state == "PROCESSING_FOR_APP_STORE"
FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: nil, app_store_state: state)
else
FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: state)
end
client = FakeClient.new(
versions: [in_flight],
builds: [make_build("0.18.1", "18001999")],
)
deliver_calls = []
result = IosReview.submit_review(
client: client,
app: @app,
ui: ui,
target_version: "0.18.1",
target_build: "18001999",
replace_in_review: false,
deliver_runner: ->(args) { deliver_calls << args },
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :skipped, result[:status], "Expected skip for blocking state #{state}"
assert_equal "0.18.0", result[:in_review_version]
assert_equal state, result[:in_review_state]
assert_equal "0.18.1", result[:waiting_version]
assert_equal "18001999", result[:waiting_build]
assert_empty client.canceled_submission_ids, "Must never cancel when replace_in_review is false (#{state})"
assert_empty deliver_calls, "Must not invoke deliver when skipping (#{state})"
assert_includes ui.importants.first, "IOS_REVIEW_SKIPPED in_review_version=0.18.0 in_review_state=#{state} waiting_version=0.18.1 waiting_build=18001999"
end
end
def test_submit_review_never_sends_deprecated_app_store_state_in_api_filter
client = FakeClient.new(
versions: [FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "READY_FOR_DISTRIBUTION")],
builds: [make_build("0.18.1", "18001999")],
)
IosReview.submit_review(
client: client,
app: @app,
ui: @ui,
target_version: "0.18.1",
target_build: "18001999",
replace_in_review: false,
deliver_runner: ->(_args) {},
sleep_fn: @sleep_fn,
clock: @clock,
)
client.queried_version_state_filters.each do |states|
refute_includes states, "PROCESSING_FOR_APP_STORE"
refute_includes states, "READY_FOR_SALE"
end
end
def test_submit_review_skips_and_resolves_latest_testflight_build_when_inputs_unset
in_flight = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "IN_REVIEW")
client = FakeClient.new(
versions: [in_flight],
builds: [make_build("0.18.2", "18002999")],
)
deliver_calls = []
result = IosReview.submit_review(
client: client,
app: @app,
ui: @ui,
target_version: "",
target_build: "",
replace_in_review: false,
deliver_runner: ->(args) { deliver_calls << args },
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :skipped, result[:status]
assert_equal "0.18.2", result[:waiting_version]
assert_equal "18002999", result[:waiting_build]
assert_empty client.canceled_submission_ids
assert_empty deliver_calls
assert_includes @ui.importants.first, "IOS_REVIEW_SKIPPED in_review_version=0.18.0 in_review_state=IN_REVIEW waiting_version=0.18.2 waiting_build=18002999"
end
def test_submit_review_auto_submits_when_slot_is_free
free_states = %w[
READY_FOR_DISTRIBUTION
READY_FOR_SALE
PREPARE_FOR_SUBMISSION
DEVELOPER_REJECTED
REJECTED
METADATA_REJECTED
]
free_states.each do |state|
ui = FakeUI.new
existing = FakeAppStoreVersion.new(
id: "v-1",
version_string: "0.18.0",
app_version_state: state == "READY_FOR_SALE" ? nil : state,
app_store_state: state == "READY_FOR_SALE" ? state : nil,
)
client = FakeClient.new(
versions: [existing],
builds: [make_build("0.18.1", "18001999")],
)
deliver_calls = []
result = IosReview.submit_review(
client: client,
app: @app,
ui: ui,
target_version: "0.18.1",
target_build: "18001999",
replace_in_review: false,
deliver_runner: ->(args) { deliver_calls << args },
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :submitted, result[:status], "Expected auto-submit when state is #{state}"
assert_equal false, result[:reject_if_possible]
assert_empty client.canceled_submission_ids
assert_equal [{ app_version: "0.18.1", build_number: "18001999", reject_if_possible: false }], deliver_calls
end
end
def test_submit_review_clears_stale_unresolved_issues_submission_on_rejected_version_by_default
rejected = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "REJECTED")
stale_submission = FakeReviewSubmission.new(
id: "sub-rejected",
state: "UNRESOLVED_ISSUES",
app_store_version_for_review: rejected,
)
client = FakeClient.new(
versions: [rejected],
submissions: [stale_submission],
builds: [make_build("0.18.1", "18001999")],
submission_poll_states: { "sub-rejected" => %w[CANCELING COMPLETE] },
version_poll_states: { "v-1" => %w[REJECTED DEVELOPER_REJECTED] },
)
deliver_calls = []
result = IosReview.submit_review(
client: client,
app: @app,
ui: @ui,
target_version: "0.18.1",
target_build: "18001999",
replace_in_review: false,
deliver_runner: ->(args) { deliver_calls << args },
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :submitted, result[:status]
assert_equal false, result[:reject_if_possible]
assert_equal ["sub-rejected"], client.canceled_submission_ids
assert_equal "COMPLETE", stale_submission.state
assert_equal [{ app_version: "0.18.1", build_number: "18001999", reject_if_possible: false }], deliver_calls
end
def test_submit_review_skips_if_review_starts_while_waiting_for_build_processing
processing_build = make_build("0.18.1", "18001999", processing_state: "PROCESSING")
client = FakeClient.new(versions: [], submissions: [], builds: [processing_build])
deliver_calls = []
sleep_and_start_review = lambda do |seconds|
@clock.advance(seconds)
processing_build.processing_state = "VALID"
client.versions << FakeAppStoreVersion.new(id: "v-race", version_string: "0.18.0", app_version_state: "WAITING_FOR_REVIEW")
end
result = IosReview.submit_review(
client: client,
app: @app,
ui: @ui,
target_version: "0.18.1",
target_build: "18001999",
replace_in_review: false,
deliver_runner: ->(args) { deliver_calls << args },
sleep_fn: sleep_and_start_review,
clock: @clock,
)
assert_equal :skipped, result[:status]
assert_equal "0.18.0", result[:in_review_version]
assert_equal "WAITING_FOR_REVIEW", result[:in_review_state]
assert_empty client.canceled_submission_ids
assert_empty deliver_calls
assert_includes @ui.importants.first, "IOS_REVIEW_SKIPPED in_review_version=0.18.0 in_review_state=WAITING_FOR_REVIEW waiting_version=0.18.1 waiting_build=18001999"
end
def test_submit_review_with_replace_in_review_cancels_after_validating_build_and_passes_reject_if_possible
in_flight_version = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "IN_REVIEW")
submission = FakeReviewSubmission.new(id: "sub-1", state: "IN_REVIEW", app_store_version_for_review: in_flight_version)
client = FakeClient.new(
versions: [in_flight_version],
submissions: [submission],
builds: [make_build("0.18.1", "18001999", processing_state: "VALID")],
submission_poll_states: { "sub-1" => %w[CANCELING COMPLETE] },
version_poll_states: { "v-1" => %w[IN_REVIEW DEVELOPER_REJECTED] },
)
deliver_calls = []
result = IosReview.submit_review(
client: client,
app: @app,
ui: @ui,
target_version: "0.18.1",
target_build: "18001999",
replace_in_review: true,
deliver_runner: ->(args) { deliver_calls << args },
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :submitted, result[:status]
assert_equal true, result[:reject_if_possible]
assert_equal ["sub-1"], client.canceled_submission_ids
assert_equal "DEVELOPER_REJECTED", in_flight_version.app_version_state
assert_equal [{ app_version: "0.18.1", build_number: "18001999", reject_if_possible: true }], deliver_calls
end
def test_submit_review_with_replace_in_review_does_not_cancel_if_replacement_build_is_invalid
in_flight_version = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "WAITING_FOR_REVIEW")
submission = FakeReviewSubmission.new(id: "sub-1", state: "WAITING_FOR_REVIEW", app_store_version_for_review: in_flight_version)
client = FakeClient.new(
versions: [in_flight_version],
submissions: [submission],
builds: [make_build("0.18.1", "18001999", processing_state: "INVALID")],
)
deliver_calls = []
error = assert_raises(FakeUserError) do
IosReview.submit_review(
client: client,
app: @app,
ui: @ui,
target_version: "0.18.1",
target_build: "18001999",
replace_in_review: true,
deliver_runner: ->(args) { deliver_calls << args },
sleep_fn: @sleep_fn,
clock: @clock,
)
end
assert_match(/failed App Store processing/, error.message)
assert_empty client.canceled_submission_ids, "Must not cancel active review if replacement build is INVALID"
assert_empty deliver_calls
end
def test_cancel_review_cancels_active_submission_and_logs_resulting_state
in_flight_version = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "WAITING_FOR_REVIEW")
submission = FakeReviewSubmission.new(id: "sub-99", state: "WAITING_FOR_REVIEW", app_store_version_for_review: in_flight_version)
client = FakeClient.new(
versions: [in_flight_version],
submissions: [submission],
submission_poll_states: { "sub-99" => %w[CANCELING COMPLETE] },
version_poll_states: { "v-1" => %w[WAITING_FOR_REVIEW DEVELOPER_REJECTED] },
)
result = IosReview.cancel_review(
client: client,
app: @app,
ui: @ui,
expected_version: "0.18.0",
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :canceled, result[:status]
assert_equal "0.18.0", result[:version]
assert_equal "sub-99", result[:submission_id]
assert_equal "COMPLETE", result[:submission_state]
assert_equal "DEVELOPER_REJECTED", result[:version_state]
assert_equal ["sub-99"], client.canceled_submission_ids
assert_includes @ui.successes.last, "IOS_REVIEW_CANCELED version=0.18.0 submission_id=sub-99 submission_state=COMPLETE version_state=DEVELOPER_REJECTED"
end
def test_cancel_review_refuses_on_expected_version_mismatch
in_flight_version = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.1", app_version_state: "IN_REVIEW")
submission = FakeReviewSubmission.new(id: "sub-99", state: "IN_REVIEW", app_store_version_for_review: in_flight_version)
client = FakeClient.new(
versions: [in_flight_version],
submissions: [submission],
)
error = assert_raises(FakeUserError) do
IosReview.cancel_review(
client: client,
app: @app,
ui: @ui,
expected_version: "0.18.0",
sleep_fn: @sleep_fn,
clock: @clock,
)
end
assert_match(/expected version 0\.18\.0.*version 0\.18\.1/i, error.message)
assert_empty client.canceled_submission_ids
end
def test_cancel_review_exits_cleanly_when_no_review_is_in_flight
client = FakeClient.new(versions: [], submissions: [])
result = IosReview.cancel_review(
client: client,
app: @app,
ui: @ui,
expected_version: "0.18.0",
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :noop, result[:status]
assert_empty client.canceled_submission_ids
assert_includes @ui.messages.first, "IOS_REVIEW_CANCEL_NOOP reason=no_active_review expected_version=0.18.0"
end
def test_cancel_review_errors_clearly_when_version_is_already_pending_release
pending = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "PENDING_APPLE_RELEASE")
client = FakeClient.new(versions: [pending], submissions: [])
error = assert_raises(FakeUserError) do
IosReview.cancel_review(
client: client,
app: @app,
ui: @ui,
expected_version: "0.18.0",
sleep_fn: @sleep_fn,
clock: @clock,
)
end
assert_match(/Cannot cancel iOS App Store version 0\.18\.0 \(state: PENDING_APPLE_RELEASE\)/, error.message)
assert_empty client.canceled_submission_ids
end
def test_cancel_review_waits_without_duplicate_cancel_when_already_canceling
in_flight_version = FakeAppStoreVersion.new(id: "v-1", version_string: "0.18.0", app_version_state: "WAITING_FOR_REVIEW")
submission = FakeReviewSubmission.new(id: "sub-5", state: "CANCELING", app_store_version_for_review: in_flight_version)
client = FakeClient.new(
versions: [in_flight_version],
submissions: [submission],
submission_poll_states: { "sub-5" => %w[COMPLETE] },
version_poll_states: { "v-1" => %w[DEVELOPER_REJECTED] },
)
result = IosReview.cancel_review(
client: client,
app: @app,
ui: @ui,
sleep_fn: @sleep_fn,
clock: @clock,
)
assert_equal :canceled, result[:status]
assert_empty client.canceled_submission_ids
assert_equal "DEVELOPER_REJECTED", result[:version_state]
end
def test_review_status_formats_live_active_submissions_and_top_five_testflight_builds
live = FakeAppStoreVersion.new(
id: "v-live",
version_string: "0.17.1",
app_version_state: "READY_FOR_DISTRIBUTION",
build: FakeBuild.new(version: "17001999"),
)
active = FakeAppStoreVersion.new(
id: "v-active",
version_string: "0.18.0",
app_version_state: "WAITING_FOR_REVIEW",
build: FakeBuild.new(version: "18000999"),
)
submission = FakeReviewSubmission.new(
id: "sub-10",
state: "WAITING_FOR_REVIEW",
submitted_date: "2026-11-26T12:00:00Z",
app_store_version_for_review: active,
)
builds = [
make_build("0.18.2", "18002999", processing_state: "PROCESSING", uploaded_date: "2026-11-27T11:00:00Z"),
make_build("0.18.1", "18001999", processing_state: "VALID", uploaded_date: "2026-11-27T09:00:00Z"),
make_build("0.18.0", "18000999", processing_state: "VALID", uploaded_date: "2026-11-26T11:30:00Z"),
make_build("0.18.0", "18000001", processing_state: "VALID", uploaded_date: "2026-11-25T10:00:00Z"),
make_build("0.17.1", "17001999", processing_state: "VALID", uploaded_date: "2026-11-20T08:00:00Z"),
make_build("0.17.0", "17000999", processing_state: "VALID", uploaded_date: "2026-11-15T08:00:00Z"),
]
client = FakeClient.new(
live_version_record: live,
versions: [live, active],
submissions: [submission],
builds: builds,
)
result = IosReview.review_status(client: client, app: @app, ui: @ui)
report = result[:report]
assert_equal 5, result[:recent_builds].length
assert_includes report, "=== iOS App Store Review Status (sh.paseo) ==="
assert_includes report, "version=0.17.1 | state=READY_FOR_DISTRIBUTION | build=17001999"
assert_includes report, "version=0.18.0 | state=WAITING_FOR_REVIEW | build=18000999"
assert_includes report, "id=sub-10 | version=0.18.0 | state=WAITING_FOR_REVIEW | submitted_date=2026-11-26T12:00:00Z"
assert_includes report, "1. version=0.18.2 | build=18002999 | processing_state=PROCESSING | uploaded_date=2026-11-27T11:00:00Z"
assert_includes report, "5. version=0.17.1 | build=17001999 | processing_state=VALID | uploaded_date=2026-11-20T08:00:00Z"
refute_includes report, "0.17.0"
end
def test_review_status_formats_empty_sections_cleanly
client = FakeClient.new
result = IosReview.review_status(client: client, app: @app, ui: @ui)
report = result[:report]
assert_equal 4, report.scan(" (none)").length
end
end
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@getpaseo/app",
"version": "0.17.6",
"version": "0.18.1",
"private": true,
"main": "index.ts",
"scripts": {
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.2 KiB

After

Width:  |  Height:  |  Size: 4.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.0 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 32 KiB

After

Width:  |  Height:  |  Size: 19 KiB

@@ -23,15 +23,7 @@ export interface DraftAgentProfileControls {
}
export type AgentProfileApplyTarget =
| {
kind: "agent";
agentId: string;
availableModeIds: readonly string[] | null;
currentProvider?: string | null;
isSwitchInFlight?: () => boolean;
onApplySameProvider?: () => void;
onStageProviderSwitch?: (profile: MaterializedAgentProfile) => void;
}
| { kind: "agent"; agentId: string; availableModeIds: readonly string[] | null }
| { kind: "draft"; controls: DraftAgentProfileControls };
/** Everything the model picker renders for one profile. It never sees the profile itself. */
@@ -154,16 +146,6 @@ export function useAgentProfilePicker(
return;
}
if (
target.onStageProviderSwitch &&
(target.isSwitchInFlight?.() ||
(target.currentProvider && resolved.provider !== target.currentProvider))
) {
target.onStageProviderSwitch(resolved);
return;
}
target.onApplySameProvider?.();
const reconciled = reconcileMaterializedProfileMode(resolved, target.availableModeIds);
if (!reconciled) {
return;
@@ -173,11 +155,7 @@ export function useAgentProfilePicker(
return;
}
void client
.applyAgentConfig(
target.agentId,
toAgentConfigApply(reconciled),
target.currentProvider ? { expectedProvider: target.currentProvider } : undefined,
)
.applyAgentConfig(target.agentId, toAgentConfigApply(reconciled))
.then((notice) => showProviderNoticeToast(toast, notice))
.catch((error) => {
console.warn("[useAgentProfilePicker] applyAgentConfig failed", error);
@@ -56,7 +56,6 @@ export function ChatFind({
agentId,
serverId,
epoch,
rewindSeq,
items,
viewportRef,
revealLoadedMessage,
@@ -96,8 +95,8 @@ export function ChatFind({
);
const state = useSyncExternalStore(model.subscribe, model.getSnapshot, model.getSnapshot);
useEffect(() => {
model.updateHistory(epoch, items, rewindSeq);
}, [model, epoch, items, rewindSeq]);
model.updateHistory(epoch, items);
}, [model, epoch, items]);
useEffect(() => () => model.close(), [model]);
useEffect(() => {
if (!active) model.close();
@@ -18,7 +18,7 @@ function message(seq: number, text = "target"): StreamItem {
kind: "assistant_message",
text,
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch", seq },
};
}
@@ -39,7 +39,7 @@ it("loads an older location and searches a response merged across suppressed tas
source.map((item, index) => ({
event: { type: "timeline" as const, provider: "claude" as const, item },
timestamp: new Date(0),
timelineCursor: { epoch: "epoch", seq: index + 1, anchorSeq: index + 1 },
timelineCursor: { epoch: "epoch", seq: index + 1 },
})),
{ source: "canonical" },
);
@@ -55,7 +55,7 @@ it("loads an older location and searches a response merged across suppressed tas
},
async load(_epoch, seq) {
loaded.push(seq);
model.updateHistory("epoch", history, null);
model.updateHistory("epoch", history);
},
async reveal(_id, _query, occurrence) {
revealed.push(occurrence);
@@ -64,7 +64,7 @@ it("loads an older location and searches a response merged across suppressed tas
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -99,7 +99,7 @@ it("skips a source-only candidate and highlights a displayed match", async () =>
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
@@ -129,7 +129,7 @@ it("ignores replies after closing and does not navigate", async () => {
},
clear() {},
});
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => calls).toEqual(["search"]);
@@ -155,7 +155,7 @@ it("retains a failed search for retry and distinguishes failure from zero matche
};
const model = new ChatFindModel(operations);
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -185,7 +185,7 @@ it("reports a failed timeline load as a connection failure", async () => {
clear() {},
});
try {
model.updateHistory("epoch", [], null);
model.updateHistory("epoch", []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("error");
@@ -207,160 +207,24 @@ it("reports a search result that outlived its epoch as a changed history", async
clear() {},
});
try {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch-2", [message(1)], null);
model.updateHistory("epoch-2", [message(1)]);
expect(model.getSnapshot()).toMatchObject({ phase: "error", failure: "historyChanged" });
} finally {
model.close();
}
});
it("reports results that a rewind took messages from as a changed history", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 2, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
expect(model.getSnapshot()).toMatchObject({ selectedItemId: "row-2", count: 1 });
// Another client rewinds the turn holding the match; the epoch stays.
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a search still receiving pages when a rewind lands between them", async () => {
let pages = 0;
let releaseSecondPage!: () => void;
const secondPage = new Promise<void>((resolve) => {
releaseSecondPage = resolve;
});
const model = new ChatFindModel({
async search(_query, cursor) {
pages += 1;
if (cursor === undefined)
return { ...response([{ seq: 2, role: "assistant" }]), nextCursor: 2 };
await secondPage;
return response([{ seq: 1, role: "assistant" }]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => pages).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
releaseSecondPage();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it.each([
["Next", "next"],
["Previous", "previous"],
] as const)("reports a rewind after %s as a changed history", async (_label, step) => {
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model[step]();
await expect.poll(() => model.getSnapshot().selectedItemId).toBe("row-2");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.updateHistory("epoch", [message(1)], 3);
expect(model.getSnapshot()).toMatchObject({
phase: "error",
failure: "historyChanged",
selectedItemId: null,
});
} finally {
model.close();
}
});
it("stops a pending Next when a rewind lands before it reveals", async () => {
let reveals = 0;
let revealSecond!: () => void;
const secondReveal = new Promise<void>((resolve) => {
revealSecond = resolve;
});
const model = new ChatFindModel({
async search() {
return response([
{ seq: 1, role: "assistant" },
{ seq: 2, role: "assistant" },
]);
},
async load() {},
async reveal() {
reveals += 1;
if (reveals > 1) await secondReveal;
return { count: 1, occurrence: 0 };
},
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
model.next();
await expect.poll(() => reveals).toBe(2);
model.updateHistory("epoch", [message(1)], 3);
revealSecond();
await expect.poll(() => model.getSnapshot().failure).toBe("historyChanged");
expect(model.getSnapshot()).toMatchObject({ phase: "error", selectedItemId: null });
} finally {
model.close();
}
});
it("can load a search location before the initial chat history has arrived", async () => {
const model = new ChatFindModel({
async search() {
return response([{ seq: 1, role: "assistant" }]);
},
async load() {
model.updateHistory("epoch", [message(1)], null);
model.updateHistory("epoch", [message(1)]);
},
async reveal() {
return { count: 1, occurrence: 0 };
@@ -368,7 +232,7 @@ it("can load a search location before the initial chat history has arrived", asy
clear() {},
});
try {
model.updateHistory(null, [], null);
model.updateHistory(null, []);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -396,7 +260,7 @@ it("reports the position across the whole chat and corrects it with rendered cou
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -433,7 +297,7 @@ it("counts one match per message from a host that reports no counts", async () =
clear() {},
});
try {
model.updateHistory("epoch", [message(1), message(2)], null);
model.updateHistory("epoch", [message(1), message(2)]);
model.open();
model.setQuery("target");
await expect.poll(() => model.getSnapshot().phase).toBe("ready");
@@ -76,10 +76,6 @@ export class ChatFindModel {
private items: StreamItem[] = [];
private epoch: string | null = null;
private resultEpoch: string | null = null;
/** The latest rewind applied to the history. A rewind keeps the epoch and retires messages. */
private rewindSeq: number | null = null;
/** The latest rewind when the current result set's search started; undefined until a search starts. */
private searchedRewindSeq: number | null | undefined = undefined;
private locations: Location[] = [];
private resolved = new Map<Location, Target>();
private current = -1;
@@ -117,7 +113,6 @@ export class ChatFindModel {
this.cancel();
this.locations = [];
this.resultEpoch = null;
this.searchedRewindSeq = undefined;
this.resolved.clear();
this.current = -1;
this.inMessage = { occurrence: 0, count: 0 };
@@ -149,7 +144,6 @@ export class ChatFindModel {
});
}
private async search(signal: AbortSignal) {
this.searchedRewindSeq = this.rewindSeq;
try {
let cursor: number | undefined;
do {
@@ -174,14 +168,15 @@ export class ChatFindModel {
this.fail(error, signal);
}
}
/** `rewindSeq` is the sequence number of the latest rewind applied to this history. */
updateHistory(epoch: string | null, items: StreamItem[], rewindSeq: number | null) {
const replaced = this.resultEpoch !== null && epoch !== null && epoch !== this.resultEpoch;
const rewound = this.searchedRewindSeq !== undefined && rewindSeq !== this.searchedRewindSeq;
if ((replaced || rewound) && this.state.open) {
updateHistory(epoch: string | null, items: StreamItem[]) {
if (
this.resultEpoch !== null &&
epoch !== null &&
epoch !== this.resultEpoch &&
this.state.open
) {
this.fail(new ChatFindFailureError("historyChanged"), this.abort.signal);
}
this.rewindSeq = rewindSeq;
this.epoch = epoch;
this.items = items;
this.historyListeners.forEach((listener) => listener());
@@ -9,8 +9,6 @@ export interface ChatFindProps {
agentId: string;
serverId: string;
epoch: string | null;
/** The sequence number of the latest rewind applied to this history, if any. */
rewindSeq: number | null;
items: StreamItem[];
viewportRef: RefObject<StreamViewportHandle | null>;
revealLoadedMessage(messageId: string): boolean;
@@ -139,7 +139,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "live prompt",
timestamp: new Date(seq),
timelineCursor: { epoch: "epoch-1", seq, anchorSeq: seq },
timelineCursor: { epoch: "epoch-1", seq },
});
rerender({ tail: [loadedPrompt(2)] });
await waitFor(() => expect(runtime.listAgentTimelinePrompts).toHaveBeenCalledTimes(2));
@@ -198,7 +198,7 @@ describe("useChatOutline", () => {
kind: "assistant_message",
text: "chunk",
timestamp: new Date(),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
},
],
timelineEpoch: "epoch-1",
@@ -219,7 +219,7 @@ describe("useChatOutline", () => {
kind: "user_message",
text: "Replaced conversation",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-2", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-2", seq: 1 },
},
],
timelineEpoch: "epoch-2",
@@ -275,7 +275,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
},
];
const { result, rerender } = renderHook(
@@ -326,7 +326,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(1),
timelineCursor: { epoch: "epoch-1", seq: 1, anchorSeq: 1 },
timelineCursor: { epoch: "epoch-1", seq: 1 },
};
const { result, rerender } = renderHook(
({ tail, mountedHistoryMessageIds }) =>
@@ -381,7 +381,7 @@ describe("useChatOutline", () => {
kind: "user_message" as const,
text: "prompt",
timestamp: new Date(2),
timelineCursor: { epoch: "epoch-1", seq: 2, anchorSeq: 2 },
timelineCursor: { epoch: "epoch-1", seq: 2 },
};
const revealLoadedMessage = vi.fn();
revealLoadedMessage.mockReturnValue(false);
@@ -320,7 +320,7 @@ describe("stream presentation through installed plugins", () => {
const source = harness.source();
const live = source.head[0];
if (live?.kind !== "assistant_message") throw new Error("Expected a live assistant message");
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 } };
const canonical = { ...live, timelineCursor: { epoch: "epoch-1", seq: 42 } };
const present = createStreamPresentation();
present({ ...presentationOptions, tail: [], head: [live], transform: undefined });
const repointed = rows(
@@ -330,7 +330,7 @@ describe("stream presentation through installed plugins", () => {
{
id: streamed[0]!.id,
text: "Streamed answer",
timelineCursor: { epoch: "epoch-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "epoch-1", seq: 42 },
},
]);
});
@@ -517,7 +517,7 @@ describe("timeline presentation", () => {
messageId: "provider-message",
clientMessageId: "client-message",
turnId: "turn-1",
timelineCursor: { epoch: "epoch", seq: 12, anchorSeq: 12 },
timelineCursor: { epoch: "epoch", seq: 12 },
});
const presentMessage = () =>
present({
@@ -33,7 +33,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("forks a failed assistant turn from its Paseo timeline cursor without a provider message id", () => {
const failedTurn = {
...assistantMessage("assistant-error", 2),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -50,7 +50,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("includes the provider message id with a supported timeline cursor", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -68,7 +68,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("falls back to the provider message id when timeline cursors are unsupported", () => {
const selected = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
expect(
@@ -116,7 +116,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
it("resolves a fork boundary from the reply a plugin card replaced", () => {
const reply = {
...assistantMessage("assistant-1", 2, "msg-assistant-1"),
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
};
const card: StreamItem = {
kind: "plugin",
@@ -154,7 +154,7 @@ describe("resolveAssistantTurnForkBoundary", () => {
const appended: StreamItem = {
kind: "plugin",
id: "plugin/card-1",
timelineCursor: { epoch: "timeline-1", seq: 42, anchorSeq: 42 },
timelineCursor: { epoch: "timeline-1", seq: 42 },
timestamp: timestamp(2),
pluginId: "plugin",
pluginItemId: "card-1",
@@ -1,13 +1,7 @@
import { getAssistantReply, type StreamItem } from "@/types/stream";
/** The daemon's timeline cursor; the row's anchor stays in the client. */
interface TimelineBoundaryCursor {
epoch: string;
seq: number;
}
import { getAssistantReply, type StreamItem, type TimelinePosition } from "@/types/stream";
export type AssistantTurnForkBoundary =
| { boundaryCursor: TimelineBoundaryCursor; boundaryMessageId?: string }
| { boundaryCursor: TimelinePosition; boundaryMessageId?: string }
| { boundaryCursor?: undefined; boundaryMessageId: string };
export function resolveAssistantTurnForkBoundary(input: {
@@ -21,7 +15,7 @@ export function resolveAssistantTurnForkBoundary(input: {
}
if (input.supportsTimelineCursor && reply.timelineCursor) {
return {
boundaryCursor: { epoch: reply.timelineCursor.epoch, seq: reply.timelineCursor.seq },
boundaryCursor: reply.timelineCursor,
...(reply.messageId ? { boundaryMessageId: reply.messageId } : {}),
};
}
@@ -139,7 +139,7 @@ describe("collapseTurns", () => {
it("stands at its host's timeline position, taking a new row when that position lands", () => {
const live = collapse([user("u1"), shell("c1"), reply("r1")]);
expect(live.summaryRowsByHostId.get("u1")).not.toHaveProperty("timelineCursor");
const cursor = { epoch: "epoch-1", seq: 7, anchorSeq: 7 };
const cursor = { epoch: "epoch-1", seq: 7 };
const placed = [{ ...user("u1"), timelineCursor: cursor }, shell("c1"), reply("r1")];
const canonical = collapse(placed, { previousSummaryRowsByHostId: live.summaryRowsByHostId });
expect(canonical.summaryRowsByHostId.get("u1")).not.toBe(live.summaryRowsByHostId.get("u1"));
@@ -101,7 +101,7 @@ function summaryRow(
}
function staysVisibleWhenCollapsed(item: StreamItem): boolean {
return isTurnTrigger(item) || item.kind === "compaction" || item.kind === "provider_switch";
return isTurnTrigger(item) || item.kind === "compaction";
}
function findLastReplyIndex(tail: StreamItem[], start: number, end: number): number {
@@ -159,10 +159,10 @@ const projectedReply: StreamItem = {
id: "reply",
messageId: "provider-reply-1",
text: 'Done.\n\n```ui\nCard("Summary", [])\n```',
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
},
timelineCursor: { epoch: "e1", seq: 5, anchorSeq: 5 },
timelineCursor: { epoch: "e1", seq: 5 },
timestamp: FRIDAY_NIGHT,
pluginId: "genui",
pluginItemId: "reply/1",
+2 -35
View File
@@ -37,7 +37,6 @@ import {
ToolCall,
TodoListCard,
CompactionMarker,
ProviderSwitchMarker,
MessageOuterSpacingProvider,
type InlinePathTarget,
} from "@/components/message";
@@ -58,7 +57,6 @@ import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
import { useLoadOlderAgentHistory } from "@/hooks/use-load-older-agent-history";
import { resolveContentMaxWidth, useSettings } from "@/hooks/use-settings";
import type { ToastApi } from "@/components/toast-host";
import { isPromptInActiveSegment } from "@/components/rewind/use-rewind-capabilities";
import { returnToTimelineTail } from "./timeline-tail-navigation";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import { ToolCallDetailsContent } from "@/components/tool-call-details";
@@ -410,10 +408,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const timelineEpoch = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.epoch ?? null,
);
const timelineRewindSeq = useSessionStore((state) => {
const rewind = state.sessions[resolvedServerId]?.agentTimelineLatestRewind.get(agentId);
return rewind && rewind.epoch === timelineEpoch ? rewind.seq : null;
});
const isTimelineDetached = useSessionStore(
(state) => state.sessions[resolvedServerId]?.agentTimelineHasNewer.get(agentId) === true,
);
@@ -717,15 +711,8 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
const setToolCallGroupExpanded = toolCallExpansion.setGroupExpanded;
const activeSegmentStartSeq = useSessionStore(
(state) =>
state.sessions[resolvedServerId]?.agentTimelineCursor.get(agentId)?.activeSegmentStartSeq ??
0,
);
const renderUserMessageItem = useCallback(
(layoutItem: StreamLayoutItem, item: Extract<StreamItem, { kind: "user_message" }>) => {
const canRewindPrompt = isPromptInActiveSegment(item.timelineCursor, activeSegmentStartSeq);
return (
<UserMessage
itemId={item.id}
@@ -737,7 +724,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
images={item.images}
attachments={item.attachments}
timestamp={item.timestamp.getTime()}
capabilities={canRewindPrompt ? context.capabilities : undefined}
capabilities={context.capabilities}
client={client}
isFirstInGroup={layoutItem.isFirstInUserGroup}
isLastInGroup={layoutItem.isLastInUserGroup}
@@ -748,14 +735,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
/>
);
},
[
activeSegmentStartSeq,
context.capabilities,
agentId,
client,
pendingClientMessageIds,
resolvedServerId,
],
[context.capabilities, agentId, client, pendingClientMessageIds, resolvedServerId],
);
const renderAssistantMessageItem = useCallback(
@@ -961,18 +941,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
/>
);
case "provider_switch":
return (
<ProviderSwitchMarker
serverId={resolvedServerId}
fromProvider={item.fromProvider}
toProvider={item.toProvider}
fromModel={item.fromModel}
toModel={item.toModel}
context={item.context}
/>
);
case "plugin":
return (
<PluginTimelineItemView agentId={agentId} item={item} serverId={resolvedServerId} />
@@ -1198,7 +1166,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
agentId={agentId}
serverId={resolvedServerId}
epoch={timelineEpoch}
rewindSeq={timelineRewindSeq}
items={findItems}
viewportRef={viewportRef}
revealLoadedMessage={revealLoadedMessage}
@@ -75,7 +75,6 @@ export function estimateStreamItemHeight({
case "notification":
return 88;
case "compaction":
case "provider_switch":
return 72;
default:
return 120;
@@ -366,6 +366,111 @@ describe("Command Center relevance ordering", () => {
expect(sectionResultIds(sections)).toEqual(["z-first", "a-second"]);
});
it("does not flip a higher-ranked prefix match when a shorter title completes on the last letter", () => {
const contributions = [
action({
id: "workspace:rename",
group: "workspace",
groupRank: -1,
rank: 21,
title: "Rename workspace",
}),
action({
id: "tab:rename-current",
group: "workspace",
groupRank: -1,
rank: 33,
title: "Rename",
}),
];
for (const query of ["r", "re", "ren", "rena", "renam", "rename"]) {
expect(sectionResultIds(buildContributionSections(contributions, query)), query).toEqual([
"workspace:rename",
"tab:rename-current",
]);
}
});
it("does not let a mid-phrase whole word leapfrog a start-of-title prefix mid-word", () => {
const contributions = [
action({
id: "workspace:pin",
group: "workspace",
groupRank: -1,
rank: 20,
title: "Pin to top",
}),
action({
id: "workspace:toggle-explorer-sidebar",
group: "workspace",
groupRank: -1,
rank: 25,
title: "Toggle Explorer sidebar",
}),
];
for (const query of ["t", "to"]) {
expect(sectionResultIds(buildContributionSections(contributions, query)), query).toEqual([
"workspace:toggle-explorer-sidebar",
"workspace:pin",
]);
}
});
it("keeps start-of-title priority even when the same token also appears as a whole word later", () => {
const contributions = [
action({
id: "later-only",
group: "workspace",
groupRank: -1,
rank: 1,
title: "Pin to top",
}),
action({
id: "starts-with-and-contains",
group: "workspace",
groupRank: -1,
rank: 2,
title: "Toggle to main",
}),
];
for (const query of ["t", "to"]) {
expect(sectionResultIds(buildContributionSections(contributions, query)), query).toEqual([
"starts-with-and-contains",
"later-only",
]);
}
});
it("does not flip word-start matches when one word finishes earlier than another", () => {
const contributions = [
action({
id: "workspace:toggle-explorer-sidebar",
group: "workspace",
groupRank: -1,
rank: 25,
title: "Toggle Explorer sidebar",
}),
action({
id: "tab:open:pull-request:side-pane",
group: "workspace",
groupRank: -1,
rank: 14,
title: "Open Pull request in side pane",
}),
];
// Registry order puts the lower-index item first; neither should jump past the other on "side".
for (const query of ["si", "sid", "side"]) {
expect(sectionResultIds(buildContributionSections(contributions, query)), query).toEqual([
"workspace:toggle-explorer-sidebar",
"tab:open:pull-request:side-pane",
]);
}
});
it("keeps Workspaces below contributions even on a perfect match", () => {
const projection = projectCommandCenterRows(
[
+55 -20
View File
@@ -1,9 +1,8 @@
import {
compareMatchScores,
type MatchClass,
type MatchScore,
scoreTextFields,
scoreMatch,
textFieldsMatchClass,
tokenizeQuery,
} from "@getpaseo/protocol/search/text-match";
import type { CommandCenterContribution } from "./contributions";
import type { CommandCenterListMetrics } from "./list-metrics";
@@ -20,10 +19,26 @@ const VISIBLE_FIELD_RANK = 0;
/** At least one token only matched a hidden keyword. */
const KEYWORD_FIELD_RANK = 1;
/**
* Left-edge match ranks for Command Center scoring, best to worst.
*
* Right-edge promotions (`TIER_EXACT`, `TIER_WHOLE_WORD`) are deliberately excluded here:
* whether a word or title happens to end on the latest keystroke flips row order mid-word as
* the user types (e.g., `"renam"` → `"rename"` jumping a shorter title ahead of `"Rename
* workspace"`, or `"t"` → `"to"` jumping `"Pin to top"` ahead of `"Toggle Explorer sidebar"`).
* Left-edge ranks can only stay the same or worsen as characters are appended to a token, so
* two rows that keep matching at the same left edge never swap places.
*/
const FIELD_START_RANK = 0;
const WORD_START_RANK = 1;
const INSIDE_WORD_RANK = 2;
const SCATTERED_RANK = 3;
export interface CommandCenterScore {
/** VISIBLE_FIELD_RANK or KEYWORD_FIELD_RANK. Compared before match quality. */
fieldRank: number;
match: MatchScore;
/** Sum of per-token left-edge ranks (FIELD_START..SCATTERED). Lower is better. */
matchRank: number;
}
/**
@@ -44,7 +59,7 @@ export function compareCommandCenterScores(
left: CommandCenterScore,
right: CommandCenterScore,
): number {
return left.fieldRank - right.fieldRank || compareMatchScores(left.match, right.match);
return left.fieldRank - right.fieldRank || left.matchRank - right.matchRank;
}
export interface CommandCenterWorkspaceProject {
@@ -148,12 +163,41 @@ export interface CommandCenterSearchFields {
hidden: readonly string[];
}
function scoreTokenInField(token: string, field: string): number | null {
// Check start-of-field first: `scoreMatch` prefers a later whole word (tier 1) over a leading
// prefix (tier 2), which would otherwise demote a field starting with the token when the same
// token also appears as a standalone word later in the field.
if (field.toLowerCase().startsWith(token)) return FIELD_START_RANK;
const score = scoreMatch(token, field);
if (!score) return null;
if (score.tier <= 3) return WORD_START_RANK;
if (score.tier === 4) return INSIDE_WORD_RANK;
return SCATTERED_RANK;
}
function scoreFieldsLeftEdge(tokens: readonly string[], fields: readonly string[]): number | null {
let total = 0;
for (const token of tokens) {
let best: number | null = null;
for (const field of fields) {
const rank = scoreTokenInField(token, field);
if (rank !== null && (best === null || rank < best)) {
best = rank;
if (best === FIELD_START_RANK) break;
}
}
if (best === null) return null;
total += best;
}
return total;
}
/**
* The one definition of "how well did this row match", shared by every scored row kind. Null
* means the row is filtered out, so scoring and filtering are the same pass — a separate boolean
* predicate would throw this result away and force the token scan a second time.
*
* Matching is per-token (`scoreTextFields` splits on whitespace and every token must land in
* Matching is per-token (`tokenizeQuery` splits on whitespace and every token must land in
* some field), so token order does not matter and `lab des` finds "Label as Design". This can
* only ever widen the result set: tokens hold no whitespace, so any token that was found in the
* old space-joined haystack lies entirely within one field and is still found here.
@@ -165,11 +209,12 @@ export function scoreSearchFields(
query: string,
fields: CommandCenterSearchFields,
): CommandCenterScore | null {
const visible = scoreTextFields(query, [...fields.visible]);
if (visible) return { fieldRank: VISIBLE_FIELD_RANK, match: visible };
const tokens = tokenizeQuery(query);
const visible = scoreFieldsLeftEdge(tokens, fields.visible);
if (visible !== null) return { fieldRank: VISIBLE_FIELD_RANK, matchRank: visible };
if (fields.hidden.length === 0) return null;
const match = scoreTextFields(query, [...fields.visible, ...fields.hidden]);
return match ? { fieldRank: KEYWORD_FIELD_RANK, match } : null;
const matchRank = scoreFieldsLeftEdge(tokens, [...fields.visible, ...fields.hidden]);
return matchRank !== null ? { fieldRank: KEYWORD_FIELD_RANK, matchRank } : null;
}
/** How closely the query matched the fields; see `MatchClass`. Null when it does not match. */
@@ -245,16 +290,6 @@ export function compareByRecency(left: CommandCenterRecentRow, right: CommandCen
return (right.activityAt?.getTime() ?? 0) - (left.activityAt?.getTime() ?? 0);
}
/**
* Rank built-in rows by the kind of match they made: which fields matched, then the matcher's
* tier. Offset and spread are deliberately left out. They only say where in the title the word
* happened to sit, so "usage" in "Deliver sidebar usage" and in "expose usage data" would be
* ordered by sentence position. Leaving them out makes those rows equal, and recency decides.
*/
export function compareBuiltInScores(left: CommandCenterScore, right: CommandCenterScore): number {
return left.fieldRank - right.fieldRank || left.match.tier - right.match.tier;
}
/**
* Group contributions into their sections, ranked by the query. `includeQueryOnly` lists the
* contributions that otherwise wait for a query, for a list whose whole job is browsing them.
@@ -49,7 +49,8 @@ function source(gitActions: GitActions): {
previousTab: "Previous tab",
nextTab: "Next tab",
closeCurrentTab: "Close current tab",
renameTab: "Rename",
renameAgent: "Rename agent",
renameTerminal: "Rename terminal",
reloadAgent: "Reload agent",
copyResumeCommand: "Copy resume command",
copyAgentId: "Copy agent id",
@@ -282,6 +283,26 @@ describe("workspace command center contributions", () => {
expect(fixture.dispatched).toEqual([{ id: "workspace.rename", scope: "workspace" }]);
});
it("labels active tab rename by the active tab kind", () => {
const agentFixture = source({ primary: null, secondary: [], menu: [] });
agentFixture.value.activeTabCount = 1;
agentFixture.value.activeTabIndex = 0;
agentFixture.value.activeTabKind = "agent";
const agentRename = buildWorkspaceCommandCenterContributions(agentFixture.value).find(
(item) => item.id === "tab:rename-current",
);
expect(agentRename?.presentation).toMatchObject({ title: "Rename agent" });
const terminalFixture = source({ primary: null, secondary: [], menu: [] });
terminalFixture.value.activeTabCount = 1;
terminalFixture.value.activeTabIndex = 0;
terminalFixture.value.activeTabKind = "terminal";
const terminalRename = buildWorkspaceCommandCenterContributions(terminalFixture.value).find(
(item) => item.id === "tab:rename-current",
);
expect(terminalRename?.presentation).toMatchObject({ title: "Rename terminal" });
});
it("copies the workspace path without going through the dispatcher", () => {
const fixture = source({ primary: null, secondary: [], menu: [] });
const contributions = buildWorkspaceCommandCenterContributions(fixture.value);
@@ -29,7 +29,8 @@ export interface WorkspaceCommandCenterLabels {
previousTab: string;
nextTab: string;
closeCurrentTab: string;
renameTab: string;
renameAgent: string;
renameTerminal: string;
reloadAgent: string;
copyResumeCommand: string;
copyAgentId: string;
@@ -299,7 +300,10 @@ function buildActiveTabContributions(
buildQueryAction(source, {
id: "tab:rename-current",
rank: 33,
title: source.labels.renameTab,
title:
source.activeTabKind === "agent"
? source.labels.renameAgent
: source.labels.renameTerminal,
keywords: ["tab", "rename", "current"],
icon: source.icons.rename,
action: { id: "workspace.tab.rename-current", scope: "workspace" },
@@ -249,7 +249,8 @@ export function useWorkspaceCommandCenterActions(): void {
previousTab: t("settings.shortcuts.help.previousTab"),
nextTab: t("settings.shortcuts.help.nextTab"),
closeCurrentTab: t("settings.shortcuts.help.closeCurrentTab"),
renameTab: t("workspace.tabs.menu.rename"),
renameAgent: t("workspace.tabs.menu.renameAgent"),
renameTerminal: t("workspace.tabs.menu.renameTerminal"),
reloadAgent: t("workspace.tabs.menu.reloadAgent"),
copyResumeCommand: t("workspace.tabs.menu.copyResumeCommand"),
copyAgentId: t("workspace.tabs.menu.copyAgentId"),
@@ -94,7 +94,7 @@ describe("workspace ranking", () => {
expect(ids([text, subject], "42")).toEqual(["payments", "a-text"]);
});
it("orders workspaces in the same match tier by recency", () => {
it("orders workspaces in the same match class by recency at every prefix", () => {
const older = workspace({
id: "older",
title: "Usage hover card",
@@ -105,7 +105,25 @@ describe("workspace ranking", () => {
title: "Deliver sidebar usage",
activityAt: new Date("2026-10-17T00:00:00Z"),
});
expect(ids([older, newer], "usage")).toEqual(["newer", "older"]);
for (const query of ["u", "us", "usa", "usag", "usage"]) {
expect(ids([older, newer], query), query).toEqual(["newer", "older"]);
}
});
it("does not flip a newer workspace below an older exact-title workspace on the final character", () => {
const newer = workspace({
id: "newer",
title: "paseo command center",
activityAt: new Date("2026-10-17T00:00:00Z"),
});
const older = workspace({
id: "older",
title: "paseo",
activityAt: new Date("2026-10-01T00:00:00Z"),
});
for (const query of ["p", "pa", "pas", "pase", "paseo"]) {
expect(ids([newer, older], query), query).toEqual(["newer", "older"]);
}
});
it("lists every workspace most recent first when the query is empty", () => {
@@ -1,7 +1,7 @@
import { compareMatchClasses, type MatchClass } from "@getpaseo/protocol/search/text-match";
import {
compareBuiltInScores,
compareByRecency,
compareCommandCenterScores,
scoreSearchFields,
searchFieldsMatchClass,
type CommandCenterScore,
@@ -69,13 +69,14 @@ function scoreCandidate(query: string, fields: CommandCenterSearchFields): Candi
function compareCandidates(left: Candidate, right: Candidate): number {
return (
compareMatchClasses(left.matchClass, right.matchClass) ||
compareBuiltInScores(left.score, right.score)
compareCommandCenterScores(left.score, right.score)
);
}
/**
* Change-request hits first, host-only matches last; then match class, the workspace's own text
* ahead of an agent, match quality, and recency.
* ahead of an agent, and recency. Positional sub-tiers inside a match class are deliberately
* omitted so workspaces do not flip mid-word as a prefix finishes a word or title.
*/
function compareScoredWorkspaces(left: ScoredWorkspace, right: ScoredWorkspace): number {
if (left.changeRequestHit !== right.changeRequestHit) {
@@ -89,10 +90,6 @@ function compareScoredWorkspaces(left: ScoredWorkspace, right: ScoredWorkspace):
if (classDelta !== 0) return classDelta;
}
if (left.via !== right.via) return left.via - right.via;
if (left.candidate && right.candidate) {
const scoreDelta = compareBuiltInScores(left.candidate.score, right.candidate.score);
if (scoreDelta !== 0) return scoreDelta;
}
return compareByRecency(left.workspace, right.workspace);
}
@@ -61,6 +61,8 @@ export function appearanceStyleBoundaryKey(theme: Theme): string {
theme.colors.syntax.meta,
theme.colors.syntax.heading,
theme.colors.syntax.link,
theme.colors.syntax.diffAddition,
theme.colors.syntax.diffDeletion,
].join("\u0000");
}
@@ -81,7 +81,6 @@ export function ArchivedAgentCallout({
agentId,
isWorkspaceRestoring = false,
}: ArchivedAgentCalloutProps) {
const { t } = useTranslation();
const targetKey = `${serverId}:${agentId}`;
const toast = useToast();
const { unarchive, isUnarchiving, canUnarchive } = useUnarchiveAgent({ serverId, agentId });
@@ -111,15 +110,7 @@ export function ArchivedAgentCallout({
const attemptKey = targetKey;
setUnarchiveErrorState(null);
try {
await unarchive({
onRefreshed: (refreshed) => {
if (refreshed.historyDiverged) {
toast.show(t("workspace.tabs.toasts.reloadedAgentHistoryDiverged"), {
variant: "warning",
});
}
},
});
await unarchive();
} catch (error) {
deliverUnarchiveError({
error,
@@ -130,7 +121,7 @@ export function ArchivedAgentCallout({
onToastError: toast.error,
});
}
}, [canUnarchive, t, targetKey, toast, unarchive]);
}, [canUnarchive, targetKey, toast, unarchive]);
return (
<KeyboardTranslateView style={styles.container}>
@@ -10,6 +10,7 @@ import {
resolveDesktopAppChromeLayout,
resolveDesktopAppContentMinimum,
resolveDesktopSidebarInsetLeft,
resolveDesktopSidebarInsetTop,
resolveDesktopSidebarVisibility,
resolveSidebarActivity,
resolveDesktopSidebarWidth,
@@ -248,3 +249,13 @@ it("insets an overlay sidebar's content by the left safe area and leaves the doc
expect(resolveDesktopSidebarInsetLeft({ overlay: true, safeAreaLeft: 20 })).toBe(20);
expect(resolveDesktopSidebarInsetLeft({ overlay: false, safeAreaLeft: 20 })).toBe(0);
});
it("gives the overlay sidebar the window's top inset, which a wide layout surface spends", () => {
// A wide web surface pads the status bar itself and leaves its content a top inset of 0.
expect(
resolveDesktopSidebarInsetTop({ overlay: true, safeAreaTop: 0, windowSafeAreaTop: 32 }),
).toBe(32);
expect(
resolveDesktopSidebarInsetTop({ overlay: false, safeAreaTop: 0, windowSafeAreaTop: 32 }),
).toBe(0);
});
@@ -52,6 +52,18 @@ export function resolveDesktopSidebarInsetLeft(input: {
return input.overlay ? input.safeAreaLeft : 0;
}
/**
* The overlay sidebar also starts at the window's top edge, over the layout surface's top padding,
* so it takes the window's top inset. The dock reads the inset the surface leaves its content.
*/
export function resolveDesktopSidebarInsetTop(input: {
overlay: boolean;
safeAreaTop: number;
windowSafeAreaTop: number;
}): number {
return input.overlay ? input.windowSafeAreaTop : input.safeAreaTop;
}
export function resolveDesktopAppChromeLayout(input: {
desktopSidebarRendered: boolean;
hasTopLeftWindowControls: boolean;
@@ -0,0 +1,85 @@
import React, { act, useMemo } from "react";
import { createRoot } from "react-dom/client";
import { View } from "react-native";
import { Gesture, GestureHandlerRootView } from "react-native-gesture-handler";
import { SafeAreaInsetsContext, useSafeAreaInsets } from "react-native-safe-area-context";
import { afterEach, expect, it, vi } from "vitest";
import { resolveDesktopSidebarInsetTop } from "@/components/desktop-sidebar-layout";
import { MobilePanelOverlay } from "@/mobile-panels/presentation";
import { MobilePanelsProvider } from "@/mobile-panels/provider";
import { usePanelStore } from "@/stores/panel-store";
import {
WindowLayoutProvider,
WindowLayoutSurface,
useWindowSafeAreaInsets,
} from "@/window-layout";
vi.stubGlobal("React", React);
const statusBarInsets = { top: 24, right: 0, bottom: 0, left: 0 };
const fill = { flex: 1 };
const rowStyle = { height: 40 };
const container = document.createElement("div");
container.style.height = "800px";
document.body.appendChild(container);
const root = createRoot(container);
afterEach(() => {
act(() => root.render(null));
});
/** The first row of the sidebar, padded the way `DesktopSidebar` pads it. */
function SidebarFirstRow({ overlay }: { overlay: boolean }) {
const insetTop = resolveDesktopSidebarInsetTop({
overlay,
safeAreaTop: useSafeAreaInsets().top,
windowSafeAreaTop: useWindowSafeAreaInsets().top,
});
const style = useMemo(() => ({ paddingTop: insetTop }), [insetTop]);
return (
<View style={style}>
<View testID="sidebar-first-row" style={rowStyle} />
</View>
);
}
function firstRowTop(): number {
const row = document.querySelector<HTMLElement>('[data-testid="sidebar-first-row"]');
expect(row).not.toBeNull();
return row!.getBoundingClientRect().top - container.getBoundingClientRect().top;
}
async function renderSidebar(overlay: boolean) {
const closeGesture = Gesture.Pan();
await act(async () => {
root.render(
<GestureHandlerRootView style={fill}>
<SafeAreaInsetsContext.Provider value={statusBarInsets}>
<WindowLayoutProvider>
<WindowLayoutSurface compact={false} style={fill}>
<MobilePanelsProvider>
<MobilePanelOverlay
panel="agent-list"
presentation={overlay ? "overlay" : "dock"}
dockVisible={!overlay}
closeGesture={closeGesture}
>
<SidebarFirstRow overlay={overlay} />
</MobilePanelOverlay>
</MobilePanelsProvider>
</WindowLayoutSurface>
</WindowLayoutProvider>
</SafeAreaInsetsContext.Provider>
</GestureHandlerRootView>,
);
});
}
it("keeps the overlay sidebar's first row below the status bar on a wide layout", async () => {
usePanelStore.getState().showMobileAgentList();
await renderSidebar(true);
expect(firstRowTop()).toBe(statusBarInsets.top);
});
it("keeps the docked sidebar's first row below the status bar without padding it twice", async () => {
await renderSidebar(false);
expect(firstRowTop()).toBe(statusBarInsets.top);
});
@@ -0,0 +1,66 @@
import { describe, expect, it } from "vitest";
import { tokenizeToLines } from "@/utils/highlight-cache";
import { fenceLanguageToExtension } from "./highlighted-code-block";
describe("fenceLanguageToExtension", () => {
it.each([
["shell", "sh"],
["ruby", "rb"],
["kotlin", "kt"],
["powershell", "ps1"],
["pwsh", "ps1"],
["protobuf", "proto"],
["latex", "tex"],
["stex", "tex"],
["diff", "diff"],
["patch", "patch"],
["sql", "sql"],
["lua", "lua"],
["proto", "proto"],
["groovy", "groovy"],
["gradle", "gradle"],
["scala", "scala"],
["cmake", "cmake"],
["properties", "properties"],
["ini", "ini"],
["conf", "conf"],
["r", "r"],
["perl", "pl"],
["toml", "toml"],
])("maps fence info %s to %s", (info, expected) => {
expect(fenceLanguageToExtension(info)).toBe(expected);
});
it("produces syntax tokens for every mapped fence alias", () => {
const samples: Array<[string, string]> = [
["shell", 'export FOO="bar"'],
["ruby", 'def hi\n "ok"\nend'],
["kotlin", 'val x: String = "ok"'],
["powershell", 'function Get-X { "ok" }'],
["pwsh", '$x = "ok"'],
["protobuf", 'syntax = "proto3";'],
["latex", "\\documentclass{article}"],
["perl", 'my $x = "ok";'],
["sql", "SELECT 1;"],
["lua", "local x = 1"],
["gradle", 'id "java"'],
["scala", "val x = 1"],
["cmake", "project(Paseo)"],
["ini", "[section]\nkey = value"],
["r", "x <- function(a) a"],
["toml", '[server]\nhost = "localhost"'],
["diff", "+added"],
["patch", "-removed"],
];
for (const [info, code] of samples) {
const ext = fenceLanguageToExtension(info);
const lines = tokenizeToLines(code, ext);
expect(lines, info).not.toBeNull();
expect(
lines?.flat().some((token) => token.style !== null),
info,
).toBe(true);
}
});
});
@@ -39,9 +39,18 @@ const LANGUAGE_ALIASES: Record<string, string> = {
markdown: "md",
elixir: "ex",
terraform: "tf",
shell: "sh",
ruby: "rb",
kotlin: "kt",
powershell: "ps1",
pwsh: "ps1",
protobuf: "proto",
perl: "pl",
latex: "tex",
stex: "tex",
};
function fenceLanguageToExtension(info: string | null | undefined): string | null {
export function fenceLanguageToExtension(info: string | null | undefined): string | null {
if (!info) return null;
const first = info.trim().split(/\s+/)[0]?.toLowerCase();
if (!first) return null;
+13 -2
View File
@@ -44,9 +44,15 @@ import {
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
resolveDesktopSidebarInsetTop,
resolveDesktopSidebarWidth,
} from "@/components/desktop-sidebar-layout";
import { useTopBand, useWindowLayout, resolveDesktopDivisionLayout } from "@/window-layout";
import {
useTopBand,
useWindowLayout,
useWindowSafeAreaInsets,
resolveDesktopDivisionLayout,
} from "@/window-layout";
import {
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
SIDEBAR_RESIZE_FAIL_OFFSET,
@@ -173,6 +179,7 @@ export const LeftSidebar = memo(function LeftSidebar({
const { theme } = useUnistyles();
const { t } = useTranslation();
const insets = useSafeAreaInsets();
const windowInsets = useWindowSafeAreaInsets();
const isCompactLayout = useIsCompactFormFactor();
const activeWorkspace = useActiveWorkspaceSelection();
const showMobileAgent = usePanelStore((state) => state.showMobileAgent);
@@ -289,7 +296,11 @@ export const LeftSidebar = memo(function LeftSidebar({
<DesktopSidebar
{...sharedProps}
{...handlers}
insetsTop={insets.top}
insetsTop={resolveDesktopSidebarInsetTop({
overlay: desktopOverlay,
safeAreaTop: insets.top,
windowSafeAreaTop: windowInsets.top,
})}
active={active}
overlay={desktopOverlay}
/>
@@ -0,0 +1,39 @@
import React, { act } from "react";
import { createRoot } from "react-dom/client";
import { SafeAreaInsetsContext } from "react-native-safe-area-context";
import { afterEach, expect, it, vi } from "vitest";
import { WindowLayoutProvider, WindowLayoutSurface } from "@/window-layout";
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
vi.stubGlobal("React", React);
const statusBarInsets = { top: 32, right: 0, bottom: 20, left: 0 };
const surfaceStyle = { flex: 1 };
function noClose() {}
const container = document.createElement("div");
document.body.appendChild(container);
const root = createRoot(container);
afterEach(() => {
act(() => root.render(null));
});
it("keeps the close button below the status bar when opened from a wide layout", async () => {
await act(async () => {
root.render(
<SafeAreaInsetsContext.Provider value={statusBarInsets}>
<WindowLayoutProvider>
<WindowLayoutSurface compact={false} style={surfaceStyle}>
<MermaidFullscreenViewer
source={"graph TD\n A --> B"}
colorScheme="light"
onClose={noClose}
/>
</WindowLayoutSurface>
</WindowLayoutProvider>
</SafeAreaInsetsContext.Provider>,
);
});
const close = document.querySelector<HTMLElement>('[data-testid="mermaid-fullscreen-close"]');
expect(close).not.toBeNull();
expect(close!.getBoundingClientRect().top).toBeGreaterThanOrEqual(statusBarInsets.top);
});
@@ -8,6 +8,7 @@ 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 { WindowSafeArea } from "@/window-layout";
import { MermaidIframeRuntime, type MermaidRenderedMessage } from "./iframe-runtime.web";
import type { DiagramColorScheme } from "./render-model";
import { useMermaidRenderModel } from "./use-render-model";
@@ -23,11 +24,25 @@ interface MermaidFullscreenViewerProps {
const FALLBACK_SIZE = { width: 240, height: 240 };
const VIEWER_FIT = { padding: SPACING[6] };
export function MermaidFullscreenViewer({
source,
colorScheme,
onClose,
}: MermaidFullscreenViewerProps) {
export function MermaidFullscreenViewer(props: MermaidFullscreenViewerProps) {
return (
<Modal
transparent
animationType="fade"
statusBarTranslucent
visible
onRequestClose={props.onClose}
>
{/* The modal draws over the whole window: its insets are the window's, not the ones left
where the diagram was opened (wide layouts spend the top one above the content). */}
<WindowSafeArea>
<MermaidFullscreenContent {...props} />
</WindowSafeArea>
</Modal>
);
}
function MermaidFullscreenContent({ source, colorScheme, onClose }: MermaidFullscreenViewerProps) {
const { t } = useTranslation();
const insets = useSafeAreaInsets();
const { state, request, rendered, renderFailed } = useMermaidRenderModel({
@@ -93,35 +108,33 @@ export function MermaidFullscreenViewer({
);
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>
<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>
</WindowChromeRootRegion>
</Modal>
</View>
</WindowChromeRootRegion>
);
}
@@ -135,7 +148,11 @@ const focusLayerDomStyle: React.CSSProperties = {
const styles = StyleSheet.create((theme) => ({
root: { flex: 1, minHeight: 0, minWidth: 0 },
backdrop: { position: "absolute", inset: 0, backgroundColor: theme.colors.surface0 },
backdrop: {
position: "absolute",
inset: 0,
backgroundColor: theme.colors.surface0,
},
contentLayer: { position: "absolute", inset: 0 },
viewport: { flex: 1 },
}));
-206
View File
@@ -19,11 +19,9 @@ import {
type RewindMode,
} from "@/components/rewind";
import { TaskListRow } from "@/components/task-list-row";
import { Button } from "@/components/ui/button";
import { LoadingSpinner } from "@/components/ui/loading-spinner";
import { useIsCompactFormFactor } from "@/constants/layout";
import { isNative, isWeb } from "@/constants/platform";
import { useProvidersSnapshot } from "@/hooks/use-providers-snapshot";
import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
import { ICON_SIZE, type Theme } from "@/styles/theme";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
@@ -42,17 +40,13 @@ import type { AgentMessage } from "@getpaseo/protocol/agent-message";
import type {
AgentCapabilityFlags,
AgentMetric,
AgentProvider,
ProviderSwitchContextSummary,
ToolCallDetail,
} from "@getpaseo/protocol/agent-types";
import type { AgentAttachment } from "@getpaseo/protocol/messages";
import MaskedView from "@react-native-masked-view/masked-view";
import {
ArrowRightLeft,
Check,
CheckSquare,
ChevronDown,
ChevronRight,
CircleDot,
Copy,
@@ -1493,206 +1487,6 @@ export const CompactionMarker = memo(function CompactionMarker({
);
});
const StyledSwitchIcon = withUnistyles(ArrowRightLeft, (theme) => ({
color: theme.colors.foregroundMuted,
}));
const StyledChevronDownIcon = withUnistyles(ChevronDown, (theme) => ({
color: theme.colors.foregroundMuted,
}));
const StyledChevronRightIcon = withUnistyles(ChevronRight, (theme) => ({
color: theme.colors.foregroundMuted,
}));
export interface ProviderSwitchMarkerProps {
serverId?: string | null;
fromProvider: AgentProvider;
toProvider: AgentProvider;
fromModel?: string | null;
toModel?: string | null;
context?: ProviderSwitchContextSummary;
}
const providerSwitchStylesheet = StyleSheet.create((theme) => ({
wrapper: {
paddingVertical: theme.spacing[2],
gap: theme.spacing[2],
},
row: {
flexDirection: "row",
alignItems: "center",
gap: theme.spacing[2],
width: "100%",
},
line: {
flex: 1,
minWidth: 12,
height: 1,
backgroundColor: theme.colors.border,
},
triggerButton: {
flexShrink: 1,
minWidth: 0,
maxWidth: "85%",
},
triggerContent: {
flexDirection: "row",
alignItems: "center",
flexShrink: 1,
minWidth: 0,
maxWidth: "100%",
gap: theme.spacing[1.5],
},
triggerText: {
flexShrink: 1,
minWidth: 0,
fontFamily: theme.fontFamily.ui,
fontSize: 13,
color: theme.colors.foregroundMuted,
},
chevronSlot: {
width: 12,
height: 12,
alignItems: "center",
justifyContent: "center",
},
detailsCard: {
alignSelf: "center",
maxWidth: 480,
width: "100%",
paddingVertical: theme.spacing[2],
paddingHorizontal: theme.spacing[3],
borderRadius: theme.borderRadius.md,
borderWidth: 1,
borderColor: theme.colors.border,
backgroundColor: theme.colors.surface0,
gap: theme.spacing[1],
},
detailRow: {
fontFamily: theme.fontFamily.ui,
fontSize: 12,
color: theme.colors.foregroundMuted,
},
}));
function resolveProviderSwitchLabel(
provider: string,
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
): string {
return entries?.find((entry) => entry.provider === provider)?.label ?? provider;
}
function resolveProviderSwitchModelLabel(
provider: string,
modelId: string | null | undefined,
entries: ReturnType<typeof useProvidersSnapshot>["entries"],
): string | null {
if (!modelId) return null;
const entry = entries?.find((candidate) => candidate.provider === provider);
return entry?.models?.find((model) => model.id === modelId)?.label ?? modelId;
}
function formatProviderSwitchEndpoint(providerLabel: string, modelLabel: string | null): string {
return modelLabel ? `${providerLabel} (${modelLabel})` : providerLabel;
}
export const ProviderSwitchMarker = memo(function ProviderSwitchMarker({
serverId = null,
fromProvider,
toProvider,
fromModel,
toModel,
context,
}: ProviderSwitchMarkerProps) {
const { t } = useTranslation();
const { entries: providerEntries } = useProvidersSnapshot(serverId);
const [expanded, setExpanded] = useState(false);
const handleToggle = useCallback(() => setExpanded((prev) => !prev), []);
const fromLabel = resolveProviderSwitchLabel(fromProvider, providerEntries);
const toLabel = resolveProviderSwitchLabel(toProvider, providerEntries);
const fromModelLabel = resolveProviderSwitchModelLabel(fromProvider, fromModel, providerEntries);
const toModelLabel = resolveProviderSwitchModelLabel(toProvider, toModel, providerEntries);
const title = t("message.providerSwitch.switched", {
from: fromLabel,
to: toLabel,
});
const contextLine = context
? t("message.providerSwitch.contextSummary", {
count: context.includedItems,
chars: context.charCount.toLocaleString(),
budget: context.budgetChars.toLocaleString(),
})
: null;
const reasonsLine =
context?.truncated && context.omittedReasons?.length
? t("message.providerSwitch.trimmed", {
reasons: context.omittedReasons
.map((reason) => {
if (reason === "tail_window_limit") {
return t("message.providerSwitch.reasonTailWindow");
}
if (reason === "char_budget") {
return t("message.providerSwitch.reasonCharBudget");
}
return reason;
})
.join(", "),
})
: null;
let chevronIcon: React.ReactNode = null;
if (context) {
chevronIcon = expanded ? (
<StyledChevronDownIcon size={12} />
) : (
<StyledChevronRightIcon size={12} />
);
}
return (
<View style={providerSwitchStylesheet.wrapper} testID="provider-switch-marker">
<View style={providerSwitchStylesheet.row}>
<View style={providerSwitchStylesheet.line} />
<Button
variant="ghost"
size="sm"
style={providerSwitchStylesheet.triggerButton}
onPress={context ? handleToggle : undefined}
accessibilityLabel={title}
testID="provider-switch-marker-toggle"
>
<View style={providerSwitchStylesheet.triggerContent}>
<StyledSwitchIcon size={12} />
<Text
style={providerSwitchStylesheet.triggerText}
numberOfLines={1}
ellipsizeMode="tail"
>
{title}
</Text>
<View style={providerSwitchStylesheet.chevronSlot}>{chevronIcon}</View>
</View>
</Button>
<View style={providerSwitchStylesheet.line} />
</View>
{expanded && context ? (
<View style={providerSwitchStylesheet.detailsCard} testID="provider-switch-marker-details">
<Text style={providerSwitchStylesheet.detailRow}>
{`${formatProviderSwitchEndpoint(fromLabel, fromModelLabel)} → ${formatProviderSwitchEndpoint(toLabel, toModelLabel)}`}
</Text>
{contextLine ? (
<Text style={providerSwitchStylesheet.detailRow}>{contextLine}</Text>
) : null}
{reasonsLine ? (
<Text style={providerSwitchStylesheet.detailRow}>{reasonsLine}</Text>
) : null}
</View>
) : null}
</View>
);
});
interface TodoListCardProps {
items: TodoEntry[];
activity: TaskActivity;
@@ -10,11 +10,7 @@ import { useToast } from "@/contexts/toast-context";
import type { AgentScreenReadySyncState } from "@/hooks/use-agent-screen-state-machine";
import { selectAgentTimelineState, useSessionStore } from "@/stores/session-store";
import { useRewindAgentMutation } from "./use-rewind-agent-mutation";
import {
isPromptInActiveSegment,
isRewindableMessage,
useRewindMenuItems,
} from "./use-rewind-capabilities";
import { isRewindableMessage, useRewindMenuItems } from "./use-rewind-capabilities";
export function RewindCommandCenterRegistration({
serverId,
@@ -46,16 +42,10 @@ export function RewindCommandCenterRegistration({
if (timeline.status !== "synced" || timeline.newer === "available") {
return undefined;
}
const candidate =
return (
session.agentStreamHead.get(agentId)?.findLast((item) => item.kind === "user_message") ??
timeline.items.findLast((item) => item.kind === "user_message");
if (
!candidate ||
!isPromptInActiveSegment(candidate.timelineCursor, timeline.range?.activeSegmentStartSeq)
) {
return undefined;
}
return candidate;
timeline.items.findLast((item) => item.kind === "user_message")
);
});
const { rewindAgent, isPending } = useRewindAgentMutation({
serverId,
@@ -9,7 +9,6 @@ import { useRewindComposerRestore } from "./composer-restore";
import { useSessionStore } from "@/stores/session-store";
import { shouldRestoreComposerForRewindMode } from "./rewind-mode";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { hostSupportsFeature } from "@/runtime/host-features";
interface UseRewindAgentMutationInput {
serverId?: string;
@@ -43,16 +42,7 @@ export function useRewindAgentMutation(input: UseRewindAgentMutationInput): {
throw new Error(t("common.errors.daemonClientUnavailable"));
}
await input.client.rewindAgent(input.agentId, input.messageId, mode);
// COMPAT(timelineRewindOperations): added in v0.18.0, remove after 2027-05-25. A daemon with
// the feature delivers the rewind on the live timeline; an older one replaced the timeline
// and this client has to read it again.
const appliesLive =
input.serverId !== undefined &&
hostSupportsFeature(
useSessionStore.getState().sessions[input.serverId]?.serverInfo,
"timelineRewindOperations",
);
if (mode !== "files" && !appliesLive) {
if (mode !== "files") {
const cursor = input.serverId
? useSessionStore
.getState()
@@ -26,20 +26,6 @@ export function isRewindableMessage(messageId: string | undefined, text: string)
return Boolean(messageId) && text.trim().length > 0;
}
/**
* Whether a user prompt belongs to the active provider segment (after the latest provider switch).
* Prompts from earlier provider segments cannot be rewound.
*/
export function isPromptInActiveSegment(
timelineCursor: { anchorSeq?: number; seq?: number } | undefined,
activeSegmentStartSeq: number | undefined,
): boolean {
if (!activeSegmentStartSeq || activeSegmentStartSeq <= 0) return true;
const anchor = timelineCursor?.anchorSeq ?? timelineCursor?.seq;
if (anchor === undefined) return true;
return anchor > activeSegmentStartSeq;
}
export function resolveRewindMenuItems(
capabilities:
| Pick<
@@ -4,10 +4,11 @@ import { createRoot, type Root } from "react-dom/client";
import { PortalProvider } from "@gorhom/portal";
import { View } from "react-native";
import { KeyboardProvider } from "react-native-keyboard-controller";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { SafeAreaInsetsContext, SafeAreaProvider } from "react-native-safe-area-context";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { RetainedPanel } from "@/components/retained-panel";
import { KeyboardShiftProvider } from "@/keyboard/shift";
import { WindowLayoutProvider, WindowLayoutSurface } from "@/window-layout";
import type { AutocompleteOption } from "./autocomplete";
import { AutocompletePopover } from "./autocomplete-popover";
import { FloatingPanelPortalHost } from "./floating-panel-portal";
@@ -572,3 +573,64 @@ it("scrolls towards rows further from the composer when the wheel turns up", asy
expect(isRowInView("/skill-7")).toBe(true);
expect(popover.getBoundingClientRect().bottom).toBe(rectOf("composer-input")!.top - 12);
});
const STATUS_BAR_INSETS = { top: 32, left: 0, right: 0, bottom: 0 };
const SURFACE_STYLE = { flex: 1 };
const COMPOSER_NEAR_TOP_STYLE = { position: "absolute" as const, top: 60, left: 16, width: 358 };
/**
* A wide browser layout surface pads the status bar and gives its content a top inset of 0. The
* root portal host sits outside that surface, against the window's top edge, so a composer inside
* the surface that portals there still has to keep the popover below the status bar.
*/
function ComposerNearTop(): ReactNode {
return (
<View style={COMPOSER_NEAR_TOP_STYLE}>
<AutocompletePopover
visible
options={OPTIONS}
selectedIndex={OPTIONS.length - 1}
onSelect={ignoreSelection}
>
<View testID="composer-input" style={inputStyle(40)} />
</AutocompletePopover>
</View>
);
}
/** A composer near the top of a wide surface, portalling into the root host outside it. */
function WideSurfaceScreen(): ReactNode {
return (
<View style={SCREEN_STYLE}>
<WindowLayoutSurface compact={false} style={SURFACE_STYLE}>
<ComposerNearTop />
</WindowLayoutSurface>
<FloatingPanelPortalHost />
</View>
);
}
function WideSurfaceWindow(): ReactNode {
return (
<Providers>
<SafeAreaInsetsContext.Provider value={STATUS_BAR_INSETS}>
<WindowLayoutProvider>
<RetainedPanel active>
<WideSurfaceScreen />
</RetainedPanel>
</WindowLayoutProvider>
</SafeAreaInsetsContext.Provider>
</Providers>
);
}
it("keeps its top below the status bar when it portals out of a wide layout surface", async () => {
render(<WideSurfaceWindow />);
const popover = await waitForPopover();
await new Promise((resolve) => setTimeout(resolve, 200));
const screenTop = container!.getBoundingClientRect().top;
expect(popover.getBoundingClientRect().top - screenTop).toBeGreaterThanOrEqual(
STATUS_BAR_INSETS.top,
);
});
@@ -9,7 +9,6 @@ import {
import { Portal } from "@gorhom/portal";
import { useAnimatedReaction, useAnimatedRef } from "react-native-reanimated";
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import {
Autocomplete,
type AutocompleteOption,
@@ -56,7 +55,6 @@ export function AutocompletePopover({
);
const [anchorAtRest, setAnchorAtRest] = useState<AnchorAtRest | null>(null);
const windowDimensions = useWindowDimensions();
const safeAreaInsets = useSafeAreaInsets();
const portalHostName = useFloatingPanelPortalHostName();
const { isMoving } = useKeyboardShift();
const anchor = useKeyboardAnchor();
@@ -132,7 +130,6 @@ export function AutocompletePopover({
anchorRef={anchorRef}
anchorAtRest={anchorAtRest}
reservedLift={anchor.reservedLift}
topInset={safeAreaInsets.top}
>
<Autocomplete
options={options}
@@ -5,6 +5,7 @@ import Animated, {
useFrameCallback,
useSharedValue,
} from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { placeAboveAnchor, type PopoverFrameProps } from "./placement";
/**
@@ -20,11 +21,13 @@ export function PopoverFrame({
anchorRef,
anchorAtRest,
reservedLift,
topInset,
children,
}: PopoverFrameProps): ReactElement {
"use no memo";
// React Compiler memoizes effect captures by reading SharedValue.value during render.
// The frame renders in the portal host, so these are the host's insets, not the composer's: a
// host against the window's top edge keeps the popover below the status bar.
const topInset = useSafeAreaInsets().top;
const anchorHeight = useSharedValue(anchorAtRest.height);
const anchorLost = useSharedValue(false);
const readAnchorHeight = useCallback(() => {
@@ -2,6 +2,7 @@ import { useLayoutEffect, useRef, useState, type ReactElement } from "react";
import { flushSync } from "react-dom";
import { View } from "react-native";
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { placeAboveAnchor, type AnchorAtRest, type PopoverFrameProps } from "./placement";
type AnchorRect = Omit<AnchorAtRest, "height">;
@@ -26,11 +27,13 @@ export function PopoverFrame({
anchorRef,
anchorAtRest,
reservedLift,
topInset,
children,
}: PopoverFrameProps): ReactElement {
"use no memo";
// React Compiler memoizes effect captures by reading SharedValue.value during render.
// The frame renders in the portal host, so these are the host's insets, not the composer's: a
// host against the window's top edge keeps the popover below the status bar.
const topInset = useSafeAreaInsets().top;
const frameRef = useRef<View>(null);
const [anchor, setAnchor] = useState<AnchorRect>(anchorAtRest);
@@ -19,7 +19,6 @@ export interface PopoverFrameProps {
/** Taken asynchronously; the frame follows the anchor's live size between measurements. */
anchorAtRest: AnchorAtRest;
reservedLift: DerivedValue<number>;
topInset: number;
children: ReactNode;
}
@@ -70,4 +70,34 @@ describe("buildDesktopFrameStyle", () => {
expect(frameStyle).toMatchObject({ width: 360, minWidth: 360, maxWidth: 360 });
});
it("clamps a fixed height's minHeight and maxHeight to the available viewport height", () => {
const styles = buildDesktopFrameStyle({
desktopMinWidth: 440,
desktopLockWidth: false,
referenceWidth: 120,
desktopFixedHeight: 400,
desktopPositionStyle: { left: 0, top: 0 },
shouldHideDesktopContent: false,
availableHeight: 280,
}) as Array<ViewStyle | null>;
expect(styles[1]).toEqual({ minHeight: 280, maxHeight: 280 });
expect(styles[4]).toBeNull();
});
it("keeps the requested fixed height when viewport space exceeds it", () => {
const styles = buildDesktopFrameStyle({
desktopMinWidth: 440,
desktopLockWidth: false,
referenceWidth: 120,
desktopFixedHeight: 400,
desktopPositionStyle: { left: 0, top: 0 },
shouldHideDesktopContent: false,
availableHeight: 600,
}) as Array<ViewStyle | null>;
expect(styles[1]).toEqual({ minHeight: 400, maxHeight: 400 });
expect(styles[4]).toBeNull();
});
});
@@ -10,6 +10,17 @@ export interface DesktopFrameStyleInput {
availableHeight: number | undefined;
}
function resolveFixedHeight(
desktopFixedHeight: number | undefined,
availableHeight: number | undefined,
): number | null {
if (desktopFixedHeight == null) return null;
if (typeof availableHeight === "number") {
return Math.min(availableHeight, desktopFixedHeight);
}
return desktopFixedHeight;
}
export function buildDesktopFrameStyle(input: DesktopFrameStyleInput): StyleProp<ViewStyle> {
const {
desktopMinWidth,
@@ -20,14 +31,15 @@ export function buildDesktopFrameStyle(input: DesktopFrameStyleInput): StyleProp
shouldHideDesktopContent,
availableHeight,
} = input;
const resolvedFixedHeight = resolveFixedHeight(desktopFixedHeight, availableHeight);
const fixedHeightStyle =
desktopFixedHeight != null
? { minHeight: desktopFixedHeight, maxHeight: desktopFixedHeight }
resolvedFixedHeight != null
? { minHeight: resolvedFixedHeight, maxHeight: resolvedFixedHeight }
: null;
const hiddenStyle = shouldHideDesktopContent ? { opacity: 0 } : null;
const availableHeightStyle =
typeof availableHeight === "number"
? { maxHeight: Math.min(availableHeight, desktopFixedHeight ?? 400) }
resolvedFixedHeight == null && typeof availableHeight === "number"
? { maxHeight: Math.min(availableHeight, 400) }
: null;
const floor = Math.max(desktopMinWidth ?? 0, referenceWidth ?? 200);
const widthStyle = desktopLockWidth

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