Compare commits

..
Author SHA1 Message Date
Mohamed Boudra 2e646303b6 chore(gpui): bump runtime packages to paseo-4 2026-11-28 19:44:55 +01:00
Mohamed Boudra 122041acd4 test(gpui): check pointer control height within one device pixel
Query display scaleFactor from the test driver so pointer control height assertions handle non-integer DPI snapping (such as 1.9167 on Linux Xvfb).
2026-11-28 19:10:27 +01:00
Mohamed Boudra 8e5cab31ec refactor(app): export resource budget values and move sizing to presentation
Replace usesMobileResourceBudget with per-target budget limits (workspaceDeckRetentionLimit, sourceFileBudgets, deferModelSelectorMount) so callers read values directly and GPUI can tune its retention limit independently. Move initial font defaults and composer minimum height into presentation, and export plain values without resolve helpers from .gpui.ts owners.
2026-11-28 19:10:27 +01:00
Mohamed Boudra 5ef07a0335 test(gpui): verify Enter submit and workspace retention in native harness
Exercise multiline Shift+Enter newline insertion, Enter message submission, and retained workspace TextInput state across workspace switches in native.test.ts.
2026-11-28 19:10:27 +01:00
Mohamed Boudra d17ca42d1f fix(app): disable touch press delay, holds, and haptics on GPUI
Add a touch-timing owner and press-highlight.gpui.tsx so GPUI gets immediate press highlights and skips touch-hold delays and haptics on composer alternate send, draggable lists, and sidebar long-press interactions.
2026-11-28 19:10:26 +01:00
Mohamed Boudra b2b862b1ea fix(app): use desktop presentation defaults on GPUI
Add a presentation capabilities owner with a GPUI override so GPUI matches desktop inline rename, popover spacing, and non-sheet modal/browser presentation while keeping iOS, Android, web, and Electron unchanged.
2026-11-28 19:10:26 +01:00
Mohamed Boudra 8aaa01ad07 fix(app): give GPUI desktop resource budgets
Add a resource-budget owner with a GPUI override so mounted workspace retention, source highlight budgets, model selector mount deferral, font defaults, and composer minimum input height use desktop values on GPUI without altering iOS, Android, web, or Electron.
2026-11-28 19:10:26 +01:00
Mohamed Boudra 1887eb5220 fix(app): answer hardware keyboard presence and conventions on GPUI
Add GPUI hardware keyboard presence and convention files, expose hasSoftwareKeyboard from keyboard, and move composer Enter/hint/autofocus/blur, model browser autofocus/dismiss, terminal virtual key bar/paste/copy/insets, and panel keyboard dismiss onto the keyboard owner.
2026-11-28 19:10:26 +01:00
Mohamed Boudra 3576503027 fix(app): wire ResizeHandle fine-pointer branch for non-web GPUI
Use the pointer capability owner in ResizeHandle without calling DOM pointer capture or document/window APIs when running on GPUI. iOS, Android, web, and Electron keep their exact behavior.
2026-11-28 19:10:26 +01:00
Mohamed Boudra aeebea8d3d style(gpui): format desktop Cargo.toml 2026-11-28 19:10:20 +01:00
Mohamed Boudra b57648b196 chore(gpui): bump runtime packages to paseo-3 2026-11-28 17:46:32 +01:00
Mohamed Boudra 90aa1eef3f chore(gpui): install runtime packages from release tarballs
Replace the vendored react-native-gpui tree with pinned tarballs from the getpaseo/react-native-gpui paseo-2 release for the four runtime packages and seven @react-native-gpui modules, and add a --local install path for testing against a local fork checkout.
2026-11-28 16:14:04 +01:00
Mohamed Boudra 7a5be97a4c fix(gpui): report a fine pointer on GPUI so controls take pointer sizes
pointer-capabilities answers touch-primary for every non-web build, so the
GPUI desktop client took iOS touch sizes: 44 pt controls and rows instead
of 28 and 36. GPUI reports every pointer as a mouse, so its branch answers
fine pointer, no touch screen. iOS, Android and web resolve the same file
as before.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 1390e83b30 fix(gpui): export RefreshControl and VirtualizedList from the Unistyles adapter
The Unistyles Babel plugin sends RefreshControl and VirtualizedList imports
from react-native to the GPUI adapter, which did not export them. History
rendered the agent list with an undefined RefreshControl and showed
Element type is invalid.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 12b284335e fix(gpui): clamp enriched-markdown measurements to layoutConstraints
Forward minimum and maximum LayoutConstraints through measureMarkdown and clamp measured dimensions to Yoga bounds so stretched narrow content does not violate minimumSize.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 0706cdfeb6 fix(gpui): include LayoutConstraints in enriched-markdown shadow nodes
Apple clang does not reach LayoutConstraints.h transitively, so
measureContent saw only the forward declaration and failed to compile.
2026-11-28 16:13:35 +01:00
Mohamed Boudra b2b683a5d4 test(gpui): expand markdown block checks and add release stage benchmark
Add caller-level layout and pixel assertions across every Phase 1 block type, verify regression.png rendering output, and add the standalone release stage benchmark example.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 56eb19b7ca fix(gpui): match native enriched-markdown font, inline code, and code block defaults
Drop the Linux Nimbus Sans font remap so markdown resolves font families the same way as RN <Text>, fix serde renaming for isGFM, apply inline code fontScale, and add the iOS/Android code block language header and divider bar.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 418e676c87 feat(gpui): add enriched-markdown desktop GPUI backend
Implements EnrichedMarkdown and EnrichedMarkdownText inside packages/react-native-enriched-markdown/desktop by reusing the shared C++ MD4C parser, link recognizer, and tree-sitter code highlighter for Fabric measurement and rendering blocks, inline styles, links, lists, highlighted code, and tables on GPUI with zero changes under packages/app/src.
2026-11-28 16:13:35 +01:00
Mohamed Boudra 35a5cd4311 gpui: dispatch onLayout for any node that sets it 2026-11-28 13:10:11 +01:00
Mohamed Boudra 1eb69a4217 feat(gpui): add .gpui.* Metro resolution rule 2026-11-28 12:38:31 +01:00
Mohamed Boudra c1f6992a6c fix(gpui): adapt press-feedback and stabilize native test after main merge 2026-11-28 12:20:46 +01:00
Mohamed Boudra 4de5e7e4df Merge remote-tracking branch 'origin/main' into gpui-ship-readiness-assessment
# Conflicts:
#	.oxfmtrc.json
#	.oxlintrc.json
#	package.json
#	packages/relay/src/e2e.test.ts
2026-11-28 11:58:16 +01:00
Mohamed Boudra d0129a4f90 chore(gpui): catch up vendored react-native-gpui to ad502d80d
Update vendor/react-native-gpui packages/{cli,codegen,core,hermes} to streetwriters/react-native-gpui@ad502d80d and modules/* to streetwriters/react-native-gpui-modules@7435b7f4d, drop upstreamed local patches, retain the remaining local patches documented in UPSTREAM, refresh packages/app/gpui dependencies and Cargo lockfile, and include the updated GPUI README rules.
2026-11-28 11:55:55 +01:00
paseo-bot[bot]andChristoph Leiter b261d207c2 fix(server): reuse provider images across daemon restarts (#7895)
* fix(server): reuse provider images across daemon restarts

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

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

---------

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

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

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

* docs: document non-agent activeTurnBehavior queue support

* chore: tag nonAgentMessageQueue COMPAT comments with v0.18.2

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

Closes #2795
Supersedes #4345

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

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

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

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

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

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

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

Closes #5530
Refs #9487, #7760

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

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

---------

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

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

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

Closes #4679
Supersedes #10603

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

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

---------

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

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

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

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

Closes #3589

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Refs #10699

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

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

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

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

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

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

---------

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

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

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

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

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

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

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

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

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

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

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

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

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

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

---------

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

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

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

Fixes #6903

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

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

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

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

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

Co-authored-by: Desmond Leong <desmond@returning.ai>
Co-authored-by: Nicholas Salgueiro <nickmaglowsch3@gmail.com>
2026-11-28 13:23:40 +07:00
e994be2958 fix(app): send phone photos as downscaled JPEG instead of full-size PNG (#9328)
Add image converted HEIC photos to full-resolution PNG. Inlined as base64,
a sub-5 MB iPhone photo became a 56 MiB message and was rejected by the
32 MiB relay limit (getpaseo/paseo#2668).

HEIC/HEIF now becomes JPEG (quality 0.85); other unsupported formats still
become PNG to keep transparency. Any picked image whose long edge exceeds
2000 px is downscaled to fit, keeping its JPEG/PNG format.

Co-authored-by: Brandon Elliott <923787+Brandon168@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 10:56:29 +07:00
e0eebe3307 Show ACP form elicitations as native question cards (#11135)
* feat(plugin): show ACP form elicitations as native question cards

The shared plugin ACP client advertised empty clientCapabilities and
had no createElicitation handler, so ACP agents like Antigravity (agy)
could not send structured form elicitations and fell back to plain
markdown option lists (leaving ask_question unanswerable via Paseo's
question card).

Advertise clientCapabilities.elicitation.form by default and map ACP
1.x form elicitation schemas onto Paseo's existing kind: "question"
permission card inside packages/plugin/src/server/acp-internal:
- Track tool approvals and form elicitations in one unified pending map
  so deferred turns, mode-switch guards, turn end, interrupt, close,
  and failure cleanup stay consistent.
- Never auto-accept elicitations in autoAcceptMode; decline url mode,
  out-of-turn, mismatched-session, and unsupported/malformed schemas
  cleanly without throwing.
- Fold optional sibling <key>_other string fields into allowOther for
  both no-sentinel (agy) and "other"-sentinel schemas, preserve unique
  headers/labels and ", " multi-select handling, mark defaults, and
  keep __proto__ keys safe via Object.hasOwn and Object.fromEntries.

Co-authored-by: Daniel JB Clark <djbclark@gmail.com>
Co-authored-by: Jake Cattrall <krazyjakee@gmail.com>

* fix(plugin): keep _other separate when required choice has no other sentinel

---------

Co-authored-by: Daniel JB Clark <djbclark@gmail.com>
Co-authored-by: Jake Cattrall <krazyjakee@gmail.com>
2026-11-28 10:40:23 +07:00
paseo-bot[bot]andClaude Opus 5.5 6d8938e260 test(server): wait for a stopped script's program before cleanup (#11127)
On Windows the PTY kill ends the shell at once and the script's node
process later, so the test's temp-dir rm raced it and failed with EBUSY.
The test now records the script's pid and waits for it to exit after
the stopped status.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 00:42:38 +00:00
paseo-bot[bot] b15ac514d9 fix(app): keep Changes responsive when wrapping long diff lines (#11113)
Wrapping a long line with Unicode or code ligatures repeatedly measured most of the remaining line. Start the search near the next wrap so narrow viewports avoid shaping the same text repeatedly.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-11-27 23:12:44 +00:00
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 291c8ad1a8 fix(gpui): stabilize macOS packaging, connections and appearance
Release terminal WebSocket clients on the JS thread so daemon retries do not exhaust descriptors or join their own IO thread. Preserve Cargo symbols and seal ad-hoc macOS bundles with a library-loading policy that works with hardened runtime.

Use rounded border decoration without changing Fabric child layout, and route desktop hover through pointer events and Pressable render props. Include native regressions and reproducible package verification.
2026-11-08 04:40:38 +01:00
Mohamed Boudra 6d247815fd test(relay): keep local E2E traffic off production upstream 2026-11-02 02:32:15 +01:00
Mohamed Boudra d785a685a0 feat(app): add an experimental native desktop target 2026-11-02 02:19:47 +01:00
Mohamed Boudra 5518c25ac5 chore(gpui): vendor the experimental native runtime 2026-11-02 02:19:36 +01:00
630 changed files with 69897 additions and 11739 deletions
+2
View File
@@ -0,0 +1,2 @@
packages/app/gpui/package-lock.json linguist-generated
packages/app/gpui/desktop/Cargo.lock linguist-generated
+3
View File
@@ -86,6 +86,7 @@ packages/server/src/server/fixtures/dictation/dictation-debug-largest.wav
packages/server/src/server/fixtures/dictation/dictation-debug-largest.transcript.txt
packages/protocol/src/generated/validation/*.aot.ts
packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts
packages/protocol/src/generated/validation/message-defaults.ts
packages/protocol/codegen/generated/
/artifacts
@@ -98,3 +99,5 @@ app.json
# Project-local Serena configuration and memories.
.serena/
!packages/app/gpui/app.json
+1
View File
@@ -15,6 +15,7 @@
"*.lock",
"**/*.gen.ts",
"**/*.gen.tsx",
"**/*.icon/**",
"packages/react-native-enriched-markdown/**"
]
}
+1 -1
View File
@@ -58,7 +58,7 @@
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo のスポンサーになる</a></td>
</tr>
+1 -1
View File
@@ -52,7 +52,7 @@
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo 스폰서 되기</a></td>
</tr>
+1 -1
View File
@@ -57,7 +57,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="56"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
</tr>
+1 -1
View File
@@ -58,7 +58,7 @@
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
<table>
<tr valign="top">
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
<td align="center" width="33%"><a href="https://paseo.sh/zh-CN/sponsor">成为 Paseo 赞助商</a></td>
</tr>
+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();
+4 -4
View File
@@ -154,17 +154,17 @@ Users can also detach an existing subagent from the subagents track. Detach is d
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
An agent sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. `steer` and `interrupt` mean what they mean for a person. A person's send has no `queue`. Each kind of prompt is released this way:
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
- **`queue`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries. Finish notifications and change-request updates always queue.
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages. Finish notifications and change-request updates always queue.
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
- **A person's prompt** (app, CLI, top-level MCP) is dispatched directly with its existing steer or interrupt behavior and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) is dispatched directly and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`.
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`. A new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
A command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and a `steer` or `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text.
+7
View File
@@ -29,6 +29,13 @@ the titlebar row. Production builds leave the variable unset and show no label.
`npm run dev` is only a shorthand for `npm run dev:server`. Keep `127.0.0.1:6767` for the packaged app and production-style `~/.paseo` state.
## Experimental GPUI client
The opt-in [GPUI target](../packages/app/gpui/README.md) runs the existing React
Native app on Linux. Its contributor guide covers setup, the renderer comparison,
unsupported features, native checks, and experiments to pick up. It connects to
an already-running daemon and does not replace the Electron dev command.
## Nix desktop package
The flake exposes `packages.<system>.desktop` on Linux and macOS:
+1 -3
View File
@@ -72,9 +72,7 @@ hashes, never prompts, environment values, or credentials.
Before messaging an archived workspace, call `workspace.recovery.inspect.request`, then
`workspace.recovery.restore.request` and await success. The native message handler unarchives the
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so
`activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn
when that provider cannot steer. The daemon rejects `queue` on a direct send.
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so `activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn when that provider cannot steer, and `activeTurnBehavior: "queue"` waits for the running turn to end when the host advertises `server_info.features.nonAgentMessageQueue`.
Execution completion and arrival-specific output authority remain Hub responsibilities.
The older `hub.execution.*` RPCs remain accepted for existing clients. Their execution ownership
+3 -3
View File
@@ -95,9 +95,9 @@ A focused terminal excludes that binding. The source leaves terminal Escape alon
terminal Escape/Ctrl forwarding is a separate feature.
Terminal arrows never pass through the shortcut pipeline. The Android hardware
module claims them while the terminal's hidden input (`nativeID`) owns the focus.
`TextInput.onKeyPress` only sees IME keys, and an arrow that falls through moves
the hidden caret and desyncs the next text change, so the pipeline cannot own them.
module claims them while the terminal's native input (`nativeID`) owns the focus,
so Android DPAD focus search cannot move focus away from the terminal view, while
leaving active IME composition spans untouched for candidate navigation.
## Keys shared with text editing
+2
View File
@@ -12,6 +12,8 @@ Every block is separated by one gap, `density.blockGap`: 12 on compact layouts,
Workspace file links use the shared file-link resolver. The workspace supplies its client, root and open-file action once; chat can supply the agent's more specific context. URLs use the same link press path. Recognized inline-code paths stay tappable. The library callback carries the tapped occurrence’s syntax context. Preserve it when opening files: explicit Markdown links decode URL escapes, while recognized inline-code paths preserve literal percent characters and use suffix lookup. Identical URL strings in different occurrences must stay distinct. Explicit absolute workspace links receive a relative hover title; existing authored titles remain intact. Inside a workspace, forge references such as `#12` and `owner/repo#12` are recognized in prose (not code) and open the workspace forge; the reference pattern comes before path recognition so `group/project#12` is not read as a path. See [forge providers](forge-providers.md#gotchas).
Right-click on web and long press on native open one link menu per rendered part (`components/markdown/link-menu`), not one per link: a menu root cannot sit inside a paragraph without producing invalid markup on web. The native long-press event carries only the URL, with no position and no syntax context. The menu takes the position from the touch that started the press, and treats a URL that is no `](destination)` in the source as recognized text.
Pass `external` for author-controlled Markdown from outside the host, such as a plugin README. It follows the registry's overview contract in `packages/protocol/src/plugin-overview.ts`, which the website also uses: only absolute https links and images work, and any other destination renders as its label or alt text. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only https. None of the workspace recognition above applies, so `Node.js` is prose, not a file. The lines of a paragraph join, as they do on the README's forge.
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[![Retrigger](badge.svg)](url) Confidence` stay inline on web; the library's web renderer only checked direct paragraph children, so it rendered them as full-width block images (fixed in the fork).
+2
View File
@@ -63,6 +63,8 @@ An arbitrary Activity launch with data extras does not exercise Expo's FCM path.
Foreground pushes remain in Notification Center without a banner or sound.
This preserves notifications sent with stale presence information.
Native clients have no DOM events, so presence comes from `@/hooks/native-user-activity`: touches on the root `GestureHandlerRootView` and edits in the native `EditingTextInput` refresh `lastActivityAt`. Touches inside a native `Modal` open a separate window and do not reach the root.
## Startup and verification
Wait for the root navigator, host registry, remembered selection, and startup
+7
View File
@@ -103,6 +103,13 @@ The `worktree-include` built-in copies gitignored files selected by
[`.worktreeinclude`](../public-docs/worktrees.md#copy-local-files-with-worktreeinclude)
before setup and agents, through `worktree.create.after`.
The `cloudflared-tunnel` and `tailscale-funnel` built-ins register tunnel providers through
`server.registerTunnelProvider()`. Both start without installed binaries or credentials and report
availability through `status()`. `cloudflared-tunnel` runs quick tunnels only, with `--url` set to
the exposure target. Named Cloudflare tunnels are not supported: the Cloudflare dashboard sets
their routing, so their URL does not serve the exposure target. `tailscale-funnel` runs `tailscale funnel` in the foreground: with
`--bg`, tailscaled keeps the Funnel public after a crash with no owner.
Desktop packaging ships the entire built-in plugin directory as an external resource,
including declarations. The external esbuild compiler cannot read Electron's `app.asar`
filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation.
+1 -1
View File
@@ -21,7 +21,7 @@ The protocol package owns generation.
- `packages/protocol/src/validation/ws-outbound-envelope.ts` defines the tag-only envelope schema and exposes the session message schemas that get their own validators.
- `packages/protocol/scripts/generate-validation-aot.mjs` writes the zod-aot discovery entry and the runtime schema metadata, runs the exact-pinned compiler, and applies the small local compiler patches before generation. It also emits the `type` → validator map the boundary dispatches through.
- `packages/protocol/scripts/watch-validation-aot.mjs` reruns generation while editing protocol sources.
- `packages/protocol/codegen/generated/ws-outbound.compile.ts`, `packages/protocol/src/generated/validation/ws-outbound.aot.ts`, and `packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts` are generated and gitignored. The metadata module lets generated code reach schema fallback/default values.
- `packages/protocol/codegen/generated/ws-outbound.compile.ts`, `packages/protocol/src/generated/validation/ws-outbound.aot.ts`, `packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts`, and `packages/protocol/src/generated/validation/message-defaults.ts` are generated and gitignored. The metadata module lets generated code reach schema fallback/default values, and `message-defaults.ts` lets zero-Zod clients (`packages/protocol/src/validation/message-defaults.ts`) apply every schema `.default()` without loading Zod or `ws-outbound.aot.ts`.
Generation runs from protocol-owned lifecycle hooks: `prebuild`, `pretypecheck`, `pretest`, and `watch`. Installs do not run generation: published packages consume protocol from prebuilt `dist`, and local build/typecheck/test flows generate the source file at the point it is actually needed.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 19 KiB

After

Width:  |  Height:  |  Size: 19 KiB

+8 -2
View File
@@ -47,8 +47,14 @@
"ignore": ["android/**", "ios/**", ".expo/**", "dist/**", "scripts/reset-project.js"]
},
"packages/cli": {
"entry": ["src/index.ts", "bin/paseo", "src/**/*.test.{ts,tsx}", "tests/**/*.{ts,tsx}"],
"project": ["src/**/*.{ts,tsx}", "tests/**/*.{ts,tsx}"]
"entry": [
"src/index.ts",
"bin/paseo",
"scripts/**/*.mjs",
"src/**/*.test.{ts,tsx}",
"tests/**/*.{ts,tsx}"
],
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.mjs", "tests/**/*.{ts,tsx}"]
},
"packages/relay": {
"entry": ["src/index.ts", "src/e2ee.ts", "src/cloudflare-adapter.ts", "src/**/*.test.ts"],
+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-SZV3WTKLb+JhxWNo/jWyx+2sipzfL93YbbqQSihd3Wo=
sha256-aal9eR571blWuL7CZt1LR+KfA4QPJ0ivVl/GSTWy93o=
+5 -1
View File
@@ -126,7 +126,11 @@
"release:push": "node scripts/push-current-release-tag.mjs",
"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"
"release:reconcile": "node scripts/reconcile-release.mjs",
"gpui:install": "node scripts/gpui.mjs install",
"gpui:bundle": "node scripts/gpui.mjs bundle",
"build:gpui": "node scripts/gpui.mjs build",
"dev:gpui": "node scripts/gpui.mjs run"
},
"devDependencies": {
"@types/ws": "^8.5.14",
+2
View File
@@ -2,6 +2,7 @@ const fs = require("node:fs");
const path = require("node:path");
const pkg = require("./package.json");
const withAndroidAsyncStorageSize = require("./plugins/with-android-async-storage-size");
const withAndroidIgnoreBoldText = require("./plugins/with-android-ignore-bold-text");
const withAndroidOptionalCamera = require("./plugins/with-android-optional-camera");
const withAndroidProfileable = require("./plugins/with-android-profileable");
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
@@ -148,6 +149,7 @@ export default {
withPasteInput,
withAndroidScroll,
withAndroidDisplayMetrics,
withAndroidIgnoreBoldText,
[withAndroidAsyncStorageSize, 64],
...buildProfile.cameraPlugins,
withAndroidOptionalCamera,
+89
View File
@@ -112,3 +112,92 @@ describe("hardware keyboard scene integration", () => {
expect(configureHardwareKeyboardAppDelegate(configured)).toBe(configured);
});
});
// Android Bold text bolds unstyled text at draw time after React Native measured it
// unbolded, which clips trailing words (#4057, #10152, #10850). The activity must opt out
// with a sparse Configuration() so other configuration fields still update live.
describe("Android Bold text opt-out", () => {
const {
configureIgnoreBoldTextMainActivity,
} = require("./plugins/with-android-ignore-bold-text.js");
const {
configureDisplayMetricsActivity,
} = require("./modules/paseo-display-metrics/app.plugin.js");
const mainActivity = [
"package sh.paseo",
"import expo.modules.splashscreen.SplashScreenManager",
"",
"import android.os.Build",
"import android.os.Bundle",
"",
"import com.facebook.react.ReactActivity",
"",
"class MainActivity : ReactActivity() {",
" override fun onCreate(savedInstanceState: Bundle?) {",
" super.onCreate(null)",
" }",
"}",
"",
].join("\n");
it("zeroes fontWeightAdjustment on a sparse Configuration before attaching and is idempotent", () => {
const configured = configureIgnoreBoldTextMainActivity(mainActivity);
expect(configured).toMatch(/^import android\.content\.Context$/m);
expect(configured).toMatch(/^import android\.content\.res\.Configuration$/m);
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
expect(configured).toContain("val override = Configuration()");
expect(configured).not.toContain("Configuration(configuration)");
expect(configured).toContain("override.fontWeightAdjustment = 0");
expect(configured).toContain(
"super.attachBaseContext(newBase.createConfigurationContext(override))",
);
expect(configured.indexOf("attachBaseContext")).toBeLessThan(configured.indexOf("onCreate"));
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
});
it("composes cleanly with withAndroidDisplayMetrics in both plugin orders", () => {
const displayFirst = configureIgnoreBoldTextMainActivity(
configureDisplayMetricsActivity(mainActivity),
);
const boldFirst = configureDisplayMetricsActivity(
configureIgnoreBoldTextMainActivity(mainActivity),
);
for (const configured of [displayFirst, boldFirst]) {
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
expect(configured).toContain("val override = Configuration()");
expect(configured).toContain("override.fontWeightAdjustment = 0");
expect(configured).toContain("override fun onContentChanged()");
expect(configured).toContain(
"override fun onConfigurationChanged(newConfig: android.content.res.Configuration)",
);
expect(configured).toContain(
"sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)",
);
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
expect(configureDisplayMetricsActivity(configured)).toBe(configured);
}
});
it("fails the prebuild when the MainActivity template changes shape", () => {
expect(() => configureIgnoreBoldTextMainActivity("package sh.paseo\n")).toThrow(
/MainActivity class declaration/,
);
});
it("fails the prebuild rather than duplicate an existing attachBaseContext override", () => {
const withExistingOverride = mainActivity.replace(
"override fun onCreate",
"override fun attachBaseContext(newBase: Context) { super.attachBaseContext(newBase) }\n\n override fun onCreate",
);
expect(() => configureIgnoreBoldTextMainActivity(withExistingOverride)).toThrow(
/existing attachBaseContext override/,
);
});
it("is registered in the app config", async () => {
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
// Expo records function plugins by name.
expect(exp.plugins).toContain("withAndroidIgnoreBoldText");
}, 30_000);
});
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

@@ -1042,7 +1042,7 @@ test("changes context menu recursively collapses descendant folders", async ({ p
nestedLabel.boundingBox(),
]);
if (!rootBounds || !nestedBounds) throw new Error("Changes tree rows have no bounds");
expect(nestedBounds.x - rootBounds.x).toBe(12);
expect(nestedBounds.x - rootBounds.x).toBe(16);
await tree.getByTestId("diff-folder-src-toggle").click({ button: "right" });
await page.getByTestId("diff-folder-src-collapse-folder").click();
@@ -3,6 +3,7 @@ import path from "node:path";
import { expect, test } from "../support/fixtures";
import { expectComposerVisible } from "../support/helpers/composer";
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import {
expectSubagentRowGone,
@@ -29,6 +30,89 @@ import {
const FILE_LINK = "linked.ts:3";
test("compact offers file actions from a link and from the file sheet", async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await seedMockAgentWorkspace({
repoPrefix: "compact-file-actions-",
title: "File actions",
initialPrompt: promptMentioning(FILE_LINK),
});
try {
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
const fileLink = page.getByText(FILE_LINK, { exact: true });
await expect(fileLink).toBeVisible({ timeout: 15_000 });
// Native opens the same sheet from a long press.
await fileLink.click({ button: "right" });
const linkMenu = page.getByTestId("markdown-link-menu-content");
await expect(linkMenu.getByRole("menuitem")).toHaveText([
"Open file",
"Reveal in Files",
"Download",
"Copy path",
"Copy relative path",
]);
await linkMenu.getByRole("menuitem", { name: "Open file" }).click();
await expect(sheet(page, "linked.ts")).toBeVisible();
await page.getByTestId("sheet-file-menu-trigger").click();
const sheetMenu = page.getByTestId("sheet-file-menu-content");
await expect(sheetMenu.getByRole("menuitem")).toHaveText([
"Reveal in Files",
"Download",
"Copy path",
"Copy relative path",
]);
await expect(sheetMenu.getByRole("menuitem").last()).toBeInViewport({ ratio: 1 });
await page.screenshot({
path: test.info().outputPath("compact-file-sheet-menu.png"),
animations: "disabled",
});
await sheetMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
await expectNoSheetOpen(page);
await expect(
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
).toContainText("linked.ts");
await page.screenshot({
path: test.info().outputPath("compact-reveal-in-files.png"),
animations: "disabled",
});
} finally {
await workspace.cleanup();
}
});
test("a narrow desktop window keeps the desktop actions in the file sheet menu", async ({
page,
}) => {
await page.setViewportSize({ width: 390, height: 844 });
const workspace = await seedMockAgentWorkspace({
repoPrefix: "narrow-desktop-file-actions-",
title: "File actions",
initialPrompt: promptMentioning(FILE_LINK),
});
try {
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
await installLocalDesktopHost(page, workspace.cwd, { fileManager: "Dolphin" });
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
await page.getByText(FILE_LINK, { exact: true }).click();
await expect(sheet(page, "linked.ts")).toBeVisible({ timeout: 15_000 });
await page.getByTestId("sheet-file-menu-trigger").click();
await expect(page.getByTestId("sheet-file-menu-content").getByRole("menuitem")).toHaveText([
"Reveal in Files",
"Reveal in Dolphin",
"Open in default app",
"Download",
"Copy path",
"Copy relative path",
]);
} finally {
await workspace.cleanup();
}
});
test("compact opens files and subagents in a sheet, leaving the tabs for agents", async ({
page,
}) => {
@@ -0,0 +1,143 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, type Page } from "@playwright/test";
import { test } from "../support/fixtures";
import {
expectExplorerEntryHidden,
expectExplorerEntryVisible,
expandFolder,
expectFileTabOpen,
openFileExplorer,
} from "../support/helpers/file-explorer";
import { gotoWorkspace } from "../support/helpers/launcher";
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
let workspace: SeededWorkspace;
test.beforeEach(async () => {
workspace = await seedWorkspace({ repoPrefix: "file-explorer-filter-" });
await mkdir(path.join(workspace.repoPath, "data/nested"), { recursive: true });
await writeFile(path.join(workspace.repoPath, "data/nested/report.csv"), "name,total\n");
await mkdir(path.join(workspace.repoPath, "docs"), { recursive: true });
await writeFile(path.join(workspace.repoPath, "docs/guide.md"), "# Guide\n");
});
test.afterEach(async () => {
await workspace?.cleanup();
});
function filterInput(page: Page) {
return page.getByTestId("files-filter-input");
}
function matches(page: Page) {
return page.locator('[data-testid^="file-filter-row-"][aria-selected]');
}
function match(page: Page, name: string) {
return matches(page).filter({ hasText: name });
}
test("finds files in collapsed folders and acts on them", async ({ page }) => {
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
await expandFolder(page, "docs");
await expectExplorerEntryVisible(page, "guide.md");
await filterInput(page).fill("report");
await expect(matches(page)).toHaveCount(1);
await expect(match(page, "report.csv")).toContainText("data/nested");
// Draggable onto the chat, like a tree row.
await expect(match(page, "report.csv").locator('[draggable="true"]')).toHaveCount(1);
await match(page, "report.csv").click({ button: "right" });
const menu = page.getByTestId(/file-filter-row-\d+-context-menu$/);
for (const name of [
"Reveal in Files",
"Copy path",
"Copy relative path",
"Download",
"Rename",
"Delete",
]) {
await expect(menu.getByRole("menuitem", { name, exact: true })).toBeVisible();
}
await expect(menu.getByRole("menuitem", { name: "New file", exact: true })).toHaveCount(0);
await page.keyboard.press("Escape");
await expect(menu).toHaveCount(0);
await match(page, "report.csv").click();
await expectFileTabOpen(page, "data/nested/report.csv");
// Escape restores the tree with its expanded folders.
await filterInput(page).press("Escape");
await expect(filterInput(page)).toHaveValue("");
await expectExplorerEntryVisible(page, "guide.md");
await expectExplorerEntryHidden(page, "report.csv");
// So does the clear button.
await filterInput(page).fill("zzz-no-such-file");
await expect(page.getByText("No matching files", { exact: true })).toBeVisible();
await page.getByTestId("files-filter-clear").click();
await expect(filterInput(page)).toHaveValue("");
await expectExplorerEntryVisible(page, "guide.md");
// Revealing a match leaves the filter and selects the file in the tree.
await filterInput(page).fill("report");
await match(page, "report.csv").click({ button: "right" });
await page.getByRole("menuitem", { name: "Reveal in Files", exact: true }).click();
await expect(filterInput(page)).toHaveValue("");
await expect(
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
).toContainText("report.csv");
});
/** The directory listings the app asks the host for, by path. */
function recordDirectoryListings(page: Page): string[] {
const listed: string[] = [];
page.on("websocket", (socket) => {
socket.on("framesent", ({ payload }) => {
if (typeof payload !== "string") return;
const { message } = JSON.parse(payload);
if (message?.type === "file_explorer_request" && message.mode === "list") {
listed.push(message.path);
}
});
});
return listed;
}
test("opens a matching folder in the tree", async ({ page }) => {
const listed = recordDirectoryListings(page);
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
await filterInput(page).fill("nested");
await match(page, "nested").first().click();
await expect(filterInput(page)).toHaveValue("");
await expectExplorerEntryVisible(page, "report.csv");
await expect(
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
).toContainText("nested");
// One walk down to the folder: its collapsed parent is listed once.
expect(listed.filter((directory) => directory === "data")).toEqual(["data"]);
});
test("renames and deletes a match without leaving the filter", async ({ page }) => {
await gotoWorkspace(page, workspace.workspaceId);
await openFileExplorer(page);
await filterInput(page).fill("guide");
await match(page, "guide.md").click({ button: "right" });
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
const nameInput = page.getByTestId("file-explorer-name-input");
await nameInput.fill("guide-v2.md");
await nameInput.press("Enter");
await expect(match(page, "guide-v2.md")).toBeVisible();
page.once("dialog", (dialog) => void dialog.accept());
await match(page, "guide-v2.md").click({ button: "right" });
await page.getByRole("menuitem", { name: "Delete", exact: true }).click();
await expect(page.getByText("No matching files", { exact: true })).toBeVisible();
});
@@ -0,0 +1,135 @@
import { mkdir, writeFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import { commandCenterSection, openCommandCenter } from "../support/helpers/command-center";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
const REPLY = [
"Read [the report](data/report.csv), the [settings](.config/nested/file-55.json),",
"the [data folder](data) or the [website](https://example.test/docs).",
"Nothing is at gone.md.",
].join(" ");
async function seedLinkedFiles() {
const agent = await seedMockAgentWorkspace({
repoPrefix: "file-link-menu-",
title: "File link actions",
initialPrompt: "Show the links",
featureValues: { mockAssistantResponse: REPLY },
});
await mkdir(path.join(agent.cwd, "data"), { recursive: true });
await writeFile(path.join(agent.cwd, "data/report.csv"), "name,total\nalpha,1\n");
await mkdir(path.join(agent.cwd, ".config/nested"), { recursive: true });
// Enough siblings that the target row starts outside the tree's viewport.
await Promise.all(
Array.from({ length: 60 }, (_, index) =>
writeFile(
path.join(agent.cwd, `.config/nested/file-${String(index).padStart(2, "0")}.json`),
"{}\n",
),
),
);
await agent.client.waitForFinish(agent.agentId, 30_000);
return agent;
}
function replyLink(page: Page, name: string) {
return page.getByTestId("assistant-message").getByRole("link", { name, exact: true });
}
function linkMenu(page: Page) {
return page.getByTestId("markdown-link-menu");
}
function selectedTreeRow(page: Page) {
return page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]');
}
async function expectMenuItems(page: Page, names: string[]) {
await expect(linkMenu(page).getByRole("menuitem")).toHaveText(names);
}
async function dismissMenu(page: Page) {
await page.keyboard.press("Escape");
await expect(linkMenu(page)).toHaveCount(0);
}
async function screenshot(page: Page, name: string) {
await page.screenshot({
path: test.info().outputPath(`${name}.png`),
animations: "disabled",
});
}
test("links in chat and file tabs offer file actions and reveal the file in Files", async ({
page,
}, testInfo) => {
testInfo.setTimeout(180_000);
const agent = await seedLinkedFiles();
try {
await page.addInitScript(() => {
localStorage.setItem(
"panel-state",
JSON.stringify({ state: { explorerShowHiddenFiles: false }, version: 0 }),
);
});
await openAgentRoute(page, agent);
await replyLink(page, "the report").click({ button: "right" });
await expectMenuItems(page, [
"Open file",
"Open to the side",
"Reveal in Files",
"Download",
"Copy path",
"Copy relative path",
]);
await screenshot(page, "chat-file-link-menu");
await dismissMenu(page);
await replyLink(page, "data folder").click({ button: "right" });
await expectMenuItems(page, ["Reveal in Files", "Copy path", "Copy relative path"]);
await dismissMenu(page);
await replyLink(page, "website").click({ button: "right" });
await expectMenuItems(page, ["Open in default browser", "Copy link"]);
await screenshot(page, "chat-web-link-menu");
await dismissMenu(page);
// A bare name is looked up while the menu is open; acting on one that matches nothing says so.
await replyLink(page, "gone.md").click({ button: "right" });
await linkMenu(page).getByRole("menuitem", { name: "Download" }).click();
await expect(page.getByTestId("assistant-file-link-not-found-toast")).toContainText("gone.md");
await replyLink(page, "the report").click({ button: "right" });
await linkMenu(page).getByRole("menuitem", { name: "Reveal in Files" }).click();
await expect(selectedTreeRow(page)).toContainText("report.csv");
await expect(replyLink(page, "the report")).toBeVisible();
await screenshot(page, "reveal-in-files-from-chat-link");
// A hidden folder, a freshly expanded tree and a row far below the fold.
await replyLink(page, "settings").click();
const fileTab = page.getByTestId("workspace-tab-file_.config/nested/file-55.json").first();
await expect(fileTab).toBeVisible();
await fileTab.click({ button: "right" });
const tabMenu = page.getByTestId("workspace-tab-context-file_.config/nested/file-55.json");
await expect(tabMenu.getByRole("menuitem", { name: "Reveal in Files" })).toBeVisible();
await expect(tabMenu.getByRole("menuitem", { name: "Copy relative path" })).toBeVisible();
await screenshot(page, "file-tab-menu");
await tabMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
await expect(selectedTreeRow(page)).toContainText("file-55.json");
await expect(selectedTreeRow(page)).toBeInViewport();
await screenshot(page, "reveal-in-files-from-file-tab");
// The tree is already mounted and scrolled elsewhere. Command Center reveals the active tab.
await page.getByTestId("file-explorer-tree-scroll").hover();
await page.mouse.wheel(0, -100_000);
await expect(selectedTreeRow(page)).not.toBeInViewport();
const commandCenter = await openCommandCenter(page);
await commandCenter.getByTestId("command-center-input").fill("Reveal in Files");
await commandCenterSection(commandCenter, "Reveal in Files").click();
await expect(selectedTreeRow(page)).toBeInViewport();
} finally {
await agent.cleanup();
}
});
@@ -13,11 +13,17 @@ import { pluginRequirements } from "../support/helpers/plugin-fixture";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { pathToFileURL } from "node:url";
import type { Locator } from "@playwright/test";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
const PLUGIN_ID = "plugin-host-ui-e2e";
const TINY_PNG = Buffer.from(
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
"base64",
);
const PLUGIN_SOURCE = `import { usePaseo } from "@getpaseo/plugin/client";
import { Icon, Modal, useToast, Markdown } from "@getpaseo/plugin/client/ui";
@@ -39,6 +45,7 @@ function ModalBody({ onSaved }) {
<Text>Plugin modal contexts ready</Text>
<Markdown>{"## Plugin report"}</Markdown>
<Markdown>{"Checks **passed**. [Documentation](https://paseo.sh/docs/plugins)"}</Markdown>
<Markdown>{"![Modal preview](" + SCREENSHOT_PATH + ")"}</Markdown>
<Markdown>{""}</Markdown>
<Pressable accessibilityRole="button" onPress={save}>
<Text>Save issue</Text>
@@ -56,6 +63,7 @@ function Surface({ playAudio }) {
const [open, setOpen] = useState(false);
return <View>
<Text>{audioStatus}</Text>
<Markdown>{"![Before](" + SCREENSHOT_PATH + ")\\n\\n![After](" + SCREENSHOT_FILE_URL + ")"}</Markdown>
<Pressable accessibilityRole="button" onPress={() => play(AUDIO_BASE64)}><Text>Play plugin audio</Text></Pressable>
<Pressable accessibilityRole="button" onPress={() => play("UklGRg==")}><Text>Play invalid audio</Text></Pressable>
<Pressable accessibilityRole="button" onPress={() => setOpen(true)}>
@@ -105,20 +113,39 @@ async function openPluginModal(page: Page): Promise<void> {
await page.getByRole("button", { name: "Open plugin modal", exact: true }).click();
}
async function expectPluginMarkdown(page: Page): Promise<void> {
await expect(page.getByRole("heading", { name: "Plugin report" })).toBeVisible();
await expect(page.getByText("Checks passed.", { exact: false })).toBeVisible();
await expect(page.getByRole("link", { name: "Documentation", exact: true })).toHaveAttribute(
async function expectLoadedMarkdownImage(scope: Page | Locator, alt: string): Promise<void> {
const image = scope.getByAltText(alt, { exact: true });
await expect(image).toBeVisible();
await expect
.poll(() =>
image.evaluate((node) => {
const img = node as HTMLImageElement;
return {
isBlob: img.src.startsWith("blob:"),
complete: img.complete,
naturalWidth: img.naturalWidth,
};
}),
)
.toEqual({ isBlob: true, complete: true, naturalWidth: 1 });
}
async function expectPluginMarkdown(scope: Page | Locator): Promise<void> {
await expect(scope.getByRole("heading", { name: "Plugin report" })).toBeVisible();
await expect(scope.getByText("Checks passed.", { exact: false })).toBeVisible();
await expect(scope.getByRole("link", { name: "Documentation", exact: true })).toHaveAttribute(
"href",
"https://paseo.sh/docs/plugins",
);
await expectLoadedMarkdownImage(scope, "Modal preview");
await expect(scope.getByText("Image unavailable")).toHaveCount(0);
}
async function expectCenteredPluginDialog(page: Page): Promise<void> {
const dialog = page.getByRole("dialog");
await expect(dialog.getByText("Edit plugin issue", { exact: true })).toBeVisible();
await expect(dialog.getByText("Plugin modal contexts ready", { exact: true })).toBeVisible();
await expectPluginMarkdown(page);
await expectPluginMarkdown(dialog);
}
async function closeCenteredPluginDialog(page: Page): Promise<void> {
@@ -147,10 +174,15 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
const beforePath = path.join(directory, "before.png");
const afterPath = path.join(directory, "after.png");
const afterFileUrl = pathToFileURL(afterPath).href;
await writeFile(beforePath, TINY_PNG);
await writeFile(afterPath, TINY_PNG);
const audio = await readFile(path.resolve(__dirname, "../../assets/audio/thinking-tone.wav"));
await writeFile(
path.join(directory, "index.client.tsx"),
`const AUDIO_BASE64 = ${JSON.stringify(audio.toString("base64"))};\n${PLUGIN_SOURCE}`,
`const AUDIO_BASE64 = ${JSON.stringify(audio.toString("base64"))};\nconst SCREENSHOT_PATH = ${JSON.stringify(beforePath)};\nconst SCREENSHOT_FILE_URL = ${JSON.stringify(afterFileUrl)};\n${PLUGIN_SOURCE}`,
);
try {
@@ -159,6 +191,12 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
await useNonCompactLayout(page);
await openHostUiPlugin(page);
await test.step("plugin screen Markdown renders local absolute and file:// PNG images inline", async () => {
await expectLoadedMarkdownImage(page, "Before");
await expectLoadedMarkdownImage(page, "After");
await expect(page.getByText("Image unavailable")).toHaveCount(0);
});
await test.step("plugin audio finishes, rejects corrupt files, and recovers", async () => {
await playPluginAudio(page, "Play plugin audio", "Audio finished");
await playPluginAudio(page, "Play invalid audio", "Audio rejected");
@@ -0,0 +1,51 @@
import { test, expect } from "../support/fixtures";
import { TerminalE2EHarness, withTerminalInApp } from "../support/helpers/terminal-dsl";
import { waitForTerminalContent } from "../support/helpers/terminal-perf";
const CODE_FONT = "monospace";
const INTERFACE_FONT = "serif";
test("terminal text keeps the code font when an interface font is set", async ({ page }) => {
// Without WebGL2 the terminal falls back to xterm's DOM renderer, whose rows are
// styled by CSS and so can inherit the interface font.
await page.addInitScript(() => {
const getContext = HTMLCanvasElement.prototype.getContext;
HTMLCanvasElement.prototype.getContext = function (
this: HTMLCanvasElement,
type: string,
...rest: unknown[]
) {
if (type === "webgl2") return null;
return (getContext as (...args: unknown[]) => unknown).call(this, type, ...rest);
} as typeof getContext;
});
await page.addInitScript(
(fonts) => {
const saved = JSON.parse(localStorage.getItem("@paseo:app-settings") ?? "{}");
localStorage.setItem("@paseo:app-settings", JSON.stringify({ ...saved, ...fonts }));
},
{ monoFontFamily: CODE_FONT, uiFontFamily: INTERFACE_FONT },
);
const harness = await TerminalE2EHarness.create({ tempPrefix: "terminal-font-family-" });
try {
await withTerminalInApp(page, harness, { name: "font-family" }, async () => {
await harness.setupPrompt(page);
await harness
.terminalSurface(page)
.pressSequentially("clear; printf 'iiiiiiiiii\\nWWWWWWWWWW\\n'\n", { delay: 0 });
await waitForTerminalContent(page, (text) => text.includes("WWWWWWWWWW"), 10_000);
await harness
.terminalSurface(page)
.screenshot({ path: test.info().outputPath("terminal-font-family.png") });
const rowFont = await page
.locator(".xterm-rows")
.evaluate((rows) => getComputedStyle(rows).fontFamily);
expect(rowFont).toBe(CODE_FONT);
});
} finally {
await harness.cleanup();
}
});
@@ -4,7 +4,9 @@ import path from "node:path";
import type { Page } from "@playwright/test";
import { test, expect } from "../support/fixtures";
import { holdFileUploadResponse } from "../support/helpers/file-upload-gate";
import { clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
import { TerminalE2EHarness } from "../support/helpers/terminal-dsl";
import { getTerminalBufferText, waitForTerminalContent } from "../support/helpers/terminal-perf";
@@ -23,13 +25,134 @@ if (process.stdin.isTTY) {
process.stdin.resume();
process.stdin.on("data", (chunk) => {
captured = Buffer.concat([captured, chunk]);
if (captured.includes(Buffer.from("rgb:"))) {
finish();
}
});
setTimeout(finish, 700);
`;
const TERMINAL_PALETTE_PROBE_SCRIPT = `
process.stdin.setRawMode(true);
process.stdin.resume();
const mode = process.argv[2];
let buf = "";
const timer = setTimeout(() => {
process.stdout.write("PROBE_TIMEOUT:" + mode + ":" + buf.replace(/\\x1b/g, "ESC") + "\\n");
process.exit(2);
}, 5000);
if (mode === "osc") {
const code = process.argv[3];
process.stdin.on("data", (chunk) => {
buf += chunk.toString("binary");
const match = buf.match(new RegExp("\\\\x1b\\\\]" + code + ";rgb:[0-9a-f/]+\\\\x1b\\\\\\\\"));
if (!match) return;
clearTimeout(timer);
process.stdout.write("OSC_COLOR_OK:" + code + ":" + match[0].replace(/\\x1b/g, "ESC") + "\\n");
process.exit(0);
});
process.stdout.write("\\x1b]" + code + ";?\\x07");
} else if (mode === "dsr996") {
process.stdin.on("data", (chunk) => {
buf += chunk.toString("binary");
const match = buf.match(/\\x1b\\[\\?997;([12])n/);
if (!match) return;
clearTimeout(timer);
process.stdout.write("DSR996_OK:" + match[1] + "\\n");
process.exit(0);
});
process.stdout.write("\\x1b[?996n");
} else if (mode === "watch2031") {
clearTimeout(timer);
process.stdin.on("data", (chunk) => {
buf += chunk.toString("binary");
if (buf.includes("Q")) {
process.stdout.write("\\x1b[?2031lWATCH2031_DONE\\n");
process.exit(0);
}
let match;
while ((match = buf.match(/\\x1b\\[\\?997;([12])n/))) {
process.stdout.write("WATCH2031_EVENT:" + match[1] + "\\n");
buf = buf.slice(match.index + match[0].length);
}
});
process.stdout.write("\\x1b[?2031hWATCH2031_READY\\n");
}
`;
const TERMINAL_PALETTE_SCENARIOS = {
light: {
label: "Light",
colorFgBg: "0;15",
schemeCode: "2",
colors: {
10: "rgb:1a1a/1a1a/1e1e",
11: "rgb:ffff/ffff/ffff",
12: "rgb:1a1a/1a1a/1e1e",
},
},
dark: {
label: "Dark",
colorFgBg: "15;0",
schemeCode: "1",
colors: {
10: "rgb:fafa/fafa/fafa",
11: "rgb:1818/1b1b/1a1a",
12: "rgb:fafa/fafa/fafa",
},
},
} as const;
type TerminalPaletteScenario =
(typeof TERMINAL_PALETTE_SCENARIOS)[keyof typeof TERMINAL_PALETTE_SCENARIOS];
async function selectAppThemeInApp(
page: Page,
label: TerminalPaletteScenario["label"],
): Promise<void> {
await page.getByRole("button", { name: "Settings", exact: true }).click();
await expect(page.getByTestId("settings-sidebar")).toBeVisible();
await openSettingsSection(page, "appearance");
const themeRadio = page.getByRole("radio", { name: label, exact: true });
await themeRadio.click();
await expect(themeRadio).toBeChecked();
await clickSettingsBackToWorkspace(page);
}
function collectBrowserOsc11Replies(page: Page): string[] {
const replies: string[] = [];
page.on("websocket", (ws) => {
ws.on("framesent", ({ payload }) => {
const text = typeof payload === "string" ? payload : payload.toString("latin1");
if (text.includes("]11;rgb:")) {
replies.push(text);
}
});
});
return replies;
}
async function waitForCreatedTerminal(
harness: TerminalE2EHarness,
knownTerminalIds: Set<string>,
): Promise<string> {
let createdTerminalId: string | undefined;
await expect
.poll(
async () => {
const result = await harness.client.listTerminals(harness.tempRepo.path, undefined, {
workspaceId: harness.workspaceId,
});
createdTerminalId = result.terminals.find(
(terminal) => !knownTerminalIds.has(terminal.id),
)?.id;
return createdTerminalId;
},
{ timeout: 10_000 },
)
.toBeTruthy();
return createdTerminalId!;
}
// A TUI stand-in: turns on bracketed paste, reads every quoted path in each
// bracketed paste, and echoes typed lines, so the PTY output proves what reached
// the terminal and where the file was read from.
@@ -158,6 +281,10 @@ test.describe("Terminal protocol queries", () => {
test.beforeAll(async () => {
harness = await TerminalE2EHarness.create({ tempPrefix: "terminal-protocol-query-" });
await writeFile(path.join(harness.tempRepo.path, "osc11-capture.cjs"), OSC11_CAPTURE_SCRIPT);
await writeFile(
path.join(harness.tempRepo.path, "palette-probe.cjs"),
TERMINAL_PALETTE_PROBE_SCRIPT,
);
await writeFile(path.join(harness.tempRepo.path, "file-receiver.cjs"), FILE_RECEIVER_SCRIPT);
});
@@ -166,6 +293,8 @@ test.describe("Terminal protocol queries", () => {
});
test("does not send browser OSC 11 color-query replies back to the PTY", async ({ page }) => {
const browserOscReplies = collectBrowserOsc11Replies(page);
const terminalInstance = await harness.createTerminal({ name: "osc11-query" });
try {
await harness.openTerminal(page, { terminalId: terminalInstance.id });
@@ -178,14 +307,110 @@ test.describe("Terminal protocol queries", () => {
await page.waitForTimeout(500);
const text = await getTerminalBufferText(page);
const captureLine =
text.split("\n").find((line) => line.includes("PASEO_OSC11_CAPTURE:")) ?? "";
const capturedMatches = captureLine.match(/\]11;rgb:[0-9a-f/]+/g) ?? [];
expect(text).toContain("rgb:0b0b/0b0b/0b0b");
expect(text).not.toContain("rgb:ffff/ffff/ffff");
expect(capturedMatches).toHaveLength(1);
expect(browserOscReplies).toEqual([]);
const afterCapture = text.slice(text.indexOf("PASEO_OSC11_CAPTURE:") + captureLine.length);
expect(afterCapture).not.toContain("rgb:");
} finally {
await harness.killTerminal(terminalInstance.id);
}
});
test("reports Light and Dark palettes through OSC 10/11/12, COLORFGBG, DSR 996/997, and live DEC 2031 toggles", async ({
page,
}) => {
const createAppTerminal = async (): Promise<string> => {
const existing = await harness.client.listTerminals(harness.tempRepo.path, undefined, {
workspaceId: harness.workspaceId,
});
const knownIds = new Set(existing.terminals.map((entry) => entry.id));
await clickNewTerminal(page);
const terminalId = await waitForCreatedTerminal(harness, knownIds);
const surface = terminalSurface(page);
await expect(surface).toBeVisible({ timeout: 20_000 });
await surface.click();
const readyTag = `READY_${Date.now()}`;
await surface.pressSequentially(`echo ${readyTag}\n`, { delay: 0 });
await expectTerminalOutput(terminalId, readyTag);
return terminalId;
};
const runPaletteChecks = async (
terminalId: string,
scenario: TerminalPaletteScenario,
options: { checkColorFgBg: boolean },
): Promise<void> => {
const surface = terminalSurface(page);
await surface.click();
if (options.checkColorFgBg) {
await surface.pressSequentially('echo "CFGBG=$COLORFGBG"\n', { delay: 0 });
await expectTerminalOutput(terminalId, `CFGBG=${scenario.colorFgBg}`);
}
for (const code of [10, 11, 12] as const) {
await surface.pressSequentially(`${process.execPath} palette-probe.cjs osc ${code}\n`, {
delay: 0,
});
await expectTerminalOutput(
terminalId,
`OSC_COLOR_OK:${code}:ESC]${code};${scenario.colors[code]}ESC\\`,
);
}
await surface.pressSequentially(`${process.execPath} palette-probe.cjs dsr996\n`, {
delay: 0,
});
await expectTerminalOutput(terminalId, `DSR996_OK:${scenario.schemeCode}`);
};
// 1. Open workspace once, switch to Light in-app, and create a fresh Light terminal.
await gotoWorkspace(page, harness.workspaceId);
await selectAppThemeInApp(page, "Light");
const lightTerminalId = await createAppTerminal();
let darkTerminalId: string | null = null;
try {
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.light, {
checkColorFgBg: true,
});
// 2. Start DEC 2031 watcher in that running Light terminal, then toggle Light -> Dark -> Light.
await terminalSurface(page).pressSequentially(
`${process.execPath} palette-probe.cjs watch2031\n`,
{ delay: 0 },
);
await expectTerminalOutput(lightTerminalId, "WATCH2031_READY");
await selectAppThemeInApp(page, "Dark");
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:1");
await selectAppThemeInApp(page, "Light");
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:2");
// Stop watcher, toggle to Dark, and verify live OSC 10/11/12 + DSR 996 update on the same PTY.
await terminalSurface(page).click();
await terminalSurface(page).pressSequentially("Q", { delay: 0 });
await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE");
await selectAppThemeInApp(page, "Dark");
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
checkColorFgBg: false,
});
// 3. Fresh Dark terminal reports Dark OSC 10/11/12, COLORFGBG=15;0, and DSR 996 -> dark (1).
darkTerminalId = await createAppTerminal();
await runPaletteChecks(darkTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
checkColorFgBg: true,
});
} finally {
await harness.killTerminal(lightTerminalId);
if (darkTerminalId) {
await harness.killTerminal(darkTerminalId);
}
}
});
async function openFileReceiver(page: Page, name: string) {
const terminal = await harness.createTerminal({
name,
@@ -668,3 +668,186 @@ test("sidebar usage falls back to period shorthands before dropping all labels",
await dragSidebarTo(300);
await expectPinnedUsage(page, ["6%", "20%", "100%", "14%", "22%", "97%"]);
});
test("pushed status.usage_report_changed updates sidebar summary and open Usage modal without polling", async ({
page,
}) => {
const [claude] = claudeAndCodexReports();
const initialFetchedAt = new Date(Date.now() - 60_000).toISOString();
const usage = await installUsageReportsFixture(page, {
lists: [
() => [
{
...claude!,
fetchedAt: initialFetchedAt,
successfulAt: initialFetchedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 31 },
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 54 },
],
},
},
],
],
});
await page.setViewportSize(WIDE);
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "54% wk"]);
await usage.waitForUsageReportSubscription();
await openUsageFromItem(page);
const modal = usageModal(page);
await expect(modal.getByText("31% used")).toBeVisible();
const requestsBeforePush = usage.listRequests();
const updatedAt = new Date().toISOString();
usage.pushReportUpdate({
...claude!,
fetchedAt: updatedAt,
successfulAt: updatedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 64 },
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 54 },
],
},
});
await expectPinnedUsage(page, ["64% 5h", "54% wk"]);
await expect(modal.getByText("64% used")).toBeVisible();
expect(usage.listRequests()).toEqual(requestsBeforePush);
});
test("a pushed report for one source does not postpone the five-minute poll of other sources", async ({
page,
}) => {
const [claude, codex] = claudeAndCodexReports();
let codexUsedPct = 7;
let listFetchedAt = "2026-11-28T10:00:00.000Z";
const usage = await installUsageReportsFixture(page, {
lists: [
() => [
{
...claude!,
fetchedAt: listFetchedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 31 },
],
},
},
{
...codex!,
fetchedAt: listFetchedAt,
report: {
status: "available",
windows: [
{
id: "five_hour",
label: "Session",
shortLabel: "5h",
summary: true,
usedPct: codexUsedPct,
},
],
},
},
],
],
});
await page.clock.install();
await page.setViewportSize(WIDE);
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h", "7% 5h"]);
await usage.waitForUsageReportSubscription();
const initialRequests = usage.listRequests();
// Push a Claude update 2 minutes into the 5-minute poll window.
await page.clock.fastForward(2 * 60_000);
const pushedAt = "2026-11-28T10:02:00.000Z";
usage.pushReportUpdate({
...claude!,
fetchedAt: pushedAt,
successfulAt: pushedAt,
report: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 64 },
],
},
});
await expectPinnedUsage(page, ["64% 5h", "7% 5h"]);
expect(usage.listRequests()).toEqual(initialRequests);
// Only 3 minutes later (t = 5m from initial fetch), the scheduled poll still runs for Codex.
codexUsedPct = 19;
listFetchedAt = "2026-11-28T10:05:00.000Z";
await page.clock.fastForward(3 * 60_000);
await expectPinnedUsage(page, ["31% 5h", "19% 5h"]);
expect(usage.listRequests()).toHaveLength(initialRequests.length + 1);
});
test("hiding and showing the sidebar preserves the five-minute poll schedule and failed reports retry after one minute", async ({
page,
}) => {
const [claude] = claudeAndCodexReports();
let mode: "ok" | "error" = "ok";
let usedPct = 31;
const usage = await installUsageReportsFixture(page, {
lists: [
() => [
{
...claude!,
fetchedAt: new Date().toISOString(),
report:
mode === "error"
? { status: "error", error: "Temporary 503" }
: {
status: "available",
windows: [
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct },
],
},
},
],
],
});
await page.clock.install();
await page.setViewportSize(WIDE);
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
await gotoAppShell(page);
await expectPinnedUsage(page, ["31% 5h"]);
const initialRequests = usage.listRequests();
// Hide and reopen the sidebar within the stale window: no extra fetch starts on remount,
// and the original 5-minute poll slot fires on time rather than restarting from zero.
await page.clock.fastForward(20_000);
await page.setViewportSize(COMPACT);
await expect(usageItem(page)).toHaveCount(0);
await page.clock.fastForward(15_000);
await openCompactSidebar(page);
await expectPinnedUsage(page, ["31% 5h"]);
expect(usage.listRequests()).toEqual(initialRequests);
usedPct = 44;
await page.clock.fastForward(4 * 60_000 + 25_000);
await expectPinnedUsage(page, ["44% 5h"]);
expect(usage.listRequests()).toHaveLength(initialRequests.length + 1);
// When a report enters error state, the app retries after 1 minute instead of waiting 5 minutes.
mode = "error";
await page.clock.fastForward(5 * 60_000);
const requestsAfterError = usage.listRequests();
expect(requestsAfterError).toHaveLength(initialRequests.length + 2);
mode = "ok";
usedPct = 58;
await page.clock.fastForward(60_000);
await expectPinnedUsage(page, ["58% 5h"]);
expect(usage.listRequests()).toHaveLength(requestsAfterError.length + 1);
});
@@ -31,7 +31,7 @@ function keyboardState() {
return {
shown: /^ mInputShown=true$/m.test(state),
// The native object identity survives layout/flag changes but not a remount.
input: view.match(/ReactEditText\{(\w+)/)?.[1] ?? null,
input: view.match(/PaseoTerminalInputView\{(\w+)/)?.[1] ?? null,
};
}
async function waitForKeyboard(shown) {
@@ -3,15 +3,35 @@ import type { Page } from "@playwright/test";
// Poses as the desktop app running the e2e daemon as its own managed daemon, so
// `useIsLocalDaemon` reports the host as this machine. `directory` is where the
// desktop bridge claims dropped files live on disk.
export async function installLocalDesktopHost(page: Page, directory: string): Promise<void> {
export async function installLocalDesktopHost(
page: Page,
directory: string,
// `fileManager` adds the editor bridge: a file manager of that name, and the default-app opener.
{ fileManager = null }: { fileManager?: string | null } = {},
): Promise<void> {
const serverId = process.env.E2E_SERVER_ID;
if (!serverId) {
throw new Error("E2E_SERVER_ID is not set");
}
await page.addInitScript(
(localHost: { serverId: string; directory: string }) => {
(localHost: { serverId: string; directory: string; fileManager: string | null }) => {
const editor = localHost.fileManager
? {
listTargets: async () => [
{
id: "file-manager",
label: localHost.fileManager,
kind: "file-manager",
icon: { kind: "symbol", name: "folder" },
},
],
openTarget: async () => undefined,
openDefaultApp: async () => undefined,
}
: undefined;
(window as unknown as { paseoDesktop: unknown }).paseoDesktop = {
platform: "linux",
editor,
invoke: async (command: string) => {
if (command === "desktop_daemon_status") {
return {
@@ -33,6 +53,6 @@ export async function installLocalDesktopHost(page: Page, directory: string): Pr
webUtils: { getPathForFile: (file: File) => `${localHost.directory}/${file.name}` },
};
},
{ serverId, directory },
{ serverId, directory, fileManager },
);
}
@@ -1,5 +1,6 @@
import path from "node:path";
import { readFileSync } from "node:fs";
import type { TerminalDefaultColors } from "@getpaseo/protocol/messages";
import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity";
import { connectDaemonClient } from "./daemon-client-loader";
import { withProjectOwnership } from "./project-ownership";
@@ -94,7 +95,13 @@ export interface SeedDaemonClient {
cwd: string,
name?: string,
requestId?: string,
options?: { agentId?: string; command?: string; args?: string[]; workspaceId?: string },
options?: {
agentId?: string;
command?: string;
args?: string[];
workspaceId?: string;
defaultColors?: TerminalDefaultColors;
},
): Promise<{
terminal: { id: string; name: string; cwd: string; activity?: TerminalActivity | null } | null;
error: string | null;
@@ -1,4 +1,5 @@
import type { Page } from "@playwright/test";
import type { TerminalDefaultColors } from "@getpaseo/protocol/messages";
import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity";
import { createTempGitRepo } from "./workspace";
import { navigateToTerminal, setupDeterministicPrompt } from "./terminal-perf";
@@ -19,6 +20,7 @@ interface CreateTerminalInput {
name: string;
command?: string;
args?: string[];
defaultColors?: TerminalDefaultColors;
}
function sleep(ms: number): Promise<void> {
@@ -69,14 +71,11 @@ export class TerminalE2EHarness {
}
async createTerminal(input: CreateTerminalInput): Promise<TerminalInstance> {
const options =
input.command || input.args
? {
command: input.command,
args: input.args,
workspaceId: this.workspaceId,
}
: { workspaceId: this.workspaceId };
const options = {
...(input.command || input.args ? { command: input.command, args: input.args } : {}),
workspaceId: this.workspaceId,
...(input.defaultColors ? { defaultColors: input.defaultColors } : {}),
};
const result = await this.client.createTerminal(
this.tempRepo.path,
input.name,
@@ -11,6 +11,10 @@ export interface UsageListRequest {
export interface UsageReportsFixture {
listRequests(): UsageListRequest[];
waitForListRequests(count: number): Promise<void>;
/** Waits until the app holds an active `status.usage_report_changed` subscription. */
waitForUsageReportSubscription(): Promise<void>;
/** Pushes a `status.usage_report_changed` update to every active app subscription. */
pushReportUpdate(report: UsageReportEntry): void;
/** Runs `action`, then waits until the app has received the agent's next usage scope. */
untilUsageScopeChanges(agentId: string, action: () => Promise<unknown>): Promise<void>;
}
@@ -28,6 +32,8 @@ interface UsageReportsFixtureOptions {
*/
usageSupported?: boolean | (() => boolean);
usageSettingSupported?: boolean;
/** Overrides `server_info.features.usageReportUpdates` when set. */
usageReportUpdates?: boolean;
/** Released hosts expose provider.usage.list with no source icons. */
providerUsageListOnly?: boolean;
/** The host daemon's port; defaults to the E2E daemon. */
@@ -67,6 +73,7 @@ function withUsageSupportFeature(
enabled: boolean,
providerUsageListOnly: boolean,
usageSettingSupported: boolean,
usageReportUpdates?: boolean,
): string | null {
const envelope = parseJson(message) as {
type?: unknown;
@@ -93,6 +100,7 @@ function withUsageSupportFeature(
usageSetting: usageSettingSupported ? true : undefined,
usageSources: enabled && !providerUsageListOnly,
providerUsageList: enabled,
...(usageReportUpdates !== undefined ? { usageReportUpdates } : {}),
},
},
},
@@ -143,12 +151,37 @@ function createCounter() {
};
}
function trackUsageReportSubscriptionMessage(
request: Record<string, unknown> | null,
pendingUsageSubRequestIds: Set<string>,
usageReportSubscriptions: Map<string, { send: (payload: string) => void }>,
socketSubIds: Set<string>,
): void {
if (
request?.type === "session.events.set_subscription.request" &&
typeof request.requestId === "string" &&
Array.isArray(request.events) &&
request.events.includes("status.usage_report_changed")
) {
pendingUsageSubRequestIds.add(request.requestId);
}
if (
request?.type === "subscription.release.request" &&
typeof request.subscriptionId === "string"
) {
usageReportSubscriptions.delete(request.subscriptionId);
socketSubIds.delete(request.subscriptionId);
}
}
export async function installUsageReportsFixture(
page: Page,
options: UsageReportsFixtureOptions,
): Promise<UsageReportsFixture> {
const listRequests: UsageListRequest[] = [];
const listCounter = createCounter();
const usageReportSubscriptions = new Map<string, { send: (payload: string) => void }>();
const usageReportSubCounter = createCounter();
const usageScopes = new Map<string, string>();
const usageScopeChanges = new Map<string, ReturnType<typeof createCounter>>();
const usageScopeCounts = new Map<string, number>();
@@ -171,10 +204,23 @@ export async function installUsageReportsFixture(
options.port === undefined ? daemonWsRoutePattern() : wsRoutePatternForPort(`${options.port}`);
await page.routeWebSocket(route, (ws) => {
const server = ws.connectToServer();
const pendingUsageSubRequestIds = new Set<string>();
const socketSubIds = new Set<string>();
ws.onClose(() => {
for (const id of socketSubIds) usageReportSubscriptions.delete(id);
socketSubIds.clear();
});
ws.onMessage((message) => {
const request = getSessionMessage(message);
const requestId = request?.requestId;
trackUsageReportSubscriptionMessage(
request,
pendingUsageSubRequestIds,
usageReportSubscriptions,
socketSubIds,
);
if (request?.type === requestType && typeof requestId === "string") {
const listRequest: UsageListRequest = {
forceRefresh: request.forceRefresh === true,
@@ -262,6 +308,26 @@ export async function installUsageReportsFixture(
});
server.onMessage((message) => {
const sessionMessage = getSessionMessage(message);
const subPayload =
sessionMessage?.type === "session.events.set_subscription.response"
? (sessionMessage.payload as
| { requestId?: unknown; subscriptionId?: unknown }
| undefined)
: undefined;
if (
typeof subPayload?.requestId === "string" &&
pendingUsageSubRequestIds.delete(subPayload.requestId) &&
typeof subPayload.subscriptionId === "string"
) {
usageReportSubscriptions.set(subPayload.subscriptionId, {
send: (payload) => ws.send(payload),
});
socketSubIds.add(subPayload.subscriptionId);
ws.send(message);
usageReportSubCounter.increment();
return;
}
const serverInfo =
typeof message === "string"
? withUsageSupportFeature(
@@ -269,6 +335,7 @@ export async function installUsageReportsFixture(
isUsageSupported(),
providerUsageListOnly,
options.usageSettingSupported ?? true,
options.usageReportUpdates,
)
: null;
const scope = agentUsageScope(message);
@@ -287,6 +354,24 @@ export async function installUsageReportsFixture(
return {
listRequests: () => [...listRequests],
waitForListRequests: (count) => listCounter.waitFor(count),
waitForUsageReportSubscription: () => usageReportSubCounter.waitFor(1),
pushReportUpdate: (report) => {
for (const [subscriptionId, target] of usageReportSubscriptions) {
target.send(
JSON.stringify({
type: "session",
message: {
type: "status",
payload: {
status: "usage_report_changed",
subscriptionId,
report,
},
},
}),
);
}
},
untilUsageScopeChanges: async (agentId, action) => {
const next = (usageScopeCounts.get(agentId) ?? 0) + 1;
await action();
+3
View File
@@ -0,0 +1,3 @@
node_modules/
desktop/build/
desktop/autolink/
+3
View File
@@ -0,0 +1,3 @@
workspaces=false
legacy-peer-deps=true
install-links=true
+283
View File
@@ -0,0 +1,283 @@
# Experimental GPUI client
Run Paseo's existing React Native app in a native GPUI window on Linux or macOS. This is
a community starting point: the real workspace UI runs, but terminal/diff
renderers and several native services still need porting. The normal desktop
build remains Electron. The native app connects to a separately running daemon.
## Run it
Start from the repository's [development setup](../../../docs/development.md).
A fresh checkout needs the root dependencies and workspace build outputs:
```sh
npm ci
npm run build:server
npm run gpui:install
EXPO_PUBLIC_LOCAL_DAEMON=localhost:6768 npm run dev:gpui
```
Use an already-running compatible daemon and replace `localhost:6768` with its
endpoint. These GPUI commands never start or restart a daemon. The address is
inlined at bundle time. The app's normal connection/authentication rules apply.
You also need Rust stable through rustup, CMake, Ninja, Clang, Linux X11/Wayland
development libraries, and Vulkan. The tested Linux x86_64 host already had
most build tools; it additionally needed `libxkbcommon-x11-dev`. A clean-machine
prerequisite check is still needed. The first native build downloads dependencies
and builds Rust/C++; allow several minutes and several GB of disk.
`dev:gpui` bundles the app, autolinks native modules, builds, and opens the window.
Restart after editing. It uses an offline production JS bundle; Fast Refresh is
not wired into this launcher. `build:gpui` builds without opening a window.
`gpui:bundle -- --dev false` only writes the JS bundle, source map, and assets to
`.artifacts/gpui/`. Bundle validation checks that the real routes are present and
that no `react-native-webview` modules were included.
## Build a macOS test DMG
On an Apple Silicon Mac, install the dependencies above plus Xcode, CMake, and
Ninja. From the repository root, after `npm run gpui:install`:
```sh
gpui_repo_root="$PWD"
cd packages/app/gpui
MACOSX_DEPLOYMENT_TARGET=15.0 NODE_OPTIONS=--max-old-space-size=6144 CARGO_BUILD_JOBS=4 \
CARGO_TARGET_DIR="$gpui_repo_root/.artifacts/gpui/macos/target" \
PASEO_RENDERER=gpui EXPO_PUBLIC_LOCAL_DAEMON=localhost:6767 \
node node_modules/react-native/cli.js package-desktop \
--target app,dmg --out "$gpui_repo_root/.artifacts/gpui/macos/dist"
```
Use the React Native CLI entry point shown here; the standalone GPUI CLI rejects
`package-desktop`. Keep one absolute `CARGO_TARGET_DIR` for both compilation and
packaging because their default target directories differ. Metro needs more than
Node's default 2 GiB heap for this app.
Keep `MACOSX_DEPLOYMENT_TARGET` aligned with `desktop/desktop.json` when building
from source; it controls both Rust and CMake's macOS API availability.
The DMG requires macOS 15 or later, matching the bundled Hermes/JSI libraries.
It contains `Paseo GPUI.app` with ad-hoc signing and the library-validation
exception required for loading ad-hoc dylibs under hardened runtime. It is not
notarized or signed with Developer ID. Copy it out of the mounted DMG before testing. Its daemon
address is fixed at bundle time, and the installer does not include a daemon.
Native terminals and diff rendering remain unsupported.
Check the installed bundle before sharing it:
```sh
node packages/app/gpui/verify-macos-package.mjs "/Applications/Paseo GPUI.app"
```
This checks the sealed signature, ad-hoc library-loading entitlement, and the
minimum macOS version of each bundled dylib. A successful launch on a Mac with
SIP disabled does not test Team ID library validation; verify the signing policy
and use a Mac with SIP enabled for distribution launch acceptance.
Namespace GUI testing needs an active remote desktop session; SSH alone can leave
GPUI waiting for a display. Use Namespace's `devbox desktop` commands before
launching the app. Keep Cargo's generated debug-symbol symlink intact when
rebuilding; the packager copies its contents alongside the installer.
## Rules for working on this target
iOS, Android, web, and macOS all run from the same app code. This target does too.
- **Change the app as little as possible.** Add what GPUI needs in GPUI-specific
code. Do not edit shared app code to make GPUI work.
- **Select GPUI code with a GPUI-specific Metro rule.** A `.gpui.ts` / `.gpui.tsx`
file sits next to the `.native` and `.web` files it stands in for.
`desktop/metro.config.js` prepends `gpui.<ext>` entries to
`resolver.sourceExts`, so Metro resolves `.gpui.*` ahead of `.desktop.`,
`.native.`, and base extensions. No other target (iOS, Android, web, or
Electron) resolves `.gpui.*`. `adapters/` holds package-level redirects only.
- **Fill the branches where it matters.** A piece the app needs and GPUI lacks,
such as markdown, selection in the chat, or diffs, gets a GPUI implementation
behind the interface the app already uses.
- **Fix the renderer, not the React code.** When something looks or behaves
wrong only on GPUI, such as the tab track, the same React code is correct on
every other platform. The defect is in [getpaseo/react-native-gpui](https://github.com/getpaseo/react-native-gpui); fix it there.
## Approach and renderer choice
```text
Existing Paseo RootApp + Expo Router + state/client/plugin code
|
React in Hermes
|
React Native Fabric
|
Rust GPUI native renderer
|
Linux GPU window
Existing Paseo client <-- WebSocket --> separately running Node daemon
```
The separate npm project is deliberate: the selected runtime uses RN 0.87.1,
while Paseo's mobile app uses RN 0.86.3. Metro redirects native dependencies to
that installation and resolves the rest from the app. This avoids changing the
mobile dependency baseline just to try another renderer. It also creates a
version-maintenance cost that needs testing before this becomes a supported target.
The choice was to preserve the existing app's RN component and library contracts:
| Candidate | Integration model | Consequence for this experiment |
| ----------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [Streetwriters react-native-gpui](https://github.com/streetwriters/react-native-gpui/tree/de11aa265e6fb36c80e8a30315bce6d34a9be7d6) | React Native Fabric, Hermes, and GPUI, with ports of screens, gestures, Reanimated/worklets, safe areas, and SVG | Chosen because it lets the existing RN app reach a real Linux window with targeted adapters. These ports are still experimental. |
| [natew/react-native-gpui](https://github.com/natew/react-native-gpui/tree/b2254543357f02fdd983d0d8a584d1d1bd93f5da) | Custom React reconciler with an RN-like component surface; its README targets macOS arm64/Metal | Useful implementation reference. Running this Linux app would also require platform work and compatibility with the RN libraries it imports. |
| [GPUIX](https://github.com/remorses/gpuix) | Custom React/Solid renderer, its own JSX primitives, and Node-API native bindings; supports Bun/Node execution | Also native GPUI, with interesting packaging and specialized surfaces. Adopting it would require replacing or adapting Paseo's RN component/library contracts. It remains an alternative worth testing, not a rejected renderer. |
| Existing Electron target | RN Web inside Chromium, with the desktop host bridge | Preserves the working desktop feature set, but does not answer the experiment's question of running the app through a native renderer. |
This is an integration choice, not a performance comparison. There are no
controlled CPU, memory, startup, or frame-time results against these alternatives.
## What belongs in the change
| Area | Why it is here |
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `packages/app/gpui/package.json` and `package-lock.json` | Pinned tarballs from a [getpaseo/react-native-gpui](https://github.com/getpaseo/react-native-gpui/releases) release (`paseo-*`) for `@react-native-gpui/{cli,codegen,core,hermes}` and the seven `@react-native-gpui/*` modules. |
| `packages/app/gpui/desktop/Cargo.lock` | Pins Rust crates for the desktop shell (`../node_modules/@react-native-gpui/core/ReactGpui/...` path dependencies). |
| `desktop/`, `index.js`, `routes.js`, Metro/Babel config, root launcher | Register the full app, select the native runtime, compile native services, and bundle the actual route graph. The explicit route context prevents an apparently successful build with no app routes. |
| `adapters/` | Desktop implementations of npm packages used by the app, plus explicit unavailable-capability implementations for mobile packages. Limited ports, not complete replacements for Expo/Unistyles. App-module overrides live next to the shared files as `.gpui.ts` / `.gpui.tsx`. |
| Shared app edits | One capability gate for alpha-mask shimmer. GPUI shows the logo and labels without that effect. Existing web/iOS/Android paths keep their behavior. |
| Native tests and this guide | Make the working slice reproducible and give contributors bounded follow-up work. |
### Testing changes against a local fork checkout
To build Paseo against a local checkout of `getpaseo/react-native-gpui` instead of the pinned release:
```sh
npm run gpui:install -- --local /path/to/react-native-gpui
```
You can also pass the path via `PASEO_GPUI_LOCAL=/path/to/react-native-gpui npm run gpui:install`.
This installs locked dependencies and the seven `@react-native-gpui/*` modules from the release, then packs `@react-native-gpui/{cli,codegen,core,hermes}` from the local checkout into `packages/app/gpui/node_modules/@react-native-gpui/` without modifying `package.json` or `package-lock.json`. Re-run the same command after editing the fork, then rebuild (`npm run build:gpui` or `npm run dev:gpui`). Run `npm run gpui:install` without `--local` to restore the release packages.
GPUI remains a pinned Cargo git dependency. Upstream tooling downloads Hermes
and builds the C++ runtime when needed; release packaging has not been verified across all platforms.
## Working slice and limits
Verified on Linux x86_64 and macOS arm64: all 24 app routes in the bundle, connection to the
daemon, the real project/workspace sidebar, opening an existing workspace,
existing message rendering, and native composer typing/deletion. The native
regression test restores the draft and does not send a message. Rust tests cover
SHA-256/random-byte bounds and real SQLite parameter binding/transaction rollback.
The macOS build also passed draft restoration after restarting the native process.
The following are not feature-parity claims:
| Area | Current state |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Styling | Adapter evaluates existing Unistyles theme/style factories and breakpoints. No Nitro shadow-tree integration. Full theme/resize behavior needs QA. |
| Storage/crypto/localization | Native filesystem + SQLite + SHA-256 + OS randomness. Intl ships English locale data and IANA time zones. The Rust service contains Linux-specific OS access. |
| Clipboard/files | Text clipboard, native file dialogs, PNG/JPEG picking, and download/export adapters exist. End-to-end dialog/transfer coverage is still missing. |
| Voice/camera/push/power inhibition | Unavailable. Requests either report the missing capability or use the app's existing unavailable-capability implementation. |
| Image conversion/image clipboard | Unavailable. The picker accepts PNG/JPEG without conversion. |
| Mermaid/HTML/document previews | Mermaid and HTML show source. Document previews report unavailable. No embedded browser backend. |
| Terminals | The mobile view expects an Expo `PaseoTerminal` component. No GPUI implementation yet. |
| Diffs | The mobile surface uses React Native Skia. No GPUI drawing backend yet. |
| Plugins | The existing loader evaluates JS and injects host React/RN. No end-to-end plugin verification on GPUI yet. |
| Other platforms | Linux x86_64 and macOS arm64 have been exercised. Windows remains unverified. |
The initial stripped development executable was about 68 MiB, with about 10 MiB
of Hermes/JSI libraries and a 21 MiB JS bundle, approximately 100 MiB uncompressed.
That measurement excludes the daemon, is not an optimized release installer, and
does not establish memory usage or a size advantage over another renderer.
## Experiments to pick up
Each experiment should preserve the real app and demonstrate a user workflow.
1. **Native terminal.** Implement a GPUI component for the existing
[`PaseoTerminalView`](../modules/paseo-terminal/index.tsx) frame contract.
Keep the JS headless xterm emulator, transport, and frame generation initially.
Verify resize/replay, keyboard/IME/paste, scrollback/selection, and the existing
Unicode corpus. [Terminal rendering](../../../docs/terminal-rendering.md)
explains why shaping must preserve xterm's cell columns.
2. **Diff surface.** Keep `src/git/diff-document`'s model and review actions;
add GPUI text measurement and painting instead of the Skia surface. Test
unified/split views, wrapping, scrolling, selection, and inline reviews on
large real diffs. The [C++ layout experiment](../modules/paseo-diff-prototype/README.md)
is a separate candidate for shared geometry; it is not a finished renderer.
3. **Plugins.** Load a small plugin into an isolated daemon, open its real screen
or workspace panel, call a plugin RPC, and reload it. Verify subscriptions and
cleanup. Track unsupported services explicitly instead of adding fake APIs.
4. **Native services and styling.** Exercise dialogs, downloads, clipboard,
persistence/restart, theme switching, resizing, and focus. Replace the narrow
adapters with complete implementations only where the app needs them.
5. **Portability and packaging.** Build on clean Linux, then macOS/Windows. Replace
Linux-only randomness/timezone access, check font/shaping and IME behavior, and
verify relocatable libraries/assets. Measure a release build and a controlled
workflow before claiming a performance or size improvement.
6. **Bundled daemon, independently.** First run the unchanged daemon under Bun
in isolation. Verify PTY/native dependencies, terminal-worker subprocesses,
provider launches, and dynamic plugins. Then compare standalone/AOT packaging
and size. This branch neither ports the daemon nor embeds it in the UI process.
A Rust/GPUI terminal or diff painter can share desktop implementation across the
upstream renderer's supported OSes. Reusing it on mobile still requires mobile
bindings and graphics integration; choosing Rust or C++ alone does not provide that.
## Verification
Run the normal checks from the root. `.gpui.ts` and `.gpui.tsx` files in
`packages/app/src` and `packages/app/modules` are checked by root `typecheck`
and `lint`, while `packages/app/gpui/adapters/` is excluded from the mobile
TypeScript project.
```sh
npm run typecheck
npm run lint
npm run format:check
```
For the native UI regression, use a daemon with an existing workspace and build
with the driver. Run the native app on an isolated display when testing on a
machine in use:
```sh
EXPO_PUBLIC_LOCAL_DAEMON=localhost:6768 npm run build:gpui -- --features test-driver,visual-capture
RN_GPUI_TEST_DRIVER=1 RN_GPUI_TEST_DRIVER_TOKEN=local-test \
RN_GPUI_DEV_MODE=0 RN_GPUI_BUNDLE="$PWD/.artifacts/gpui/paseo.bundle" \
RN_GPUI_ASSETS_DIR="$PWD/.artifacts/gpui/assets/assets" \
xvfb-run -a -s '-screen 0 2560x1600x24' \
packages/app/gpui/desktop/target/debug/react-native-gpui-paseo-gpui
```
Use the printed `RN_GPUI_TEST_DRIVER_PORT` in another shell:
```sh
PASEO_GPUI_TEST_URL=ws://127.0.0.1:PORT PASEO_GPUI_TEST_TOKEN=local-test \
npx vitest run packages/app/gpui/native.test.ts --bail=1
```
Without a driver URL the test is skipped. Put diagnostic logs/captures in
`.artifacts/gpui/`; do not commit them or publish private workspace contents as QA.
For border and hover regressions, bundle the isolated scene from `packages/app/gpui`:
```sh
PASEO_RENDERER=gpui node node_modules/react-native/cli.js bundle --platform desktop \
--entry-file appearance-regression.fixture.js --config desktop/metro.config.js \
--bundle-output ../../../.artifacts/gpui/appearance.bundle --dev false --max-workers 1
```
Launch the driver-enabled executable with `RN_GPUI_BUNDLE` pointing at that bundle.
Run `native.test.ts` from the root with the driver URL/token above and
`PASEO_GPUI_TEST_SCENE=appearance`. It checks the rendered border pixels,
Pressable hover callbacks and render props, and hover across nested controls.
No daemon is needed for this scene.
On macOS, test WebSocket cleanup against a compiled native executable:
```sh
PASEO_GPUI_TEST_BINARY="/absolute/path/to/react-native-gpui-paseo-gpui" \
npx vitest run packages/app/gpui/websocket.native.test.ts --bail=1
```
This opens an isolated native window and uses a loopback peer for 128 rejected
handshakes, 128 server closes, and 128 client closes under a 256-descriptor limit.
It needs an active display and the GPUI npm dependencies, but no Paseo daemon.
Without the executable path it is skipped. Its bundle and logs stay in `.artifacts/gpui/`.
@@ -0,0 +1,73 @@
import { promises as fs, paths } from "@react-native-gpui/fs";
import Desktop from "../desktop/src/NativePaseoDesktop";
let writes = Promise.resolve();
const directory = () => `${paths.appData}/paseo-gpui/storage`;
const filename = (key) => `${directory()}/${Desktop.sha256(key)}.json`;
async function read(key) {
try {
return JSON.parse(await fs.readFile(filename(key), "utf8")).value;
} catch (error) {
if (error.code === "ENOENT") return null;
throw error;
}
}
function mutate(operation) {
const result = writes.then(operation);
writes = result.catch(() => {});
return result;
}
async function write(key, value) {
await fs.mkdir(directory(), { recursive: true });
const target = filename(key);
await fs.writeFile(`${target}.tmp`, JSON.stringify({ key, value }), "utf8");
await fs.rename(`${target}.tmp`, target);
}
async function keys() {
let entries;
try {
entries = await fs.readdir(directory());
} catch (error) {
if (error.code === "ENOENT") return [];
throw error;
}
return Promise.all(
entries
.filter((name) => name.endsWith(".json"))
.map(async (name) => JSON.parse(await fs.readFile(`${directory()}/${name}`, "utf8")).key),
);
}
const storage = {
async getItem(key) {
await writes;
return read(key);
},
setItem(key, value) {
return mutate(() => write(key, value));
},
removeItem(key) {
return mutate(() => fs.rm(filename(key), { force: true }));
},
async getAllKeys() {
await writes;
return keys();
},
async multiGet(items) {
await writes;
return Promise.all(items.map(async (key) => [key, await read(key)]));
},
multiSet(items) {
return mutate(async () => {
for (const [key, value] of items) await write(key, value);
});
},
multiRemove(items) {
return mutate(async () => {
for (const key of items) await fs.rm(filename(key), { force: true });
});
},
clear() {
return mutate(() => fs.rm(directory(), { recursive: true, force: true }));
},
};
export default storage;
+16
View File
@@ -0,0 +1,16 @@
import { TurboModuleRegistry } from "react-native";
const clipboard = TurboModuleRegistry.getEnforcing("Clipboard");
export const getStringAsync = () => clipboard.getString();
export async function setStringAsync(value) {
clipboard.setString(value);
return true;
}
export async function hasStringAsync() {
return (await getStringAsync()).length > 0;
}
export async function getImageAsync() {
throw new Error("Image clipboard is not implemented for GPUI yet");
}
export async function setImageAsync() {
throw new Error("Image clipboard is not implemented for GPUI yet");
}
+24
View File
@@ -0,0 +1,24 @@
import Desktop from "../desktop/src/NativePaseoDesktop";
export function getRandomValues(array) {
if (
!ArrayBuffer.isView(array) ||
array instanceof DataView ||
array instanceof Float32Array ||
array instanceof Float64Array
) {
throw new TypeError("getRandomValues requires an integer typed array");
}
if (array.byteLength > 65536) throw new RangeError("Random request exceeds 65536 bytes");
new Uint8Array(array.buffer, array.byteOffset, array.byteLength).set(
Desktop.randomBytes(array.byteLength),
);
return array;
}
export function randomUUID() {
return globalThis.crypto.randomUUID();
}
export const CryptoDigestAlgorithm = { SHA256: "SHA-256" };
export async function digestStringAsync(algorithm, text) {
if (algorithm !== "SHA-256") throw new Error(`Unsupported digest algorithm: ${algorithm}`);
return Desktop.sha256(text);
}
@@ -0,0 +1,14 @@
import { dialog, promises } from "@react-native-gpui/fs";
export async function getDocumentAsync(options = {}) {
const paths = await dialog.open({ multiple: options.multiple ?? false });
return {
canceled: paths.length === 0,
assets: await Promise.all(
paths.map(async (path) => ({
uri: `file://${path}`,
name: path.split("/").at(-1),
size: (await promises.stat(path)).size,
})),
),
};
}
@@ -0,0 +1,11 @@
import {
EventEmitter,
NativeModule,
SharedObject,
SharedRef,
} from "expo-modules-core/src/polyfill/CoreModule";
export function ensureNativeModulesAreInstalled() {
if (globalThis.expo) return;
globalThis.expo = { EventEmitter, NativeModule, SharedObject, SharedRef, modules: {} };
}
ensureNativeModulesAreInstalled();
@@ -0,0 +1,30 @@
import { Linking } from "react-native";
import { NativeModule } from "expo-modules-core/src/polyfill/CoreModule";
class DesktopLinking extends NativeModule {
initialURL = null;
subscription;
constructor() {
super();
Linking.getInitialURL()
.then((url) => {
this.initialURL = url;
if (url) this.emit("onURLReceived", { url });
return url;
})
.catch((error) => console.error("[GPUI linking]", error));
}
getLinkingURL = () => this.initialURL;
clearInitialURL() {
this.initialURL = null;
}
startObserving() {
this.subscription = Linking.addEventListener("url", (event) =>
this.emit("onURLReceived", event),
);
}
stopObserving() {
this.subscription?.remove();
}
}
export default new DesktopLinking();
+129
View File
@@ -0,0 +1,129 @@
import fs, { promises, paths } from "@react-native-gpui/fs";
import { Buffer } from "buffer";
const pathOf = (value) => String(value?.uri ?? value).replace(/^file:\/\//, "");
const join = (parts) =>
parts
.map(pathOf)
.join("/")
.replace(/\/{2,}/g, "/");
export const cacheDirectory = `file://${paths.appCache}/paseo-gpui/`;
export const documentDirectory = `file://${paths.appData}/paseo-gpui/`;
export const EncodingType = { Base64: "base64", UTF8: "utf8" };
export const Paths = { cache: cacheDirectory, document: documentDirectory };
export async function getInfoAsync(uri) {
try {
const stat = await promises.stat(pathOf(uri));
return { exists: true, isDirectory: stat.isDirectory(), size: stat.size, uri };
} catch (error) {
if (error.code === "ENOENT") return { exists: false, uri };
throw error;
}
}
export const makeDirectoryAsync = (uri, options = {}) =>
promises.mkdir(pathOf(uri), { recursive: options.intermediates });
export const copyAsync = ({ from, to }) => promises.copyFile(pathOf(from), pathOf(to));
export const moveAsync = ({ from, to }) => promises.rename(pathOf(from), pathOf(to));
export const readAsStringAsync = (uri, options = {}) =>
promises.readFile(pathOf(uri), options.encoding ?? "utf8");
export const writeAsStringAsync = (uri, contents, options = {}) =>
promises.writeFile(pathOf(uri), contents, options.encoding ?? "utf8");
export const deleteAsync = (uri, options = {}) =>
promises.rm(pathOf(uri), { recursive: true, force: options.idempotent });
export const readDirectoryAsync = (uri) => promises.readdir(pathOf(uri));
export class File {
constructor(...parts) {
this.uri = `file://${join(parts)}`;
}
get name() {
return pathOf(this).split("/").at(-1);
}
get exists() {
return fs.existsSync(pathOf(this));
}
get size() {
return fs.statSync(pathOf(this)).size;
}
create({ overwrite = false, intermediates = false } = {}) {
if (intermediates)
fs.mkdirSync(pathOf(this).split("/").slice(0, -1).join("/"), { recursive: true });
fs.writeFileSync(pathOf(this), "", { flag: overwrite ? "w" : "wx" });
}
write(value) {
fs.writeFileSync(pathOf(this), value);
}
delete() {
fs.rmSync(pathOf(this));
}
async bytes() {
return promises.readFile(pathOf(this));
}
async arrayBuffer() {
const bytes = await this.bytes();
return bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
}
async base64() {
return Buffer.from(await this.bytes()).toString("base64");
}
async text() {
return promises.readFile(pathOf(this), "utf8");
}
move(destination) {
fs.renameSync(pathOf(this), pathOf(destination));
this.uri = destination.uri;
}
copy(destination) {
fs.copyFileSync(pathOf(this), pathOf(destination));
}
static async downloadFileAsync(url, destination) {
const response = await fetch(url);
if (!response.ok) throw new Error(`Download failed: ${response.status}`);
const file = destination instanceof File ? destination : new File(destination);
await promises.writeFile(pathOf(file), new Uint8Array(await response.arrayBuffer()));
return file;
}
}
export class Directory {
constructor(...parts) {
this.uri = `file://${join(parts)}`;
}
get exists() {
return fs.existsSync(pathOf(this));
}
create({ intermediates = false } = {}) {
fs.mkdirSync(pathOf(this), { recursive: intermediates });
}
delete() {
fs.rmSync(pathOf(this), { recursive: true });
}
list() {
return fs
.readdirSync(pathOf(this), { withFileTypes: true })
.map((entry) =>
entry.isDirectory() ? new Directory(this, entry.name) : new File(this, entry.name),
);
}
}
export function createDownloadResumable(url, uri, options = {}, onProgress) {
const controller = new AbortController();
return {
async downloadAsync() {
const response = await fetch(url, { headers: options.headers, signal: controller.signal });
if (!response.ok) throw new Error(`Download failed: ${response.status}`);
const bytes = new Uint8Array(await response.arrayBuffer());
const target = pathOf(uri);
await promises.mkdir(target.split("/").slice(0, -1).join("/"), { recursive: true });
await promises.writeFile(`${target}.part`, bytes);
await promises.rename(`${target}.part`, target);
onProgress?.({ totalBytesWritten: bytes.length, totalBytesExpectedToWrite: bytes.length });
return {
uri,
status: response.status,
headers: Object.fromEntries(response.headers.entries()),
};
},
async cancelAsync() {
controller.abort();
},
};
}
@@ -0,0 +1,8 @@
// The GPUI picker accepts JPEG/PNG directly. Other formats require a future
// native decoder; never claim conversion succeeded for an unsupported format.
export const SaveFormat = { PNG: "png", JPEG: "jpeg", WEBP: "webp" };
export const ImageManipulator = {
manipulate() {
throw new Error("Image conversion is not available in the GPUI build; select a PNG or JPEG.");
},
};
@@ -0,0 +1,28 @@
import { dialog, promises } from "@react-native-gpui/fs";
// Desktop access is granted for each selection by the system file dialog.
export const PermissionStatus = {
GRANTED: "granted",
DENIED: "denied",
UNDETERMINED: "undetermined",
};
const permission = { status: "granted", granted: true, canAskAgain: true, expires: "never" };
export const requestMediaLibraryPermissionsAsync = async () => permission;
export const useMediaLibraryPermissions = () => [permission, requestMediaLibraryPermissionsAsync];
export const getPendingResultAsync = async () => null;
export async function launchImageLibraryAsync(options = {}) {
const paths = await dialog.open({
multiple: options.allowsMultipleSelection,
filters: [{ name: "Images", extensions: ["png", "jpg", "jpeg"] }],
});
return {
canceled: !paths.length,
assets: await Promise.all(
paths.map(async (path) => ({
uri: `file://${path}`,
fileName: path.split("/").at(-1),
fileSize: (await promises.stat(path)).size,
mimeType: /\.png$/i.test(path) ? "image/png" : "image/jpeg",
})),
),
};
}
@@ -0,0 +1,5 @@
export function setDefaultTimeZone(timeZone) {
// macOS uses the IANA alias GMT. FormatJS's timezone data omits that alias;
// normalize it at the polyfill boundary while preserving other system zones.
Intl.DateTimeFormat.__setDefaultTimeZone(timeZone.toUpperCase() === "GMT" ? "UTC" : timeZone);
}
@@ -0,0 +1,23 @@
/* oxlint-disable import/no-unassigned-import -- Exercise the actual GPUI Intl implementation. */
import "@formatjs/intl-datetimeformat/polyfill-force.js";
import "@formatjs/intl-datetimeformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/add-all-tz.js";
import { afterEach, expect, test } from "vitest";
import { setDefaultTimeZone } from "./intl-timezone";
afterEach(() => setDefaultTimeZone("UTC"));
test.each([
["GMT", "UTC"],
["gmt", "UTC"],
["UTC", "UTC"],
["Europe/Berlin", "Europe/Berlin"],
["US/Pacific", "America/Los_Angeles"],
])("initializes the system timezone %s as %s", (systemZone, expectedZone) => {
setDefaultTimeZone(systemZone);
expect(new Intl.DateTimeFormat("en").resolvedOptions().timeZone).toBe(expectedZone);
});
test("does not silently replace an invalid system timezone", () => {
expect(() => setDefaultTimeZone("Invalid/Zone")).toThrow(RangeError);
});
+17
View File
@@ -0,0 +1,17 @@
/* oxlint-disable import/no-unassigned-import -- These packages install Intl and locale data by side effect. */
// Hermes' Linux build omits Intl; install real locale algorithms before app code.
import "@formatjs/intl-getcanonicallocales/polyfill-force.js";
import "@formatjs/intl-locale/polyfill-force.js";
import "@formatjs/intl-pluralrules/polyfill-force.js";
import "@formatjs/intl-pluralrules/locale-data/en.js";
import "@formatjs/intl-numberformat/polyfill-force.js";
import "@formatjs/intl-numberformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/polyfill-force.js";
import "@formatjs/intl-datetimeformat/locale-data/en.js";
import "@formatjs/intl-datetimeformat/add-all-tz.js";
import "@formatjs/intl-displaynames/polyfill-force.js";
import "@formatjs/intl-displaynames/locale-data/en.js";
import "@formatjs/intl-segmenter/polyfill-force.js";
import Desktop from "../desktop/src/NativePaseoDesktop";
import { setDefaultTimeZone } from "./intl-timezone";
setDefaultTimeZone(Desktop.timezone());
+6
View File
@@ -0,0 +1,6 @@
// No desktop power-inhibition lease is acquired by this backend yet.
export const isAvailableAsync = async () => false;
export async function activateKeepAwakeAsync() {
throw new Error("Power inhibition is not available in the GPUI build.");
}
export async function deactivateKeepAwake() {}
+60
View File
@@ -0,0 +1,60 @@
import { useEffect } from "react";
import { Keyboard, ScrollView, useAnimatedValue } from "react-native";
import { useSharedValue } from "react-native-reanimated";
// A GPUI desktop window has no software-keyboard inset. RN still owns focus
// and physical keyboard events; the mobile layout API observes its events.
export function KeyboardProvider({ children }) {
return children;
}
export const KeyboardAwareScrollView = ScrollView;
export const KeyboardController = {
isVisible: () => Keyboard.isVisible(),
dismiss: () => Keyboard.dismiss(),
};
export const KeyboardEvents = { addListener: (...args) => Keyboard.addListener(...args) };
export function useReanimatedKeyboardAnimation() {
const height = useSharedValue(0);
const progress = useSharedValue(0);
useEffect(() => {
const shown = Keyboard.addListener("keyboardDidShow", (event) => {
height.value = -event.endCoordinates.height;
progress.value = 1;
});
const hidden = Keyboard.addListener("keyboardDidHide", () => {
height.value = 0;
progress.value = 0;
});
return () => {
shown.remove();
hidden.remove();
};
}, [height, progress]);
return { height, progress };
}
export function useKeyboardAnimation() {
const height = useAnimatedValue(0);
const progress = useAnimatedValue(0);
return { height, progress };
}
export function useGenericKeyboardHandler(handlers) {
useEffect(() => {
const subscriptions = [
Keyboard.addListener("keyboardDidShow", (event) => {
const value = {
height: event.endCoordinates.height,
progress: 1,
duration: event.duration,
};
handlers.onStart?.(value);
handlers.onEnd?.(value);
}),
Keyboard.addListener("keyboardDidHide", () => {
const value = { height: 0, progress: 0, duration: 0 };
handlers.onStart?.(value);
handlers.onEnd?.(value);
}),
];
return () => subscriptions.forEach((subscription) => subscription.remove());
}, [handlers]);
}
@@ -0,0 +1,5 @@
import Desktop from "../desktop/src/NativePaseoDesktop";
export function getLocales() {
const languageTag = Desktop.locale().split(".")[0].replaceAll("_", "-");
return [{ languageTag, languageCode: languageTag.split("-")[0] }];
}
@@ -0,0 +1,5 @@
import { Buffer } from "buffer";
import Desktop from "../desktop/src/NativePaseoDesktop";
export function randomBytes(length) {
return Buffer.from(Desktop.randomBytes(length));
}
@@ -0,0 +1,3 @@
// GPUI's native TextInput owns text paste, selection, and IME. The mobile
// PasteInput module's image-paste extension is not available on this target.
export { TextInput as default } from "react-native";
+11
View File
@@ -0,0 +1,11 @@
import { dialog, promises } from "@react-native-gpui/fs";
// Linux exports a downloaded file through the native Save dialog.
export const isAvailableAsync = async () => true;
export async function shareAsync(uri, options = {}) {
const source = uri.replace(/^file:\/\//, "");
const destination = await dialog.save({
title: options.dialogTitle ?? "Save file",
defaultName: source.split("/").at(-1),
});
if (destination) await promises.copyFile(source, destination);
}
+37
View File
@@ -0,0 +1,37 @@
import Desktop from "../desktop/src/NativePaseoDesktop";
let pending = Promise.resolve();
function enqueue(operation) {
const result = pending.then(operation);
pending = result.catch(() => {});
return result;
}
const connection = {
async execAsync(sql) {
Desktop.sqlite(sql, "batch");
},
async runAsync(sql, params = []) {
Desktop.sqlite(sql, JSON.stringify(params));
},
async getAllAsync(sql, params = []) {
return JSON.parse(Desktop.sqlite(sql, JSON.stringify(params)));
},
};
export async function openDatabaseAsync(name) {
if (name !== "paseo-replica-row-store.db") throw new Error(`Unknown GPUI database: ${name}`);
return {
execAsync: (...args) => enqueue(() => connection.execAsync(...args)),
runAsync: (...args) => enqueue(() => connection.runAsync(...args)),
getAllAsync: (...args) => enqueue(() => connection.getAllAsync(...args)),
withExclusiveTransactionAsync: (operation) =>
enqueue(async () => {
await connection.execAsync("BEGIN IMMEDIATE");
try {
await operation(connection);
await connection.execAsync("COMMIT");
} catch (error) {
await connection.execAsync("ROLLBACK");
throw error;
}
}),
};
}
@@ -0,0 +1,28 @@
import * as RN from "react-native";
import { createUnistylesElement } from "./unistyles";
export const View = createUnistylesElement(RN.View);
export const Text = createUnistylesElement(RN.Text);
export const ScrollView = createUnistylesElement(RN.ScrollView);
export const TextInput = createUnistylesElement(RN.TextInput);
export const Pressable = createUnistylesElement(RN.Pressable);
export const Image = createUnistylesElement(RN.Image);
export const ImageBackground = createUnistylesElement(RN.ImageBackground);
export const FlatList = createUnistylesElement(RN.FlatList);
export const SectionList = createUnistylesElement(RN.SectionList);
export const TouchableOpacity = createUnistylesElement(RN.TouchableOpacity);
export const TouchableHighlight = createUnistylesElement(RN.TouchableHighlight);
export const TouchableWithoutFeedback = createUnistylesElement(RN.TouchableWithoutFeedback);
export const ActivityIndicator = createUnistylesElement(RN.ActivityIndicator);
export const KeyboardAvoidingView = createUnistylesElement(RN.KeyboardAvoidingView);
export const SafeAreaView = createUnistylesElement(RN.SafeAreaView);
export const Switch = createUnistylesElement(RN.Switch);
export const RefreshControl = createUnistylesElement(RN.RefreshControl);
export const VirtualizedList = createUnistylesElement(RN.VirtualizedList);
export const StatusBar = RN.StatusBar;
export const Animated = {
...RN.Animated,
View: createUnistylesElement(RN.Animated.View),
Text: createUnistylesElement(RN.Animated.Text),
ScrollView: createUnistylesElement(RN.Animated.ScrollView),
Image: createUnistylesElement(RN.Animated.Image),
};
+140
View File
@@ -0,0 +1,140 @@
import React, { forwardRef, useSyncExternalStore } from "react";
import * as Native from "react-native";
// GPUI has Fabric but no Nitro/Unistyles shadow-tree bindings. Keep the app's
// style factories and theme API; this backend updates subscribed React views.
const listeners = new Set();
const resolveStyle = Symbol("paseo.gpui.style");
let revision = 0;
let themes = {};
let themeName = "dark";
let adaptive = true;
let breakpoints = {};
const emit = () => {
revision += 1;
for (const listener of listeners) listener();
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const snapshot = () => revision;
const theme = () => themes[themeName];
const runtime = () => ({
themeName,
colorScheme: Native.Appearance.getColorScheme() ?? "light",
screen: Native.Dimensions.get("window"),
insets: { top: 0, bottom: 0, left: 0, right: 0, ime: 0 },
pixelRatio: Native.PixelRatio.get(),
fontScale: Native.PixelRatio.getFontScale(),
breakpoint: Object.keys(breakpoints).findLast(
(key) => breakpoints[key] <= Native.Dimensions.get("window").width,
),
});
Native.Dimensions.addEventListener("change", emit);
Native.Appearance.addChangeListener(({ colorScheme }) => {
if (adaptive && themes[colorScheme]) themeName = colorScheme;
emit();
});
function responsive(value) {
if (Array.isArray(value)) return value.map(responsive);
if (!value || typeof value !== "object") return value;
if (Object.getPrototypeOf(value) !== Object.prototype) return value;
const keys = Object.keys(value);
if (keys.length && keys.every((key) => key in breakpoints)) {
const width = Native.Dimensions.get("window").width;
const key = keys
.sort((a, b) => breakpoints[a] - breakpoints[b])
.findLast((candidate) => breakpoints[candidate] <= width);
return key === undefined ? undefined : responsive(value[key]);
}
return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, responsive(item)]));
}
function materialize(style) {
if (Array.isArray(style)) return style.map(materialize);
if (style && typeof style === "object" && style[resolveStyle]) return style[resolveStyle]();
return style;
}
function styledProps(props) {
const result = { ...props };
for (const key of ["style", "contentContainerStyle"]) {
if (typeof props[key] === "function")
result[key] = (...args) => materialize(props[key](...args));
else if (props[key]) result[key] = materialize(props[key]);
}
return result;
}
export const UnistylesRuntime = {
get themeName() {
return themeName;
},
get breakpoint() {
return runtime().breakpoint;
},
get colorScheme() {
return runtime().colorScheme;
},
getTheme: theme,
setTheme(name) {
if (!themes[name]) throw new Error(`Unknown GPUI theme: ${name}`);
themeName = name;
emit();
},
updateTheme(name, update) {
themes[name] = update(themes[name]);
emit();
},
setAdaptiveThemes(value) {
adaptive = value;
if (value && themes[runtime().colorScheme]) themeName = runtime().colorScheme;
emit();
},
};
export const StyleSheet = {
...Native.StyleSheet,
configure(config) {
themes = config.themes;
breakpoints = config.breakpoints;
adaptive = config.settings?.adaptiveThemes ?? false;
themeName =
config.settings?.initialTheme ?? (adaptive ? runtime().colorScheme : Object.keys(themes)[0]);
emit();
},
create(factory) {
const evaluate = () => (typeof factory === "function" ? factory(theme(), runtime()) : factory);
const initial = evaluate();
const sheet = {};
for (const key of Object.keys(initial)) {
const wrap = (args) => {
const resolve = () => {
const value = evaluate()[key];
return responsive(typeof value === "function" ? value(...args) : value);
};
return Object.defineProperty({ ...resolve() }, resolveStyle, { value: resolve });
};
sheet[key] = typeof initial[key] === "function" ? (...args) => wrap(args) : wrap([]);
}
return sheet;
},
};
// Existing consumers retain this API; new app code should use style factories.
export function useUnistyles() {
useSyncExternalStore(subscribe, snapshot, snapshot);
return { theme: theme(), rt: runtime() };
}
export function withUnistyles(Component, mappings) {
const Wrapped = forwardRef(function GpuiThemed(props, ref) {
useSyncExternalStore(subscribe, snapshot, snapshot);
const { uniProps, ...rest } = props;
return React.createElement(Component, {
...styledProps({
...mappings?.(theme(), runtime()),
...uniProps?.(theme(), runtime()),
...rest,
}),
ref,
});
});
return Wrapped;
}
export const createUnistylesElement = withUnistyles;
+1
View File
@@ -0,0 +1 @@
{ "name": "Paseo", "displayName": "Paseo GPUI" }
@@ -0,0 +1,121 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- Minimal native regression scene. */
import React, { useCallback, useState } from "react";
import { AppRegistry, Image, Pressable, ScrollView, Text, TextInput, View } from "react-native";
function AppearanceRegression() {
const [buttonHovered, setHovered] = useState(false);
const [entered, setEntered] = useState(false);
const [expanded, setExpanded] = useState(false);
const [layouts, setLayouts] = useState({});
const record = useCallback((key, event) => {
const layout = event?.nativeEvent?.layout;
const layoutKeys = layout ? Object.keys(layout).sort() : [];
setLayouts((prev) => ({
...prev,
[key]: {
count: (prev[key]?.count ?? 0) + 1,
keys: layoutKeys,
layout,
},
}));
}, []);
const onViewLayout = useCallback((e) => record("view", e), [record]);
const onTextLayout = useCallback((e) => record("text", e), [record]);
const onInputLayout = useCallback((e) => record("textInput", e), [record]);
const onImageLayout = useCallback((e) => record("image", e), [record]);
const onScrollLayout = useCallback((e) => record("scrollView", e), [record]);
return (
<View style={{ flex: 1, flexDirection: "row", backgroundColor: "white", padding: 40, gap: 40 }}>
<View style={{ gap: 24 }}>
<View
testID="rounded-border"
style={{
width: 200,
height: 100,
borderRadius: 24,
borderWidth: 4,
borderColor: "#ff0000",
backgroundColor: "#0000ff",
}}
/>
<Pressable
testID="hover-button"
onHoverIn={() => setHovered(true)}
onHoverOut={() => setHovered(false)}
style={{ width: 200, height: 60, backgroundColor: buttonHovered ? "#00ff00" : "#0000ff" }}
>
<Text>{buttonHovered ? "hover active" : "hover inactive"}</Text>
</Pressable>
<Pressable
testID="hover-render-prop"
style={({ hovered }) => ({
width: 200,
height: 60,
backgroundColor: hovered ? "#00ff00" : "#0000ff",
})}
>
{({ hovered }) => <Text>{hovered ? "render hovered" : "render idle"}</Text>}
</Pressable>
<View
testID="hover-row"
onPointerEnter={() => setEntered(true)}
onPointerLeave={() => setEntered(false)}
style={{ width: 200, height: 60, backgroundColor: entered ? "#00ff00" : "#0000ff" }}
>
<Pressable testID="nested-button" style={{ width: 100, height: 60 }}>
<Text>{entered ? "row active" : "row inactive"}</Text>
</Pressable>
</View>
<View testID="outside-hover" style={{ width: 200, height: 60 }} />
</View>
<View style={{ gap: 12, alignItems: "flex-start" }}>
<Pressable
testID="layout-resize-toggle"
onPress={() => setExpanded((value) => !value)}
style={{ width: 160, height: 32, backgroundColor: "#dddddd", justifyContent: "center" }}
>
<Text>{expanded ? "Shrink" : "Expand"}</Text>
</Pressable>
<View
testID="layout-view"
onLayout={onViewLayout}
style={{ width: expanded ? 180 : 120, height: 24, backgroundColor: "#eeeeee" }}
/>
<Text testID="layout-text" onLayout={onTextLayout}>
{expanded ? "Measure a much longer text label" : "Short label"}
</Text>
<TextInput
testID="layout-text-input"
onLayout={onInputLayout}
defaultValue="hi"
style={{ width: expanded ? 200 : 140, height: 32, borderWidth: 1 }}
/>
<Image
testID="layout-image"
onLayout={onImageLayout}
style={{ width: expanded ? 96 : 64, height: 32, backgroundColor: "#cccccc" }}
/>
<ScrollView
testID="layout-scroll"
onLayout={onScrollLayout}
style={{
flexGrow: 0,
flexShrink: 0,
width: expanded ? 210 : 150,
height: 40,
backgroundColor: "#eeeeee",
}}
>
<View style={{ width: expanded ? 210 : 150, height: 80 }} />
</ScrollView>
<Text testID="layout-results">{JSON.stringify(layouts)}</Text>
</View>
</View>
);
}
AppRegistry.registerComponent("Paseo", () => AppearanceRegression);
+7
View File
@@ -0,0 +1,7 @@
module.exports = function (api) {
api.cache(true);
return {
presets: [[require.resolve("babel-preset-expo"), { unstable_transformImportMeta: true }]],
plugins: [[require.resolve("react-native-unistyles/plugin"), { root: "../src" }]],
};
};
+4
View File
@@ -0,0 +1,4 @@
build/
.cache/
autolink/
target/
File diff suppressed because it is too large Load Diff
+63
View File
@@ -0,0 +1,63 @@
[package]
name = "react-native-gpui-paseo-gpui"
version = "0.1.0"
edition = "2021"
# Set CARGO_PROFILE_DEV_DEBUG=full to opt into full debug information.
[profile.dev]
debug = "line-tables-only"
split-debuginfo = "packed"
# Dependencies are optimized even in a dev build: GPUI rebuilds and paints the
# element tree on every frame, and they are only compiled once.
[profile.dev.package."*"]
debug = false
opt-level = 3
# The C++ bridge picks its CMake build type from this crate's opt-level, and a
# Release build of React Native has no dev server, inspector or Fast Refresh.
[profile.dev.package.rn-gpui-sys]
opt-level = 0
[profile.release]
debug = "line-tables-only"
# Cargo strips inside the linker, before dsymutil, so package-desktop preserves the
# Cargo dSYM and then strips. Full LTO: 2 MB smaller for 1.4x the build time.
strip = "none"
split-debuginfo = "packed"
lto = "fat"
codegen-units = 1
[build-dependencies]
rn-gpui-module-build = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module-build" }
serde_json = "1"
[features]
visual-capture = ["react-native-gpui/visual-capture"]
test-driver = ["react-native-gpui/test-driver"]
runtime-shaders = ["react-native-gpui/runtime-shaders"]
[dev-dependencies]
rn_gpui_enriched_markdown = { package = "rn-gpui-enriched-markdown", path = "../../../react-native-enriched-markdown/desktop" }
gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3", features = [
"test-support",
] }
[dependencies]
serde_json = "1"
sha2 = "0.10"
rusqlite = { version = "0.38", features = ["bundled"] }
rn-gpui-module = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module" }
rn-gpui-autolink = { path = "autolink" }
react-native-gpui = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui" }
[patch.crates-io]
# Managed by @react-native-gpui/cli autolink; do not edit between these markers.
react-native-gpui = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui" }
rn-gpui-sys = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-sys" }
rn-gpui-module = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module" }
rn-gpui-module-build = { path = "../node_modules/@react-native-gpui/core/ReactGpui/rn-gpui-module-build" }
gpui = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
gpui_platform = { git = "https://github.com/streetwriters/gpui-fast", rev = "1ad3cc3" }
# End managed by autolink.
+172
View File
@@ -0,0 +1,172 @@
fn main() {
// Forwards the engine's Node-API exports out of this executable, which is
// what lets a stock `.node` addon resolve them on Windows.
//
// A DLL records every import as a name *plus the file it comes from*, and a
// node-gyp addon records "from `node.exe`" — Windows has no global symbol
// scope for it to fall back on. Node's own answer is that the host process
// exports the Node-API functions, so that is what this does: the executable
// re-exports each of the VM's `napi_*`/`node_api_*` names, forwarded to
// `hermesvm.dll`. Addons that use node-gyp's delay-load hook (the default)
// then reach this process instead of looking for `node.exe` on disk.
//
// It is a no-op on macOS and Linux, where an addon's imports resolve against
// whatever is already loaded and need no forwarding. Declare it once, before
// the module list; it does not depend on anything else in this file.
rn_gpui_module_build::forward_node_api_exports();
// App-local Rust TurboModules: list one entry per `src/Native*.ts` spec,
// for example `&["src/NativeGreeting.ts"]`. Their glue is generated into
// this crate's OUT_DIR, and main.rs registers the modules.
rn_gpui_module_build::generate(&["src/NativePaseoDesktop.ts"]);
let desktop_root = std::path::PathBuf::from(
std::env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR is set"),
);
// `app.json` names the app; `desktop/desktop.json` carries the identifier
// and everything else the packaging step needs. The loader the CLI uses is
// JavaScript, so this reads the same file directly and applies the two
// defaults it would apply.
let project_root = desktop_root
.parent()
.expect("desktop folder has a React Native project root");
let app_json_path = project_root.join("app.json");
println!("cargo:rerun-if-changed={}", app_json_path.display());
let app_json: serde_json::Value = serde_json::from_slice(
&std::fs::read(&app_json_path)
.unwrap_or_else(|error| panic!("read {}: {error}", app_json_path.display())),
)
.unwrap_or_else(|error| panic!("parse {}: {error}", app_json_path.display()));
let app_name = app_json["name"]
.as_str()
.filter(|name| !name.is_empty())
.expect("app.json must define a nonempty name");
if app_json["desktop"]
.as_object()
.is_some_and(|desktop| !desktop.is_empty())
{
panic!("move `app.json` desktop.* into `desktop/desktop.json` (see the README)");
}
let desktop_json_path = project_root.join("desktop/desktop.json");
println!("cargo:rerun-if-changed={}", desktop_json_path.display());
let desktop_json: serde_json::Value = std::fs::read(&desktop_json_path)
.ok()
.and_then(|bytes| serde_json::from_slice(&bytes).ok())
.unwrap_or(serde_json::Value::Null);
let app_id = match desktop_json["identifier"].as_str() {
Some(identifier) if !identifier.is_empty() => identifier.to_string(),
_ => format!(
"com.example.{}",
app_name
.to_lowercase()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect::<String>()
),
};
println!("cargo:rustc-env=RN_GPUI_APP_NAME={app_name}");
println!("cargo:rustc-env=RN_GPUI_APP_ID={app_id}");
// Only a debug build names the bundle it was developed against. A release
// binary must find the bundle beside its own executable, because the path
// baked in here is where this machine happened to build it — and on the
// machine the package is installed on, that path does not exist.
println!("cargo:rerun-if-env-changed=PROFILE");
if std::env::var("PROFILE").as_deref() == Ok("debug") {
println!(
"cargo:rustc-env=RN_GPUI_DEFAULT_BUNDLE={}",
desktop_root.join("build/index.bundle").display()
);
}
println!("cargo:rerun-if-env-changed=DEP_RN_GPUI_RUNTIME_RPATHS");
println!("cargo:rerun-if-env-changed=RN_GPUI_PACKAGING");
let Ok(paths) = std::env::var("DEP_RN_GPUI_RUNTIME_RPATHS") else {
return;
};
let dirs = paths.split('|').filter(|path| !path.is_empty());
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
stage_shared_libraries(dirs);
return;
}
// `RN_GPUI_PACKAGING` means this binary is about to be installed somewhere
// else, so only the relative rpaths belong in it. Keeping the absolute ones
// would let a packaged app load this build tree's libraries in preference to
// its own on the machine that built it — which hides exactly the packaging
// bugs the packaged run exists to catch.
let packaging = std::env::var("RN_GPUI_PACKAGING").is_ok();
if !packaging {
for path in dirs {
println!("cargo:rustc-link-arg=-Wl,-rpath,{path}");
}
}
emit_relocatable_rpaths(app_name);
}
/// rpaths that survive being installed somewhere else.
///
/// The absolute paths above let a development build run from this tree. A
/// packaged app is copied to another machine, where those paths do not exist,
/// so a release build also carries paths relative to the executable: the
/// layout the installers produce.
fn emit_relocatable_rpaths(app_name: &str) {
if std::env::var("PROFILE").as_deref() != Ok("release") {
return;
}
let os = std::env::var("CARGO_CFG_TARGET_OS").unwrap_or_default();
let mut emit = |rpath: String| println!("cargo:rustc-link-arg=-Wl,-rpath,{rpath}");
match os.as_str() {
// An app bundle puts the executable in Contents/MacOS and the shipped
// libraries in Contents/Frameworks.
"macos" => emit("@executable_path/../Frameworks".into()),
// Linux installs the executable at `usr/bin` and ships its libraries
// under `usr/lib`:
// - the deb puts them in `usr/lib/<app>`;
// - an AppImage's libraries are flat in `usr/lib`, because that is the
// directory AppRun puts on the library path and the one linuxdeploy
// resolves dependencies from before the image is assembled.
// Both are covered, so one binary works in either layout.
"linux" => {
emit(format!("$ORIGIN/../lib/{app_name}"));
emit("$ORIGIN/../lib".into());
emit("$ORIGIN".into());
}
// Windows has no rpath: the DLLs are copied beside the executable.
_ => {}
}
}
/// Windows has no rpath: the loader finds a DLL next to the executable or on
/// `PATH`, so every directory the runtime reports as holding a shared library
/// (the Hermes binary directory in particular) is copied into the profile
/// directory that receives this app's executable. Without this the app builds
/// and then fails to start with "hermesvm.dll was not found".
fn stage_shared_libraries<'a>(dirs: impl Iterator<Item = &'a str>) {
let out_dir = std::path::PathBuf::from(std::env::var("OUT_DIR").expect("OUT_DIR is set"));
// <profile>/build/<package>-<hash>/out -> <profile>
let Some(profile_dir) = out_dir.ancestors().nth(3) else {
return;
};
for dir in dirs {
let Ok(entries) = std::fs::read_dir(dir) else {
continue;
};
for entry in entries.flatten() {
let source = entry.path();
let is_shared_library = source
.extension()
.and_then(|extension| extension.to_str())
.is_some_and(|extension| extension.eq_ignore_ascii_case("dll"));
if !is_shared_library {
continue;
}
let Some(name) = source.file_name() else {
continue;
};
println!("cargo:rerun-if-changed={}", source.display());
std::fs::copy(&source, profile_dir.join(name)).unwrap_or_else(|error| {
panic!("copy {} next to the executable: {error}", source.display())
});
}
}
}
+4
View File
@@ -0,0 +1,4 @@
{
"identifier": "sh.paseo.gpui",
"bundle": { "macos": { "minimumSystemVersion": "15.0" } }
}
@@ -0,0 +1,271 @@
use gpui::{
div, px, App, AppContext, Context, IntoElement, ParentElement, Render, Styled, Window,
WindowBounds, WindowOptions,
};
use react_native_gpui::DesktopAppConfig;
use rn_gpui_enriched_markdown::layout::{layout_document, LaidOutDocument};
use rn_gpui_enriched_markdown::model::MarkdownSnapshot;
use rn_gpui_enriched_markdown::render::render_document;
use std::ffi::{c_char, c_int, CStr, CString};
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
extern "C" {
fn rn_gpui_markdown_bench_stages(
markdown: *const c_char,
is_gfm: bool,
style_json: *const c_char,
out_parse_ns: *mut f64,
out_highlight_ns: *mut f64,
out_serialize_ns: *mut f64,
out_json: *mut *mut c_char,
out_json_len: *mut usize,
) -> c_int;
fn rn_gpui_markdown_bench_free(ptr: *mut c_char);
}
struct BenchState {
render_doc_ns: f64,
}
struct BenchView {
doc: Arc<LaidOutDocument>,
state: Arc<Mutex<BenchState>>,
}
impl Render for BenchView {
fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
let t0 = Instant::now();
let el = render_document(&self.doc, 1);
let elapsed_ns = t0.elapsed().as_secs_f64() * 1e9;
if let Ok(mut s) = self.state.lock() {
s.render_doc_ns = elapsed_ns;
}
div().w(px(720.0)).bg(gpui::rgb(0xffffff)).child(el)
}
}
const STYLE_JSON: &str = r##"{
"paragraph": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "marginBottom": 12 },
"h1": { "fontSize": 24, "lineHeight": 31, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"h2": { "fontSize": 21, "lineHeight": 27, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"h3": { "fontSize": 18, "lineHeight": 23, "fontWeight": "bold", "color": 4279900702, "marginBottom": 12 },
"list": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "bulletColor": 4285624698, "markerColor": 4285624698, "gapWidth": 7, "itemSpacing": 4, "marginLeft": 20, "marginBottom": 12 },
"blockquote": { "fontSize": 15, "lineHeight": 21, "color": 4279900702, "backgroundColor": 4294638330, "borderColor": 4293190887, "borderWidth": 3, "padding": 12, "gapWidth": 8, "marginBottom": 12 },
"link": { "color": 4280523094, "underline": false },
"code": { "fontFamily": "monospace", "fontScale": 0.8, "color": 4279900702, "backgroundColor": 4294243573 },
"codeBlock": {
"fontFamily": "monospace", "fontSize": 12, "lineHeight": 21, "color": 4279900702,
"backgroundColor": 4294243573, "borderColor": 4293190887, "borderRadius": 8, "padding": 12, "marginBottom": 12,
"syntaxColors": {
"keyword": 4294933362, "string": 4289058559, "comment": 4287337630, "number": 4286169343,
"type": 4294944343, "function": 4291995903, "operatorColor": 4294933362, "punctuation": 4286495103
}
},
"table": {
"fontSize": 15, "lineHeight": 21, "color": 4279900702,
"headerBackgroundColor": 4294243573, "headerTextColor": 4279900702,
"rowEvenBackgroundColor": 4294967295, "rowOddBackgroundColor": 4294638330,
"borderColor": 4293190887, "marginBottom": 12
}
}"##;
fn build_realistic_reply(target_bytes: usize) -> String {
let section_prose = "\n## Module Analysis and Data Flow\n\n\
The renderer translates snapshots from `packages/react-native-enriched-markdown/cpp/GpuiMarkdownBridge.cpp` into \
**GPUI elements** with *inline styles* and links such as [protocol docs](https://paseo.sh/docs/protocol). \
When a streaming token arrives, React commits the updated `markdown` string and re-measures the node.\n\n\
- Preserves AST structure for headings, paragraphs, emphasis, and `inline_code`\n\
- Highlights fenced code blocks using Tree-sitter grammars\n\
- Lays out GFM tables with measured column widths\n";
let section_code = "\n```ts\n\
export interface StreamDelta {\n\
readonly messageId: string;\n\
readonly seq: number;\n\
readonly chunk: string;\n\
}\n\n\
export function applyDelta(acc: Map<string, string>, delta: StreamDelta): string {\n\
const prev = acc.get(delta.messageId) ?? \"\";\n\
const next = prev + delta.chunk;\n\
acc.set(delta.messageId, next);\n\
return next;\n\
}\n\
```\n";
let section_table = "\n| Stage | Input | Output | Owner |\n\
| --- | --- | --- | --- |\n\
| Parse | Markdown UTF-8 | MD4C AST | C++ |\n\
| Highlight | Code lines | Token ranges | Tree-sitter |\n\
| Serialize | AST + Style | JSON string | folly::toJson |\n\
| Deserialize | JSON string | MarkdownSnapshot | serde_json |\n\
| Layout | Snapshot + width | LaidOutDocument | layout.rs |\n\
| Paint | LaidOutDocument | GPUI scene | render.rs + gpui |\n";
let mut out = String::from("# Architecture Overview\n\nStreaming reply benchmark fixture with realistic prose, code blocks, lists, and a table.\n");
out.push_str(section_table);
let mut i = 0usize;
while out.len() < target_bytes {
out.push_str(section_prose);
if i % 2 == 0 {
out.push_str(section_code);
}
if i % 5 == 4 && out.len() + section_table.len() < target_bytes {
out.push_str(section_table);
}
i += 1;
}
out
}
fn median_ms(samples: &mut [f64]) -> f64 {
samples.sort_by(|a, b| a.total_cmp(b));
let mid = samples.len() / 2;
if samples.len() % 2 == 0 {
((samples[mid - 1] + samples[mid]) * 0.5) / 1e6
} else {
samples[mid] / 1e6
}
}
fn mean_ms(samples: &[f64]) -> f64 {
let sum: f64 = samples.iter().sum();
(sum / samples.len() as f64) / 1e6
}
fn run_bench_on_app(cx: &mut App) {
let bench_state = Arc::new(Mutex::new(BenchState { render_doc_ns: 0.0 }));
let bench_state_init = bench_state.clone();
let window = cx
.open_window(
WindowOptions {
window_bounds: Some(WindowBounds::Windowed(gpui::Bounds::centered(
None,
gpui::size(px(800.0), px(1200.0)),
cx,
))),
..Default::default()
},
|_, cx| {
cx.new(|_| BenchView {
doc: Arc::new(LaidOutDocument::default()),
state: bench_state_init,
})
},
)
.unwrap();
let _ = cx.update_window(window.into(), |_, window, cx| {
window.draw(cx).clear(cx);
});
let style_c = CString::new(STYLE_JSON).unwrap();
for &(label, target_bytes, iters) in &[
("5 KB", 5 * 1024usize, 25usize),
("20 KB", 20 * 1024usize, 15usize),
("100 KB", 100 * 1024usize, 7usize),
] {
let base = build_realistic_reply(target_bytes);
let actual_bytes = base.len();
let mut parse_s = Vec::with_capacity(iters);
let mut hl_s = Vec::with_capacity(iters);
let mut ser_s = Vec::with_capacity(iters);
let mut deser_s = Vec::with_capacity(iters);
let mut layout_s = Vec::with_capacity(iters);
let mut paint_s = Vec::with_capacity(iters);
let mut build_el_s = Vec::with_capacity(iters);
for step in 0..=iters {
let md = if step == 0 {
base.clone()
} else {
format!("{base}\nStreamed token chunk #{step}.")
};
let md_c = CString::new(md).unwrap();
let mut parse_ns = 0.0f64;
let mut hl_ns = 0.0f64;
let mut ser_ns = 0.0f64;
let mut out_ptr: *mut c_char = std::ptr::null_mut();
let mut out_len: usize = 0;
let rc = unsafe {
rn_gpui_markdown_bench_stages(
md_c.as_ptr(),
true,
style_c.as_ptr(),
&mut parse_ns,
&mut hl_ns,
&mut ser_ns,
&mut out_ptr,
&mut out_len,
)
};
assert_eq!(rc, 0, "C++ bench failed");
let json = unsafe { CStr::from_ptr(out_ptr) }
.to_str()
.unwrap()
.to_owned();
unsafe { rn_gpui_markdown_bench_free(out_ptr) };
let t_deser = Instant::now();
let snapshot: MarkdownSnapshot = serde_json::from_str(&json).unwrap();
let deser_ns = t_deser.elapsed().as_secs_f64() * 1e9;
let t_layout = Instant::now();
let doc = Arc::new(layout_document(&snapshot, Some(680.0)));
let layout_ns = t_layout.elapsed().as_secs_f64() * 1e9;
let mut paint_elapsed = Duration::ZERO;
let _ = window.update(cx, |v, _, cx| {
v.doc = doc.clone();
cx.notify();
});
let _ = cx.update_window(window.into(), |_, window, cx| {
let t_paint = Instant::now();
window.refresh();
window.draw(cx).clear(cx);
paint_elapsed = t_paint.elapsed();
});
let render_doc_ns = bench_state.lock().map(|s| s.render_doc_ns).unwrap_or(0.0);
if step > 0 {
parse_s.push(parse_ns);
hl_s.push(hl_ns);
ser_s.push(ser_ns);
deser_s.push(deser_ns);
layout_s.push(layout_ns);
paint_s.push(paint_elapsed.as_secs_f64() * 1e9);
build_el_s.push(render_doc_ns);
}
}
let p_med = median_ms(&mut parse_s);
let h_med = median_ms(&mut hl_s);
let s_med = median_ms(&mut ser_s);
let d_med = median_ms(&mut deser_s);
let l_med = median_ms(&mut layout_s);
let pt_med = median_ms(&mut paint_s);
let total_med = p_med + h_med + s_med + d_med + l_med + pt_med;
println!(
"SIZE={label} bytes={actual_bytes} iters={iters} | MEDIAN_MS: parse={p_med:.3} highlight={h_med:.3} serialize={s_med:.3} deserialize={d_med:.3} layout={l_med:.3} paint={pt_med:.3} (build_el={:.3}) total={total_med:.3} | MEAN_MS: parse={:.3} highlight={:.3} serialize={:.3} deserialize={:.3} layout={:.3} paint={:.3}",
median_ms(&mut build_el_s),
mean_ms(&parse_s),
mean_ms(&hl_s),
mean_ms(&ser_s),
mean_ms(&deser_s),
mean_ms(&layout_s),
mean_ms(&paint_s),
);
}
std::process::exit(0);
}
fn main() {
rn_gpui_autolink::ensure_linked();
let config =
DesktopAppConfig::from_env_with_defaults(env!("RN_GPUI_APP_NAME"), env!("RN_GPUI_APP_ID"))
.window_title("Markdown Bench")
.window_size(800.0, 1200.0)
.on_app_ready(run_bench_on_app);
react_native_gpui::run_with(config);
}
+77
View File
@@ -0,0 +1,77 @@
const path = require("node:path");
const { makeMetroConfig } = require("@react-native-gpui/core/metro.config");
const projectRoot = path.resolve(__dirname, "..");
process.env.EXPO_ROUTER_APP_ROOT = path.resolve(projectRoot, "../src/app");
const config = makeMetroConfig({ projectRoot });
const resolveRequest = config.resolver.resolveRequest;
config.watchFolders.push(path.resolve(projectRoot, "../../.."));
config.transformer.unstable_allowRequireContext = true;
config.resolver.disableHierarchicalLookup = false;
config.resolver.blockList = /[/\\]gpui[/\\]desktop[/\\](target|build|autolink)[/\\]/;
// Metro loops over sourceExts outside platform suffixes, so listing gpui.<ext>
// first selects .gpui.* ahead of .desktop, .native, and base extensions.
config.resolver.sourceExts = [
...config.resolver.sourceExts.map((ext) => `gpui.${ext}`),
...config.resolver.sourceExts,
];
const nativePackages = [
"react",
"react-native-reanimated",
"react-native-worklets",
"react-native-gesture-handler",
"react-native-screens",
"react-native-safe-area-context",
"react-native-svg",
];
const adapters = {
"expo-keep-awake": "keep-awake.js",
"expo-image-picker": "image-picker.js",
"expo-image-manipulator": "image-manipulator.js",
"expo-sharing": "sharing.js",
"expo-document-picker": "document-picker.js",
"@mattermost/react-native-paste-input": "paste-input.js",
"@react-native-async-storage/async-storage": "async-storage.js",
"expo-localization": "localization.js",
"expo-clipboard": "clipboard.js",
"expo-file-system": "file-system.js",
"expo-file-system/legacy": "file-system.js",
"react-native-keyboard-controller": "keyboard.jsx",
crypto: "node-crypto.js",
"node:crypto": "node-crypto.js",
"expo-sqlite": "sqlite.js",
"expo-crypto": "crypto.js",
"react-native-unistyles": "unistyles.js",
};
config.resolver.resolveRequest = (context, name, platform) => {
if (adapters[name]) name = path.resolve(projectRoot, "adapters", adapters[name]);
if (
name.endsWith("/ensureNativeModulesAreInstalled") &&
context.originModulePath.includes("expo-modules-core")
)
name = path.resolve(projectRoot, "adapters/expo-install.js");
if (name === "./ExpoLinking" && context.originModulePath.includes("expo-linking"))
name = path.resolve(projectRoot, "adapters/expo-linking.js");
// Linux has no Expo mobile push-token or camera provider; reuse the app's
// existing unavailable-capability implementations.
if (name === "expo-notifications")
name = path.resolve(projectRoot, "../src/fdroid/expo-notifications.ts");
if (name === "expo-camera") name = path.resolve(projectRoot, "../src/fdroid/expo-camera.tsx");
if (name === "expo-router/_ctx") name = path.resolve(projectRoot, "routes.js");
if (name === "qrcode") name = "qrcode/lib/browser.js";
if (name.startsWith("react-native-unistyles/components/native/"))
name = path.resolve(projectRoot, "adapters/unistyles-components.js");
if (name.startsWith("@/")) name = path.resolve(projectRoot, "../src", name.slice(2));
if (
name.startsWith("react-native/") ||
nativePackages.some((pkg) => name === pkg || name.startsWith(`${pkg}/`))
) {
context = {
...context,
disableHierarchicalLookup: true,
nodeModulesPaths: [path.join(projectRoot, "node_modules")],
};
}
return resolveRequest(context, name, platform);
};
module.exports = config;
@@ -0,0 +1,9 @@
import { TurboModuleRegistry, type TurboModule } from "react-native";
export interface Spec extends TurboModule {
sqlite(sql: string, params: string): string;
locale(): string;
timezone(): string;
sha256(text: string): string;
randomBytes(length: number): Array<number>;
}
export default TurboModuleRegistry.getEnforcing<Spec>("PaseoDesktop");
+29
View File
@@ -0,0 +1,29 @@
rn_gpui_module::include_specs!();
mod services;
fn main() {
react_native_gpui::register_module(native_paseo_desktop_module::<services::PaseoDesktop>());
rn_gpui_autolink::ensure_linked();
// A debug build knows where its own bundle is; a release build does not, and
// must not: the path would name the machine that built it. A packaged release
// app resolves the bundle beside its executable instead.
#[cfg(debug_assertions)]
if std::env::var_os("RN_GPUI_BUNDLE").is_none() {
std::env::set_var("RN_GPUI_BUNDLE", env!("RN_GPUI_DEFAULT_BUNDLE"));
}
let config = react_native_gpui::DesktopAppConfig::from_env_with_defaults(
env!("RN_GPUI_APP_NAME"),
env!("RN_GPUI_APP_ID"),
)
.window_title("Paseo GPUI")
.window_size(1024.0, 768.0)
.dev_menu(true)
.configure_window(|options| {
// GPUI window options are public: titlebar, resizability, display,
// decorations, min size, and other native window behavior.
options.is_resizable = true;
});
react_native_gpui::run_with(config);
}
+174
View File
@@ -0,0 +1,174 @@
use crate::{NativePaseoDesktopEvents, NativePaseoDesktopSpec};
use rn_gpui_module::ModuleError;
use std::io::Read;
pub struct PaseoDesktop {
database: std::sync::Mutex<Option<rusqlite::Connection>>,
}
impl PaseoDesktop {
fn database(
&self,
) -> Result<std::sync::MutexGuard<'_, Option<rusqlite::Connection>>, ModuleError> {
let mut guard = self
.database
.lock()
.map_err(|e| ModuleError::new(e.to_string()))?;
if guard.is_none() {
let base = std::env::var("XDG_DATA_HOME")
.map(std::path::PathBuf::from)
.unwrap_or_else(|_| {
std::path::PathBuf::from(std::env::var("HOME").expect("HOME is set"))
.join(".local/share")
});
let dir = base.join("paseo-gpui");
std::fs::create_dir_all(&dir).map_err(|e| ModuleError::new(e.to_string()))?;
*guard = Some(
rusqlite::Connection::open(dir.join("replica.db"))
.map_err(|e| ModuleError::new(e.to_string()))?,
);
}
Ok(guard)
}
}
impl NativePaseoDesktopSpec for PaseoDesktop {
fn new(_events: NativePaseoDesktopEvents) -> Self {
Self {
database: std::sync::Mutex::new(None),
}
}
fn sqlite(&self, sql: String, params: String) -> Result<String, ModuleError> {
let fail = |e: rusqlite::Error| ModuleError::new(e.to_string());
let db = self.database()?;
let db = db.as_ref().unwrap();
if params == "batch" {
db.execute_batch(&sql).map_err(fail)?;
return Ok("[]".into());
}
let values: Vec<serde_json::Value> =
serde_json::from_str(&params).map_err(|e| ModuleError::new(e.to_string()))?;
let values: Vec<rusqlite::types::Value> = values
.into_iter()
.map(|v| match v {
serde_json::Value::Null => rusqlite::types::Value::Null,
serde_json::Value::String(v) => rusqlite::types::Value::Text(v),
serde_json::Value::Number(v) => v
.as_i64()
.map(rusqlite::types::Value::Integer)
.unwrap_or_else(|| rusqlite::types::Value::Real(v.as_f64().unwrap())),
_ => rusqlite::types::Value::Text(v.to_string()),
})
.collect();
let mut stmt = db.prepare(&sql).map_err(fail)?;
let names: Vec<String> = stmt.column_names().into_iter().map(str::to_owned).collect();
let mut rows = stmt
.query(rusqlite::params_from_iter(values))
.map_err(fail)?;
let mut results = Vec::new();
while let Some(row) = rows.next().map_err(fail)? {
let mut object = serde_json::Map::new();
for (index, name) in names.iter().enumerate() {
let value = match row.get_ref(index).map_err(fail)? {
rusqlite::types::ValueRef::Null => serde_json::Value::Null,
rusqlite::types::ValueRef::Integer(v) => v.into(),
rusqlite::types::ValueRef::Real(v) => serde_json::json!(v),
rusqlite::types::ValueRef::Text(v) => {
String::from_utf8_lossy(v).into_owned().into()
}
rusqlite::types::ValueRef::Blob(_) => {
return Err(ModuleError::new(
"Replica store does not support blob columns",
))
}
};
object.insert(name.clone(), value);
}
results.push(object);
}
serde_json::to_string(&results).map_err(|e| ModuleError::new(e.to_string()))
}
fn timezone(&self) -> Result<String, ModuleError> {
if let Ok(zone) = std::env::var("TZ") {
if !zone.is_empty() {
return Ok(zone.trim_start_matches(':').into());
}
}
if let Ok(path) = std::fs::read_link("/etc/localtime") {
if let Some((_, zone)) = path.to_string_lossy().split_once("/zoneinfo/") {
return Ok(zone.into());
}
}
Ok(std::fs::read_to_string("/etc/timezone")
.map(|s| s.trim().into())
.unwrap_or_else(|_| "UTC".into()))
}
fn locale(&self) -> Result<String, ModuleError> {
Ok(["LC_ALL", "LC_MESSAGES", "LANG"]
.iter()
.find_map(|key| std::env::var(key).ok().filter(|v| !v.is_empty()))
.unwrap_or_else(|| "en_US.UTF-8".into()))
}
fn sha256(&self, text: String) -> Result<String, ModuleError> {
use sha2::{Digest, Sha256};
Ok(format!("{:x}", Sha256::digest(text.as_bytes())))
}
fn random_bytes(&self, length: f64) -> Result<Vec<f64>, ModuleError> {
if !length.is_finite() || length < 0.0 || length > 65536.0 || length.fract() != 0.0 {
return Err(ModuleError::new("Invalid random byte count"));
}
let mut bytes = vec![0u8; length as usize];
std::fs::File::open("/dev/urandom")
.and_then(|mut source| source.read_exact(&mut bytes))
.map_err(|error| ModuleError::new(error.to_string()))?;
Ok(bytes.into_iter().map(f64::from).collect())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn service() -> PaseoDesktop {
PaseoDesktop {
database: std::sync::Mutex::new(Some(rusqlite::Connection::open_in_memory().unwrap())),
}
}
#[test]
fn crypto_matches_sha256_and_bounds_random_requests() {
let service = service();
assert_eq!(
service.sha256("abc".into()).unwrap(),
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"
);
assert_eq!(service.random_bytes(32.0).unwrap().len(), 32);
assert!(service.random_bytes(65537.0).is_err());
assert!(service.random_bytes(-1.0).is_err());
}
#[test]
fn replica_transactions_bind_values_and_roll_back() {
let service = service();
service
.sqlite(
"CREATE TABLE rows (key TEXT PRIMARY KEY, value TEXT);".into(),
"batch".into(),
)
.unwrap();
service
.sqlite(
"INSERT INTO rows VALUES (?, ?)".into(),
r#"["key","quoted ' value"]"#.into(),
)
.unwrap();
service
.sqlite(
"BEGIN IMMEDIATE; DELETE FROM rows; ROLLBACK;".into(),
"batch".into(),
)
.unwrap();
let result = service
.sqlite("SELECT key, value FROM rows".into(), "[]".into())
.unwrap();
assert_eq!(
serde_json::from_str::<serde_json::Value>(&result).unwrap(),
serde_json::json!([{"key":"key","value":"quoted ' value"}])
);
}
}
+10
View File
@@ -0,0 +1,10 @@
/* oxlint-disable import/no-unassigned-import -- Install globals before app modules evaluate. */
import "./adapters/intl";
import "../src/polyfills/install-early";
import "../src/styles/unistyles";
import { AppRegistry } from "react-native";
import { RootApp } from "../src/root-app";
// GPUI owns the native surface. Keep Paseo's full router and providers, while
// leaving Expo's mobile registration and WebView-based dev overlay out.
AppRegistry.registerComponent("Paseo", () => RootApp);
@@ -0,0 +1,401 @@
/* oxlint-disable react-perf/jsx-no-new-function-as-prop, react-perf/jsx-no-new-object-as-prop -- Minimal markdown native regression scene. */
import React, { useCallback, useState } from "react";
import { AppRegistry, Pressable, Text, View } from "react-native";
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
const BASE_MARKDOWN = `# Phase 1 Heading
## Subhead \`code\`
**bold**, *italic*, ~~struck~~, [docs](https://example.com/guide).
> Blockquote note
- Bullet one
- Bullet two
1. Ordered one
2. Ordered two
- [x] Done task
- [ ] Open task
\`\`\`ts
const n: number = 42;
function hi(s: string): string {
return \`Hi \${s}\`;
}
\`\`\`
| Component | Status |
| --- | --- |
| Parser | Ready |`;
const STREAM_APPEND = `
### Streamed
Appended **live** and [next](https://example.com/streamed).`;
const MARKDOWN_STYLE = {
paragraph: {
fontSize: 13,
lineHeight: 17,
color: "#111827",
marginBottom: 4,
},
h1: {
fontSize: 19,
lineHeight: 23,
fontWeight: "700",
color: "#0f172a",
marginBottom: 4,
},
h2: {
fontSize: 16,
lineHeight: 20,
fontWeight: "600",
color: "#1e293b",
marginTop: 2,
marginBottom: 4,
},
h3: {
fontSize: 14,
lineHeight: 18,
fontWeight: "600",
color: "#1e293b",
marginTop: 2,
marginBottom: 2,
},
h5: {
fontSize: 13,
lineHeight: 17,
fontWeight: "600",
color: "#334155",
marginBottom: 2,
},
strong: { fontWeight: "700" },
em: { fontStyle: "italic" },
strikethrough: { textDecorationLine: "line-through", color: "#64748b" },
code: {
fontFamily: "monospace",
fontScale: 0.85,
color: "#0f172a",
backgroundColor: "#e2e8f0",
},
link: {
color: "#2563eb",
underline: true,
},
list: {
fontSize: 13,
lineHeight: 17,
color: "#111827",
bulletColor: "#475569",
markerColor: "#475569",
bulletSize: 5,
gapWidth: 6,
marginLeft: 14,
itemSpacing: 1,
marginBottom: 4,
},
taskList: {
checkedColor: "#2563eb",
borderColor: "#475569",
checkmarkColor: "#ffffff",
checkedTextColor: "#64748b",
checkedStrikethrough: true,
checkboxSize: 13,
},
blockquote: {
fontSize: 13,
lineHeight: 17,
color: "#1e293b",
backgroundColor: "#eff6ff",
borderColor: "#2563eb",
borderWidth: 4,
padding: 6,
gapWidth: 6,
marginBottom: 4,
},
codeBlock: {
fontFamily: "monospace",
fontSize: 11,
lineHeight: 15,
color: "#e2e8f0",
backgroundColor: "#0f172a",
borderColor: "#334155",
borderWidth: 1,
borderRadius: 6,
padding: 6,
marginBottom: 4,
syntaxColors: {
keyword: "#c084fc",
string: "#86efac",
comment: "#94a3b8",
number: "#fbbf24",
type: "#38bdf8",
function: "#60a5fa",
operator: "#f472b6",
punctuation: "#cbd5e1",
},
},
table: {
fontSize: 12,
lineHeight: 16,
color: "#111827",
headerFontWeight: "700",
headerBackgroundColor: "#dbeafe",
headerTextColor: "#0f172a",
rowEvenBackgroundColor: "#ffffff",
rowOddBackgroundColor: "#f8fafc",
borderColor: "#2563eb",
borderWidth: 1,
borderRadius: 5,
cellPaddingHorizontal: 6,
cellPaddingVertical: 3,
marginBottom: 4,
},
};
function MarkdownRegression() {
const [streamed, setStreamed] = useState(false);
const [pressedLink, setPressedLink] = useState("none");
const [taskEvent, setTaskEvent] = useState("none");
const [codeEvent, setCodeEvent] = useState("none");
const [layoutText, setLayoutText] = useState("{}");
const handleLinkPress = useCallback((event) => {
setPressedLink(event?.url ?? "missing");
}, []);
const handleTaskPress = useCallback((event) => {
setTaskEvent(`${event?.index}:${event?.checked}:${event?.text}`);
}, []);
const handleCodePress = useCallback((event) => {
setCodeEvent(`${event?.language}:${String(event?.code ?? "").trim().length}`);
}, []);
const handleLayout = useCallback((event) => {
const layout = event?.nativeEvent?.layout;
if (layout) setLayoutText(JSON.stringify(layout));
}, []);
const markdown = streamed ? `${BASE_MARKDOWN}${STREAM_APPEND}` : BASE_MARKDOWN;
return (
<View
style={{ flex: 1, flexDirection: "row", padding: 8, gap: 10, backgroundColor: "#ffffff" }}
>
<View style={{ width: 320, gap: 4, backgroundColor: "#ffffff" }}>
<View style={{ flexDirection: "row", alignItems: "center", gap: 6, flexWrap: "wrap" }}>
<EnrichedMarkdownText
testID="markdown-link-target"
flavor="github"
markdown="[Open docs](https://example.com/docs)"
markdownStyle={MARKDOWN_STYLE}
onLinkPress={handleLinkPress}
allowTrailingMargin={false}
style={{ alignSelf: "flex-start" }}
/>
<Pressable
testID="markdown-stream-next"
onPress={() => setStreamed(true)}
style={{
width: 82,
height: 20,
backgroundColor: "#e2e8f0",
justifyContent: "center",
alignItems: "center",
}}
>
<Text style={{ fontSize: 12 }}>Stream Next</Text>
</Pressable>
<Text testID="pressed-link" style={{ fontSize: 11 }}>
{pressedLink}
</Text>
<Text testID="task-event" style={{ fontSize: 11 }}>
{taskEvent}
</Text>
<Text testID="code-event" style={{ fontSize: 11 }}>
{codeEvent}
</Text>
</View>
<Text testID="markdown-layout" style={{ fontSize: 10 }}>
{layoutText}
</Text>
<EnrichedMarkdownText
testID="markdown-view"
flavor="github"
markdown={markdown}
md4cFlags={{ underline: true, latexMath: true }}
markdownStyle={MARKDOWN_STYLE}
onLinkPress={handleLinkPress}
onLayout={handleLayout}
allowTrailingMargin={false}
/>
</View>
<View style={{ width: 320, gap: 3, backgroundColor: "#ffffff" }}>
<View style={{ flexDirection: "row", gap: 6, backgroundColor: "#ffffff" }}>
<View testID="probe-text-plain" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, color: "#111827" }}>Sample</Text>
</View>
<View testID="probe-text-bold" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, fontWeight: "700", color: "#111827" }}>Sample</Text>
</View>
<View testID="probe-text-italic" style={{ backgroundColor: "#ffffff" }}>
<Text style={{ fontSize: 13, fontStyle: "italic", color: "#111827" }}>Sample</Text>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6, alignItems: "flex-start" }}>
<View testID="block-h1" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-h1-md"
flavor="github"
markdown="# Heading A"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-h5" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-h5-md"
flavor="github"
markdown="##### Heading A"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-emphasis-plain" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="alpha beta gamma"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-emphasis-styled" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="**alpha** *beta* ~~gamma~~"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-inline-code-plain" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="use code_val"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-inline-code" style={{ width: 155, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"use `code_val`"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-ul" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"- One\n- Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-ol-1" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"1. One\n2. Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-ol-8" style={{ width: 100, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"8. One\n9. Two"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
<View style={{ flexDirection: "row", gap: 6 }}>
<View testID="block-task-checked" style={{ width: 132, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="- [x] Done task"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-task-unchecked" style={{ width: 132, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="- [ ] Open task"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<EnrichedMarkdownText
testID="block-task-toggle-md"
flavor="github"
markdown="- [ ] Ok"
markdownStyle={MARKDOWN_STYLE}
enableTaskListItemToggle={true}
onTaskListItemPress={handleTaskPress}
allowTrailingMargin={false}
style={{ width: 44, height: 17 }}
/>
</View>
<View testID="block-blockquote" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown="> Quoted note"
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
<View testID="block-code" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
testID="block-code-md"
flavor="github"
markdown={"```ts\nconst n: number = 42;\n```"}
markdownStyle={MARKDOWN_STYLE}
onCodeBlockPress={handleCodePress}
allowTrailingMargin={false}
/>
</View>
<View testID="block-table" style={{ width: 320, backgroundColor: "#ffffff" }}>
<EnrichedMarkdownText
flavor="github"
markdown={"| ColA | ColB |\n| --- | --- |\n| Left | Right |"}
markdownStyle={MARKDOWN_STYLE}
allowTrailingMargin={false}
/>
</View>
</View>
</View>
);
}
AppRegistry.registerComponent("Paseo", () => MarkdownRegression);
+341
View File
@@ -0,0 +1,341 @@
import { afterAll, beforeAll, expect, test } from "vitest";
import sharp from "sharp";
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
import path from "node:path";
const endpoint = process.env.PASEO_GPUI_TEST_URL;
const token = process.env.PASEO_GPUI_TEST_TOKEN;
const markdownFixture = process.env.PASEO_GPUI_TEST_SCENE === "markdown";
const driverLogPath = process.env.PASEO_GPUI_DRIVER_LOG;
interface Node {
tag: number;
component: string;
testID: string;
text: string;
frame?: [number, number, number, number];
children?: Node[];
}
let socket: WebSocket;
let nextId = 0;
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
function request<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
const id = ++nextId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`GPUI ${method} timed out`));
}, 15_000);
pending.set(id, {
resolve: (value) => {
clearTimeout(timer);
resolve(value as T);
},
reject: (error) => {
clearTimeout(timer);
reject(error);
},
});
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params: { ...params, token } }));
});
}
function flatten(node: Node): Node[] {
return [node, ...(node.children ?? []).flatMap(flatten)];
}
async function nodes() {
return (await request<{ children: Node[] }>("tree")).children.flatMap(flatten);
}
async function nodeWithId(testID: string) {
await expect
.poll(async () => {
const node = (await nodes()).find((item) => item.testID === testID);
return (node?.frame?.[2] ?? 0) > 0 && (node?.frame?.[3] ?? 0) > 0;
})
.toBe(true);
return (await nodes()).find((node) => node.testID === testID)!;
}
beforeAll(async () => {
if (!endpoint) return;
if (!token) throw new Error("PASEO_GPUI_TEST_TOKEN is required");
socket = new WebSocket(endpoint);
await new Promise<void>((resolve, reject) => {
socket.addEventListener("open", () => resolve(), { once: true });
socket.addEventListener("error", () => reject(new Error("GPUI driver connection failed")), {
once: true,
});
});
socket.addEventListener("message", (event) => {
const response = JSON.parse(String(event.data));
const waiter = pending.get(response.id);
if (!waiter) return;
pending.delete(response.id);
const error = response.error ?? response.result?.error;
if (error) waiter.reject(new Error(JSON.stringify(error)));
else waiter.resolve(response.result);
});
await new Promise((r) => setTimeout(r, 800));
});
afterAll(() => socket?.close());
async function captureRaw(tag: number) {
let png: string | undefined;
await expect
.poll(
async () => {
try {
const res = await request<{ png: string }>("screenshot", { tag });
png = res.png;
return true;
} catch {
return false;
}
},
{ timeout: 10_000, interval: 100 },
)
.toBe(true);
const bytes = Buffer.from(png!, "base64");
const { data, info } = await sharp(bytes)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
return { bytes, data, width: info.width, height: info.height, channels: info.channels };
}
function diffPixelCount(
a: { data: Buffer; width: number; height: number; channels: number },
b: { data: Buffer; width: number; height: number; channels: number },
xMax = Math.min(a.width, b.width),
) {
const w = Math.min(a.width, b.width, xMax);
const h = Math.min(a.height, b.height);
let diff = 0;
for (let y = 0; y < h; y++) {
for (let x = 0; x < w; x++) {
const ia = (y * a.width + x) * a.channels;
const ib = (y * b.width + x) * b.channels;
if (
Math.abs(a.data[ia]! - b.data[ib]!) > 12 ||
Math.abs(a.data[ia + 1]! - b.data[ib + 1]!) > 12 ||
Math.abs(a.data[ia + 2]! - b.data[ib + 2]!) > 12
) {
diff++;
}
}
}
return diff;
}
function countMatchingPixels(
img: { data: Buffer; width: number; height: number; channels: number },
pred: (r: number, g: number, b: number, x: number, y: number) => boolean,
) {
let count = 0;
for (let y = 0; y < img.height; y++) {
for (let x = 0; x < img.width; x++) {
const i = (y * img.width + x) * img.channels;
if (pred(img.data[i]!, img.data[i + 1]!, img.data[i + 2]!, x, y)) {
count++;
}
}
}
return count;
}
test.skipIf(!endpoint || !markdownFixture)(
"RN <Text> bold and italic probe matches renderer font resolution",
async () => {
const plain = await captureRaw((await nodeWithId("probe-text-plain")).tag);
const bold = await captureRaw((await nodeWithId("probe-text-bold")).tag);
const italic = await captureRaw((await nodeWithId("probe-text-italic")).tag);
const boldDiff = diffPixelCount(plain, bold);
const italicDiff = diffPixelCount(plain, italic);
console.log(
`[probe-text] plain=${plain.width}x${plain.height} boldDiff=${boldDiff} italicDiff=${italicDiff}`,
);
expect(bold.width).toBeGreaterThan(20);
},
20_000,
);
test.skipIf(!endpoint || !markdownFixture)(
"EnrichedMarkdown renders every Phase 1 block type through caller interfaces and asserts regression.png",
async () => {
const view = await nodeWithId("markdown-view");
expect(view.component).toBe("EnrichedMarkdown");
expect(view.frame?.[2] ?? 0).toBeGreaterThan(200);
expect(view.frame?.[3] ?? 0).toBeGreaterThan(250);
const layoutNode = await nodeWithId("markdown-layout");
const initialLayout = JSON.parse(layoutNode.text) as { height?: number; width?: number };
expect(initialLayout.width ?? 0).toBeGreaterThan(200);
expect(initialLayout.height ?? 0).toBeGreaterThan(250);
// 1. Headings scale vertically between H1 and H5.
const h1Node = await nodeWithId("block-h1-md");
const h5Node = await nodeWithId("block-h5-md");
expect(h1Node.frame?.[3] ?? 0).toBeGreaterThan((h5Node.frame?.[3] ?? 0) + 4);
// 2. Emphasis + strikethrough visibly alter rendered ink vs plain prose.
const empPlain = await captureRaw((await nodeWithId("block-emphasis-plain")).tag);
const empStyled = await captureRaw((await nodeWithId("block-emphasis-styled")).tag);
expect(diffPixelCount(empPlain, empStyled)).toBeGreaterThan(30);
// 3. Inline code paints its #e2e8f0 pill background and keeps distinct glyph pixels.
const codePlain = await captureRaw((await nodeWithId("block-inline-code-plain")).tag);
const codeStyled = await captureRaw((await nodeWithId("block-inline-code")).tag);
const pillBg = (r: number, g: number, b: number) =>
Math.abs(r - 0xe2) <= 8 && Math.abs(g - 0xe8) <= 8 && Math.abs(b - 0xf0) <= 8 && b - r >= 6;
expect(countMatchingPixels(codePlain, pillBg)).toBeLessThan(15);
expect(countMatchingPixels(codeStyled, pillBg)).toBeGreaterThan(150);
// 4. Unordered and ordered lists paint distinct gutter markers.
const ulImg = await captureRaw((await nodeWithId("block-ul")).tag);
const ulGutterX = Math.round(ulImg.width * 0.28);
const ulGutterInk = countMatchingPixels(
ulImg,
(r, g, b, x) => x < ulGutterX && r < 140 && g < 140 && b < 140,
);
expect(ulGutterInk).toBeGreaterThan(12);
const ol1 = await captureRaw((await nodeWithId("block-ol-1")).tag);
const ol8 = await captureRaw((await nodeWithId("block-ol-8")).tag);
expect(diffPixelCount(ol1, ol8, Math.round(ol1.width * 0.3))).toBeGreaterThan(10);
// 5. Task lists paint checked vs unchecked state and toggle via caller event.
const taskChecked = await captureRaw((await nodeWithId("block-task-checked")).tag);
const taskUnchecked = await captureRaw((await nodeWithId("block-task-unchecked")).tag);
const taskGutterX = Math.round(taskChecked.width * 0.22);
const accentBlue = (r: number, g: number, b: number, x: number) =>
x < taskGutterX && b - r > 50 && r < 80;
expect(countMatchingPixels(taskChecked, accentBlue)).toBeGreaterThan(40);
expect(countMatchingPixels(taskUnchecked, accentBlue)).toBe(0);
const taskToggleNode = await nodeWithId("block-task-toggle-md");
expect(await request("click", { tag: taskToggleNode.tag })).toEqual({ clicked: true });
await expect.poll(async () => (await nodeWithId("task-event")).text).toBe("0:true:Ok");
// 6. Blockquote paints left accent bar and tinted background.
const bqImg = await captureRaw((await nodeWithId("block-blockquote")).tag);
const bqBarX = Math.max(24, Math.round(bqImg.width * 0.08));
const bqBar = countMatchingPixels(bqImg, (r, g, b, x) => x < bqBarX && b - r > 80 && r < 80);
const bqFill = countMatchingPixels(
bqImg,
(r, g, b) => Math.abs(r - 0xef) < 12 && Math.abs(g - 0xf6) < 12 && b > 240,
);
expect(bqBar).toBeGreaterThan(40);
expect(bqFill).toBeGreaterThan(400);
// 7. Code block paints dark card, TypeScript header band, syntax-highlighted tokens, and fires onCodeBlockPress.
const cbImg = await captureRaw((await nodeWithId("block-code")).tag);
const cbSplitY = Math.round(cbImg.height * 0.42);
const cbDarkBg = countMatchingPixels(cbImg, (r, g, b) => r < 30 && g < 40 && b < 70);
const cbHeaderInk = countMatchingPixels(
cbImg,
(r, g, b, _x, y) => y < cbSplitY && (r > 90 || g > 90 || b > 100),
);
const cbSyntaxColors = countMatchingPixels(
cbImg,
(r, g, b, _x, y) =>
y >= cbSplitY &&
((r > 150 && b > 200 && g < 180) || // purple keyword (#c084fc)
(b > 200 && g > 150 && r < 120) || // cyan type (#38bdf8)
(r > 200 && g > 150 && b < 110)), // amber number (#fbbf24)
);
expect(cbDarkBg).toBeGreaterThan(2000);
expect(cbHeaderInk).toBeGreaterThan(25);
expect(cbSyntaxColors).toBeGreaterThan(30);
const codeNode = await nodeWithId("block-code-md");
expect(await request("click", { tag: codeNode.tag })).toEqual({ clicked: true });
await expect.poll(async () => (await nodeWithId("code-event")).text).toBe("ts:21");
// 8. Table paints header tint and blue border.
const tableImg = await captureRaw((await nodeWithId("block-table")).tag);
const tableHeaderFill = countMatchingPixels(
tableImg,
(r, g, b) => Math.abs(r - 0xdb) < 16 && Math.abs(g - 0xea) < 16 && b > 240,
);
const tableBorderBlue = countMatchingPixels(tableImg, (r, g, b) => b - r > 80 && r < 80);
expect(tableHeaderFill).toBeGreaterThan(400);
expect(tableBorderBlue).toBeGreaterThan(100);
// 9. Capture and structurally assert regression.png for the full composite document.
const initialComposite = await captureRaw(view.tag);
const directory = path.resolve(import.meta.dirname, "../../../.artifacts/gpui/markdown");
mkdirSync(directory, { recursive: true });
writeFileSync(path.join(directory, "regression.png"), initialComposite.bytes);
expect(
countMatchingPixels(initialComposite, (r, g, b) => r < 60 && g < 60 && b < 60),
).toBeGreaterThan(1500);
expect(
countMatchingPixels(initialComposite, (r, g, b) => b - r > 60 && r < 100),
).toBeGreaterThan(300);
expect(
countMatchingPixels(
initialComposite,
(r, g, b) =>
(r > 150 && b > 200 && g < 180) ||
(g > 180 && r < 160 && b < 190) ||
(r > 200 && g > 150 && b < 110),
),
).toBeGreaterThan(80);
// Dark code card + blue header table bands must both exist in the composite screenshot.
expect(
countMatchingPixels(initialComposite, (r, g, b) => r < 25 && g < 35 && b < 60),
).toBeGreaterThan(2000);
expect(
countMatchingPixels(
initialComposite,
(r, g, b) => Math.abs(r - 0xdb) < 16 && Math.abs(g - 0xea) < 16 && b > 240,
),
).toBeGreaterThan(300);
// 10. Clicking a rendered link dispatches onLinkPress with the URL.
const linkTarget = await nodeWithId("markdown-link-target");
expect(linkTarget.frame?.[2] ?? 0).toBeGreaterThan(40);
expect(linkTarget.frame?.[3] ?? 0).toBeGreaterThan(10);
expect(await request("click", { tag: linkTarget.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodeWithId("pressed-link")).text)
.toBe("https://example.com/docs");
// 11. Streaming append increases layout height and paints new ink pixels in the composite screenshot.
const streamBtn = await nodeWithId("markdown-stream-next");
expect(await request("click", { tag: streamBtn.tag })).toEqual({ clicked: true });
await expect
.poll(
async () =>
(JSON.parse((await nodeWithId("markdown-layout")).text) as { height?: number }).height ??
0,
)
.toBeGreaterThan(initialLayout.height ?? 0);
await expect
.poll(async () => {
const streamedComposite = await captureRaw(view.tag);
if (streamedComposite.height <= initialComposite.height) return 0;
return countMatchingPixels(
streamedComposite,
(r, g, b, _x, y) => y >= initialComposite.height && r < 140 && g < 140 && b < 140,
);
})
.toBeGreaterThan(80);
if (driverLogPath) {
const invalidLines = readFileSync(driverLogPath, "utf8")
.split("\n")
.filter((line) => line.includes("returned an invalid measurement"));
expect(invalidLines).toEqual([]);
}
},
30_000,
);
+251
View File
@@ -0,0 +1,251 @@
import { realpathSync, statSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { afterEach, describe, expect, test } from "vitest";
const require = createRequire(import.meta.url);
const GPUI_DIR = import.meta.dirname;
const APP_DIR = path.resolve(GPUI_DIR, "..");
interface MetroConfig {
resolver: {
sourceExts: string[];
resolveRequest: (
context: Record<string, unknown>,
moduleName: string,
platform: string | null,
) => { type: string; filePath?: string };
};
}
function createResolutionContext(
originModulePath: string,
sourceExts: string[],
preferNativePlatform: boolean,
resolverModule: { resolve: (...args: unknown[]) => unknown },
) {
const fileSystemLookup = (candidatePath: string) => {
try {
const stats = statSync(candidatePath);
if (stats.isFile() || stats.isDirectory()) {
return {
exists: true,
type: stats.isFile() ? "f" : "d",
realPath: realpathSync(candidatePath),
};
}
} catch {
// Missing candidate path.
}
return { exists: false };
};
return {
allowHaste: false,
assetExts: new Set(["png", "jpg", "jpeg", "gif", "webp", "svg"]),
customResolverOptions: {},
dev: false,
disableHierarchicalLookup: false,
doesFileExist: (filePath: string) => fileSystemLookup(filePath).exists,
extraNodeModules: {},
fileSystemLookup,
getPackage: () => null,
getPackageForModule: () => null,
mainFields: ["react-native", "browser", "main"],
nodeModulesPaths: [path.join(GPUI_DIR, "node_modules"), path.join(APP_DIR, "node_modules")],
originModulePath,
preferNativePlatform,
redirectModulePath: (modulePath: string) => modulePath,
resolveAsset: () => null,
resolveHasteModule: () => null,
resolveHastePackage: () => null,
resolveRequest: resolverModule.resolve,
sourceExts,
unstable_conditionNames: ["require", "react-native"],
unstable_conditionsByPlatform: {},
unstable_enablePackageExports: false,
unstable_incrementalResolution: false,
unstable_logWarning: () => {},
};
}
function loadAppMetroConfig(webPlatform?: string) {
const previous = process.env.PASEO_WEB_PLATFORM;
if (webPlatform === undefined) delete process.env.PASEO_WEB_PLATFORM;
else process.env.PASEO_WEB_PLATFORM = webPlatform;
const configPath = path.join(APP_DIR, "metro.config.cjs");
delete require.cache[configPath];
try {
return {
config: require(configPath) as MetroConfig,
resolver: require(
require.resolve("metro-resolver", { paths: [APP_DIR, path.resolve(APP_DIR, "../..")] }),
) as { resolve: (...args: unknown[]) => unknown },
};
} finally {
if (previous === undefined) delete process.env.PASEO_WEB_PLATFORM;
else process.env.PASEO_WEB_PLATFORM = previous;
}
}
const CASES = [
{
label: "audio engine",
origin: path.join(APP_DIR, "src/audio/index.ts"),
specifier: "./audio-engine",
gpui: path.join(APP_DIR, "src/audio/audio-engine.gpui.ts"),
native: path.join(APP_DIR, "src/audio/audio-engine.native.ts"),
web: path.join(APP_DIR, "src/audio/audio-engine.web.ts"),
},
{
label: "mermaid fence host",
origin: path.join(APP_DIR, "src/components/markdown/fence/mermaid/index.tsx"),
specifier: "./host",
gpui: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.gpui.tsx"),
native: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.native.tsx"),
web: path.join(APP_DIR, "src/components/markdown/fence/mermaid/host.web.tsx"),
},
{
label: "html preview",
origin: path.join(APP_DIR, "src/file-panels/builtin.tsx"),
specifier: "./html-preview",
gpui: path.join(APP_DIR, "src/file-panels/html-preview.gpui.tsx"),
native: path.join(APP_DIR, "src/file-panels/html-preview.tsx"),
web: path.join(APP_DIR, "src/file-panels/html-preview.web.tsx"),
},
{
label: "document frame",
origin: path.join(APP_DIR, "src/plugins/react-native/ui.ts"),
specifier: "@/file-panels/document-frame",
gpui: path.join(APP_DIR, "src/file-panels/document-frame/index.gpui.tsx"),
native: path.join(APP_DIR, "src/file-panels/document-frame/index.tsx"),
web: path.join(APP_DIR, "src/file-panels/document-frame/index.web.tsx"),
},
{
label: "press feedback",
origin: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/index.tsx"),
specifier: "./feedback",
gpui: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.gpui.tsx"),
native: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.native.tsx"),
web: path.join(APP_DIR, "modules/paseo-press-feedback/src/ui/feedback.tsx"),
},
{
label: "pointer capabilities",
origin: path.join(APP_DIR, "src/components/ui/control-sizing.ts"),
specifier: "@/hooks/pointer-capabilities",
gpui: path.join(APP_DIR, "src/hooks/pointer-capabilities.gpui.ts"),
native: path.join(APP_DIR, "src/hooks/pointer-capabilities.ts"),
web: path.join(APP_DIR, "src/hooks/pointer-capabilities.ts"),
},
{
label: "keyboard presence",
origin: path.join(APP_DIR, "src/keyboard/availability.ts"),
specifier: "./internal/presence",
gpui: path.join(APP_DIR, "src/keyboard/internal/presence.gpui.ts"),
native: path.join(APP_DIR, "src/keyboard/internal/presence.ts"),
web: path.join(APP_DIR, "src/keyboard/internal/presence.web.ts"),
},
{
label: "keyboard conventions",
origin: path.join(APP_DIR, "src/keyboard/index.ts"),
specifier: "./internal/conventions",
gpui: path.join(APP_DIR, "src/keyboard/internal/conventions.gpui.ts"),
native: path.join(APP_DIR, "src/keyboard/internal/conventions.ts"),
web: path.join(APP_DIR, "src/keyboard/internal/conventions.web.ts"),
},
{
label: "resource budget",
origin: path.join(APP_DIR, "src/hooks/use-settings/storage.ts"),
specifier: "@/constants/resource-budget",
gpui: path.join(APP_DIR, "src/constants/resource-budget.gpui.ts"),
native: path.join(APP_DIR, "src/constants/resource-budget.ts"),
web: path.join(APP_DIR, "src/constants/resource-budget.ts"),
},
{
label: "presentation",
origin: path.join(APP_DIR, "src/command-center/command-center.tsx"),
specifier: "@/constants/presentation",
gpui: path.join(APP_DIR, "src/constants/presentation.gpui.ts"),
native: path.join(APP_DIR, "src/constants/presentation.ts"),
web: path.join(APP_DIR, "src/constants/presentation.ts"),
},
{
label: "touch timing",
origin: path.join(APP_DIR, "src/composer/input/input.tsx"),
specifier: "@/constants/touch-timing",
gpui: path.join(APP_DIR, "src/constants/touch-timing.gpui.ts"),
native: path.join(APP_DIR, "src/constants/touch-timing.ts"),
web: path.join(APP_DIR, "src/constants/touch-timing.ts"),
},
{
label: "press highlight",
origin: path.join(APP_DIR, "src/components/sidebar-workspace-list.tsx"),
specifier: "@/components/ui/press-highlight",
gpui: path.join(APP_DIR, "src/components/ui/press-highlight.gpui.tsx"),
native: path.join(APP_DIR, "src/components/ui/press-highlight.native.tsx"),
web: path.join(APP_DIR, "src/components/ui/press-highlight.tsx"),
},
];
afterEach(() => {
delete require.cache[path.join(APP_DIR, "metro.config.cjs")];
});
describe("GPUI Metro platform rule", () => {
test("GPUI resolves .gpui.* files ahead of .desktop, .native, and base files", () => {
const config = require(path.join(GPUI_DIR, "desktop/metro.config.js")) as MetroConfig;
const resolver = require(require.resolve("metro-resolver", { paths: [GPUI_DIR] })) as {
resolve: (...args: unknown[]) => unknown;
};
for (const item of CASES) {
const ctx = createResolutionContext(item.origin, config.resolver.sourceExts, true, resolver);
expect(
config.resolver.resolveRequest(ctx, item.specifier, "desktop").filePath,
item.label,
).toBe(item.gpui);
}
// GPUI must not pick Electron's .electron.* files as "desktop".
const browserCtx = createResolutionContext(
path.join(APP_DIR, "src/components/split-container.tsx"),
config.resolver.sourceExts,
true,
resolver,
);
expect(
config.resolver.resolveRequest(browserCtx, "@/desktop/browser/pane", "desktop").filePath,
).toBe(path.join(APP_DIR, "src/desktop/browser/pane/index.tsx"));
});
test("iOS, Android, web, and Electron never resolve .gpui.* files", () => {
const relativeCases = CASES.filter((item) => !item.specifier.startsWith("@/"));
const standard = loadAppMetroConfig();
const electron = loadAppMetroConfig("electron");
const targets = [
{ ...standard, platform: "ios", preferNative: true, expected: "native" as const },
{ ...standard, platform: "android", preferNative: true, expected: "native" as const },
{ ...standard, platform: "web", preferNative: false, expected: "web" as const },
{ ...electron, platform: "web", preferNative: false, expected: "web" as const },
];
for (const target of targets) {
for (const item of relativeCases) {
const ctx = createResolutionContext(
item.origin,
target.config.resolver.sourceExts,
target.preferNative,
target.resolver,
);
const filePath = target.config.resolver.resolveRequest(
ctx,
item.specifier,
target.platform,
).filePath;
expect(filePath, `${target.platform}: ${item.label}`).toBe(item[target.expected]);
expect(filePath).not.toContain(".gpui.");
}
}
});
});
+434
View File
@@ -0,0 +1,434 @@
import { afterAll, beforeAll, expect, test } from "vitest";
import sharp from "sharp";
import { mkdirSync, writeFileSync } from "node:fs";
import path from "node:path";
// Runs against the actual Paseo bundle in the compiled GPUI app. Start with
// RN_GPUI_TEST_DRIVER=1 and pass its loopback URL and token to this test.
const endpoint = process.env.PASEO_GPUI_TEST_URL;
const token = process.env.PASEO_GPUI_TEST_TOKEN;
const appearanceFixture = process.env.PASEO_GPUI_TEST_SCENE === "appearance";
let socket: WebSocket;
let nextId = 0;
interface Node {
tag: number;
component: string;
testID: string;
text: string;
frame?: [number, number, number, number];
children?: Node[];
}
const pending = new Map<number, { resolve(value: unknown): void; reject(error: Error): void }>();
function request<T = unknown>(method: string, params: Record<string, unknown> = {}): Promise<T> {
const id = ++nextId;
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`GPUI ${method} timed out`));
}, 15_000);
pending.set(id, {
resolve: (value) => {
clearTimeout(timer);
resolve(value as T);
},
reject: (error) => {
clearTimeout(timer);
reject(error);
},
});
socket.send(JSON.stringify({ jsonrpc: "2.0", id, method, params: { ...params, token } }));
});
}
function flatten(node: Node): Node[] {
return [node, ...(node.children ?? []).flatMap(flatten)];
}
async function nodes() {
return (await request<{ children: Node[] }>("tree")).children.flatMap(flatten);
}
beforeAll(async () => {
if (!endpoint) return;
if (!token) throw new Error("PASEO_GPUI_TEST_TOKEN is required");
socket = new WebSocket(endpoint);
await new Promise<void>((resolve, reject) => {
socket.addEventListener("open", () => resolve(), { once: true });
socket.addEventListener("error", () => reject(new Error("GPUI driver connection failed")), {
once: true,
});
});
socket.addEventListener("message", (event) => {
const response = JSON.parse(String(event.data));
const waiter = pending.get(response.id);
if (!waiter) return;
pending.delete(response.id);
const error = response.error ?? response.result?.error;
if (error) waiter.reject(new Error(JSON.stringify(error)));
else waiter.resolve(response.result);
});
});
afterAll(() => socket?.close());
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo portal passes workspace clicks and the native composer edits text",
async () => {
const workspace = (await nodes()).find((node) =>
node.testID.startsWith("sidebar-workspace-row-"),
);
expect(workspace, "connected daemon must have an existing workspace").toBeDefined();
// Regression: the upstream box-none portal hit area intercepted this click.
expect(await request("click", { tag: workspace!.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodes()).some((node) => node.testID === "workspace-header-title"), {
timeout: 15_000,
})
.toBe(true);
await expect
.poll(async () => (await nodes()).some((node) => node.component === "TextInput"), {
timeout: 15_000,
})
.toBe(true);
// Wait for async draft hydration (which resets an empty native TextInput once after mount).
let settledTag: number | undefined;
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput")?.tag;
const stable = current !== undefined && current === settledTag;
settledTag = current;
return stable;
},
{ timeout: 15_000, interval: 500 },
)
.toBe(true);
const input = (await nodes()).find((node) => node.component === "TextInput")!;
const original = (await request<{ text: string }>("getProps", { tag: input.tag })).text;
try {
await request("click", { tag: input.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
expect(
await request("type", { tag: input.tag, text: "GPUI native input regression" }),
).toEqual({ typed: true });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe("GPUI native input regression");
} finally {
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
if (original) await request("type", { tag: input.tag, text: original });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe(original);
}
},
45_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo sizes controls for a pointer, not for touch",
async () => {
// Regression: GPUI took the native touch answer, so a 28 pt pointer control rendered at 44.
const settings = await nodeWithId("sidebar-settings");
const displays = await request<Array<{ primary: boolean; scaleFactor: number }>>("displays");
const scale =
displays.find((display) => display.primary)?.scaleFactor ?? displays[0]?.scaleFactor ?? 1;
expect(settings.frame?.[3]).toBeDefined();
expect(Math.abs(settings.frame![3] - 28)).toBeLessThanOrEqual(1 / scale);
},
20_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo opens History",
async () => {
// Regression: the agent list's RefreshControl was undefined on GPUI, so History rendered
// "Element type is invalid" instead of the list. The daemon needs at least one agent.
const history = await nodeWithId("sidebar-sessions");
expect(await request("click", { tag: history.tag })).toEqual({ clicked: true });
// The list mounts after the agents load, so wait for a row, not for the search input.
await expect
.poll(
async () => {
const current = await nodes();
if (current.some((node) => node.testID === "root-error-boundary")) return "error screen";
return current.some((node) => node.testID.startsWith("agent-row-")) ? "list" : "loading";
},
{ timeout: 15_000 },
)
.toBe("list");
},
30_000,
);
async function openWorkspaceAndWaitForComposer(workspaceRow: Node): Promise<Node> {
expect(await request("click", { tag: workspaceRow.tag })).toEqual({ clicked: true });
await expect
.poll(async () => (await nodes()).some((node) => node.testID === "workspace-header-title"), {
timeout: 15_000,
})
.toBe(true);
await expect
.poll(async () => (await nodes()).some((node) => node.component === "TextInput"), {
timeout: 15_000,
})
.toBe(true);
let settledTag: number | undefined;
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput")?.tag;
const stable = current !== undefined && current === settledTag;
settledTag = current;
return stable;
},
{ timeout: 15_000, interval: 500 },
)
.toBe(true);
return (await nodes()).find((node) => node.component === "TextInput")!;
}
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo submits the composer on Enter and inserts a newline on Shift+Enter",
async () => {
await expect
.poll(
async () => (await nodes()).some((n) => n.testID.startsWith("sidebar-workspace-row-")),
{
timeout: 15_000,
},
)
.toBe(true);
const workspace = (await nodes()).find((n) => n.testID.startsWith("sidebar-workspace-row-"))!;
const input = await openWorkspaceAndWaitForComposer(workspace);
await request("click", { tag: input.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
const marker = `GPUI Enter ${Date.now()}`;
await request("type", { tag: input.tag, text: marker });
await request("press", { key: "shift-enter" });
await request("type", { tag: input.tag, text: "line2" });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: input.tag })).text)
.toBe(`${marker}\nline2`);
await request("press", { key: "enter" });
await expect
.poll(
async () => {
const current = (await nodes()).find((node) => node.component === "TextInput");
if (!current) return null;
return (await request<{ text: string }>("getProps", { tag: current.tag })).text;
},
{ timeout: 15_000 },
)
.toBe("");
await expect
.poll(async () => (await nodes()).some((node) => node.text.includes(marker)), {
timeout: 15_000,
})
.toBe(true);
},
45_000,
);
test.skipIf(!endpoint || appearanceFixture)(
"real Paseo keeps the first workspace mounted when switching between two workspaces",
async () => {
await expect
.poll(
async () =>
(await nodes()).filter((n) => n.testID.startsWith("sidebar-workspace-row-")).length >= 2,
{ timeout: 15_000 },
)
.toBe(true);
const rows = (await nodes()).filter((n) => n.testID.startsWith("sidebar-workspace-row-"));
const firstInput = await openWorkspaceAndWaitForComposer(rows[0]!);
const firstTitle = (await nodes()).find((n) => n.testID === "workspace-header-title")?.text;
await request("click", { tag: firstInput.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
await request("type", { tag: firstInput.tag, text: "Kept across workspace switch" });
await expect
.poll(async () => (await request<{ text: string }>("getProps", { tag: firstInput.tag })).text)
.toBe("Kept across workspace switch");
try {
expect(await request("click", { tag: rows[1]!.tag })).toEqual({ clicked: true });
await expect
.poll(
async () => {
const title = (await nodes()).find((n) => n.testID === "workspace-header-title")?.text;
return title !== undefined && title !== firstTitle;
},
{ timeout: 15_000 },
)
.toBe(true);
expect(await request("click", { tag: rows[0]!.tag })).toEqual({ clicked: true });
await expect
.poll(
async () => (await nodes()).find((n) => n.testID === "workspace-header-title")?.text,
{ timeout: 15_000 },
)
.toBe(firstTitle);
// The exact Fabric node tag and draft text must survive because desktop retention keeps
// inactive workspaces mounted instead of unmounting on switch.
expect((await request<{ text: string }>("getProps", { tag: firstInput.tag })).text).toBe(
"Kept across workspace switch",
);
} finally {
await request("click", { tag: firstInput.tag });
await request("press", { key: "secondary-a" });
await request("press", { key: "backspace" });
}
},
45_000,
);
async function nodeWithId(testID: string) {
await expect.poll(async () => (await nodes()).some((node) => node.testID === testID)).toBe(true);
return (await nodes()).find((node) => node.testID === testID)!;
}
async function expectBackground(node: Node, color: number) {
await expect
.poll(
async () =>
(await request<{ backgroundColor: number }>("getProps", { tag: node.tag })).backgroundColor,
)
.toBe(color);
}
test.skipIf(!endpoint || !appearanceFixture)(
"Pressable render props receive hover state",
async () => {
const button = await nodeWithId("hover-render-prop");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: button.tag });
await expectBackground(button, 0xff00ff00);
await expect
.poll(async () => (await nodes()).some((node) => node.text === "render hovered"))
.toBe(true);
await request("hover", { tag: outside.tag });
await expectBackground(button, 0xff0000ff);
await expect
.poll(async () => (await nodes()).some((node) => node.text === "render idle"))
.toBe(true);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"rounded borders follow the background curve",
async () => {
const node = await nodeWithId("rounded-border");
const { png } = await request<{ png: string }>("screenshot", { tag: node.tag });
const bytes = Buffer.from(png, "base64");
const directory = path.resolve(import.meta.dirname, "../../../.artifacts/gpui/appearance");
mkdirSync(directory, { recursive: true });
writeFileSync(path.join(directory, "rounded-border.png"), bytes);
const { data, info } = await sharp(bytes)
.removeAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
const pixel = (x: number, y: number) => {
const offset =
(Math.floor((y * info.height) / 100) * info.width + Math.floor((x * info.width) / 200)) *
info.channels;
return [...data.subarray(offset, offset + 3)];
};
// Outside the arc must be clear; the diagonal must have an actual curved
// border, not four straight rules clipped to a rounded rectangle.
expect(pixel(1, 1)).toEqual([255, 255, 255]);
expect(pixel(8, 8)).toEqual([255, 0, 0]);
expect(pixel(15, 15)).toEqual([0, 0, 255]);
expect(pixel(100, 1)).toEqual([255, 0, 0]);
expect(pixel(198, 98)).toEqual([255, 255, 255]);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"Pressable hover highlights enter and leave",
async () => {
const button = await nodeWithId("hover-button");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: button.tag });
await expectBackground(button, 0xff00ff00);
await request("hover", { tag: outside.tag });
await expectBackground(button, 0xff0000ff);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"row hover survives entering a nested Pressable",
async () => {
const row = await nodeWithId("hover-row");
const child = await nodeWithId("nested-button");
const outside = await nodeWithId("outside-hover");
await request("hover", { tag: row.tag });
await request("hover", { tag: child.tag });
await expectBackground(row, 0xff00ff00);
await request("hover", { tag: outside.tag });
await expectBackground(row, 0xff0000ff);
},
);
test.skipIf(!endpoint || !appearanceFixture)(
"onLayout fires with React Native layout shape for View, Text, TextInput, Image, and ScrollView",
async () => {
interface LayoutEntry {
count: number;
keys: string[];
layout: { x: number; y: number; width: number; height: number };
}
const readLayouts = async () => {
const node = await nodeWithId("layout-results");
return JSON.parse(node.text) as Record<string, LayoutEntry>;
};
const targets = [
["view", "layout-view"],
["text", "layout-text"],
["textInput", "layout-text-input"],
["image", "layout-image"],
["scrollView", "layout-scroll"],
] as const;
await expect
.poll(async () => Object.keys(await readLayouts()).sort())
.toEqual(targets.map(([key]) => key).sort());
const initial = await readLayouts();
const treeNodes = await nodes();
for (const [key, testID] of targets) {
const entry = initial[key];
expect(entry.count, `${key} initial onLayout count`).toBe(1);
expect(entry.keys, `${key} layout keys`).toEqual(["height", "width", "x", "y"]);
expect(entry.layout.width, `${key} width`).toBeGreaterThan(0);
expect(entry.layout.height, `${key} height`).toBeGreaterThan(0);
const treeNode = treeNodes.find((n) => n.testID === testID);
expect(treeNode?.frame, `${testID} frame`).toBeDefined();
expect(entry.layout.x).toBeCloseTo(treeNode!.frame![0], 2);
expect(entry.layout.y).toBeCloseTo(treeNode!.frame![1], 2);
expect(entry.layout.width).toBeCloseTo(treeNode!.frame![2], 2);
expect(entry.layout.height).toBeCloseTo(treeNode!.frame![3], 2);
}
const toggle = await nodeWithId("layout-resize-toggle");
expect(await request("click", { tag: toggle.tag })).toEqual({ clicked: true });
await expect
.poll(async () => {
const parsed = await readLayouts();
return targets.every(([key]) => (parsed[key]?.count ?? 0) >= 2);
})
.toBe(true);
const resized = await readLayouts();
for (const [key] of targets) {
expect(resized[key].count, `${key} resized onLayout count`).toBe(2);
expect(resized[key].layout.width, `${key} resized width`).toBeGreaterThan(
initial[key].layout.width,
);
}
},
);
+6737
View File
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"name": "paseo-gpui",
"version": "0.0.0",
"private": true,
"dependencies": {
"@formatjs/intl-datetimeformat": "^7.9.0",
"@formatjs/intl-displaynames": "^7.4.0",
"@formatjs/intl-getcanonicallocales": "^3.3.0",
"@formatjs/intl-locale": "^5.4.1",
"@formatjs/intl-numberformat": "^9.5.0",
"@formatjs/intl-pluralrules": "^6.4.0",
"@formatjs/intl-segmenter": "^12.3.0",
"@react-native-gpui/codegen": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-codegen-0.87.0-alpha.2.tgz",
"@react-native-gpui/core": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-core-0.87.0-alpha.5.tgz",
"@react-native-gpui/fs": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-fs-0.0.1-alpha.1.tgz",
"@react-native-gpui/gesture-handler": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-gesture-handler-3.3.0-alpha.1.tgz",
"@react-native-gpui/hermes": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-hermes-0.87.0-alpha.1.tgz",
"@react-native-gpui/reanimated": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-reanimated-4.7.0-alpha.1.tgz",
"@react-native-gpui/safe-area-context": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-safe-area-context-5.10.0-alpha.0.tgz",
"@react-native-gpui/screens": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-screens-4.28.0-alpha.2.tgz",
"@react-native-gpui/svg": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-svg-15.15.0-alpha.1.tgz",
"@react-native-gpui/worklets": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-worklets-0.13.0-alpha.1.tgz",
"@react-native/assets-registry": "^0.87.1",
"react": "19.2.3",
"react-native": "0.87.1",
"react-native-gesture-handler": "3.3.0",
"react-native-reanimated": "https://github.com/ammarahm-ed/react-native-reanimated/releases/download/4.7.1-desktop.1/react-native-reanimated-4.7.1.tgz",
"react-native-safe-area-context": "5.10.1",
"react-native-screens": "4.28.0",
"react-native-svg": "15.15.5",
"react-native-worklets": "https://github.com/ammarahm-ed/react-native-reanimated/releases/download/worklets-0.13.0-desktop.1/react-native-worklets-0.13.0.tgz"
},
"devDependencies": {
"@react-native-community/cli": "20.2.0",
"@react-native-gpui/cli": "https://github.com/getpaseo/react-native-gpui/releases/download/paseo-4/react-native-gpui-cli-0.87.0-alpha.5.tgz",
"@react-native/babel-preset": "0.87.1",
"@react-native/metro-config": "0.87.1",
"typescript": "^5.8.3"
}
}
+2
View File
@@ -0,0 +1,2 @@
/// <reference types="@react-native-gpui/core/types" />
// Added by react-native-gpui. Do not edit: it is regenerated.
+22
View File
@@ -0,0 +1,22 @@
const path = require("node:path");
module.exports = {
// This target only launches desktop. RN CLI 20.2's built-in
// run-ios/run-android option lists conflict with the CLI's global verbose
// option, and this app has no native mobile projects to launch.
commands: ["build-android", "build-ios", "log-android", "log-ios", "run-android", "run-ios"].map(
(name) => ({
name,
description: `${name} is not configured for Paseo GPUI`,
func: () => {
throw new Error(`${name} is not configured for Paseo GPUI`);
},
}),
),
project: { desktop: {} },
dependencies: {
"react-native-enriched-markdown": {
root: path.resolve(__dirname, "../../react-native-enriched-markdown"),
},
},
reactNativePath: path.dirname(require.resolve("react-native/package.json")),
};
+7
View File
@@ -0,0 +1,7 @@
// Use the existing route tree. Expo's transformer normally supplies this root
// through a Babel caller field; the RN desktop transformer does not.
export const ctx = require.context(
"../src/app",
true,
/^(?:\.\/)(?!(?:(?:(?:.*\+api)|(?:\+(html|native-intent))))\.[tj]sx?$).*\.[tj]sx?$/,
);
+3
View File
@@ -0,0 +1,3 @@
[toolchain]
channel = "stable"
profile = "minimal"
@@ -0,0 +1,47 @@
import { readdirSync, readFileSync } from "node:fs";
import { createRequire } from "node:module";
import path from "node:path";
import { parse } from "@babel/parser";
import { expect, test } from "vitest";
const require = createRequire(import.meta.url);
const GPUI_DIR = import.meta.dirname;
// The Unistyles Babel plugin rewrites `import { X } from "react-native"` to
// `react-native-unistyles/components/native/X`, and the GPUI Metro config sends
// every such path to this one adapter. A component Unistyles wraps but the
// adapter does not export arrives as `undefined` and React throws
// "Element type is invalid" when it renders.
const ADAPTER = path.join(GPUI_DIR, "adapters/unistyles-components.js");
// NativeText and NativeView are reached only through
// `react-native/Libraries/...` imports, which the app does not use.
const NOT_REDIRECTED_FROM_REACT_NATIVE = new Set(["NativeText", "NativeView"]);
function unistylesWrappedComponents(): string[] {
const unistylesRoot = path.dirname(require.resolve("react-native-unistyles/package.json"));
return readdirSync(path.join(unistylesRoot, "components/native"), { withFileTypes: true })
.filter((entry) => entry.isDirectory() && !NOT_REDIRECTED_FROM_REACT_NATIVE.has(entry.name))
.map((entry) => entry.name)
.sort();
}
function adapterExports(): Set<string> {
const ast = parse(readFileSync(ADAPTER, "utf8"), { sourceType: "module" });
const names = new Set<string>();
for (const node of ast.program.body) {
if (node.type !== "ExportNamedDeclaration" || node.declaration?.type !== "VariableDeclaration")
continue;
for (const declarator of node.declaration.declarations) {
if (declarator.id.type === "Identifier") names.add(declarator.id.name);
}
}
return names;
}
test("the GPUI Unistyles adapter exports every component the Unistyles plugin redirects", () => {
const wrapped = unistylesWrappedComponents();
expect(wrapped).toContain("RefreshControl");
const exported = adapterExports();
expect(wrapped.filter((name) => !exported.has(name))).toEqual([]);
});
@@ -0,0 +1,61 @@
import assert from "node:assert/strict";
import { execFileSync, spawnSync } from "node:child_process";
import { readdirSync } from "node:fs";
import path from "node:path";
assert.equal(process.platform, "darwin", "Run package verification on macOS");
assert.ok(process.argv[2], "Pass the packaged .app path");
const app = path.resolve(process.argv[2]);
const contents = path.join(app, "Contents");
const info = JSON.parse(
execFileSync("plutil", ["-convert", "json", "-o", "-", path.join(contents, "Info.plist")]),
);
const executable = path.join(contents, "MacOS", info.CFBundleExecutable);
const frameworks = path.join(contents, "Frameworks");
const libraries = readdirSync(frameworks, { recursive: true })
.filter((name) => name.endsWith(".dylib"))
.map((name) => path.join(frameworks, name));
execFileSync("codesign", ["--verify", "--deep", "--strict", app], { stdio: "inherit" });
const signature = spawnSync("codesign", ["-dvvv", executable], { encoding: "utf8" });
assert.equal(signature.status, 0, signature.stderr);
if (
signature.stderr.includes("Signature=adhoc") &&
/flags=[^\n]*\bruntime\b/.test(signature.stderr) &&
libraries.length > 0
) {
const entitlements = execFileSync("codesign", ["-d", "--entitlements", "-", "--xml", executable]);
assert.ok(entitlements.length > 0, "Ad-hoc app has no library-validation entitlement");
const values = JSON.parse(
execFileSync("plutil", ["-convert", "json", "-o", "-", "--", "-"], {
input: entitlements,
}),
);
assert.equal(
values["com.apple.security.cs.disable-library-validation"],
true,
"Ad-hoc app cannot satisfy Team ID library validation on a Mac with SIP enabled",
);
}
function version(value) {
const parts = value.split(".").map(Number);
return (parts[0] * 256 + (parts[1] ?? 0)) * 256 + (parts[2] ?? 0);
}
assert.ok(info.LSMinimumSystemVersion, "The app must declare its minimum macOS version");
for (const binary of [executable, ...libraries]) {
const build = execFileSync("xcrun", ["vtool", "-show-build", binary], { encoding: "utf8" });
const minima = [...build.matchAll(/\bminos\s+(\d+(?:\.\d+)*)/g)].map((match) => match[1]);
assert.ok(minima.length > 0, `No macOS deployment target found in ${binary}`);
for (const minimum of minima) {
assert.ok(
version(minimum) <= version(info.LSMinimumSystemVersion),
`${path.basename(binary)} requires macOS ${minimum}, above the app's ${info.LSMinimumSystemVersion}`,
);
}
}
console.log(
`PASS: bundle signatures, ad-hoc library loading policy, and macOS deployment targets: ${app}`,
);
@@ -0,0 +1,45 @@
import { AppRegistry } from "react-native";
AppRegistry.registerComponent("Paseo", () => () => null);
// The native test supplies a loopback server before loading this bundle.
const base = globalThis.__webSocketRegressionUrl;
async function connect(path, expectedCode, localClose = false) {
return new Promise((resolve, reject) => {
const socket = new WebSocket(`${base}/${path}`);
const timeout = setTimeout(() => reject(new Error(`${path}: timed out`)), 5000);
let echoed = false;
socket.addEventListener("open", () => socket.send("native websocket regression"));
socket.addEventListener("message", (event) => {
echoed = event.data === "native websocket regression";
if (localClose) socket.close(1000, "client done");
});
socket.addEventListener("close", (event) => {
clearTimeout(timeout);
if (event.code !== expectedCode || (expectedCode === 1000 && !echoed)) {
reject(new Error(`${path}: code=${event.code}, echoed=${echoed}`));
} else {
resolve();
}
});
});
}
async function run() {
// Keep retrying through the real RN WebSocket API. Before the fix, native
// clients survived terminal events and exhausted the Mac's descriptor limit.
for (const [path, code, localClose] of [
["reject", 1006, false],
["remote-close", 1000, false],
["local-close", 1000, true],
]) {
for (let attempt = 0; attempt < 128; attempt++) {
await connect(path, code, localClose);
}
console.log(`WEBSOCKET_REGRESSION_PASS ${path}`);
}
console.log("WEBSOCKET_REGRESSION_COMPLETE");
}
setTimeout(() => {
run().catch((error) => console.error(`WEBSOCKET_REGRESSION_FAIL ${error.message}`));
}, 0);
+117
View File
@@ -0,0 +1,117 @@
import { spawn, execFileSync } from "node:child_process";
import { createServer } from "node:http";
import { mkdtempSync, readFileSync, writeFileSync, mkdirSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { Server as WebSocketServer } from "ws";
import { expect, test } from "vitest";
const binary = process.env.PASEO_GPUI_TEST_BINARY;
const project = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(project, "../../..");
function createPeer() {
const server = createServer();
const sockets = new WebSocketServer({ noServer: true });
server.on("upgrade", (request, socket, head) => {
if (request.url === "/reject") {
socket.end("HTTP/1.1 400 Bad Request\r\nContent-Length: 0\r\nConnection: close\r\n\r\n");
return;
}
sockets.handleUpgrade(request, socket, head, (websocket) => {
websocket.on("message", (message) => {
websocket.send(message.toString());
if (request.url === "/remote-close") websocket.close(1000, "server done");
});
});
});
return { server, sockets };
}
test.skipIf(!binary)(
"native WebSocket retries and peer closes release their resources",
async () => {
mkdirSync(path.join(root, ".artifacts/gpui"), { recursive: true });
const artifacts = mkdtempSync(path.join(root, ".artifacts/gpui/websocket-"));
const bundle = path.join(artifacts, "regression.bundle");
execFileSync(
process.execPath,
[
"node_modules/react-native/cli.js",
"bundle",
"--platform",
"desktop",
"--entry-file",
"websocket-regression.fixture.js",
"--config",
"desktop/metro.config.js",
"--bundle-output",
bundle,
"--dev",
"false",
"--max-workers",
"1",
],
{ cwd: project, env: { ...process.env, PASEO_RENDERER: "gpui" }, timeout: 120_000 },
);
const { server, sockets } = createPeer();
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
const address = server.address();
if (!address || typeof address === "string") throw new Error("Missing server address");
writeFileSync(
bundle,
`globalThis.__webSocketRegressionUrl = "ws://127.0.0.1:${address.port}";\n${readFileSync(bundle, "utf8")}`,
);
// Match Finder's descriptor limit even when the test shell has raised it.
const app = spawn("/bin/sh", ["-c", 'ulimit -n 256; exec "$@"', "gpui-test", binary!], {
env: {
...process.env,
RN_GPUI_BUNDLE: bundle,
RN_GPUI_APP_ID: "sh.paseo.gpui.websocket-test",
XDG_DATA_HOME: path.join(artifacts, "data"),
},
stdio: ["ignore", "pipe", "pipe"],
});
let output = "";
try {
await new Promise<void>((resolve, reject) => {
const timeout = setTimeout(
() => reject(new Error(`Native retry test timed out:\n${output}`)),
60_000,
);
const collect = (chunk: Buffer) => {
output += chunk.toString();
if (output.includes("WEBSOCKET_REGRESSION_COMPLETE")) {
clearTimeout(timeout);
resolve();
} else if (output.includes("WEBSOCKET_REGRESSION_FAIL")) {
clearTimeout(timeout);
reject(new Error(output));
}
};
app.stdout.on("data", collect);
app.stderr.on("data", collect);
app.once("error", (error) => {
clearTimeout(timeout);
reject(error);
});
app.once("exit", (code, signal) => {
clearTimeout(timeout);
reject(new Error(`Native process exited (${code}, ${signal}):\n${output}`));
});
});
expect(app.exitCode).toBeNull();
expect(output).toContain("WEBSOCKET_REGRESSION_PASS reject");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS remote-close");
expect(output).toContain("WEBSOCKET_REGRESSION_PASS local-close");
} finally {
writeFileSync(path.join(artifacts, "native.log"), output);
app.kill("SIGTERM");
for (const client of sockets.clients) client.terminate();
sockets.close();
server.close();
}
},
180_000,
);
@@ -2,12 +2,16 @@ package sh.paseo.keyboard
import android.app.Activity
import android.content.Intent
import android.text.SpannableStringBuilder
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.BaseInputConnection
import android.widget.EditText
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.After
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
@@ -57,6 +61,44 @@ class TerminalArrowTest {
}
}
@Test fun customTerminalViewExposesComposingStateToHardwareArrows() {
val host = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
)
activity = host
val editable = SpannableStringBuilder("한")
lateinit var view: View
instrumentation.runOnMainSync {
view = object : View(host), ComposingTextOwner {
init {
isFocusable = true
isFocusableInTouchMode = true
setTag(com.facebook.react.R.id.view_tag_native_id, "paseo-terminal-input")
// Mirrors React Native BaseViewManager.setTestId, which overwrites the unkeyed View tag.
setTag("terminal-native-input")
}
override fun isComposingText(): Boolean =
BaseInputConnection.getComposingSpanStart(editable) >= 0
}
host.setContentView(view)
view.requestFocus()
HardwareKeyboard.observe(host.window)
}
instrumentation.waitForIdleSync()
instrumentation.runOnMainSync {
assertSame(view, host.window.currentFocus)
// When not composing, hardware arrows are claimed for the terminal.
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)))
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)))
// While composing, hardware arrows must NOT be claimed so IME candidate navigation still works.
BaseInputConnection.setComposingSpans(editable)
assertFalse(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)))
assertFalse(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)))
}
}
private fun withInput(terminal: Boolean, check: (EditText, Activity) -> Unit) {
val host = instrumentation.startActivitySync(
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
@@ -115,11 +115,23 @@ internal object HardwareKeyboard {
}
}
/**
* Implemented by custom non-EditText editor views so window-level hardware key dispatch can
* detect active IME composition without depending on `View.getTag()` (which React Native's
* `BaseViewManager.setTestId` overwrites with the string `testID`).
*/
interface ComposingTextOwner {
fun isComposingText(): Boolean
}
private class KeyboardWindowCallback(private val window: Window, val previous: Window.Callback) : Window.Callback by previous {
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val focus = window.currentFocus
val editable = (focus as? EditText)?.text
val composing = editable != null && BaseInputConnection.getComposingSpanStart(editable) >= 0
val composing = when (focus) {
is ComposingTextOwner -> focus.isComposingText()
is EditText -> focus.text != null && BaseInputConnection.getComposingSpanStart(focus.text) >= 0
else -> false
}
val terminalFocused = focus?.getTag(R.id.view_tag_native_id) == TERMINAL_INPUT_NATIVE_ID
return HardwareKeyboard.dispatcher.dispatch(
event,
@@ -0,0 +1,9 @@
import type { Ref } from "react";
export interface RowFeedbackHandle {
acknowledge(): Promise<void>;
}
export function RowFeedback(_props: { ref?: Ref<RowFeedbackHandle>; selected: boolean }) {
return null;
}
@@ -18,6 +18,7 @@ android {
}
dependencies {
implementation project(":paseo-hardware-keyboard")
implementation "androidx.customview:customview:1.1.0"
implementation "com.facebook.react:react-android"
testImplementation "junit:junit:4.13.2"
@@ -0,0 +1,337 @@
package sh.paseo.terminal
import android.text.InputType
import android.view.KeyCharacterMap
import android.view.KeyEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.platform.app.InstrumentationRegistry
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
/**
* Exercises `TerminalInputConnection` and `PaseoTerminalInputView` against real Android
* `SpannableStringBuilder`, `BaseInputConnection`, `EditorInfo`, and `KeyEvent` instances.
*/
@RunWith(AndroidJUnit4::class)
class TerminalInputConnectionTest {
private val instrumentation = InstrumentationRegistry.getInstrumentation()
private class RecordedTerminal {
val chunks = mutableListOf<String>()
val keys = mutableListOf<TerminalKeyPayload>()
fun write(data: String) {
chunks.add(data)
}
fun key(payload: TerminalKeyPayload) {
keys.add(payload)
}
val rawStream: String
get() = chunks.joinToString("")
/** Applies `\x7f` rubouts onto a simulated terminal line buffer to verify visible text. */
fun applyToLine(initial: String = ""): String {
val codePoints = mutableListOf<Int>()
initial.codePoints().forEach { codePoints.add(it) }
rawStream.codePoints().forEach { cp ->
if (cp == 0x7f) {
if (codePoints.isNotEmpty()) codePoints.removeAt(codePoints.lastIndex)
} else {
codePoints.add(cp)
}
}
val sb = StringBuilder()
codePoints.forEach { sb.appendCodePoint(it) }
return sb.toString()
}
}
private fun withInputHarness(
block: (View, TerminalInputConnection, EditorInfo, RecordedTerminal) -> Unit,
) {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val terminal = RecordedTerminal()
val view = object : View(context) {
init {
isFocusable = true
isFocusableInTouchMode = true
}
}
val editorInfo = EditorInfo()
val connection = TerminalInputConnection(
targetView = view,
onInput = terminal::write,
onTerminalKey = terminal::key,
)
TerminalInputConnection.configureEditorInfo(editorInfo)
block(view, connection, editorInfo, terminal)
}
}
@Test
fun editorInfoDisablesSuggestionsFullscreenAndPersonalizedLearning() {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val editorInfo = EditorInfo()
val view = PaseoTerminalInputView.createForTest(context)
assertTrue("Terminal input view must declare itself as a text editor", view.onCheckIsTextEditor())
assertTrue("Terminal input view must be focusable", view.isFocusable && view.isFocusableInTouchMode)
val connection = view.onCreateInputConnection(editorInfo)
assertTrue("onCreateInputConnection must return TerminalInputConnection", connection is TerminalInputConnection)
assertEquals(
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS,
editorInfo.inputType,
)
assertEquals(EditorInfo.IME_ACTION_NONE, editorInfo.imeOptions and EditorInfo.IME_MASK_ACTION)
assertNotEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_FULLSCREEN)
assertNotEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING)
}
}
@Test
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
withInputHarness { _, ic, _, terminal ->
for (ch in listOf("a", "b", "c", "d")) {
ic.beginBatchEdit()
ic.commitText(ch, 1)
ic.endBatchEdit()
}
assertEquals("abcd", terminal.rawStream)
assertEquals("", ic.editable.toString())
// Coalesced setComposingText + finishComposingText inside one batch emits once.
ic.beginBatchEdit()
ic.setComposingText("ef", 1)
ic.finishComposingText()
ic.endBatchEdit()
assertEquals("abcdef", terminal.rawStream)
assertEquals("", ic.editable.toString())
}
}
@Test
fun backspaceWorksAcrossAllThreeImePaths() {
withInputHarness { _, ic, _, terminal ->
ic.commitText("abcd", 1)
assertEquals("abcd", terminal.applyToLine())
// Path 1: deleteSurroundingText (empty editable after commit)
ic.deleteSurroundingText(0, 0)
assertEquals("abcd", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("abc", terminal.applyToLine())
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
ic.setComposingText("😀", 1)
assertEquals("ab😀", terminal.applyToLine())
ic.deleteSurroundingTextInCodePoints(1, 0)
assertEquals("ab", terminal.applyToLine())
// Path 3: sendKeyEvent(KEYCODE_DEL) emits on ACTION_DOWN only, not ACTION_UP
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
assertEquals("a", terminal.applyToLine())
// Multi-char deleteSurroundingText on empty buffer
ic.commitText("xyz", 1)
ic.deleteSurroundingText(2, 0)
assertEquals("ax", terminal.applyToLine())
}
}
@Test
fun hangulCompositionSyllableMigrationBackspaceAndPostEnter() {
withInputHarness { _, ic, _, terminal ->
// ㅎ -> 하 -> 한
ic.setComposingText("ㅎ", 1)
ic.setComposingText("하", 1)
ic.setComposingText("한", 1)
assertEquals("한", terminal.applyToLine())
// Final consonant migration: 한 + ㅏ -> commit 하 + compose 나 in one batch
ic.beginBatchEdit()
ic.commitText("하", 1)
ic.setComposingText("나", 1)
ic.endBatchEdit()
assertEquals("하나", terminal.applyToLine())
// Continue composing second syllable: 나 -> 난
ic.setComposingText("난", 1)
assertEquals("하난", terminal.applyToLine())
// Backspace decomposes 난 -> 나 -> ㄴ -> "" (leaving 하) -> ""
ic.setComposingText("나", 1)
assertEquals("하나", terminal.applyToLine())
ic.setComposingText("ㄴ", 1)
assertEquals("하ㄴ", terminal.applyToLine())
ic.commitText("", 1)
assertEquals("하", terminal.applyToLine())
ic.deleteSurroundingText(1, 0)
assertEquals("", terminal.applyToLine())
// Submit via Enter, then immediately type 한글 with zero stale newline residue (#7164)
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
ic.setComposingText("ㅎ", 1)
ic.setComposingText("하", 1)
ic.setComposingText("한", 1)
ic.beginBatchEdit()
ic.commitText("한", 1)
ic.setComposingText("ㄱ", 1)
ic.endBatchEdit()
ic.setComposingText("그", 1)
ic.setComposingText("글", 1)
ic.finishComposingText()
assertEquals("\r한글", terminal.applyToLine())
}
}
@Test
fun pinyinCompositionAndMixedChineseThenLatinCandidate() {
withInputHarness { _, ic, _, terminal ->
// Pinyin reading: nihao -> ni hao -> 你好
ic.setComposingText("n", 1)
ic.setComposingText("ni", 1)
ic.setComposingText("nih", 1)
ic.setComposingText("niha", 1)
ic.setComposingText("ni hao", 1)
ic.beginBatchEdit()
ic.commitText("你好", 1)
ic.endBatchEdit()
assertEquals("你好", terminal.applyToLine())
// WeChat Keyboard #9121: immediately compose English and pick 2nd suggestion `hello`
ic.setComposingText("h", 1)
ic.setComposingText("he", 1)
ic.setComposingText("hel", 1)
ic.beginBatchEdit()
ic.commitText("hello", 1)
ic.endBatchEdit()
assertEquals("你好hello", terminal.applyToLine())
// Backspace right after Latin candidate deletes from terminal visibly
ic.deleteSurroundingText(1, 0)
assertEquals("你好hell", terminal.applyToLine())
}
}
@Test
fun latinCandidatesAutocorrectAndRepeatedClipboardCommit() {
withInputHarness { _, ic, _, terminal ->
// Candidate completion: hel -> hello
ic.setComposingText("hel", 1)
ic.commitText("hello", 1)
assertEquals("hello", terminal.applyToLine())
// Autocorrect replacement inside composing span: teh -> the
ic.setComposingText("teh", 1)
ic.commitText("the", 1)
assertEquals("hellothe", terminal.applyToLine())
// Repeated clipboard paste of identical text works because editable clears after commit
ic.commitText("echo ok", 1)
ic.commitText("echo ok", 1)
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
}
}
@Test
fun enterKeyAndEditorActionEmitSingleCarriageReturn() {
withInputHarness { _, ic, _, terminal ->
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
assertEquals("\r", terminal.rawStream)
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER))
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_NUMPAD_ENTER))
assertEquals("\r\r", terminal.rawStream)
ic.performEditorAction(EditorInfo.IME_ACTION_NONE)
assertEquals("\r\r\r", terminal.rawStream)
ic.commitText("\n", 1)
assertEquals("\r\r\r\r", terminal.rawStream)
}
}
@Test
fun physicalKeyboardKeysAndDeadKeyAccents() {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val terminal = RecordedTerminal()
val view = PaseoTerminalInputView.createForTest(
context = context,
onInput = terminal::write,
onTerminalKey = terminal::key,
)
view.onCreateInputConnection(EditorInfo())
// Enter & Numpad Enter: ACTION_DOWN + ACTION_UP -> single \r each
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_ENTER, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)))
assertTrue(view.onKeyUp(KeyEvent.KEYCODE_ENTER, KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER)))
assertTrue(view.onKeyUp(KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_NUMPAD_ENTER)))
assertEquals("\r\r", terminal.rawStream)
// Tab, Shift+Tab, Escape, Del
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, 0, KeyEvent.META_SHIFT_ON)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_ESCAPE, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ESCAPE)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_DEL, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f", terminal.rawStream)
// Ctrl+C and Alt+B
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_C, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_C, 0, KeyEvent.META_CTRL_ON)))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_B, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_B, 0, KeyEvent.META_ALT_ON)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bb", terminal.rawStream)
// Printable key
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_A, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bba", terminal.rawStream)
// Dead key accent (acute + e -> é)
val deadAcuteEvent = object : KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E) {
override fun getUnicodeChar(metaState: Int): Int =
KeyCharacterMap.COMBINING_ACCENT or '\u00b4'.code
}
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_E, deadAcuteEvent))
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_E, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E)))
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bbaé", terminal.rawStream)
// Meta shortcuts pass through unhandled
assertFalse(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, 0, KeyEvent.META_META_ON)))
}
}
@Test
fun composingStateIsExposedOnViewForHardwareKeyboardModule() {
instrumentation.runOnMainSync {
val context = instrumentation.targetContext
val view = PaseoTerminalInputView.createForTest(context)
// Mirrors React Native BaseViewManager.setTestId, which overwrites the unkeyed View tag.
view.setTag("terminal-native-input")
val ic = checkNotNull(view.onCreateInputConnection(EditorInfo()))
assertFalse(view.isComposingText())
ic.setComposingText("한", 1)
assertTrue(view.isComposingText())
ic.commitText("한", 1)
assertFalse(view.isComposingText())
}
}
}

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