mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-28 19:25:45 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ad7f2aede1 | ||
|
|
f13b51db9c |
@@ -1,6 +1,6 @@
|
||||
# Pull-request checks are routed by the behavior they prove. Package consumers
|
||||
# do not inherit their dependencies' test suites, except where noted below; main
|
||||
# and manual runs execute every contract regardless of these paths.
|
||||
# do not inherit their dependencies' test suites; main and manual runs execute
|
||||
# every contract regardless of these paths.
|
||||
routing:
|
||||
- ".github/ci-paths.yml"
|
||||
|
||||
@@ -60,6 +60,7 @@ sdk:
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
- "packages/workflows/**"
|
||||
|
||||
browser:
|
||||
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
|
||||
@@ -87,9 +88,5 @@ browser:
|
||||
relay:
|
||||
- "packages/relay/**"
|
||||
|
||||
# cli-tests is also a daemon end-to-end suite: it drives a real daemon, built-in
|
||||
# plugins included, so daemon changes run it too.
|
||||
cli:
|
||||
- "packages/cli/**"
|
||||
- "packages/server/**"
|
||||
- "plugins/**"
|
||||
|
||||
+13
-18
@@ -8,14 +8,13 @@ on:
|
||||
merge_group:
|
||||
workflow_dispatch:
|
||||
|
||||
# A newer push cancels the run still in progress on every ref except main,
|
||||
# because a full run costs about 200 runner-minutes against the org's 20
|
||||
# concurrent jobs. A main run finishes: cancelling it mid-flight leaves CANCELLED
|
||||
# checks that paint the commit red. Each ref has one run in progress and one
|
||||
# pending, so a newer push replaces a pending main run before it starts any job.
|
||||
# A newer push to the same ref cancels the run still in progress, main included.
|
||||
# A full run costs about 200 runner-minutes against the org's 20 concurrent
|
||||
# jobs, and a superseded main run only answers a question the newer commit
|
||||
# answers again.
|
||||
concurrency:
|
||||
group: ci-${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
# CI does not use the CUDA execution provider, and the onnxruntime-node
|
||||
@@ -128,6 +127,14 @@ jobs:
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run test --workspace=@getpaseo/highlight
|
||||
|
||||
- name: Build workflows package
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run build:workflows
|
||||
|
||||
- name: Run workflows tests
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run test --workspace=@getpaseo/workflows
|
||||
|
||||
- name: Typecheck client examples
|
||||
if: ${{ !cancelled() && steps.install.outcome == 'success' && (needs.changes.outputs.full != 'false' || needs.changes.outputs.sdk != 'false') }}
|
||||
run: npm run typecheck:examples --workspace=@getpaseo/client
|
||||
@@ -175,9 +182,6 @@ jobs:
|
||||
- name: Verify dependency patch recovery
|
||||
run: node --test scripts/postinstall-patches.test.mjs
|
||||
|
||||
- name: Verify daemon runtime trace contract
|
||||
run: node --test scripts/trace-daemon.test.mjs
|
||||
|
||||
- name: Build server stack
|
||||
run: npm run build:server
|
||||
|
||||
@@ -217,15 +221,6 @@ jobs:
|
||||
- name: Verify website mockups
|
||||
run: npm run test:e2e --workspace=@getpaseo/website
|
||||
|
||||
- name: Upload website test artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
if: failure()
|
||||
with:
|
||||
name: website-playwright-results
|
||||
path: packages/website/test-results/
|
||||
if-no-files-found: ignore
|
||||
retention-days: 7
|
||||
|
||||
- name: Verify public package contents
|
||||
run: |
|
||||
npm pack --dry-run --ignore-scripts --workspace=@getpaseo/protocol
|
||||
|
||||
@@ -13,11 +13,9 @@ on:
|
||||
- ".github/workflows/desktop-packages.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
# A main run finishes. A run cancelled mid-flight leaves CANCELLED checks that
|
||||
# paint the commit red.
|
||||
concurrency:
|
||||
group: desktop-packages-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -28,11 +28,9 @@ on:
|
||||
- "false"
|
||||
- "true"
|
||||
|
||||
# main, tag and publish runs finish. A run cancelled mid-flight leaves CANCELLED
|
||||
# checks that paint a main commit red.
|
||||
concurrency:
|
||||
group: docker-${{ github.workflow }}-${{ github.event_name == 'workflow_dispatch' && inputs.publish == 'true' && format('publish-{0}', inputs.paseo_version || github.run_id) || github.ref }}
|
||||
cancel-in-progress: ${{ github.ref != 'refs/heads/main' && !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
|
||||
cancel-in-progress: ${{ !startsWith(github.ref, 'refs/tags/') && !(github.event_name == 'workflow_dispatch' && inputs.publish == 'true') }}
|
||||
|
||||
env:
|
||||
REGISTRY: ghcr.io
|
||||
|
||||
@@ -3,37 +3,8 @@ name: Nix
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
# Prove the real Nix package and daemon smoke before merge when Nix, CLI,
|
||||
# server, or daemon packaging inputs change.
|
||||
pull_request:
|
||||
paths:
|
||||
- "nix/**"
|
||||
- "flake.nix"
|
||||
- "flake.lock"
|
||||
- "package.json"
|
||||
- "package-lock.json"
|
||||
- "packages/protocol/**"
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/plugin/**"
|
||||
- "packages/server/**"
|
||||
- "packages/relay/**"
|
||||
- "packages/cli/**"
|
||||
- "packages/desktop/**"
|
||||
- "plugins/**"
|
||||
- "skills/**"
|
||||
- "scripts/trace-daemon.mjs"
|
||||
- "scripts/is-main-module.mjs"
|
||||
- "scripts/build-daemon-web-ui.mjs"
|
||||
- "scripts/update-nix.sh"
|
||||
- "scripts/fix-lockfile.mjs"
|
||||
- ".github/workflows/nix.yml"
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: nix-${{ github.ref }}
|
||||
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
@@ -131,7 +102,6 @@ jobs:
|
||||
run: nix build .#desktop -o result-desktop
|
||||
|
||||
build-desktop-darwin:
|
||||
if: ${{ github.event_name != 'pull_request' }}
|
||||
runs-on: macos-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
@@ -86,7 +86,6 @@ packages/server/src/server/fixtures/dictation/dictation-debug-largest.wav
|
||||
packages/server/src/server/fixtures/dictation/dictation-debug-largest.transcript.txt
|
||||
packages/protocol/src/generated/validation/*.aot.ts
|
||||
packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts
|
||||
packages/protocol/src/generated/validation/message-defaults.ts
|
||||
packages/protocol/codegen/generated/
|
||||
|
||||
/artifacts
|
||||
|
||||
+1
-1
@@ -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>Hoplite runs swarms of coding agents in the cloud.</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>Cloud coding agents</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
@@ -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>Hoplite runs swarms of coding agents in the cloud.</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>Cloud coding agents</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>
|
||||
|
||||
@@ -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>Hoplite runs swarms of coding agents in the cloud.</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>Cloud coding agents</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
@@ -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>Hoplite runs swarms of coding agents in the cloud.</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>Cloud coding agents</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>
|
||||
|
||||
+15
-22
@@ -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.
|
||||
|
||||
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:
|
||||
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:
|
||||
|
||||
- **`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.
|
||||
- **`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.
|
||||
- **`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 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.
|
||||
- **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.
|
||||
- **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`. A new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
|
||||
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 command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and a `steer` or `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text.
|
||||
|
||||
@@ -198,24 +198,17 @@ outstanding intent. A crash after successful dispatch but before removal commits
|
||||
notification. Clean shutdown can also flush an already queued callback while retaining its intent,
|
||||
so that callback can repeat after restart. This is an at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
|
||||
A turn end is not always a settled child. A child can end its turn with work that will start its next
|
||||
turn by itself: a running turn, queued messages, a pending provider wake-up
|
||||
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
|
||||
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
|
||||
crons, change-request watches, and other daemon background items never count: they are external
|
||||
triggers, not work the caller is waiting for.
|
||||
|
||||
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
|
||||
subscription follows the child: each later turn end reports `finished` again, and the child settling
|
||||
with nothing pending sends a final `finished` and removes the subscription, even when the work
|
||||
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
|
||||
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
|
||||
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
|
||||
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
|
||||
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
|
||||
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
|
||||
the child's last reply and the subscription ends. Remote children and providers without the probe
|
||||
report their first turn end as a settled `finished`.
|
||||
A turn end is not always a settled child. When the child ends its turn with work that will start its
|
||||
next turn by itself, the caller gets one `message` notice ("ended its turn but is still working") and
|
||||
the subscription keeps following the child. That work is a running turn, queued messages, a pending
|
||||
provider wake-up (`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and
|
||||
one-shot wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats,
|
||||
recurring crons, change-request watches, and other daemon background items never count: they are
|
||||
external triggers, not work the caller is waiting for. While following, turn ends and work changes stay
|
||||
silent until nothing is pending, which sends `finished` and removes the subscription. `followingSince`
|
||||
is stored before the notice is sent, so restarts resume following without repeating it, and following
|
||||
ends after 24 hours with an "is still working" notice. Remote children and providers without the probe
|
||||
report their first turn end as `finished`.
|
||||
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
|
||||
+4
-7
@@ -209,8 +209,7 @@ snapshot so a mixed edit can apply its live subset and still name the paths that
|
||||
listen: "127.0.0.1:6767",
|
||||
hostnames: true | string[], // legacy alias `allowedHosts` is migrated on load
|
||||
trustedProxies: true | string[], // defaults to ["loopback"]; Express proxy names/CIDRs
|
||||
tools: { enabled: boolean, groups: { orchestration, schedules, changeRequests, browser: boolean } },
|
||||
mcp: { enabled: boolean, injectIntoAgents: boolean }, // legacy, read only when `tools` is absent
|
||||
mcp: { enabled: boolean, injectIntoAgents: boolean },
|
||||
git: { maxProcessesPerSecond: number, maxProcessConcurrency: number },
|
||||
appendSystemPrompt: string, // appended to supported provider system/developer prompts
|
||||
terminalProfiles: TerminalProfile[], // named shell commands; omitted means DEFAULT_TERMINAL_PROFILES
|
||||
@@ -312,14 +311,12 @@ Each entry may include a Paseo-tool policy:
|
||||
Absent `paseoTools`, or absent fields within it, means Paseo tools are enabled and all tools are
|
||||
allowed. `enabled: false` disables the provider's Paseo catalog; `disabledTools` lists exact tool
|
||||
IDs to omit. The policy covers the core and browser catalog, not the voice-only `speak` tool.
|
||||
Browser tools also require `daemon.tools.groups.browser` and a connected browser host.
|
||||
Browser tools also require `daemon.browserTools.enabled` and a connected browser host.
|
||||
This policy controls the catalog presented to an agent. It is not an authorization boundary for
|
||||
agents that can access the host through a shell.
|
||||
|
||||
`daemon.tools` is the global override. When `enabled` is `false`, no provider receives Paseo or
|
||||
plugin tools; otherwise each group in `daemon.tools.groups` and then the provider policy applies.
|
||||
When `daemon.tools` is absent, the daemon reads the legacy `daemon.mcp.injectIntoAgents` and
|
||||
`daemon.browserTools.enabled` fields. Provider and global policy are resolved when a
|
||||
`daemon.mcp.injectIntoAgents` is the global override. When it is `false`, no provider receives
|
||||
Paseo tools; otherwise the provider policy applies. Provider and global policy are resolved when a
|
||||
session is created, resumed, imported, or reloaded, so configuration changes affect the next
|
||||
session rather than an already-running one.
|
||||
|
||||
|
||||
+4
-3
@@ -205,9 +205,10 @@ docker build \
|
||||
.
|
||||
```
|
||||
|
||||
The Docker workflow builds the image on `main` as a non-publishing check.
|
||||
Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and
|
||||
`ghcr.io/getpaseo/paseo:latest`. Beta tags publish only the exact prerelease tag, such as
|
||||
The Docker workflow builds the image on pull requests and on `main` as a
|
||||
non-publishing check. Stable `vX.Y.Z` tag pushes publish
|
||||
`ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`. Beta tags
|
||||
publish only the exact prerelease tag, such as
|
||||
`ghcr.io/getpaseo/paseo:0.1.102-beta.1`, and do not update `latest`.
|
||||
|
||||
To replace a Docker image in place without rebuilding desktop, APK, or EAS
|
||||
|
||||
+3
-1
@@ -72,7 +72,9 @@ 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, and `activeTurnBehavior: "queue"` waits for the running turn to end when the host advertises `server_info.features.nonAgentMessageQueue`.
|
||||
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.
|
||||
Execution completion and arrival-specific output authority remain Hub responsibilities.
|
||||
|
||||
The older `hub.execution.*` RPCs remain accepted for existing clients. Their execution ownership
|
||||
|
||||
@@ -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 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.
|
||||
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.
|
||||
|
||||
## Keys shared with text editing
|
||||
|
||||
|
||||
@@ -12,8 +12,6 @@ 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 `[](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).
|
||||
|
||||
@@ -63,8 +63,6 @@ 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
|
||||
|
||||
@@ -103,13 +103,6 @@ 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.
|
||||
|
||||
@@ -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`, `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`.
|
||||
- `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.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
+3
-4
@@ -118,9 +118,8 @@ An explicit user instruction can select another base.
|
||||
`chore(release): cut <version>` without a tag.
|
||||
5. Push the release branch (`git push -u origin HEAD`). Pushing any `release/**` branch triggers
|
||||
`CI` (all 21 jobs) and `Desktop Packages` (Linux user-namespace smoke) in their own concurrency
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` runs queue behind
|
||||
each other and a newer merge replaces the pending one.
|
||||
Wait for both runs on the release branch commit to pass before shipping.
|
||||
groups, isolated from `main` traffic. Never wait on `main` CI, because `main` cancels in-progress
|
||||
runs on every merge. Wait for both runs on the release branch commit to pass before shipping.
|
||||
Complete the [pre-release dependency checks](#pre-release-dependency-checks) on that commit.
|
||||
Pushing a `release/**` branch without a `v*` tag triggers no publish workflows.
|
||||
6. After go-ahead, push the tag first with `npm run release:push` so remote builds start right away.
|
||||
@@ -279,7 +278,7 @@ The tag push triggers `Desktop Release`, `Android APK Release`, `Docker`, `Relea
|
||||
|
||||
Confirm that `npm view @getpaseo/cli dist-tags` shows `latest` at the shipped version, and `beta` at the shipped version or an active newer beta, before considering the stable release complete.
|
||||
|
||||
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (a running check finishes, and a newer merge replaces the pending one). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
||||
The Docker workflow builds images from the checked-out source tree on `main` as non-publishing checks (cancelling superseded `main` runs). Stable `vX.Y.Z` tag pushes publish `ghcr.io/getpaseo/paseo:X.Y.Z` and `ghcr.io/getpaseo/paseo:latest`; beta `vX.Y.Z-beta.N` tag pushes publish only `ghcr.io/getpaseo/paseo:X.Y.Z-beta.N` and never move `latest`.
|
||||
|
||||
The production relay is the Elixir service in [getpaseo/paseo-relay](https://github.com/getpaseo/paseo-relay), with its own deployment process. Paseo releases and pushes to this repository do not deploy it. The Cloudflare relay code and workflow in this repository are legacy and are not used in production.
|
||||
|
||||
|
||||
+1
-1
@@ -200,7 +200,7 @@ Test suites in this repo are heavy. Running them in bulk freezes the machine, es
|
||||
|
||||
## Pull-request test routing
|
||||
|
||||
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. The CLI E2E tests are the exception: they drive a real daemon, so changes to the server or built-in plugins run them too. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
|
||||
PR checks are routed by the behavior each suite proves, using `.github/ci-paths.yml`. A package does not inherit every test suite of its runtime consumers: app changes do not run CLI or Electron-wrapper tests, and protocol changes do not run every package that imports the protocol. Cross-package static compatibility belongs to `typecheck`; full integration coverage runs after merge on main and in manual CI runs.
|
||||
|
||||
Required matrix legs are declared as statically named jobs. Their shared steps use YAML anchors, while job-level `if` conditions let GitHub report an unaffected leg as genuinely skipped without allocating a runner or losing the exact required-check name.
|
||||
|
||||
|
||||
+8
-24
@@ -330,35 +330,19 @@ that starts or accepts them. Received messages retain sender attribution, while
|
||||
notifications remain visible events. Collapse, timing and locally mounted history share
|
||||
these boundaries.
|
||||
|
||||
Agent-message markup belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
|
||||
Agent-message XML belongs to the daemon's `agent/agent-messages` boundary. Prompt delivery encodes
|
||||
provenance; acceptance, provider echoes, import, and replay share its projection. The delivery ID is
|
||||
also the projected call ID, so a provider echo cannot create a second row. Sender IDs are opaque and
|
||||
do not imply local ownership or authorization. Capture the sender title at delivery: archived or
|
||||
removed senders must remain understandable without a live directory lookup.
|
||||
|
||||
Each delivered message keeps its text first and ends with a `<paseo-message … length="N"/>` marker.
|
||||
Text at character 0 stays the sender's, so a provider still reads a slash command there, and bodies
|
||||
are never escaped. `length` bounds the text before the marker, so marker syntax inside a body cannot
|
||||
split it, and a batch splits back into rows by reading markers from the end. A person's prompt gets a
|
||||
marker only when it shares a provider turn with other deliveries or contains `<paseo-message` or
|
||||
`<paseo-system`. Transcripts written before markers open with a `<paseo-system>` envelope; the
|
||||
projection still reads those (`COMPAT(leadingPaseoSystemEnvelope)`).
|
||||
|
||||
The daemon decides whether a delivery is a message or a tool call, and clients render what it sends:
|
||||
|
||||
- A person's text is a `user_message`.
|
||||
- A peer message is an `agent_message` tool call whose `agentMessage` carries sender and text. The
|
||||
wire has no sender on `user_message`, so clients present it as a "Sent by" bubble.
|
||||
- Lifecycle notifications (`agent_finished`, `agent_errored`, `agent_needs_permission`,
|
||||
`agent_closed`), schedule fires (`heartbeat`), and change-request updates
|
||||
are plain tool calls. `plain_text` detail carries the sender in `label`, the body in `text`, and
|
||||
the icon. Clients render the heading from the tool name, so no notification event reaches them.
|
||||
|
||||
`isTimelineTurnTrigger` (`packages/protocol/src/timeline-turn.ts`) lists the delivered tool names that
|
||||
start a turn. Add a name there when the daemon projects a new delivery. Rows that older daemons stored
|
||||
with notification `agentMessage` metadata are rewritten to the plain call at presentation
|
||||
(`COMPAT(agentNotificationMetadata)`). Stream reduction and disk-cache serialization preserve the
|
||||
payload without rendering it.
|
||||
The optional `agentMessage` payload carries event, sender, and delivered text. Shared client
|
||||
presentation (`protocol/paseo-tool-presentation`) owns its heading and expanded details, next to the
|
||||
labels for every Paseo MCP tool. The daemon
|
||||
must not construct UI labels or prepend sender labels to the semantic message body. The existing
|
||||
`tool_call` / `plain_text` envelope is a compatibility adapter: older clients still parse the row and
|
||||
expand its body. New clients use the typed payload, never infer the event from a tool name or parse
|
||||
XML. Stream reduction and disk-cache serialization preserve the payload without rendering it.
|
||||
|
||||
The compatibility boundary for older daemons is snapshot normalization: running/idle status becomes an
|
||||
anonymous active turn or idle state once, and downstream code consumes the same activity shape. The app
|
||||
|
||||
@@ -47,14 +47,8 @@
|
||||
"ignore": ["android/**", "ios/**", ".expo/**", "dist/**", "scripts/reset-project.js"]
|
||||
},
|
||||
"packages/cli": {
|
||||
"entry": [
|
||||
"src/index.ts",
|
||||
"bin/paseo",
|
||||
"scripts/**/*.mjs",
|
||||
"src/**/*.test.{ts,tsx}",
|
||||
"tests/**/*.{ts,tsx}"
|
||||
],
|
||||
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.mjs", "tests/**/*.{ts,tsx}"]
|
||||
"entry": ["src/index.ts", "bin/paseo", "src/**/*.test.{ts,tsx}", "tests/**/*.{ts,tsx}"],
|
||||
"project": ["src/**/*.{ts,tsx}", "tests/**/*.{ts,tsx}"]
|
||||
},
|
||||
"packages/relay": {
|
||||
"entry": ["src/index.ts", "src/e2ee.ts", "src/cloudflare-adapter.ts", "src/**/*.test.ts"],
|
||||
@@ -73,6 +67,17 @@
|
||||
"entry": ["src/index.ts", "src/**/*.test.ts"],
|
||||
"project": ["src/**/*.ts"]
|
||||
},
|
||||
"packages/workflows": {
|
||||
"entry": [
|
||||
"src/index.ts",
|
||||
"src/ir.ts",
|
||||
"src/dsl.ts",
|
||||
"src/yaml.ts",
|
||||
"src/testing.ts",
|
||||
"test/**/*.test.ts"
|
||||
],
|
||||
"project": ["src/**/*.ts", "test/**/*.ts"]
|
||||
},
|
||||
"packages/expo-two-way-audio": {
|
||||
"entry": ["src/index.ts"],
|
||||
"project": ["src/**/*.ts"]
|
||||
|
||||
Generated
+20
-3
@@ -16,6 +16,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -6709,6 +6710,10 @@
|
||||
"resolved": "packages/website",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@getpaseo/workflows": {
|
||||
"resolved": "packages/workflows",
|
||||
"link": true
|
||||
},
|
||||
"node_modules/@gorhom/bottom-sheet": {
|
||||
"version": "5.2.14",
|
||||
"resolved": "https://registry.npmjs.org/@gorhom/bottom-sheet/-/bottom-sheet-5.2.14.tgz",
|
||||
@@ -14924,7 +14929,6 @@
|
||||
"version": "8.11.0",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.11.0.tgz",
|
||||
"integrity": "sha512-wGgprdCvMalC0BztXvitD2hC04YffAvtsUn93JbGXYLAtCUO4xd17mCCZQxUOItiBwZvJScWo8NIvQMQ71rdpg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fast-deep-equal": "^3.1.1",
|
||||
@@ -31398,7 +31402,6 @@
|
||||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
@@ -36228,7 +36231,6 @@
|
||||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz",
|
||||
"integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==",
|
||||
"dev": true,
|
||||
"license": "BSD-2-Clause",
|
||||
"dependencies": {
|
||||
"punycode": "^2.1.0"
|
||||
@@ -43159,6 +43161,21 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"packages/workflows": {
|
||||
"name": "@getpaseo/workflows",
|
||||
"version": "0.1.0",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"ajv": "^8.11.0",
|
||||
"js-yaml": "^4.1.1",
|
||||
"zod": "^4.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.9.0",
|
||||
"typescript": "^5.9.3",
|
||||
"vitest": "^4.1.6"
|
||||
}
|
||||
},
|
||||
"plugins": {
|
||||
"name": "@getpaseo/builtin-plugins",
|
||||
"version": "0.18.1",
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -60,6 +61,8 @@
|
||||
"build:relay:clean": "npm run build:clean --workspace=@getpaseo/relay",
|
||||
"build:protocol": "npm run build --workspace=@getpaseo/protocol",
|
||||
"build:protocol:clean": "npm run build:clean --workspace=@getpaseo/protocol",
|
||||
"build:workflows": "npm run build --workspace=@getpaseo/workflows",
|
||||
"build:workflows:clean": "npm run build:clean --workspace=@getpaseo/workflows",
|
||||
"build:client": "npm run build --workspace=@getpaseo/client",
|
||||
"build:client:clean": "npm run build:protocol:clean && npm run build:clean --workspace=@getpaseo/client",
|
||||
"build:server-deps": "npm run build:client && concurrently --kill-others-on-fail --names highlight,plugin,relay --prefix-colors yellow,green,blue \"npm run build:highlight\" \"npm run build:plugin\" \"npm run build:relay\"",
|
||||
|
||||
@@ -2,7 +2,6 @@ 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");
|
||||
@@ -149,7 +148,6 @@ export default {
|
||||
withPasteInput,
|
||||
withAndroidScroll,
|
||||
withAndroidDisplayMetrics,
|
||||
withAndroidIgnoreBoldText,
|
||||
[withAndroidAsyncStorageSize, 64],
|
||||
...buildProfile.cameraPlugins,
|
||||
withAndroidOptionalCamera,
|
||||
|
||||
@@ -112,92 +112,3 @@ describe("hardware keyboard scene integration", () => {
|
||||
expect(configureHardwareKeyboardAppDelegate(configured)).toBe(configured);
|
||||
});
|
||||
});
|
||||
|
||||
// Android Bold text bolds unstyled text at draw time after React Native measured it
|
||||
// unbolded, which clips trailing words (#4057, #10152, #10850). The activity must opt out
|
||||
// with a sparse Configuration() so other configuration fields still update live.
|
||||
describe("Android Bold text opt-out", () => {
|
||||
const {
|
||||
configureIgnoreBoldTextMainActivity,
|
||||
} = require("./plugins/with-android-ignore-bold-text.js");
|
||||
const {
|
||||
configureDisplayMetricsActivity,
|
||||
} = require("./modules/paseo-display-metrics/app.plugin.js");
|
||||
const mainActivity = [
|
||||
"package sh.paseo",
|
||||
"import expo.modules.splashscreen.SplashScreenManager",
|
||||
"",
|
||||
"import android.os.Build",
|
||||
"import android.os.Bundle",
|
||||
"",
|
||||
"import com.facebook.react.ReactActivity",
|
||||
"",
|
||||
"class MainActivity : ReactActivity() {",
|
||||
" override fun onCreate(savedInstanceState: Bundle?) {",
|
||||
" super.onCreate(null)",
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
it("zeroes fontWeightAdjustment on a sparse Configuration before attaching and is idempotent", () => {
|
||||
const configured = configureIgnoreBoldTextMainActivity(mainActivity);
|
||||
expect(configured).toMatch(/^import android\.content\.Context$/m);
|
||||
expect(configured).toMatch(/^import android\.content\.res\.Configuration$/m);
|
||||
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
|
||||
expect(configured).toContain("val override = Configuration()");
|
||||
expect(configured).not.toContain("Configuration(configuration)");
|
||||
expect(configured).toContain("override.fontWeightAdjustment = 0");
|
||||
expect(configured).toContain(
|
||||
"super.attachBaseContext(newBase.createConfigurationContext(override))",
|
||||
);
|
||||
expect(configured.indexOf("attachBaseContext")).toBeLessThan(configured.indexOf("onCreate"));
|
||||
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
|
||||
});
|
||||
|
||||
it("composes cleanly with withAndroidDisplayMetrics in both plugin orders", () => {
|
||||
const displayFirst = configureIgnoreBoldTextMainActivity(
|
||||
configureDisplayMetricsActivity(mainActivity),
|
||||
);
|
||||
const boldFirst = configureDisplayMetricsActivity(
|
||||
configureIgnoreBoldTextMainActivity(mainActivity),
|
||||
);
|
||||
|
||||
for (const configured of [displayFirst, boldFirst]) {
|
||||
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
|
||||
expect(configured).toContain("val override = Configuration()");
|
||||
expect(configured).toContain("override.fontWeightAdjustment = 0");
|
||||
expect(configured).toContain("override fun onContentChanged()");
|
||||
expect(configured).toContain(
|
||||
"override fun onConfigurationChanged(newConfig: android.content.res.Configuration)",
|
||||
);
|
||||
expect(configured).toContain(
|
||||
"sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)",
|
||||
);
|
||||
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
|
||||
expect(configureDisplayMetricsActivity(configured)).toBe(configured);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails the prebuild when the MainActivity template changes shape", () => {
|
||||
expect(() => configureIgnoreBoldTextMainActivity("package sh.paseo\n")).toThrow(
|
||||
/MainActivity class declaration/,
|
||||
);
|
||||
});
|
||||
|
||||
it("fails the prebuild rather than duplicate an existing attachBaseContext override", () => {
|
||||
const withExistingOverride = mainActivity.replace(
|
||||
"override fun onCreate",
|
||||
"override fun attachBaseContext(newBase: Context) { super.attachBaseContext(newBase) }\n\n override fun onCreate",
|
||||
);
|
||||
expect(() => configureIgnoreBoldTextMainActivity(withExistingOverride)).toThrow(
|
||||
/existing attachBaseContext override/,
|
||||
);
|
||||
});
|
||||
|
||||
it("is registered in the app config", async () => {
|
||||
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
|
||||
// Expo records function plugins by name.
|
||||
expect(exp.plugins).toContain("withAndroidIgnoreBoldText");
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
@@ -6,15 +6,16 @@ import {
|
||||
expectComposerDoesNotName,
|
||||
expectAgentProfilesEmptyPrompt,
|
||||
expectHostAgentProfiles,
|
||||
expectProfileEditTooltip,
|
||||
expectComposerMode,
|
||||
expectCreateProfileFromModelRow,
|
||||
expectComposerModel,
|
||||
expectModelRowProfileActionBesideRow,
|
||||
expectModelRowSelected,
|
||||
expectProfileEditIsPencilOnly,
|
||||
expectProfileReachableByScrolling,
|
||||
expectProfileSearchResult,
|
||||
expectPickerProfile,
|
||||
expectProfilesEditLink,
|
||||
expectProfileVisibleForProvider,
|
||||
fillAgentProfileName,
|
||||
openEditProfileFromModelRow,
|
||||
openModelPicker,
|
||||
@@ -85,19 +86,17 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await expectComposerMode(page, "Load test");
|
||||
});
|
||||
|
||||
await test.step("the picker opens on the agent's provider with Profiles beside it", async () => {
|
||||
await test.step("the sole provider opens directly", async () => {
|
||||
await openModelPicker(page);
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeFocused();
|
||||
await expect(page.getByTestId("model-provider-mock")).toHaveAttribute(
|
||||
"data-active",
|
||||
"true",
|
||||
);
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "ten-second-stream" });
|
||||
await expectPickerProfile(page, {
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
|
||||
await expect(page.getByTestId("sheet-header-back")).toHaveCount(0);
|
||||
await expect(page.locator('[data-testid^="model-provider-"]')).toHaveCount(0);
|
||||
await expectProfileVisibleForProvider(page, {
|
||||
name: PROFILE.name,
|
||||
summary: PROFILE_SUMMARY,
|
||||
});
|
||||
await expectProfilesEditLink(page);
|
||||
await expectProfileEditIsPencilOnly(page);
|
||||
await expectProfileEditTooltip(page);
|
||||
});
|
||||
|
||||
await test.step("applying it writes its model and mode into the composer", async () => {
|
||||
@@ -116,13 +115,14 @@ test.describe("Agent profiles in the model picker", () => {
|
||||
await expectComposerDoesNotName(page, PROFILE.name);
|
||||
});
|
||||
|
||||
await test.step("reopening returns to the provider models with the new model checked", async () => {
|
||||
await test.step("reopening returns directly to the provider models", async () => {
|
||||
await openModelPicker(page);
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await expectPickerProfile(page, {
|
||||
await expect(page.getByTestId("model-search-input").first()).toBeVisible();
|
||||
await expectProfileVisibleForProvider(page, {
|
||||
name: PROFILE.name,
|
||||
summary: PROFILE_SUMMARY,
|
||||
});
|
||||
await expectModelRowSelected(page, { provider: "mock", modelId: "one-minute-stream" });
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
} finally {
|
||||
|
||||
@@ -1,559 +0,0 @@
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import {
|
||||
beginTextReveal,
|
||||
retargetTextReveal,
|
||||
visibleRevealedText,
|
||||
} from "../../src/agent-stream/text-reveal";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { scrollChatAwayFromBottom } from "../support/helpers/agent-bottom-anchor";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
test.use({
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
providers: Object.fromEntries(
|
||||
[
|
||||
"claude",
|
||||
"codex",
|
||||
"copilot",
|
||||
"opencode",
|
||||
"pi",
|
||||
"omp",
|
||||
"antigravity",
|
||||
"hoplite",
|
||||
"muse",
|
||||
].map((id) => [id, { enabled: false }]),
|
||||
),
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
interface ClosingFenceFrameSample {
|
||||
text: string;
|
||||
codeBlockHeights: number[];
|
||||
codeBlockTexts: string[];
|
||||
messageHeights: number[];
|
||||
partialFenceLines: string[];
|
||||
}
|
||||
|
||||
interface ClosingFenceFrameReport {
|
||||
finished: boolean;
|
||||
samples: ClosingFenceFrameSample[];
|
||||
}
|
||||
|
||||
async function sampleClosingFenceFrames(page: Page): Promise<ClosingFenceFrameReport> {
|
||||
return await page.evaluate(async () => {
|
||||
const samples: ClosingFenceFrameSample[] = [];
|
||||
let finished = false;
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
const tick = () => {
|
||||
const messages = Array.from(
|
||||
document.querySelectorAll<HTMLElement>('[data-testid="assistant-message"]'),
|
||||
);
|
||||
const text = messages.map((message) => message.textContent ?? "").join("");
|
||||
const sample: ClosingFenceFrameSample = {
|
||||
text,
|
||||
codeBlockHeights: [],
|
||||
codeBlockTexts: [],
|
||||
messageHeights: messages.map((message) =>
|
||||
Math.round(message.getBoundingClientRect().height),
|
||||
),
|
||||
partialFenceLines: [],
|
||||
};
|
||||
|
||||
for (const message of messages) {
|
||||
for (const block of message.querySelectorAll<HTMLElement>(
|
||||
'pre, [data-paseo-markdown-tag="pre"]',
|
||||
)) {
|
||||
const code = block.querySelector<HTMLElement>('code, [data-paseo-markdown-tag="code"]');
|
||||
const codeText = code?.textContent ?? block.textContent ?? "";
|
||||
sample.codeBlockTexts.push(codeText.trimEnd());
|
||||
// Opening fence prefixes render as prose; closing artifacts live inside code blocks.
|
||||
for (const line of codeText.split(/\r?\n/)) {
|
||||
if (/^\s*`{1,2}\s*$/.test(line)) sample.partialFenceLines.push(line);
|
||||
}
|
||||
sample.codeBlockHeights.push(Math.round(block.getBoundingClientRect().height));
|
||||
}
|
||||
}
|
||||
|
||||
samples.push(sample);
|
||||
|
||||
finished = text.includes("Both blocks are closed.");
|
||||
if (finished) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
});
|
||||
|
||||
return { finished, samples };
|
||||
});
|
||||
}
|
||||
|
||||
const FIRST_PAUSE_TEXT = "Here is the first snippet:const answer = 42;\nconsole.log(answer);";
|
||||
const SECOND_PAUSE_TEXT = `${FIRST_PAUSE_TEXT}And a second one:echo done`;
|
||||
|
||||
for (const { label, html } of [
|
||||
{ label: "semantic", html: "<pre><code>const answer = 42;\n`\n``</code></pre>" },
|
||||
{
|
||||
label: "annotated",
|
||||
html: '<div data-paseo-markdown-tag="pre"><span data-paseo-markdown-tag="code">const answer = 42;\n`\n``</span><button>Copy</button></div>',
|
||||
},
|
||||
{
|
||||
label: "annotated semantic",
|
||||
html: '<pre data-paseo-markdown-tag="pre"><code data-paseo-markdown-tag="code">const answer = 42;\n`\n``</code></pre>',
|
||||
},
|
||||
]) {
|
||||
test(`samples ${label} code block DOM without duplicate blocks or controls`, async ({ page }) => {
|
||||
await page.setContent(
|
||||
`<div data-testid="assistant-message">${html}<p>Both blocks are closed.</p></div>`,
|
||||
);
|
||||
const report = await sampleClosingFenceFrames(page);
|
||||
const sample = report.samples.at(-1)!;
|
||||
expect(report.finished).toBe(true);
|
||||
expect(sample.codeBlockTexts).toEqual(["const answer = 42;\n`\n``"]);
|
||||
expect(sample.partialFenceLines).toEqual(["`", "``"]);
|
||||
expect(sample.codeBlockHeights).toHaveLength(1);
|
||||
expect(sample.codeBlockHeights[0]).toBeGreaterThan(0);
|
||||
});
|
||||
}
|
||||
|
||||
function closingFencePauseSamples(
|
||||
samples: readonly ClosingFenceFrameSample[],
|
||||
pauseText: string,
|
||||
): ClosingFenceFrameSample[] {
|
||||
return samples.filter((sample) => sample.text === pauseText);
|
||||
}
|
||||
|
||||
function expectStableGeometry(
|
||||
samples: readonly ClosingFenceFrameSample[],
|
||||
expectedCodeBlockTexts: readonly string[],
|
||||
): void {
|
||||
expect(samples.length, "the paused text state should be sampled").toBeGreaterThan(0);
|
||||
expect(
|
||||
samples.every(
|
||||
(sample) => JSON.stringify(sample.codeBlockTexts) === JSON.stringify(expectedCodeBlockTexts),
|
||||
),
|
||||
"the sampled code should contain only the authored lines",
|
||||
).toBe(true);
|
||||
const geometries = new Set(
|
||||
samples.map((sample) => JSON.stringify([sample.messageHeights, sample.codeBlockHeights])),
|
||||
);
|
||||
expect(
|
||||
geometries.size,
|
||||
"message and code block geometry should stay fixed during the pause",
|
||||
).toBe(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* A closing fence that is still being typed must not be painted as code.
|
||||
*
|
||||
* The mock reply closes each code block in two arrivals: one backtick, a pause,
|
||||
* then the other two. Painted, that first backtick is a line of code that
|
||||
* vanishes when the fence completes, so the block grows and shrinks and every
|
||||
* row below it moves twice. Each pause is sampled and its text geometry checked.
|
||||
*/
|
||||
test("does not paint a closing fence while it is still being typed", async ({ page }, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "closing-fence-",
|
||||
title: "Closing fence",
|
||||
model: "e2e-fast-stream",
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const reportPromise = sampleClosingFenceFrames(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream a code block with a split closing fence.",
|
||||
);
|
||||
const report = await reportPromise;
|
||||
|
||||
await testInfo.attach("closing-fence-frames", {
|
||||
body: JSON.stringify(report, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(report.finished, "the reply should finish streaming").toBe(true);
|
||||
expect(
|
||||
report.samples.flatMap((sample) => sample.partialFenceLines),
|
||||
"no frame, including transitions outside the pause windows, may show a partial fence inside code",
|
||||
).toEqual([]);
|
||||
const firstPauseSamples = closingFencePauseSamples(report.samples, FIRST_PAUSE_TEXT);
|
||||
const secondPauseSamples = closingFencePauseSamples(report.samples, SECOND_PAUSE_TEXT);
|
||||
expectStableGeometry(firstPauseSamples, ["const answer = 42;\nconsole.log(answer);"]);
|
||||
expectStableGeometry(secondPauseSamples, [
|
||||
"const answer = 42;\nconsole.log(answer);",
|
||||
"echo done",
|
||||
]);
|
||||
expect(secondPauseSamples[0]?.codeBlockHeights[0]).toBe(
|
||||
firstPauseSamples[0]?.codeBlockHeights[0],
|
||||
);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("excludes each revealed character of the next paragraph from both pauses", () => {
|
||||
for (const [pauseText, paragraph] of [
|
||||
[FIRST_PAUSE_TEXT, "And a second one:"],
|
||||
[SECOND_PAUSE_TEXT, "Both blocks are closed."],
|
||||
]) {
|
||||
const state = retargetTextReveal(beginTextReveal(pauseText), pauseText + paragraph);
|
||||
const samples = Array.from({ length: paragraph.length + 1 }, (_, index) => ({
|
||||
text: visibleRevealedText({ ...state, revealed: pauseText.length + index }),
|
||||
codeBlockHeights: [],
|
||||
codeBlockTexts: [],
|
||||
messageHeights: [index],
|
||||
partialFenceLines: [],
|
||||
}));
|
||||
expect(closingFencePauseSamples(samples, pauseText)).toEqual([samples[0]]);
|
||||
}
|
||||
});
|
||||
|
||||
for (const { label, markdown, expectedCode, expectedPartialFenceLines } of [
|
||||
{
|
||||
label: "opening prefixes in prose",
|
||||
markdown: "And a second one:\n\n`\n\n``\n\nBoth blocks are closed.",
|
||||
expectedCode: [],
|
||||
expectedPartialFenceLines: [],
|
||||
},
|
||||
{
|
||||
label: "partial fences inside rendered code",
|
||||
markdown: "```ts\nconst answer = 42;\n`\n``\n```\n\nBoth blocks are closed.",
|
||||
expectedCode: ["const answer = 42;\n`\n``"],
|
||||
expectedPartialFenceLines: ["`", "``"],
|
||||
},
|
||||
]) {
|
||||
test(`samples ${label} in the correct container`, async ({ page }, testInfo) => {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "fence-sample-container-",
|
||||
title: "Fence sample container",
|
||||
featureValues: { mockAssistantResponse: markdown },
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const reportPromise = sampleClosingFenceFrames(page);
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Show the fence sampling fixture.");
|
||||
const report = await reportPromise;
|
||||
await testInfo.attach("fence-container-frames", {
|
||||
body: JSON.stringify(report, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(report.finished).toBe(true);
|
||||
const messageText = await page.getByTestId("assistant-message").innerText();
|
||||
const messageLines = messageText.split(/\r?\n/);
|
||||
const messageFenceLines = messageLines.filter((line) => /^\s*`{1,2}\s*$/.test(line));
|
||||
expect(messageFenceLines).toEqual(["`", "``"]);
|
||||
const finalSample = report.samples.at(-1);
|
||||
expect(finalSample?.codeBlockTexts).toEqual(expectedCode);
|
||||
expect(finalSample?.partialFenceLines).toEqual(expectedPartialFenceLines);
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test("shows the complete reasoning after a streamed turn finishes", async ({ page }, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ toolCallDetailLevel: "detailed", autoExpandReasoning: true }),
|
||||
);
|
||||
});
|
||||
const reasoning =
|
||||
"Need to find the scroll container, the layout effect that watches for new messages, and any gesture handler that might fight with programmatic scrolling. Probably a ref on the FlatList plus a near-bottom threshold.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "finished-reasoning-",
|
||||
title: "Finished reasoning",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const historyClient = await connectDaemonClient<
|
||||
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
|
||||
>({ clientIdPrefix: "finished-reasoning-history" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream briefly to check finished reasoning.",
|
||||
);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
|
||||
const thoughts = history.entries
|
||||
.map((entry) => entry.item)
|
||||
.filter((item) => item.type === "reasoning");
|
||||
await testInfo.attach("canonical-reasoning", {
|
||||
body: JSON.stringify(thoughts, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
expect(thoughts[0]?.text).toBe(reasoning);
|
||||
const expectedCounts = new Map<string, number>();
|
||||
for (const thought of thoughts)
|
||||
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
|
||||
const rendered = page.getByText(reasoning, { exact: true });
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await expect(rendered.first()).toBeVisible();
|
||||
await testInfo.attach("finished-reasoning", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
await page.reload();
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await expect(rendered.first()).toBeVisible();
|
||||
} catch (error) {
|
||||
await testInfo.attach("reasoning-before-cleanup", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await historyClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("records equal-input long-reply rendering metrics", async ({ page }, testInfo) => {
|
||||
test.setTimeout(120_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
const markdown =
|
||||
Array.from({ length: 15 }, (_, index) =>
|
||||
[
|
||||
"### Block " + index,
|
||||
"",
|
||||
"\x60\x60\x60ts",
|
||||
...Array.from(
|
||||
{ length: 12 },
|
||||
(_value, line) => "const value_" + index + "_" + line + " = " + (index * 12 + line) + ";",
|
||||
),
|
||||
"\x60\x60\x60",
|
||||
"",
|
||||
].join("\n"),
|
||||
).join("\n") + "\nEqual-input stream complete.";
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "equal-input-long-reply-",
|
||||
title: "Equal-input long reply",
|
||||
featureValues: {
|
||||
mockStreamingAssistantResponse: markdown,
|
||||
mockStreamingAssistantIntervalMs: 5,
|
||||
},
|
||||
});
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
const session = await page.context().newCDPSession(page);
|
||||
await session.send("Performance.enable");
|
||||
const before = await session.send("Performance.getMetrics");
|
||||
const sampler = await page.evaluateHandle(() => {
|
||||
const state = {
|
||||
frames: [] as number[],
|
||||
longTasks: [] as number[],
|
||||
running: true,
|
||||
last: performance.now(),
|
||||
};
|
||||
const observer = new PerformanceObserver((list) => {
|
||||
state.longTasks.push(...list.getEntries().map((entry) => entry.duration));
|
||||
});
|
||||
observer.observe({ type: "longtask", buffered: false });
|
||||
const tick = (now: number) => {
|
||||
state.frames.push(now - state.last);
|
||||
state.last = now;
|
||||
if (state.running) requestAnimationFrame(tick);
|
||||
};
|
||||
requestAnimationFrame(tick);
|
||||
return { state, observer };
|
||||
});
|
||||
await agent.client.sendAgentMessage(agent.agentId, "Render the fixed fifteen-block fixture.");
|
||||
await agent.client.waitForFinish(agent.agentId, 60_000);
|
||||
const message = page.getByTestId("assistant-message").last();
|
||||
await expect(message).toContainText("Equal-input stream complete.", { timeout: 30_000 });
|
||||
const blocks = message.locator('pre, [data-paseo-markdown-tag="pre"]');
|
||||
await expect(blocks).toHaveCount(15);
|
||||
for (let index = 0; index < 15; index++) {
|
||||
await expect(blocks.nth(index)).toContainText(
|
||||
"const value_" + index + "_11 = " + (index * 12 + 11) + ";",
|
||||
);
|
||||
}
|
||||
const samples = await sampler.evaluate(({ state, observer }) => {
|
||||
state.running = false;
|
||||
state.longTasks.push(...observer.takeRecords().map((entry) => entry.duration));
|
||||
observer.disconnect();
|
||||
return state;
|
||||
});
|
||||
const after = await session.send("Performance.getMetrics");
|
||||
const frames = [...samples.frames].sort((a, b) => a - b);
|
||||
await testInfo.attach("equal-input-rendering", {
|
||||
body: JSON.stringify(
|
||||
{
|
||||
markdown,
|
||||
viewport: page.viewportSize(),
|
||||
intervalMs: 5,
|
||||
frameCount: frames.length,
|
||||
frameP95Ms: frames[Math.floor(frames.length * 0.95)],
|
||||
maxFrameMs: frames.at(-1),
|
||||
longTasksMs: samples.longTasks,
|
||||
before: before.metrics,
|
||||
after: after.metrics,
|
||||
},
|
||||
null,
|
||||
2,
|
||||
),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await sampler.dispose();
|
||||
await session.detach();
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("manually expands complete reasoning after leaving output following", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
test.setTimeout(90_000);
|
||||
await page.setViewportSize({ width: 1280, height: 900 });
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"@paseo:app-settings",
|
||||
JSON.stringify({ chatDisplay: "full", autoExpandReasoning: false }),
|
||||
);
|
||||
});
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "manual-finished-reasoning-",
|
||||
title: "Manual finished reasoning",
|
||||
model: "ten-second-stream",
|
||||
});
|
||||
const historyClient = await connectDaemonClient<
|
||||
Pick<DaemonClient, "connect" | "close" | "fetchAgentTimeline">
|
||||
>({ clientIdPrefix: "manual-finished-reasoning-history" });
|
||||
try {
|
||||
await openAgentRoute(page, agent);
|
||||
await expectComposerVisible(page);
|
||||
await agent.client.sendAgentMessage(
|
||||
agent.agentId,
|
||||
"Stream briefly to check finished reasoning.",
|
||||
);
|
||||
const finished = await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
expect(finished.status).toBe("idle");
|
||||
await testInfo.attach("manual-completed-turn", {
|
||||
body: JSON.stringify(finished),
|
||||
contentType: "application/json",
|
||||
});
|
||||
const history = await historyClient.fetchAgentTimeline(agent.agentId, { limit: 500 });
|
||||
const thoughts = history.entries
|
||||
.map((entry) => entry.item)
|
||||
.filter((item) => item.type === "reasoning");
|
||||
expect(thoughts.length).toBeGreaterThan(0);
|
||||
expect(thoughts.every((thought) => thought.text.length > 0)).toBe(true);
|
||||
const expectedCounts = new Map<string, number>();
|
||||
for (const thought of thoughts)
|
||||
expectedCounts.set(thought.text, (expectedCounts.get(thought.text) ?? 0) + 1);
|
||||
await testInfo.attach("manual-canonical-reasoning", {
|
||||
body: JSON.stringify(thoughts, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
const pointerCapture = await page.evaluateHandle(() => {
|
||||
const events: {
|
||||
type: string;
|
||||
timestamp: number;
|
||||
tag: string;
|
||||
label: string;
|
||||
scrollTop: number | null;
|
||||
}[] = [];
|
||||
const observe = (event: Event) => {
|
||||
const target = event.target;
|
||||
if (!(target instanceof HTMLElement)) return;
|
||||
const scroll = document.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
|
||||
events.push({
|
||||
type: event.type,
|
||||
timestamp: event.timeStamp,
|
||||
tag: target.tagName,
|
||||
label: target.textContent?.slice(0, 80) ?? "",
|
||||
scrollTop: scroll?.scrollTop ?? null,
|
||||
});
|
||||
};
|
||||
for (const type of ["pointerdown", "pointerup", "wheel"])
|
||||
document.addEventListener(type, observe, true);
|
||||
return {
|
||||
events,
|
||||
stop: () => {
|
||||
for (const type of ["pointerdown", "pointerup", "wheel"])
|
||||
document.removeEventListener(type, observe, true);
|
||||
},
|
||||
};
|
||||
});
|
||||
const badges = page.getByTestId("tool-call-badge").filter({ hasText: "Thinking" });
|
||||
await expect(badges).toHaveCount(thoughts.length);
|
||||
// Locator scrolling alone leaves output-following armed, so pointer-down can
|
||||
// snap the feed to its tail before pointer-up reaches the Thinking control.
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
|
||||
for (let index = 0; index < thoughts.length; index++) {
|
||||
await badges
|
||||
.nth(index)
|
||||
.getByRole("button", { name: "Thinking", exact: true })
|
||||
.first()
|
||||
.click();
|
||||
await expect(
|
||||
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
const first = badges.first();
|
||||
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
|
||||
await expect(first.getByText(thoughts[0].text, { exact: true })).not.toBeVisible();
|
||||
await first.getByRole("button", { name: "Thinking", exact: true }).first().click();
|
||||
await expect(first.getByText(thoughts[0].text, { exact: true })).toBeVisible();
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
await testInfo.attach("manual-expanded-reasoning", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
const pointerEvents = await pointerCapture.evaluate(({ events, stop }) => {
|
||||
stop();
|
||||
return events;
|
||||
});
|
||||
await pointerCapture.dispose();
|
||||
await testInfo.attach("manual-pointer-events", {
|
||||
body: JSON.stringify(pointerEvents, null, 2),
|
||||
contentType: "application/json",
|
||||
});
|
||||
await page.reload();
|
||||
await expect(badges).toHaveCount(thoughts.length);
|
||||
await scrollChatAwayFromBottom(page, { deltaY: -600, minDistanceFromBottom: 100 });
|
||||
for (let index = 0; index < thoughts.length; index++) {
|
||||
await badges
|
||||
.nth(index)
|
||||
.getByRole("button", { name: "Thinking", exact: true })
|
||||
.first()
|
||||
.click();
|
||||
await expect(
|
||||
badges.nth(index).getByText(thoughts[index].text, { exact: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
for (const [text, count] of expectedCounts)
|
||||
await expect(page.getByText(text, { exact: true })).toHaveCount(count);
|
||||
} catch (error) {
|
||||
await testInfo.attach("manual-before-cleanup", {
|
||||
body: await page.screenshot(),
|
||||
contentType: "image/png",
|
||||
});
|
||||
throw error;
|
||||
} finally {
|
||||
await historyClient.close();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -84,14 +84,17 @@ async function openModelSelector(page: Page) {
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function openModelPage(page: Page) {
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
await expect(page.getByTestId("mobile-model-page")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function returnHomeWithBack(page: Page) {
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
async function dismissStackedModelPickerWithBackdrop(page: Page) {
|
||||
await page
|
||||
.getByTestId("agent-controls-settings-list")
|
||||
.getByRole("button", { name: /Select model/ })
|
||||
.click();
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeInViewport();
|
||||
await page.mouse.click(MOBILE_VIEWPORT.width / 2, 24);
|
||||
// In CI, Gorhom retains the dismissed sheet below the viewport.
|
||||
// Dismissal is complete when it leaves the displayed surface.
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
}
|
||||
|
||||
@@ -110,7 +113,7 @@ async function openAndCloseModelSelectorTwice(page: Page) {
|
||||
}
|
||||
|
||||
test.describe("mobile bottom sheet reopen", () => {
|
||||
test("sheets reopen and a model pick returns to Home", async ({ page }) => {
|
||||
test("sheets reopen and model search returns to configuration", async ({ page }) => {
|
||||
const session = await openMockAgentAtMobileBreakpoint(page);
|
||||
try {
|
||||
await test.step("tab switcher opens, closes, and reopens", async () => {
|
||||
@@ -121,28 +124,24 @@ test.describe("mobile bottom sheet reopen", () => {
|
||||
await openAndCloseModelSelectorTwice(page);
|
||||
});
|
||||
|
||||
await test.step("the Model page swaps in place and Back returns to Home", async () => {
|
||||
await test.step("model search returns to configuration", async () => {
|
||||
await openModelSelector(page);
|
||||
const sheet = page.getByTestId("agent-controls-model-sheet");
|
||||
await openModelPage(page);
|
||||
await returnHomeWithBack(page);
|
||||
await expect(sheet).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("a model found by search returns to Home with that model", async () => {
|
||||
await openModelPage(page);
|
||||
const search = page.getByTestId("model-search-all-input");
|
||||
await expect(search).not.toBeFocused();
|
||||
await search.click();
|
||||
await search.fill("Ten second");
|
||||
await dismissStackedModelPickerWithBackdrop(page);
|
||||
|
||||
await page.getByTestId("model-search-all-input").click();
|
||||
const model = page.getByRole("button", { name: /^Ten second stream/ });
|
||||
await expect(model).toBeVisible({ timeout: 10_000 });
|
||||
await expect(model).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
|
||||
await model.click();
|
||||
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).toBeVisible();
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
await expect(page.getByTestId("agent-controls-model")).toContainText("Ten second stream");
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeInViewport();
|
||||
});
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
|
||||
@@ -1042,7 +1042,7 @@ test("changes context menu recursively collapses descendant folders", async ({ p
|
||||
nestedLabel.boundingBox(),
|
||||
]);
|
||||
if (!rootBounds || !nestedBounds) throw new Error("Changes tree rows have no bounds");
|
||||
expect(nestedBounds.x - rootBounds.x).toBe(16);
|
||||
expect(nestedBounds.x - rootBounds.x).toBe(12);
|
||||
|
||||
await tree.getByTestId("diff-folder-src-toggle").click({ button: "right" });
|
||||
await page.getByTestId("diff-folder-src-collapse-folder").click();
|
||||
|
||||
@@ -30,14 +30,7 @@ test.use({
|
||||
const ACTIVE_SPEED_COLOR = "rgb(251, 191, 36)";
|
||||
const NORMAL_SPEED_COLOR = "rgb(113, 113, 122)";
|
||||
|
||||
const COMPACT_SPEED_CONTROL = "agent-feature-service_tier";
|
||||
const COMPACT_SPEED_SECTION = `${COMPACT_SPEED_CONTROL}-section`;
|
||||
|
||||
async function openSpeedSelector(page: Page): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
return;
|
||||
}
|
||||
const speed = page.getByRole("button", { name: /^(Select speed|Speed: .+)$/ });
|
||||
const features = page.getByRole("button", { name: "Open agent features", exact: true });
|
||||
const modelSettings = page.getByRole("button", { name: /^Select model \(/ });
|
||||
@@ -46,12 +39,7 @@ async function openSpeedSelector(page: Page): Promise<void> {
|
||||
});
|
||||
if (!(await speed.isVisible())) {
|
||||
if (await features.isVisible()) await features.click();
|
||||
else {
|
||||
await modelSettings.click();
|
||||
await expect(compactSection).toBeVisible({ timeout: 30_000 });
|
||||
await expect(compactSection.getByText("Normal", { exact: true })).toBeVisible();
|
||||
return;
|
||||
}
|
||||
else await modelSettings.click();
|
||||
}
|
||||
await expect(speed).toBeVisible({ timeout: 30_000 });
|
||||
await speed.click();
|
||||
@@ -59,13 +47,6 @@ async function openSpeedSelector(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
const pill = compactSection.getByRole("button", { name: label, exact: true });
|
||||
await pill.click();
|
||||
await expect(pill).toHaveAttribute("aria-selected", "true");
|
||||
return;
|
||||
}
|
||||
await page.getByRole("button", { name: label, exact: true }).last().click();
|
||||
const toolbarTrigger = page.getByRole("button", { name: `Speed: ${label}`, exact: true });
|
||||
const sheetTrigger = page.getByRole("button", { name: "Select speed", exact: true });
|
||||
@@ -75,11 +56,6 @@ async function selectSpeed(page: Page, label: string): Promise<void> {
|
||||
}
|
||||
|
||||
async function expectSpeedIconColor(page: Page, color: string): Promise<void> {
|
||||
const compactSection = page.getByTestId(COMPACT_SPEED_SECTION);
|
||||
if (await compactSection.isVisible().catch(() => false)) {
|
||||
await expect(compactSection.locator("svg").first()).toHaveCSS("stroke", color);
|
||||
return;
|
||||
}
|
||||
const trigger = page
|
||||
.getByRole("button", { name: /^(Speed: .+|Select speed)$/ })
|
||||
.filter({ visible: true });
|
||||
|
||||
@@ -3,7 +3,6 @@ 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,
|
||||
@@ -30,89 +29,6 @@ import {
|
||||
|
||||
const FILE_LINK = "linked.ts:3";
|
||||
|
||||
test("compact offers file actions from a link and from the file sheet", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "compact-file-actions-",
|
||||
title: "File actions",
|
||||
initialPrompt: promptMentioning(FILE_LINK),
|
||||
});
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
|
||||
const fileLink = page.getByText(FILE_LINK, { exact: true });
|
||||
await expect(fileLink).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Native opens the same sheet from a long press.
|
||||
await fileLink.click({ button: "right" });
|
||||
const linkMenu = page.getByTestId("markdown-link-menu-content");
|
||||
await expect(linkMenu.getByRole("menuitem")).toHaveText([
|
||||
"Open file",
|
||||
"Reveal in Files",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
await linkMenu.getByRole("menuitem", { name: "Open file" }).click();
|
||||
|
||||
await expect(sheet(page, "linked.ts")).toBeVisible();
|
||||
await page.getByTestId("sheet-file-menu-trigger").click();
|
||||
const sheetMenu = page.getByTestId("sheet-file-menu-content");
|
||||
await expect(sheetMenu.getByRole("menuitem")).toHaveText([
|
||||
"Reveal in Files",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
await expect(sheetMenu.getByRole("menuitem").last()).toBeInViewport({ ratio: 1 });
|
||||
await page.screenshot({
|
||||
path: test.info().outputPath("compact-file-sheet-menu.png"),
|
||||
animations: "disabled",
|
||||
});
|
||||
await sheetMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
|
||||
await expectNoSheetOpen(page);
|
||||
await expect(
|
||||
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
|
||||
).toContainText("linked.ts");
|
||||
await page.screenshot({
|
||||
path: test.info().outputPath("compact-reveal-in-files.png"),
|
||||
animations: "disabled",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a narrow desktop window keeps the desktop actions in the file sheet menu", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "narrow-desktop-file-actions-",
|
||||
title: "File actions",
|
||||
initialPrompt: promptMentioning(FILE_LINK),
|
||||
});
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
|
||||
await installLocalDesktopHost(page, workspace.cwd, { fileManager: "Dolphin" });
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
|
||||
await page.getByText(FILE_LINK, { exact: true }).click();
|
||||
|
||||
await expect(sheet(page, "linked.ts")).toBeVisible({ timeout: 15_000 });
|
||||
await page.getByTestId("sheet-file-menu-trigger").click();
|
||||
await expect(page.getByTestId("sheet-file-menu-content").getByRole("menuitem")).toHaveText([
|
||||
"Reveal in Files",
|
||||
"Reveal in Dolphin",
|
||||
"Open in default app",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("compact opens files and subagents in a sheet, leaving the tabs for agents", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -387,10 +387,7 @@ test.describe("Composer model and effort shortcuts", () => {
|
||||
const effortLabel = page.getByTestId("combined-model-selector-thinking-label");
|
||||
await expect(effortLabel).toHaveText("Medium");
|
||||
await toggleModelPickerFromComposer(page);
|
||||
const drawerModelRow = page.getByTestId("agent-controls-model");
|
||||
await expect(drawerModelRow).toBeVisible();
|
||||
await page.keyboard.press(`${SHORTCUT_MOD}+Slash`);
|
||||
await expect(drawerModelRow).toBeHidden();
|
||||
await expectModelPickerClosesFromSearch(page);
|
||||
await cycleComposerEffort(page);
|
||||
await expect(effortLabel).toHaveText("High");
|
||||
});
|
||||
|
||||
@@ -1,143 +0,0 @@
|
||||
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();
|
||||
});
|
||||
@@ -1,135 +0,0 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { commandCenterSection, openCommandCenter } from "../support/helpers/command-center";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
const REPLY = [
|
||||
"Read [the report](data/report.csv), the [settings](.config/nested/file-55.json),",
|
||||
"the [data folder](data) or the [website](https://example.test/docs).",
|
||||
"Nothing is at gone.md.",
|
||||
].join(" ");
|
||||
|
||||
async function seedLinkedFiles() {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "file-link-menu-",
|
||||
title: "File link actions",
|
||||
initialPrompt: "Show the links",
|
||||
featureValues: { mockAssistantResponse: REPLY },
|
||||
});
|
||||
await mkdir(path.join(agent.cwd, "data"), { recursive: true });
|
||||
await writeFile(path.join(agent.cwd, "data/report.csv"), "name,total\nalpha,1\n");
|
||||
await mkdir(path.join(agent.cwd, ".config/nested"), { recursive: true });
|
||||
// Enough siblings that the target row starts outside the tree's viewport.
|
||||
await Promise.all(
|
||||
Array.from({ length: 60 }, (_, index) =>
|
||||
writeFile(
|
||||
path.join(agent.cwd, `.config/nested/file-${String(index).padStart(2, "0")}.json`),
|
||||
"{}\n",
|
||||
),
|
||||
),
|
||||
);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
return agent;
|
||||
}
|
||||
|
||||
function replyLink(page: Page, name: string) {
|
||||
return page.getByTestId("assistant-message").getByRole("link", { name, exact: true });
|
||||
}
|
||||
|
||||
function linkMenu(page: Page) {
|
||||
return page.getByTestId("markdown-link-menu");
|
||||
}
|
||||
|
||||
function selectedTreeRow(page: Page) {
|
||||
return page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]');
|
||||
}
|
||||
|
||||
async function expectMenuItems(page: Page, names: string[]) {
|
||||
await expect(linkMenu(page).getByRole("menuitem")).toHaveText(names);
|
||||
}
|
||||
|
||||
async function dismissMenu(page: Page) {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(linkMenu(page)).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function screenshot(page: Page, name: string) {
|
||||
await page.screenshot({
|
||||
path: test.info().outputPath(`${name}.png`),
|
||||
animations: "disabled",
|
||||
});
|
||||
}
|
||||
|
||||
test("links in chat and file tabs offer file actions and reveal the file in Files", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
testInfo.setTimeout(180_000);
|
||||
const agent = await seedLinkedFiles();
|
||||
try {
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"panel-state",
|
||||
JSON.stringify({ state: { explorerShowHiddenFiles: false }, version: 0 }),
|
||||
);
|
||||
});
|
||||
await openAgentRoute(page, agent);
|
||||
|
||||
await replyLink(page, "the report").click({ button: "right" });
|
||||
await expectMenuItems(page, [
|
||||
"Open file",
|
||||
"Open to the side",
|
||||
"Reveal in Files",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
await screenshot(page, "chat-file-link-menu");
|
||||
await dismissMenu(page);
|
||||
|
||||
await replyLink(page, "data folder").click({ button: "right" });
|
||||
await expectMenuItems(page, ["Reveal in Files", "Copy path", "Copy relative path"]);
|
||||
await dismissMenu(page);
|
||||
|
||||
await replyLink(page, "website").click({ button: "right" });
|
||||
await expectMenuItems(page, ["Open in default browser", "Copy link"]);
|
||||
await screenshot(page, "chat-web-link-menu");
|
||||
await dismissMenu(page);
|
||||
|
||||
// A bare name is looked up while the menu is open; acting on one that matches nothing says so.
|
||||
await replyLink(page, "gone.md").click({ button: "right" });
|
||||
await linkMenu(page).getByRole("menuitem", { name: "Download" }).click();
|
||||
await expect(page.getByTestId("assistant-file-link-not-found-toast")).toContainText("gone.md");
|
||||
|
||||
await replyLink(page, "the report").click({ button: "right" });
|
||||
await linkMenu(page).getByRole("menuitem", { name: "Reveal in Files" }).click();
|
||||
await expect(selectedTreeRow(page)).toContainText("report.csv");
|
||||
await expect(replyLink(page, "the report")).toBeVisible();
|
||||
await screenshot(page, "reveal-in-files-from-chat-link");
|
||||
|
||||
// A hidden folder, a freshly expanded tree and a row far below the fold.
|
||||
await replyLink(page, "settings").click();
|
||||
const fileTab = page.getByTestId("workspace-tab-file_.config/nested/file-55.json").first();
|
||||
await expect(fileTab).toBeVisible();
|
||||
await fileTab.click({ button: "right" });
|
||||
const tabMenu = page.getByTestId("workspace-tab-context-file_.config/nested/file-55.json");
|
||||
await expect(tabMenu.getByRole("menuitem", { name: "Reveal in Files" })).toBeVisible();
|
||||
await expect(tabMenu.getByRole("menuitem", { name: "Copy relative path" })).toBeVisible();
|
||||
await screenshot(page, "file-tab-menu");
|
||||
await tabMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
|
||||
await expect(selectedTreeRow(page)).toContainText("file-55.json");
|
||||
await expect(selectedTreeRow(page)).toBeInViewport();
|
||||
await screenshot(page, "reveal-in-files-from-file-tab");
|
||||
|
||||
// The tree is already mounted and scrolled elsewhere. Command Center reveals the active tab.
|
||||
await page.getByTestId("file-explorer-tree-scroll").hover();
|
||||
await page.mouse.wheel(0, -100_000);
|
||||
await expect(selectedTreeRow(page)).not.toBeInViewport();
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await commandCenter.getByTestId("command-center-input").fill("Reveal in Files");
|
||||
await commandCenterSection(commandCenter, "Reveal in Files").click();
|
||||
await expect(selectedTreeRow(page)).toBeInViewport();
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -3,11 +3,9 @@ import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { test, expect, type Page } from "../support/fixtures";
|
||||
import { connectDaemonClient } from "../support/helpers/daemon-client-loader";
|
||||
import {
|
||||
clearModelSearchWithEscape,
|
||||
clickModelRowWhileProviderOpens,
|
||||
closeModelPicker,
|
||||
expectModelListScrollKeepsSearchFocused,
|
||||
expectSearchProfilesAtTop,
|
||||
expectModelSearchEmptyState,
|
||||
expectModelPickerHeight,
|
||||
expectModelPickerWidth,
|
||||
@@ -21,12 +19,7 @@ import {
|
||||
seedModelProvider,
|
||||
expectSearchResultsVirtualized,
|
||||
} from "../support/helpers/agent-profiles";
|
||||
import {
|
||||
blurComposerInput,
|
||||
expectComposerFocused,
|
||||
expectComposerVisible,
|
||||
} from "../support/helpers/composer";
|
||||
import { openGlobalNewWorkspaceComposer } from "../support/helpers/new-workspace";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { clickNewChat, clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
@@ -63,7 +56,9 @@ const LARGE_CATALOG = {
|
||||
};
|
||||
|
||||
test.describe("Cross-provider model search", () => {
|
||||
test("one query reaches every provider and names each result's provider", async ({ page }) => {
|
||||
test("one query over the picker root reaches every provider and names each result's provider", async ({
|
||||
page,
|
||||
}) => {
|
||||
const provider = await seedModelProvider(STUDIO);
|
||||
const profile = await seedAgentProfiles([ROOT_VIEW_PROFILE]);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-search-providers-" });
|
||||
@@ -104,7 +99,7 @@ test.describe("Cross-provider model search", () => {
|
||||
});
|
||||
});
|
||||
|
||||
await test.step("results replace the Profiles list", async () => {
|
||||
await test.step("results replace the pinned profiles", async () => {
|
||||
await expectPinnedProfilesHidden(page);
|
||||
});
|
||||
|
||||
@@ -113,10 +108,6 @@ test.describe("Cross-provider model search", () => {
|
||||
await test.step("a query with no matches repeats the query back", async () => {
|
||||
await searchAllModels(page, "zzz");
|
||||
await expectModelSearchEmptyState(page, "zzz");
|
||||
});
|
||||
|
||||
await test.step("Escape clears the query before it closes the picker", async () => {
|
||||
await clearModelSearchWithEscape(page);
|
||||
await closeModelPicker(page);
|
||||
});
|
||||
} finally {
|
||||
@@ -144,23 +135,16 @@ test.describe("Cross-provider model search", () => {
|
||||
const restingHeight = await readModelPickerHeight(page);
|
||||
const restingWidth = await readModelPickerWidth(page);
|
||||
|
||||
await test.step("a broad query renders only the visible result window and scrolls without leaving search", async () => {
|
||||
await test.step("a broad query renders only the visible result window", async () => {
|
||||
await searchAllModels(page, "bulk model");
|
||||
await expectSearchResultsVirtualized(page, {
|
||||
provider: LARGE_CATALOG.id,
|
||||
total: LARGE_CATALOG_SIZE,
|
||||
});
|
||||
await expectModelListScrollKeepsSearchFocused(page);
|
||||
await expectModelPickerHeight(page, restingHeight);
|
||||
await expectModelPickerWidth(page, restingWidth);
|
||||
});
|
||||
|
||||
await test.step("a new query opens at the top, with the Profiles heading above the matching profile", async () => {
|
||||
// "search" matches the profile's name and every bulk model's description.
|
||||
await searchAllModels(page, "search");
|
||||
await expectSearchProfilesAtTop(page, ROOT_VIEW_PROFILE.id);
|
||||
});
|
||||
|
||||
await test.step("narrowing to one result does not resize the picker", async () => {
|
||||
await searchAllModels(page, "bulk model 199");
|
||||
await expectModelSearchResult(page, {
|
||||
@@ -195,7 +179,7 @@ test.describe("Cross-provider model search", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("arrow keys move between the rail, the model list, and search results in the composer", async ({
|
||||
test("arrow keys navigate profiles, providers, models, and search results in the composer", async ({
|
||||
page,
|
||||
}) => {
|
||||
const provider = await seedModelProvider(STUDIO);
|
||||
@@ -210,7 +194,7 @@ test.describe("Cross-provider model search", () => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-picker-arrows-" });
|
||||
|
||||
try {
|
||||
await test.step("open the composer model picker", async () => {
|
||||
await test.step("open the composer model picker on the root view", async () => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
@@ -220,42 +204,32 @@ test.describe("Cross-provider model search", () => {
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
const trigger = page.getByTestId("combined-model-selector").filter({ visible: true }).first();
|
||||
const profileRow = viewport.getByTestId("model-profile-row-agent_profile_e2e_arrows");
|
||||
const profilesRailRow = viewport.getByTestId("model-picker-rail-profiles");
|
||||
const studioProviderRow = viewport.getByTestId(`model-provider-${STUDIO.id}`);
|
||||
|
||||
await test.step("ArrowLeft moves to the rail, ArrowDown opens each entry, ArrowRight enters its list", async () => {
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
// The rail opens what it lands on, so ArrowUp from any provider reaches Profiles.
|
||||
for (let step = 0; step < 10; step += 1) {
|
||||
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
|
||||
await page.keyboard.press("ArrowUp");
|
||||
}
|
||||
await expect(profilesRailRow).toHaveAttribute("data-active", "true");
|
||||
await expect(profileRow).toBeVisible();
|
||||
await test.step("move from profiles to providers, drill in with ArrowRight, and go back with ArrowLeft", async () => {
|
||||
await expect(profileRow).toHaveAttribute("data-active", "true");
|
||||
// Root view keeps aria-selected absent while keyboard-active uses data-active.
|
||||
await expect(viewport.locator("[aria-selected]")).toHaveCount(0);
|
||||
|
||||
// Step down until Mock Studio is open (provider order can vary across environments).
|
||||
// Step down until Mock Studio is active (provider order can vary across environments).
|
||||
for (let step = 0; step < 10; step += 1) {
|
||||
if ((await studioProviderRow.getAttribute("data-active")) === "true") break;
|
||||
await page.keyboard.press("ArrowDown");
|
||||
}
|
||||
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
|
||||
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toBeVisible();
|
||||
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toHaveAttribute(
|
||||
"data-active",
|
||||
"true",
|
||||
);
|
||||
await expect(viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`)).toBeVisible();
|
||||
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(
|
||||
viewport.locator('[data-testid^="model-row-"][data-active="true"]'),
|
||||
).toHaveCount(0);
|
||||
await expect(studioProviderRow).toHaveAttribute("data-active", "true");
|
||||
});
|
||||
|
||||
await test.step("Enter moves from the rail into the list and ArrowDown + Enter selects a model", async () => {
|
||||
await test.step("Enter drills into the active provider and ArrowDown + Enter selects a model", async () => {
|
||||
await page.keyboard.press("Enter");
|
||||
const deepRow = viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`);
|
||||
await expect(deepRow).toBeVisible();
|
||||
await expectModelListScrollKeepsSearchFocused(page);
|
||||
|
||||
for (let step = 0; step < 5; step += 1) {
|
||||
if ((await deepRow.getAttribute("data-active")) === "true") break;
|
||||
@@ -266,7 +240,6 @@ test.describe("Cross-provider model search", () => {
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("Studio deep think");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("typing filters results while arrow keys select across search matches", async () => {
|
||||
@@ -285,7 +258,6 @@ test.describe("Cross-provider model search", () => {
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("Ten second stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("a press on a model row selects it while the provider list is still opening", async () => {
|
||||
@@ -293,42 +265,27 @@ test.describe("Cross-provider model search", () => {
|
||||
await clickModelRowWhileProviderOpens(page, {
|
||||
provider: "mock",
|
||||
modelLabel: "One minute stream",
|
||||
otherProvider: STUDIO.id,
|
||||
});
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("One minute stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("Enter on the active profile row applies it", async () => {
|
||||
await openModelPicker(page);
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
for (let step = 0; step < 10; step += 1) {
|
||||
if ((await profilesRailRow.getAttribute("data-active")) === "true") break;
|
||||
await page.keyboard.press("ArrowUp");
|
||||
}
|
||||
await page.keyboard.press("ArrowRight");
|
||||
await expect(profileRow).toHaveAttribute("data-active", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expect(trigger).toContainText("Ten second stream");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("the compact drawer puts Profiles in the Model accordion and lets all groups collapse", async () => {
|
||||
await test.step("folded compact sheet also supports Enter on the active profile row", async () => {
|
||||
await page.setViewportSize({ width: 390, height: 800 });
|
||||
await page.getByTestId("combined-model-selector").filter({ visible: true }).first().click();
|
||||
await expect(page.getByTestId("agent-controls-profiles")).toHaveCount(0);
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
await expect(page.getByTestId("compact-model-list")).toBeVisible();
|
||||
await page.locator('[data-testid^="model-provider-section-"]').first().click();
|
||||
await expect(page.getByTestId("compact-model-list")).toHaveCount(0);
|
||||
await page.getByTestId("model-picker-rail-profiles").click();
|
||||
const sheetProfileRow = page.getByTestId("model-profile-row-agent_profile_e2e_arrows");
|
||||
await expect(sheetProfileRow).toBeVisible();
|
||||
await sheetProfileRow.click();
|
||||
await expect(sheetProfileRow).toHaveAttribute("data-active", "true");
|
||||
await page.keyboard.press("Enter");
|
||||
await expect(sheetProfileRow).toHaveCount(0);
|
||||
await expect(page.getByTestId("agent-controls-model-sheet")).not.toBeInViewport();
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
@@ -336,43 +293,6 @@ test.describe("Cross-provider model search", () => {
|
||||
await provider.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test("choosing a model restores composer focus in workspace drafts and New Workspace", async ({
|
||||
page,
|
||||
}) => {
|
||||
const provider = await seedModelProvider(STUDIO);
|
||||
const workspace = await seedWorkspace({ repoPrefix: "model-picker-focus-" });
|
||||
|
||||
try {
|
||||
await test.step("clicking a model after blurring the workspace draft returns focus to the composer", async () => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await clickNewChat(page);
|
||||
await expectComposerVisible(page);
|
||||
await blurComposerInput(page);
|
||||
await openModelPicker(page);
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
|
||||
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-deep`).click();
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("clicking a model on the New Workspace screen returns focus to the composer", async () => {
|
||||
await openGlobalNewWorkspaceComposer(page);
|
||||
await expectComposerVisible(page);
|
||||
await blurComposerInput(page);
|
||||
await openModelPicker(page);
|
||||
const viewport = page.getByTestId("combobox-desktop-container");
|
||||
await viewport.getByTestId(`model-provider-${STUDIO.id}`).click();
|
||||
await viewport.getByTestId(`model-row-${STUDIO.id}-studio-fast`).click();
|
||||
await expect(viewport).toHaveCount(0);
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
await provider.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
async function setRuntimeCatalog(client: DaemonClient, count: number, cwd: string) {
|
||||
@@ -412,6 +332,7 @@ async function reloadSavedDraft(page: Page) {
|
||||
}
|
||||
async function expectOneCatalogChoice(page: Page, label: string) {
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("button", { name: "Back", exact: true }).click();
|
||||
await searchAllModels(page, label);
|
||||
await expect(page.getByTestId("model-row-gemini-gemini-3.5-flash")).toHaveCount(1);
|
||||
await closeModelPicker(page);
|
||||
|
||||
@@ -34,6 +34,7 @@ async function rememberModel(page: Page) {
|
||||
|
||||
async function expectRecoveredModelInPicker(page: Page) {
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
|
||||
await drillIntoProvider(page, PROVIDER);
|
||||
await expect(
|
||||
page.getByTestId("combobox-desktop-container").getByText(LABEL, { exact: true }),
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
finishSetup,
|
||||
goToSetupStep,
|
||||
hostGivesAgentsPaseoTools,
|
||||
hostToolGroups,
|
||||
openAppAsNewUser,
|
||||
openRelayPairingFromSetup,
|
||||
closeRelayPairing,
|
||||
@@ -25,7 +24,6 @@ import {
|
||||
recordFirstLaunch,
|
||||
setupModal,
|
||||
setupPrimaryButton,
|
||||
setHostTools,
|
||||
setupSheet,
|
||||
showSetupAgainFromSettings,
|
||||
skipSetup,
|
||||
@@ -428,30 +426,6 @@ test("setup choices carry over to Settings and the phone step pairs over relay",
|
||||
}
|
||||
});
|
||||
|
||||
test("setup offers only Enable tools and keeps the host's tool groups", async ({ page }) => {
|
||||
const host = await startSetupHost("tool-groups");
|
||||
|
||||
try {
|
||||
await setHostTools(host, { groups: { schedules: false, browser: true } });
|
||||
await openAppAsNewUser(page, host);
|
||||
await expectSetupStep(page, "Welcome to Paseo");
|
||||
await goToSetupStep(page, "Orchestration");
|
||||
await expectSetupStep(page, "Let agents use Paseo");
|
||||
await expect(paseoToolsSwitch(setupModal(page))).toBeChecked();
|
||||
// Setup offers only the main switch; tool groups live in Settings.
|
||||
await expect(
|
||||
setupModal(page).getByRole("switch", { name: "Browser", exact: true }),
|
||||
).toHaveCount(0);
|
||||
await continueSetup(page);
|
||||
await expectSetupStep(page, "Take your agents with you");
|
||||
|
||||
await expect.poll(() => hostGivesAgentsPaseoTools(host), { timeout: 30_000 }).toBe(true);
|
||||
expect(await hostToolGroups(host)).toMatchObject({ schedules: false, browser: true });
|
||||
} finally {
|
||||
await host.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("with no skills picked, skills read as off and Continue moves on", async ({ page }) => {
|
||||
const host = await startSetupHost("no-skills");
|
||||
|
||||
@@ -489,7 +463,6 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
|
||||
const primary = (label: string) => page.getByRole("button", { name: label, exact: true });
|
||||
|
||||
try {
|
||||
await setHostTools(host, { enabled: false });
|
||||
await openAppAsNewUser(page, host);
|
||||
await step("Welcome to Paseo");
|
||||
await primary("Continue").click();
|
||||
@@ -498,7 +471,7 @@ test("in the compact layout, Finish on Orchestration applies its switches", asyn
|
||||
await step("Add your projects");
|
||||
await primary("Continue").click();
|
||||
|
||||
// The host has tools off; the setup switch still starts on.
|
||||
// The setup host starts with Paseo tools off; the switch starts on.
|
||||
expect(await hostGivesAgentsPaseoTools(host)).toBe(false);
|
||||
await step("Let agents use Paseo");
|
||||
await expect(paseoToolsSwitch(page)).toBeChecked();
|
||||
|
||||
@@ -13,17 +13,11 @@ 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";
|
||||
@@ -45,7 +39,6 @@ function ModalBody({ onSaved }) {
|
||||
<Text>Plugin modal contexts ready</Text>
|
||||
<Markdown>{"## Plugin report"}</Markdown>
|
||||
<Markdown>{"Checks **passed**. [Documentation](https://paseo.sh/docs/plugins)"}</Markdown>
|
||||
<Markdown>{""}</Markdown>
|
||||
<Markdown>{""}</Markdown>
|
||||
<Pressable accessibilityRole="button" onPress={save}>
|
||||
<Text>Save issue</Text>
|
||||
@@ -63,7 +56,6 @@ function Surface({ playAudio }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return <View>
|
||||
<Text>{audioStatus}</Text>
|
||||
<Markdown>{"\\n\\n"}</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)}>
|
||||
@@ -113,39 +105,20 @@ async function openPluginModal(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Open plugin modal", exact: true }).click();
|
||||
}
|
||||
|
||||
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(
|
||||
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(
|
||||
"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(dialog);
|
||||
await expectPluginMarkdown(page);
|
||||
}
|
||||
|
||||
async function closeCenteredPluginDialog(page: Page): Promise<void> {
|
||||
@@ -174,15 +147,10 @@ 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"))};\nconst SCREENSHOT_PATH = ${JSON.stringify(beforePath)};\nconst SCREENSHOT_FILE_URL = ${JSON.stringify(afterFileUrl)};\n${PLUGIN_SOURCE}`,
|
||||
`const AUDIO_BASE64 = ${JSON.stringify(audio.toString("base64"))};\n${PLUGIN_SOURCE}`,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -191,12 +159,6 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
|
||||
await useNonCompactLayout(page);
|
||||
await openHostUiPlugin(page);
|
||||
|
||||
await test.step("plugin screen Markdown renders local absolute and file:// PNG images inline", async () => {
|
||||
await expectLoadedMarkdownImage(page, "Before");
|
||||
await expectLoadedMarkdownImage(page, "After");
|
||||
await expect(page.getByText("Image unavailable")).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("plugin audio finishes, rejects corrupt files, and recovers", async () => {
|
||||
await playPluginAudio(page, "Play plugin audio", "Audio finished");
|
||||
await playPluginAudio(page, "Play invalid audio", "Audio rejected");
|
||||
|
||||
@@ -26,14 +26,16 @@ async function openProviderSettingsFromModelSelector(page: Page) {
|
||||
const configuration = page.getByTestId("agent-controls-model-sheet");
|
||||
await expect(configuration).toBeVisible({ timeout: 10_000 });
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
await expect(page.getByTestId("mobile-model-page")).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
const modelBrowser = page.getByTestId("agent-controls-model-browser-sheet");
|
||||
await expect(modelBrowser).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
await page.getByRole("button", { name: /Open .* settings/ }).click();
|
||||
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
|
||||
}
|
||||
|
||||
async function expectModelPageVisible(page: Page) {
|
||||
await expect(page.getByTestId("mobile-model-page")).toBeVisible({
|
||||
async function expectModelBrowserVisible(page: Page) {
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(page.getByRole("button", { name: /Open .* settings/ })).toBeVisible();
|
||||
@@ -185,7 +187,7 @@ test.describe("provider settings overlay stack", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("provider settings and children close back to the Model page, then Back reaches Home", async ({
|
||||
test("provider settings and children close back through the model browser to configuration", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
@@ -197,15 +199,17 @@ test.describe("provider settings overlay stack", () => {
|
||||
await exerciseProviderSettingsStack(page);
|
||||
await closeSheetByHeaderButton(page, "provider-settings-sheet");
|
||||
|
||||
await expectModelPageVisible(page);
|
||||
await expectModelBrowserVisible(page);
|
||||
await page.getByRole("button", { name: /Open .* settings/ }).click();
|
||||
await expect(page.getByTestId("provider-settings-sheet")).toBeVisible({ timeout: 10_000 });
|
||||
await exerciseProviderSettingsStack(page);
|
||||
await closeSheetByHeaderButton(page, "provider-settings-sheet");
|
||||
|
||||
await expectModelPageVisible(page);
|
||||
await page.getByTestId("sheet-header-back").click();
|
||||
await expect(page.getByTestId("mobile-model-page")).toHaveCount(0);
|
||||
await expectModelBrowserVisible(page);
|
||||
await closeTopSheet(page);
|
||||
await expect(page.getByTestId("agent-controls-model-browser-sheet")).not.toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
await expect(page.getByTestId("agent-controls-settings-list")).toBeVisible();
|
||||
await closeTopSheet(page);
|
||||
} finally {
|
||||
@@ -222,6 +226,8 @@ async function openTimedOutProvider(page: Page, workspaceId: string, width: numb
|
||||
await page.getByRole("button", { name: /Select model/ }).click();
|
||||
if (width < 600) {
|
||||
await page.getByTestId("agent-controls-model").click();
|
||||
} else {
|
||||
await page.getByRole("button", { name: "Back", exact: true }).click();
|
||||
}
|
||||
await page.getByTestId("model-provider-picker-timeout").click();
|
||||
await expect(page.getByText(/Timed out refreshing Pi timeout/)).toBeVisible();
|
||||
|
||||
@@ -1,51 +0,0 @@
|
||||
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,9 +4,7 @@ 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";
|
||||
|
||||
@@ -25,134 +23,13 @@ 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.
|
||||
@@ -281,10 +158,6 @@ 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);
|
||||
});
|
||||
|
||||
@@ -293,8 +166,6 @@ 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 });
|
||||
@@ -307,110 +178,14 @@ 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(capturedMatches).toHaveLength(1);
|
||||
expect(browserOscReplies).toEqual([]);
|
||||
const afterCapture = text.slice(text.indexOf("PASEO_OSC11_CAPTURE:") + captureLine.length);
|
||||
expect(afterCapture).not.toContain("rgb:");
|
||||
expect(text).toContain("rgb:0b0b/0b0b/0b0b");
|
||||
expect(text).not.toContain("rgb:ffff/ffff/ffff");
|
||||
} finally {
|
||||
await harness.killTerminal(terminalInstance.id);
|
||||
}
|
||||
});
|
||||
|
||||
test("reports Light and Dark palettes through OSC 10/11/12, COLORFGBG, DSR 996/997, and live DEC 2031 toggles", async ({
|
||||
page,
|
||||
}) => {
|
||||
const createAppTerminal = async (): Promise<string> => {
|
||||
const existing = await harness.client.listTerminals(harness.tempRepo.path, undefined, {
|
||||
workspaceId: harness.workspaceId,
|
||||
});
|
||||
const knownIds = new Set(existing.terminals.map((entry) => entry.id));
|
||||
await clickNewTerminal(page);
|
||||
const terminalId = await waitForCreatedTerminal(harness, knownIds);
|
||||
const surface = terminalSurface(page);
|
||||
await expect(surface).toBeVisible({ timeout: 20_000 });
|
||||
await surface.click();
|
||||
const readyTag = `READY_${Date.now()}`;
|
||||
await surface.pressSequentially(`echo ${readyTag}\n`, { delay: 0 });
|
||||
await expectTerminalOutput(terminalId, readyTag);
|
||||
return terminalId;
|
||||
};
|
||||
|
||||
const runPaletteChecks = async (
|
||||
terminalId: string,
|
||||
scenario: TerminalPaletteScenario,
|
||||
options: { checkColorFgBg: boolean },
|
||||
): Promise<void> => {
|
||||
const surface = terminalSurface(page);
|
||||
await surface.click();
|
||||
if (options.checkColorFgBg) {
|
||||
await surface.pressSequentially('echo "CFGBG=$COLORFGBG"\n', { delay: 0 });
|
||||
await expectTerminalOutput(terminalId, `CFGBG=${scenario.colorFgBg}`);
|
||||
}
|
||||
for (const code of [10, 11, 12] as const) {
|
||||
await surface.pressSequentially(`${process.execPath} palette-probe.cjs osc ${code}\n`, {
|
||||
delay: 0,
|
||||
});
|
||||
await expectTerminalOutput(
|
||||
terminalId,
|
||||
`OSC_COLOR_OK:${code}:ESC]${code};${scenario.colors[code]}ESC\\`,
|
||||
);
|
||||
}
|
||||
await surface.pressSequentially(`${process.execPath} palette-probe.cjs dsr996\n`, {
|
||||
delay: 0,
|
||||
});
|
||||
await expectTerminalOutput(terminalId, `DSR996_OK:${scenario.schemeCode}`);
|
||||
};
|
||||
|
||||
// 1. Open workspace once, switch to Light in-app, and create a fresh Light terminal.
|
||||
await gotoWorkspace(page, harness.workspaceId);
|
||||
await selectAppThemeInApp(page, "Light");
|
||||
const lightTerminalId = await createAppTerminal();
|
||||
let darkTerminalId: string | null = null;
|
||||
try {
|
||||
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.light, {
|
||||
checkColorFgBg: true,
|
||||
});
|
||||
|
||||
// 2. Start DEC 2031 watcher in that running Light terminal, then toggle Light -> Dark -> Light.
|
||||
await terminalSurface(page).pressSequentially(
|
||||
`${process.execPath} palette-probe.cjs watch2031\n`,
|
||||
{ delay: 0 },
|
||||
);
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_READY");
|
||||
|
||||
await selectAppThemeInApp(page, "Dark");
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:1");
|
||||
|
||||
await selectAppThemeInApp(page, "Light");
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:2");
|
||||
|
||||
// Stop watcher, toggle to Dark, and verify live OSC 10/11/12 + DSR 996 update on the same PTY.
|
||||
await terminalSurface(page).click();
|
||||
await terminalSurface(page).pressSequentially("Q", { delay: 0 });
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE");
|
||||
|
||||
await selectAppThemeInApp(page, "Dark");
|
||||
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
|
||||
checkColorFgBg: false,
|
||||
});
|
||||
|
||||
// 3. Fresh Dark terminal reports Dark OSC 10/11/12, COLORFGBG=15;0, and DSR 996 -> dark (1).
|
||||
darkTerminalId = await createAppTerminal();
|
||||
await runPaletteChecks(darkTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
|
||||
checkColorFgBg: true,
|
||||
});
|
||||
} finally {
|
||||
await harness.killTerminal(lightTerminalId);
|
||||
if (darkTerminalId) {
|
||||
await harness.killTerminal(darkTerminalId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function openFileReceiver(page: Page, name: string) {
|
||||
const terminal = await harness.createTerminal({
|
||||
name,
|
||||
|
||||
@@ -13,12 +13,8 @@ import { test, expect } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { withDirectoryPlugin } from "../support/helpers/plugin-timeline";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { getE2EDaemonPort } from "../support/helpers/daemon-port";
|
||||
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
|
||||
test.use({
|
||||
e2eInjectPaseoTools: true,
|
||||
e2eDaemonConfig: {
|
||||
version: 1,
|
||||
agents: {
|
||||
@@ -294,89 +290,6 @@ test("received messages show their sender and open that agent", async ({ page })
|
||||
}
|
||||
});
|
||||
|
||||
/** Calls a Paseo MCP tool as `callerAgentId`, the way that agent's provider would. */
|
||||
async function callPaseoToolAs(
|
||||
callerAgentId: string,
|
||||
name: string,
|
||||
args: Record<string, unknown>,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const mcp = new Client({ name: "turn-collapse-e2e", version: "1" });
|
||||
await mcp.connect(
|
||||
new StreamableHTTPClientTransport(
|
||||
new URL(`http://127.0.0.1:${getE2EDaemonPort()}/mcp/agents?callerAgentId=${callerAgentId}`),
|
||||
),
|
||||
);
|
||||
try {
|
||||
const response = await mcp.callTool({ name, arguments: args });
|
||||
expect(response, name).not.toMatchObject({ isError: true });
|
||||
return response.structuredContent as Record<string, unknown>;
|
||||
} finally {
|
||||
await mcp.close();
|
||||
}
|
||||
}
|
||||
|
||||
test("a delegated child reports each turn end as a compact tool call until its own delegate is done", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
const frames: string[] = [];
|
||||
page.on("websocket", (socket) => {
|
||||
socket.on("framereceived", ({ payload }) => {
|
||||
if (typeof payload === "string") frames.push(payload);
|
||||
});
|
||||
});
|
||||
const childNoticeFrames = () => frames.filter((frame) => frame.includes('"label":"Child"'));
|
||||
const parent = await seedMockAgentWorkspace({ repoPrefix: "child-notices-", title: "Lead" });
|
||||
try {
|
||||
await openAgentRoute(page, parent);
|
||||
await expectComposerVisible(page);
|
||||
const child = await callPaseoToolAs(parent.agentId, "create_agent", {
|
||||
workspaceId: parent.workspaceId,
|
||||
title: "Child",
|
||||
provider: "mock/e2e-fast-stream",
|
||||
settings: { modeId: "load-test" },
|
||||
initialPrompt: "Delegate the slow part",
|
||||
});
|
||||
const childId = String(child.agentId);
|
||||
// The child's own delegate outlives the child's first turn.
|
||||
const grandchild = await callPaseoToolAs(childId, "create_agent", {
|
||||
workspaceId: parent.workspaceId,
|
||||
title: "Grandchild",
|
||||
provider: "mock/ten-second-stream",
|
||||
settings: { modeId: "load-test" },
|
||||
initialPrompt: "Take your time",
|
||||
});
|
||||
const notices = page.getByRole("button", { name: /^Agent .*Child/ });
|
||||
const finished = page.getByRole("button", { name: /^Agent finished.*Child/ });
|
||||
|
||||
// The child ended its turn while waiting on its delegate: the parent hears it now.
|
||||
await expect(finished).toHaveCount(1, { timeout: 30_000 });
|
||||
const delegate = await parent.client.waitForAgentUpsert(String(grandchild.agentId), () => true);
|
||||
expect(delegate.status, "the delegate must still be running").toBe("running");
|
||||
expect(
|
||||
childNoticeFrames().some((frame) => frame.includes("It still has agents it is waiting on.")),
|
||||
).toBe(true);
|
||||
|
||||
// The delegate reports to the child, and the child's settled turn reaches the parent.
|
||||
await expect(finished).toHaveCount(2, { timeout: 60_000 });
|
||||
await expect(notices).toHaveCount(2);
|
||||
await expect(page.getByText(/still working/i)).toHaveCount(0);
|
||||
await expect(page.getByText(/Sent by/)).toHaveCount(0);
|
||||
await expect(page.getByText(/<agent-response>/)).toHaveCount(0);
|
||||
await finished.last().scrollIntoViewIfNeeded();
|
||||
await page.screenshot({ path: testInfo.outputPath("child-notices.png") });
|
||||
// Notification events stay on the daemon: clients get only plain tool calls.
|
||||
expect(frames.filter((frame) => frame.includes('"agentMessage"'))).toEqual([]);
|
||||
expect(childNoticeFrames().some((frame) => frame.includes('"name":"agent_finished"'))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(childNoticeFrames().filter((frame) => /"name":"agent_(?!finished)/.test(frame))).toEqual(
|
||||
[],
|
||||
);
|
||||
} finally {
|
||||
await parent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("long sender attribution stays on one line in compact chat", async ({ page }, testInfo) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.addInitScript(() =>
|
||||
|
||||
@@ -668,186 +668,3 @@ 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(/PaseoTerminalInputView\{(\w+)/)?.[1] ?? null,
|
||||
input: view.match(/ReactEditText\{(\w+)/)?.[1] ?? null,
|
||||
};
|
||||
}
|
||||
async function waitForKeyboard(shown) {
|
||||
|
||||
@@ -587,12 +587,7 @@ export async function openModelPicker(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page)).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
/** Escape clears a typed query first; the next Escape closes the picker. */
|
||||
export async function closeModelPicker(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
if ((await search.count()) > 0 && (await search.inputValue()) !== "") {
|
||||
await clearModelSearchWithEscape(page);
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
@@ -603,40 +598,70 @@ export function profilePickerRow(page: Page, name: string): Locator {
|
||||
.filter({ hasText: name });
|
||||
}
|
||||
|
||||
/** Desktop keeps profiles behind the rail's Profiles entry, beside the providers. */
|
||||
export async function openPickerProfiles(page: Page): Promise<void> {
|
||||
await pickerViewport(page).getByTestId("model-picker-rail-profiles").click();
|
||||
}
|
||||
|
||||
export async function expectPickerProfile(
|
||||
/**
|
||||
* Profiles are pinned above the provider list, so "pinned" is an ordering claim:
|
||||
* the profile row's top edge sits above every provider row's.
|
||||
*/
|
||||
export async function expectProfilePinnedAboveProviders(
|
||||
page: Page,
|
||||
input: { name: string; summary: string },
|
||||
): Promise<void> {
|
||||
await openPickerProfiles(page);
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
const row = profilePickerRow(page, input.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
|
||||
|
||||
const profileTop = await boxTop(row);
|
||||
const providerRows = viewport.locator('[data-testid^="model-provider-"]');
|
||||
await expect(providerRows.first()).toBeVisible();
|
||||
const providerCount = await providerRows.count();
|
||||
for (let index = 0; index < providerCount; index += 1) {
|
||||
expect(profileTop).toBeLessThan(await boxTop(providerRows.nth(index)));
|
||||
}
|
||||
}
|
||||
|
||||
export async function expectProfileVisibleForProvider(
|
||||
page: Page,
|
||||
input: { name: string; summary: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
const row = profilePickerRow(page, input.name);
|
||||
await expect(row).toBeVisible({ timeout: 30_000 });
|
||||
await expect(row.getByText(input.summary, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectProfilesEditLink(page: Page): Promise<void> {
|
||||
export async function expectProfileEditIsPencilOnly(page: Page): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(
|
||||
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(viewport.getByText("Edit", { exact: true })).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.getByText("Profiles", { exact: true })).toHaveCount(0);
|
||||
await expect(
|
||||
viewport.getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toHaveCount(0);
|
||||
await expect(viewport.getByRole("button", { name: "Create profile", exact: true })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
|
||||
export async function expectProfileEditTooltip(page: Page): Promise<void> {
|
||||
const edit = pickerViewport(page).getByRole("button", {
|
||||
name: "Edit agent profiles",
|
||||
exact: true,
|
||||
});
|
||||
await expect(edit).toBeVisible();
|
||||
await expect(edit).toHaveText("Edit");
|
||||
}
|
||||
|
||||
/** With no profiles, the Profiles entry offers to create one instead of listing any. */
|
||||
export async function expectAgentProfilesEmptyPrompt(page: Page): Promise<void> {
|
||||
await openPickerProfiles(page);
|
||||
const viewport = pickerViewport(page);
|
||||
await expect(viewport.locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
|
||||
await expect(viewport.getByTestId("model-profiles-empty")).toBeVisible({ timeout: 30_000 });
|
||||
await edit.hover();
|
||||
await expect(page.getByText("Edit agent profiles", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openAgentProfilesFromEmptyPrompt(page: Page): Promise<void> {
|
||||
await pickerViewport(page).getByTestId("model-profiles-empty").click();
|
||||
await pickerViewport(page).getByRole("button", { name: "Create profile", exact: true }).click();
|
||||
await expect(page.getByTestId("agent-profiles-card")).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
@@ -684,17 +709,25 @@ export async function expectProfileReachableByScrolling(page: Page, name: string
|
||||
}
|
||||
|
||||
export async function applyProfileFromPicker(page: Page, name: string): Promise<void> {
|
||||
const row = profilePickerRow(page, name);
|
||||
if (!(await row.isVisible().catch(() => false))) {
|
||||
const profilesRail = pickerViewport(page).getByTestId("model-picker-rail-profiles");
|
||||
if (await profilesRail.isVisible().catch(() => false)) {
|
||||
await profilesRail.click();
|
||||
}
|
||||
}
|
||||
await row.click();
|
||||
await profilePickerRow(page, name).click();
|
||||
await expect(pickerViewport(page)).toHaveCount(0, { timeout: 30_000 });
|
||||
}
|
||||
|
||||
/**
|
||||
* Applying a profile materializes it and forgets it: nothing in the root view
|
||||
* claims selection. Model rows do carry `aria-selected`, so a count of zero here
|
||||
* is the absence of a checkmark, not the absence of the attribute everywhere.
|
||||
*/
|
||||
export async function expectNothingSelectedInPickerRoot(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page).locator("[aria-selected]")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectAgentProfilesEditShortcut(page: Page): Promise<void> {
|
||||
await expect(
|
||||
pickerViewport(page).getByRole("button", { name: "Edit agent profiles", exact: true }),
|
||||
).toBeVisible({ timeout: 30_000 });
|
||||
}
|
||||
|
||||
export async function drillIntoProvider(page: Page, providerId: string): Promise<void> {
|
||||
await pickerViewport(page).getByTestId(`model-provider-${providerId}`).click();
|
||||
}
|
||||
@@ -765,13 +798,13 @@ export async function selectModelRow(
|
||||
*/
|
||||
export async function clickModelRowWhileProviderOpens(
|
||||
page: Page,
|
||||
input: { provider: string; modelLabel: string; otherProvider: string },
|
||||
input: { provider: string; modelLabel: string },
|
||||
): Promise<void> {
|
||||
const viewport = pickerViewport(page);
|
||||
await drillIntoProvider(page, input.provider);
|
||||
const rowBox = await viewport.getByText(input.modelLabel, { exact: true }).boundingBox();
|
||||
if (!rowBox) throw new Error(`Model row ${input.modelLabel} has no box`);
|
||||
await drillIntoProvider(page, input.otherProvider);
|
||||
await viewport.getByRole("button", { name: "Back", exact: true }).click();
|
||||
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
await cdp.send("Emulation.setCPUThrottlingRate", { rate: 10 });
|
||||
@@ -789,7 +822,7 @@ export async function clickModelRowWhileProviderOpens(
|
||||
/** Scrolling a provider's model list with the wheel leaves typing and Enter in the search field. */
|
||||
export async function expectModelListScrollKeepsSearchFocused(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
const list = pickerViewport(page).getByTestId("model-picker-model-list");
|
||||
const list = pickerViewport(page).getByTestId("compact-model-list");
|
||||
await expect(search).toBeFocused();
|
||||
await list.hover();
|
||||
await page.mouse.wheel(0, 200);
|
||||
@@ -800,18 +833,11 @@ export async function expectModelListScrollKeepsSearchFocused(page: Page): Promi
|
||||
// ─── Cross-provider model search ───────────────────────────────────────────
|
||||
|
||||
export async function searchAllModels(page: Page, query: string): Promise<void> {
|
||||
const input = pickerViewport(page).getByTestId("model-search-input");
|
||||
const input = page.getByTestId("model-search-all-input");
|
||||
await expect(input).toBeVisible({ timeout: 30_000 });
|
||||
await input.fill(query);
|
||||
}
|
||||
|
||||
/** Search results open at the top, with the Profiles heading above the first matching profile. */
|
||||
export async function expectSearchProfilesAtTop(page: Page, profileId: string): Promise<void> {
|
||||
const list = pickerViewport(page).getByTestId("model-picker-model-list");
|
||||
await expect(list.getByText("Profiles", { exact: true })).toBeInViewport({ ratio: 1 });
|
||||
await expect(list.getByTestId(`model-profile-row-${profileId}`)).toBeInViewport({ ratio: 1 });
|
||||
}
|
||||
|
||||
export async function expectModelSearchResult(
|
||||
page: Page,
|
||||
expected: { provider: string; modelId: string; providerLabel: string; modelLabel: string },
|
||||
@@ -830,19 +856,11 @@ function escapeForRegex(value: string): string {
|
||||
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
|
||||
/** Search results replace both panes, the Profiles list included. */
|
||||
/** Search results replace the whole root view, pinned profiles included. */
|
||||
export async function expectPinnedProfilesHidden(page: Page): Promise<void> {
|
||||
await expect(pickerViewport(page).locator('[data-testid^="model-profile-row-"]')).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function clearModelSearchWithEscape(page: Page): Promise<void> {
|
||||
const search = pickerViewport(page).getByTestId("model-search-input");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(search).toHaveValue("");
|
||||
await expect(search).toBeFocused();
|
||||
await expect(pickerViewport(page)).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectModelSearchEmptyState(page: Page, query: string): Promise<void> {
|
||||
const empty = page.getByTestId("model-search-empty");
|
||||
await expect(empty).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
@@ -362,8 +362,8 @@ export const selectModel = async (page: Page, model: string) => {
|
||||
// Type to search/filter models
|
||||
await searchInput.fill(normalizedModel);
|
||||
|
||||
const viewport = page.getByTestId("combobox-desktop-container").or(page.getByRole("dialog"));
|
||||
const exactOption = viewport
|
||||
const dialog = page.getByRole("dialog");
|
||||
const exactOption = dialog
|
||||
.getByText(new RegExp(`^${escapeRegex(normalizedModel)}$`, "i"))
|
||||
.first();
|
||||
const exactVisible = await exactOption.isVisible().catch(() => false);
|
||||
@@ -375,10 +375,8 @@ export const selectModel = async (page: Page, model: string) => {
|
||||
await searchInput.press("Enter");
|
||||
}
|
||||
|
||||
// Wait for dropdown to close; when a query has no match, the first Escape clears the query
|
||||
// and the second closes the picker.
|
||||
for (let attempt = 0; attempt < 2; attempt += 1) {
|
||||
if (!(await searchInput.isVisible().catch(() => false))) break;
|
||||
// Wait for dropdown to close
|
||||
if (await searchInput.isVisible().catch(() => false)) {
|
||||
await page.keyboard.press("Escape").catch(() => undefined);
|
||||
}
|
||||
await expect(searchInput).not.toBeVisible({ timeout: 5000 });
|
||||
|
||||
@@ -3,35 +3,15 @@ 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,
|
||||
// `fileManager` adds the editor bridge: a file manager of that name, and the default-app opener.
|
||||
{ fileManager = null }: { fileManager?: string | null } = {},
|
||||
): Promise<void> {
|
||||
export async function installLocalDesktopHost(page: Page, directory: string): 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; 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;
|
||||
(localHost: { serverId: string; directory: string }) => {
|
||||
(window as unknown as { paseoDesktop: unknown }).paseoDesktop = {
|
||||
platform: "linux",
|
||||
editor,
|
||||
invoke: async (command: string) => {
|
||||
if (command === "desktop_daemon_status") {
|
||||
return {
|
||||
@@ -53,6 +33,6 @@ export async function installLocalDesktopHost(
|
||||
webUtils: { getPathForFile: (file: File) => `${localHost.directory}/${file.name}` },
|
||||
};
|
||||
},
|
||||
{ serverId, directory, fileManager },
|
||||
{ serverId, directory },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export async function chooseModel(page: Page, provider: string, label: string) {
|
||||
export async function reselectModel(page: Page, provider: string, label: string) {
|
||||
await expectRememberedModel(page, label);
|
||||
await openModelPicker(page);
|
||||
await page.getByRole("dialog").getByRole("button", { name: "Back", exact: true }).click();
|
||||
await selectProviderModel(page, provider, label);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,10 +4,6 @@ import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import type { DaemonClient as InternalDaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type {
|
||||
MutableDaemonToolGroups,
|
||||
MutableDaemonToolsConfigPatch,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import { addProjectFlow, addProjectFlowInput, expectAddProjectTab } from "./add-project-flow";
|
||||
import { connectDaemonClient } from "./daemon-client-loader";
|
||||
import { buildCreateAgentPreferences, buildSeededHost } from "./daemon-registry";
|
||||
@@ -142,7 +138,7 @@ export async function goToSetupStep(page: Page, label: string): Promise<void> {
|
||||
}
|
||||
|
||||
export function paseoToolsSwitch(scope: Page | Locator): Locator {
|
||||
return scope.getByRole("switch", { name: "Enable tools", exact: true });
|
||||
return scope.getByRole("switch", { name: "Inject Paseo tools", exact: true });
|
||||
}
|
||||
|
||||
/** Whether the host gives its agents Paseo tools, read from the host itself. */
|
||||
@@ -151,37 +147,7 @@ export async function hostGivesAgentsPaseoTools(host: { port: number }): Promise
|
||||
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
|
||||
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
|
||||
try {
|
||||
const config = (await client.getDaemonConfig()).config;
|
||||
return config.tools?.enabled ?? config.mcp.injectIntoAgents !== false;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** The host's saved tool groups, read from the host itself. */
|
||||
export async function hostToolGroups(host: {
|
||||
port: number;
|
||||
}): Promise<MutableDaemonToolGroups | undefined> {
|
||||
const client = await connectDaemonClient<
|
||||
Pick<InternalDaemonClient, "connect" | "close" | "getDaemonConfig">
|
||||
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
|
||||
try {
|
||||
return (await client.getDaemonConfig()).config.tools?.groups;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
|
||||
/** Saves tool settings on the host, the way Settings does. */
|
||||
export async function setHostTools(
|
||||
host: { port: number },
|
||||
tools: MutableDaemonToolsConfigPatch,
|
||||
): Promise<void> {
|
||||
const client = await connectDaemonClient<
|
||||
Pick<InternalDaemonClient, "connect" | "close" | "patchDaemonConfig">
|
||||
>({ clientIdPrefix: "app-e2e-onboarding", port: host.port });
|
||||
try {
|
||||
await client.patchDaemonConfig({ tools });
|
||||
return (await client.getDaemonConfig()).config.mcp.injectIntoAgents !== false;
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
|
||||
@@ -44,8 +44,9 @@ async function expectProviderIcon(surface: Locator, paths: string[]): Promise<vo
|
||||
|
||||
async function selectPluginModel(page: Page): Promise<void> {
|
||||
await openModelPicker(page);
|
||||
await page.getByTestId("model-provider-direct-example").click();
|
||||
await page.getByTestId("model-row-direct-example-example-1").click();
|
||||
await page.getByRole("button", { name: "Back", exact: true }).click();
|
||||
await page.getByText("Direct provider example", { exact: true }).click();
|
||||
await page.getByText("Example 1", { exact: true }).click();
|
||||
await expect(page.getByRole("button", { name: MODEL_LABEL, exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
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";
|
||||
@@ -95,13 +94,7 @@ export interface SeedDaemonClient {
|
||||
cwd: string,
|
||||
name?: string,
|
||||
requestId?: string,
|
||||
options?: {
|
||||
agentId?: string;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
workspaceId?: string;
|
||||
defaultColors?: TerminalDefaultColors;
|
||||
},
|
||||
options?: { agentId?: string; command?: string; args?: string[]; workspaceId?: string },
|
||||
): Promise<{
|
||||
terminal: { id: string; name: string; cwd: string; activity?: TerminalActivity | null } | null;
|
||||
error: string | null;
|
||||
|
||||
@@ -480,7 +480,7 @@ export async function expectHostConnectionsCard(page: Page, port: string): Promi
|
||||
export async function expectHostInjectMcpCard(page: Page): Promise<void> {
|
||||
const card = page.getByTestId("host-page-inject-mcp-card");
|
||||
await expect(card).toBeVisible();
|
||||
await expect(card.getByRole("switch", { name: "Enable tools" })).toBeVisible();
|
||||
await expect(card.getByRole("switch", { name: "Inject Paseo tools" })).toBeVisible();
|
||||
}
|
||||
|
||||
function idleAgentReleaseSwitch(page: Page) {
|
||||
|
||||
@@ -463,15 +463,16 @@ export async function delegateFleetThroughMcp() {
|
||||
direction: "tail",
|
||||
limit: 100,
|
||||
});
|
||||
return timeline.entries.filter(
|
||||
({ item }) =>
|
||||
item.type === "tool_call" &&
|
||||
item.name === "agent_finished" &&
|
||||
item.detail.type === "plain_text" &&
|
||||
item.detail.label === child.title &&
|
||||
item.detail.text?.includes(child.agentId) &&
|
||||
item.detail.text.includes(`Server: ${child.serverId}`),
|
||||
).length;
|
||||
return timeline.entries
|
||||
.flatMap(({ item }) =>
|
||||
item.type === "tool_call" && item.agentMessage ? [item.agentMessage] : [],
|
||||
)
|
||||
.filter(
|
||||
(message) =>
|
||||
message.event === "finished" &&
|
||||
message.sender.id === child.agentId &&
|
||||
message.text.includes(`Server: ${child.serverId}`),
|
||||
).length;
|
||||
})
|
||||
.toBe(1);
|
||||
},
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
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";
|
||||
@@ -20,7 +19,6 @@ interface CreateTerminalInput {
|
||||
name: string;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
defaultColors?: TerminalDefaultColors;
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
@@ -71,11 +69,14 @@ export class TerminalE2EHarness {
|
||||
}
|
||||
|
||||
async createTerminal(input: CreateTerminalInput): Promise<TerminalInstance> {
|
||||
const options = {
|
||||
...(input.command || input.args ? { command: input.command, args: input.args } : {}),
|
||||
workspaceId: this.workspaceId,
|
||||
...(input.defaultColors ? { defaultColors: input.defaultColors } : {}),
|
||||
};
|
||||
const options =
|
||||
input.command || input.args
|
||||
? {
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
workspaceId: this.workspaceId,
|
||||
}
|
||||
: { workspaceId: this.workspaceId };
|
||||
const result = await this.client.createTerminal(
|
||||
this.tempRepo.path,
|
||||
input.name,
|
||||
|
||||
@@ -11,10 +11,6 @@ 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>;
|
||||
}
|
||||
@@ -32,8 +28,6 @@ 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. */
|
||||
@@ -73,7 +67,6 @@ function withUsageSupportFeature(
|
||||
enabled: boolean,
|
||||
providerUsageListOnly: boolean,
|
||||
usageSettingSupported: boolean,
|
||||
usageReportUpdates?: boolean,
|
||||
): string | null {
|
||||
const envelope = parseJson(message) as {
|
||||
type?: unknown;
|
||||
@@ -100,7 +93,6 @@ function withUsageSupportFeature(
|
||||
usageSetting: usageSettingSupported ? true : undefined,
|
||||
usageSources: enabled && !providerUsageListOnly,
|
||||
providerUsageList: enabled,
|
||||
...(usageReportUpdates !== undefined ? { usageReportUpdates } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -151,37 +143,12 @@ 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>();
|
||||
@@ -204,23 +171,10 @@ 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,
|
||||
@@ -308,26 +262,6 @@ 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(
|
||||
@@ -335,7 +269,6 @@ export async function installUsageReportsFixture(
|
||||
isUsageSupported(),
|
||||
providerUsageListOnly,
|
||||
options.usageSettingSupported ?? true,
|
||||
options.usageReportUpdates,
|
||||
)
|
||||
: null;
|
||||
const scope = agentUsageScope(message);
|
||||
@@ -354,24 +287,6 @@ 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();
|
||||
|
||||
-42
@@ -2,16 +2,12 @@ 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
|
||||
@@ -61,44 +57,6 @@ 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)
|
||||
|
||||
+2
-14
@@ -115,23 +115,11 @@ 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 composing = when (focus) {
|
||||
is ComposingTextOwner -> focus.isComposingText()
|
||||
is EditText -> focus.text != null && BaseInputConnection.getComposingSpanStart(focus.text) >= 0
|
||||
else -> false
|
||||
}
|
||||
val editable = (focus as? EditText)?.text
|
||||
val composing = editable != null && BaseInputConnection.getComposingSpanStart(editable) >= 0
|
||||
val terminalFocused = focus?.getTag(R.id.view_tag_native_id) == TERMINAL_INPUT_NATIVE_ID
|
||||
return HardwareKeyboard.dispatcher.dispatch(
|
||||
event,
|
||||
|
||||
@@ -18,7 +18,6 @@ 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"
|
||||
|
||||
-337
@@ -1,337 +0,0 @@
|
||||
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())
|
||||
}
|
||||
}
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.text.InputType
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import com.facebook.react.bridge.BridgeReactContext
|
||||
import com.facebook.react.uimanager.DisplayMetricsHolder
|
||||
import com.facebook.react.uimanager.ThemedReactContext
|
||||
import com.facebook.react.views.textinput.ReactEditText
|
||||
import com.facebook.react.views.textinput.ReactTextInputManager
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/**
|
||||
* Builds React Native's own text input and applies `nativeID` through its view manager, which is
|
||||
* how Fabric mounts the hidden terminal input. The app runs bridgeless, so the context is too.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class TerminalInputKeyboardTest {
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
|
||||
@Test fun terminalInputAsksTheKeyboardNotToLearnWhatIsTyped() {
|
||||
onInput("paseo-terminal-input") { input, editorInfo ->
|
||||
assertNotEquals(
|
||||
"The keyboard must not learn passwords typed at a terminal prompt",
|
||||
0,
|
||||
editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING,
|
||||
)
|
||||
assertEquals(
|
||||
"Suggestions stay off and the input stays multiline",
|
||||
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE,
|
||||
editorInfo.inputType and (InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or InputType.TYPE_TEXT_FLAG_MULTI_LINE),
|
||||
)
|
||||
val connection = checkNotNull(input.onCreateInputConnection(EditorInfo()))
|
||||
connection.setComposingText("su", 1)
|
||||
connection.commitText("sudo ls", 1)
|
||||
connection.deleteSurroundingText(1, 0)
|
||||
assertEquals("sudo l", input.text.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun otherInputsKeepPersonalizedLearning() {
|
||||
onInput("message-composer") { _, editorInfo ->
|
||||
assertEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING)
|
||||
}
|
||||
}
|
||||
|
||||
private fun onInput(nativeId: String, check: (ReactEditText, EditorInfo) -> Unit) {
|
||||
TerminalInputKeyboard.install()
|
||||
instrumentation.runOnMainSync {
|
||||
val app = instrumentation.targetContext
|
||||
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(app)
|
||||
val react = object : BridgeReactContext(app) {
|
||||
override fun isBridgeless() = true
|
||||
}
|
||||
val input = ReactEditText(ThemedReactContext(react, app, null, -1))
|
||||
input.inputType = InputType.TYPE_CLASS_TEXT or
|
||||
InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS or
|
||||
InputType.TYPE_TEXT_FLAG_MULTI_LINE
|
||||
ReactTextInputManager().setNativeId(input, nativeId)
|
||||
val editorInfo = EditorInfo()
|
||||
input.onCreateInputConnection(editorInfo)
|
||||
check(input, editorInfo)
|
||||
}
|
||||
}
|
||||
}
|
||||
-168
@@ -1,168 +0,0 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.content.Context
|
||||
import android.graphics.Rect
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.inputmethod.BaseInputConnection
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputConnection
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
import expo.modules.kotlin.viewevent.EventDispatcher
|
||||
import sh.paseo.keyboard.ComposingTextOwner
|
||||
|
||||
/**
|
||||
* Focusable 1x1 native Android text editor view that owns the terminal's [InputConnection] and
|
||||
* physical keyboard [onKeyDown] delivery directly, bypassing React Native's `TextInput`.
|
||||
*
|
||||
* Implements [ComposingTextOwner] so `PaseoHardwareKeyboardModule` reads active IME composition
|
||||
* reliably even after React Native's `BaseViewManager.setTestId` overwrites `View.getTag()`.
|
||||
*/
|
||||
class PaseoTerminalInputView(context: Context) : View(context), ComposingTextOwner {
|
||||
private val onTerminalInput by EventDispatcher<Map<String, String>>()
|
||||
private val onTerminalKey by EventDispatcher<Map<String, Any>>()
|
||||
private val onFocusChange by EventDispatcher<Map<String, Boolean>>()
|
||||
|
||||
private val editable = SpannableStringBuilder()
|
||||
private var inputSink: ((String) -> Unit)? = null
|
||||
private var keySink: ((TerminalKeyPayload) -> Unit)? = null
|
||||
private var focusSink: ((Boolean) -> Unit)? = null
|
||||
private var inputConnection: TerminalInputConnection? = null
|
||||
|
||||
init {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
importantForAutofill = IMPORTANT_FOR_AUTOFILL_NO
|
||||
contentDescription = "Terminal input"
|
||||
}
|
||||
|
||||
override fun isComposingText(): Boolean =
|
||||
BaseInputConnection.getComposingSpanStart(editable) >= 0
|
||||
|
||||
override fun onCheckIsTextEditor(): Boolean = true
|
||||
|
||||
override fun onCreateInputConnection(outAttrs: EditorInfo): InputConnection {
|
||||
TerminalInputConnection.configureEditorInfo(outAttrs)
|
||||
val connection = ensureInputConnection()
|
||||
connection.resetState()
|
||||
return connection
|
||||
}
|
||||
|
||||
override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
|
||||
if (ensureInputConnection().handleKeyDown(keyCode, event)) {
|
||||
return true
|
||||
}
|
||||
return super.onKeyDown(keyCode, event)
|
||||
}
|
||||
|
||||
override fun onKeyUp(keyCode: Int, event: KeyEvent): Boolean {
|
||||
if (ensureInputConnection().handleKeyUp(keyCode, event)) {
|
||||
return true
|
||||
}
|
||||
return super.onKeyUp(keyCode, event)
|
||||
}
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
override fun onKeyMultiple(keyCode: Int, repeatCount: Int, event: KeyEvent): Boolean {
|
||||
if (ensureInputConnection().handleKeyMultiple(event)) {
|
||||
return true
|
||||
}
|
||||
return super.onKeyMultiple(keyCode, repeatCount, event)
|
||||
}
|
||||
|
||||
override fun onFocusChanged(gainFocus: Boolean, direction: Int, previouslyFocusedRect: Rect?) {
|
||||
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect)
|
||||
if (!gainFocus) {
|
||||
inputConnection?.resetState()
|
||||
}
|
||||
val sink = focusSink
|
||||
if (sink != null) {
|
||||
sink(gainFocus)
|
||||
} else {
|
||||
onFocusChange(mapOf("focused" to gainFocus))
|
||||
}
|
||||
}
|
||||
|
||||
fun focusInput() {
|
||||
showKeyboard()
|
||||
}
|
||||
|
||||
fun showKeyboard() {
|
||||
val show: () -> Unit = {
|
||||
if (!hasFocus()) {
|
||||
requestFocus()
|
||||
}
|
||||
val imm = context.getSystemService(InputMethodManager::class.java)
|
||||
imm?.showSoftInput(this, 0)
|
||||
}
|
||||
if (hasFocus()) {
|
||||
show()
|
||||
} else {
|
||||
requestFocus()
|
||||
post(show)
|
||||
}
|
||||
}
|
||||
|
||||
fun blurInput() {
|
||||
inputConnection?.resetState()
|
||||
if (hasFocus()) {
|
||||
clearFocus()
|
||||
}
|
||||
val imm = context.getSystemService(InputMethodManager::class.java)
|
||||
imm?.hideSoftInputFromWindow(windowToken, 0)
|
||||
}
|
||||
|
||||
private fun ensureInputConnection(): TerminalInputConnection {
|
||||
val existing = inputConnection
|
||||
if (existing != null) return existing
|
||||
val created = TerminalInputConnection(
|
||||
targetView = this,
|
||||
sharedEditable = editable,
|
||||
onInput = ::emitInput,
|
||||
onTerminalKey = ::emitKey,
|
||||
)
|
||||
inputConnection = created
|
||||
return created
|
||||
}
|
||||
|
||||
private fun emitInput(data: String) {
|
||||
val sink = inputSink
|
||||
if (sink != null) {
|
||||
sink(data)
|
||||
} else {
|
||||
onTerminalInput(mapOf("data" to data))
|
||||
}
|
||||
}
|
||||
|
||||
private fun emitKey(payload: TerminalKeyPayload) {
|
||||
val sink = keySink
|
||||
if (sink != null) {
|
||||
sink(payload)
|
||||
} else {
|
||||
onTerminalKey(
|
||||
mapOf(
|
||||
"key" to payload.key,
|
||||
"ctrl" to payload.ctrl,
|
||||
"shift" to payload.shift,
|
||||
"alt" to payload.alt,
|
||||
"meta" to payload.meta,
|
||||
),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
internal fun createForTest(
|
||||
context: Context,
|
||||
onInput: (String) -> Unit = {},
|
||||
onTerminalKey: (TerminalKeyPayload) -> Unit = {},
|
||||
onFocus: (Boolean) -> Unit = {},
|
||||
): PaseoTerminalInputView =
|
||||
PaseoTerminalInputView(context).apply {
|
||||
inputSink = onInput
|
||||
keySink = onTerminalKey
|
||||
focusSink = onFocus
|
||||
}
|
||||
}
|
||||
}
|
||||
+2
-8
@@ -7,6 +7,8 @@ class PaseoTerminalModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoTerminal")
|
||||
|
||||
OnCreate { TerminalInputKeyboard.install() }
|
||||
|
||||
View(PaseoTerminalView::class) {
|
||||
Events("onCellMetrics")
|
||||
|
||||
@@ -20,13 +22,5 @@ class PaseoTerminalModule : Module() {
|
||||
|
||||
OnViewDidUpdateProps { view: PaseoTerminalView -> view.commit() }
|
||||
}
|
||||
|
||||
View(PaseoTerminalInputView::class) {
|
||||
Events("onTerminalInput", "onTerminalKey", "onFocusChange")
|
||||
|
||||
AsyncFunction("focusInput") { view: PaseoTerminalInputView -> view.focusInput() }
|
||||
AsyncFunction("showKeyboard") { view: PaseoTerminalInputView -> view.showKeyboard() }
|
||||
AsyncFunction("blurInput") { view: PaseoTerminalInputView -> view.blurInput() }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
-501
@@ -1,501 +0,0 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.text.Editable
|
||||
import android.text.InputType
|
||||
import android.text.Selection
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.inputmethod.BaseInputConnection
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.view.inputmethod.InputMethodManager
|
||||
|
||||
internal data class TerminalKeyPayload(
|
||||
val key: String,
|
||||
val ctrl: Boolean = false,
|
||||
val shift: Boolean = false,
|
||||
val alt: Boolean = false,
|
||||
val meta: Boolean = false,
|
||||
)
|
||||
|
||||
/**
|
||||
* Single authoritative IME + key stream for the Android native terminal.
|
||||
*
|
||||
* Keeps a private [SpannableStringBuilder] so Android IMEs can compose Hangul, Pinyin, and Latin
|
||||
* candidates normally, diffs the editable against what was last sent to the PTY once each batch
|
||||
* edit settles, and clears the editable as soon as no composing span remains.
|
||||
*/
|
||||
internal class TerminalInputConnection(
|
||||
private val targetView: View,
|
||||
private val sharedEditable: SpannableStringBuilder = SpannableStringBuilder(),
|
||||
private val onInput: (String) -> Unit,
|
||||
private val onTerminalKey: (TerminalKeyPayload) -> Unit,
|
||||
) : BaseInputConnection(targetView, true) {
|
||||
private var batchEditDepth = 0
|
||||
private var lastSentText = ""
|
||||
private var pendingBackspaces = 0
|
||||
private var deadAccent = 0
|
||||
private var lastSelStart = 0
|
||||
private var lastSelEnd = 0
|
||||
private var lastCompStart = -1
|
||||
private var lastCompEnd = -1
|
||||
|
||||
override fun getEditable(): Editable = sharedEditable
|
||||
|
||||
override fun beginBatchEdit(): Boolean {
|
||||
batchEditDepth += 1
|
||||
return super.beginBatchEdit()
|
||||
}
|
||||
|
||||
override fun endBatchEdit(): Boolean {
|
||||
val result = super.endBatchEdit()
|
||||
if (batchEditDepth > 0) {
|
||||
batchEditDepth -= 1
|
||||
}
|
||||
if (batchEditDepth == 0) {
|
||||
flush()
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
override fun setComposingText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
val result = super.setComposingText(text, newCursorPosition)
|
||||
if (batchEditDepth == 0) flush()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun setComposingRegion(start: Int, end: Int): Boolean {
|
||||
val result = super.setComposingRegion(start, end)
|
||||
if (batchEditDepth == 0) flush()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun commitText(text: CharSequence?, newCursorPosition: Int): Boolean {
|
||||
val result = super.commitText(text, newCursorPosition)
|
||||
if (batchEditDepth == 0) flush()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun finishComposingText(): Boolean {
|
||||
val result = super.finishComposingText()
|
||||
if (batchEditDepth == 0) flush()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun deleteSurroundingText(beforeLength: Int, afterLength: Int): Boolean {
|
||||
if (beforeLength <= 0 && afterLength <= 0) return true
|
||||
val lengthBefore = sharedEditable.length
|
||||
val result = super.deleteSurroundingText(beforeLength, afterLength)
|
||||
val deletedChars = maxOf(0, lengthBefore - sharedEditable.length)
|
||||
var remaining = maxOf(0, beforeLength - deletedChars)
|
||||
if (remaining > 0 && sharedEditable.isNotEmpty()) {
|
||||
val toTrim = minOf(remaining, sharedEditable.length)
|
||||
sharedEditable.delete(sharedEditable.length - toTrim, sharedEditable.length)
|
||||
Selection.setSelection(sharedEditable, sharedEditable.length)
|
||||
remaining -= toTrim
|
||||
}
|
||||
if (remaining > 0) {
|
||||
pendingBackspaces += remaining
|
||||
}
|
||||
if (batchEditDepth == 0) flush()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun deleteSurroundingTextInCodePoints(beforeLength: Int, afterLength: Int): Boolean {
|
||||
if (beforeLength <= 0 && afterLength <= 0) return true
|
||||
val codePointsBefore = Character.codePointCount(sharedEditable, 0, sharedEditable.length)
|
||||
val result = super.deleteSurroundingTextInCodePoints(beforeLength, afterLength)
|
||||
val codePointsAfter = Character.codePointCount(sharedEditable, 0, sharedEditable.length)
|
||||
val deletedCodePoints = maxOf(0, codePointsBefore - codePointsAfter)
|
||||
var remaining = maxOf(0, beforeLength - deletedCodePoints)
|
||||
if (remaining > 0 && codePointsAfter > 0) {
|
||||
val toTrim = minOf(remaining, codePointsAfter)
|
||||
val trimStart = Character.offsetByCodePoints(sharedEditable, sharedEditable.length, -toTrim)
|
||||
sharedEditable.delete(trimStart, sharedEditable.length)
|
||||
Selection.setSelection(sharedEditable, sharedEditable.length)
|
||||
remaining -= toTrim
|
||||
}
|
||||
if (remaining > 0) {
|
||||
pendingBackspaces += remaining
|
||||
}
|
||||
if (batchEditDepth == 0) flush()
|
||||
return result
|
||||
}
|
||||
|
||||
override fun performEditorAction(editorAction: Int): Boolean {
|
||||
submitEnter()
|
||||
return true
|
||||
}
|
||||
|
||||
override fun sendKeyEvent(event: KeyEvent): Boolean {
|
||||
return when (event.action) {
|
||||
KeyEvent.ACTION_DOWN -> handleKeyDown(event.keyCode, event)
|
||||
KeyEvent.ACTION_UP -> isHandledKeyCode(event.keyCode, event)
|
||||
@Suppress("DEPRECATION")
|
||||
KeyEvent.ACTION_MULTIPLE -> handleKeyMultiple(event)
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
override fun closeConnection() {
|
||||
resetState()
|
||||
super.closeConnection()
|
||||
}
|
||||
|
||||
internal fun resetState() {
|
||||
batchEditDepth = 0
|
||||
pendingBackspaces = 0
|
||||
deadAccent = 0
|
||||
lastSentText = ""
|
||||
clearEditableSilently()
|
||||
lastSelStart = 0
|
||||
lastSelEnd = 0
|
||||
lastCompStart = -1
|
||||
lastCompEnd = -1
|
||||
}
|
||||
|
||||
internal fun handleKeyDown(keyCode: Int, event: KeyEvent): Boolean {
|
||||
if (KeyEvent.isModifierKey(keyCode)) return false
|
||||
if (event.isMetaPressed) return false
|
||||
|
||||
when (keyCode) {
|
||||
KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> {
|
||||
submitEnter(altPressed = event.isAltPressed && !event.isCtrlPressed && !event.isShiftPressed)
|
||||
return true
|
||||
}
|
||||
KeyEvent.KEYCODE_DEL -> {
|
||||
handleDeleteKey(altPressed = event.isAltPressed && !event.isCtrlPressed)
|
||||
return true
|
||||
}
|
||||
KeyEvent.KEYCODE_FORWARD_DEL -> {
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
onInput("\u001b[3~")
|
||||
return true
|
||||
}
|
||||
KeyEvent.KEYCODE_TAB -> {
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
val sequence = when {
|
||||
event.isShiftPressed && !event.isCtrlPressed && !event.isAltPressed -> "\u001b[Z"
|
||||
event.isAltPressed && !event.isCtrlPressed -> "\u001b\t"
|
||||
else -> "\t"
|
||||
}
|
||||
onInput(sequence)
|
||||
return true
|
||||
}
|
||||
KeyEvent.KEYCODE_ESCAPE -> {
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
onInput("\u001b")
|
||||
return true
|
||||
}
|
||||
KeyEvent.KEYCODE_DPAD_UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT -> {
|
||||
deadAccent = 0
|
||||
val name = when (keyCode) {
|
||||
KeyEvent.KEYCODE_DPAD_UP -> "ArrowUp"
|
||||
KeyEvent.KEYCODE_DPAD_DOWN -> "ArrowDown"
|
||||
KeyEvent.KEYCODE_DPAD_LEFT -> "ArrowLeft"
|
||||
else -> "ArrowRight"
|
||||
}
|
||||
onTerminalKey(
|
||||
TerminalKeyPayload(
|
||||
key = name,
|
||||
ctrl = event.isCtrlPressed,
|
||||
shift = event.isShiftPressed,
|
||||
alt = event.isAltPressed,
|
||||
meta = event.isMetaPressed,
|
||||
),
|
||||
)
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
if (event.isCtrlPressed) {
|
||||
val ctrlSeq = encodeCtrlKey(keyCode, event) ?: return false
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
onInput(if (event.isAltPressed) "\u001b$ctrlSeq" else ctrlSeq)
|
||||
return true
|
||||
}
|
||||
|
||||
if (event.isAltPressed) {
|
||||
val withAlt = event.getUnicodeChar(event.metaState)
|
||||
val withoutAlt = event.getUnicodeChar(event.metaState and KeyEvent.META_ALT_MASK.inv())
|
||||
if (withAlt != 0 && withAlt != withoutAlt) {
|
||||
return handleUnicodeChar(withAlt)
|
||||
}
|
||||
if (withoutAlt != 0 && (withoutAlt and KeyCharacterMap.COMBINING_ACCENT) == 0) {
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
onInput("\u001b" + String(Character.toChars(withoutAlt)))
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
val unicodeChar = event.getUnicodeChar(event.metaState)
|
||||
if (unicodeChar != 0) {
|
||||
return handleUnicodeChar(unicodeChar)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
internal fun handleKeyUp(keyCode: Int, event: KeyEvent): Boolean =
|
||||
isHandledKeyCode(keyCode, event)
|
||||
|
||||
@Suppress("DEPRECATION")
|
||||
internal fun handleKeyMultiple(event: KeyEvent): Boolean {
|
||||
val characters = event.characters ?: return false
|
||||
if (characters.isEmpty()) return false
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
onInput(normalizeLineEndings(characters))
|
||||
return true
|
||||
}
|
||||
|
||||
private fun isHandledKeyCode(keyCode: Int, event: KeyEvent): Boolean {
|
||||
if (KeyEvent.isModifierKey(keyCode) || event.isMetaPressed) return false
|
||||
return when (keyCode) {
|
||||
KeyEvent.KEYCODE_ENTER,
|
||||
KeyEvent.KEYCODE_NUMPAD_ENTER,
|
||||
KeyEvent.KEYCODE_DEL,
|
||||
KeyEvent.KEYCODE_FORWARD_DEL,
|
||||
KeyEvent.KEYCODE_TAB,
|
||||
KeyEvent.KEYCODE_ESCAPE,
|
||||
KeyEvent.KEYCODE_DPAD_UP,
|
||||
KeyEvent.KEYCODE_DPAD_DOWN,
|
||||
KeyEvent.KEYCODE_DPAD_LEFT,
|
||||
KeyEvent.KEYCODE_DPAD_RIGHT -> true
|
||||
else -> {
|
||||
if (event.isCtrlPressed) return encodeCtrlKey(keyCode, event) != null
|
||||
val plainMeta = event.metaState and KeyEvent.META_ALT_MASK.inv()
|
||||
event.getUnicodeChar(event.metaState) != 0 ||
|
||||
(event.isAltPressed && event.getUnicodeChar(plainMeta) != 0)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private fun handleUnicodeChar(unicodeChar: Int): Boolean {
|
||||
if (unicodeChar and KeyCharacterMap.COMBINING_ACCENT != 0) {
|
||||
deadAccent = unicodeChar and KeyCharacterMap.COMBINING_ACCENT_MASK
|
||||
return true
|
||||
}
|
||||
var codePoint = unicodeChar
|
||||
if (deadAccent != 0) {
|
||||
val combined = KeyEvent.getDeadChar(deadAccent, codePoint)
|
||||
val previousAccent = deadAccent
|
||||
deadAccent = 0
|
||||
if (combined != 0) {
|
||||
codePoint = combined
|
||||
} else {
|
||||
flushAndClear()
|
||||
val accentChar =
|
||||
KeyEvent.getDeadChar(previousAccent, ' '.code).takeIf { it != 0 } ?: previousAccent
|
||||
onInput(String(Character.toChars(accentChar)) + String(Character.toChars(codePoint)))
|
||||
return true
|
||||
}
|
||||
}
|
||||
flushAndClear()
|
||||
onInput(String(Character.toChars(codePoint)))
|
||||
return true
|
||||
}
|
||||
|
||||
private fun handleDeleteKey(altPressed: Boolean) {
|
||||
deadAccent = 0
|
||||
if (altPressed) {
|
||||
flushAndClear()
|
||||
onInput("\u001b\u007f")
|
||||
return
|
||||
}
|
||||
if (sharedEditable.isNotEmpty()) {
|
||||
val end = sharedEditable.length
|
||||
val prevCpStart = Character.offsetByCodePoints(sharedEditable, end, -1)
|
||||
sharedEditable.delete(prevCpStart, end)
|
||||
Selection.setSelection(sharedEditable, sharedEditable.length)
|
||||
flush()
|
||||
} else {
|
||||
onInput("\u007f")
|
||||
}
|
||||
}
|
||||
|
||||
private fun submitEnter(altPressed: Boolean = false) {
|
||||
deadAccent = 0
|
||||
flushAndClear()
|
||||
onInput(if (altPressed) "\u001b\r" else "\r")
|
||||
}
|
||||
|
||||
private fun flush() {
|
||||
val out = StringBuilder()
|
||||
if (pendingBackspaces > 0) {
|
||||
repeat(pendingBackspaces) { out.append('\u007f') }
|
||||
pendingBackspaces = 0
|
||||
}
|
||||
|
||||
val currentText = sharedEditable.toString()
|
||||
val diff = computeDiff(lastSentText, currentText)
|
||||
if (diff.isNotEmpty()) {
|
||||
out.append(normalizeLineEndings(diff))
|
||||
}
|
||||
|
||||
val compStart = getComposingSpanStart(sharedEditable)
|
||||
val compEnd = getComposingSpanEnd(sharedEditable)
|
||||
val isComposing = compStart >= 0 && compEnd > compStart
|
||||
|
||||
if (!isComposing) {
|
||||
val hadText = sharedEditable.isNotEmpty()
|
||||
if (hadText || compStart >= 0) {
|
||||
clearEditableSilently()
|
||||
}
|
||||
lastSentText = ""
|
||||
if (hadText) {
|
||||
// The IME just advanced its cursor for the committed text; report the reset to 0, 0.
|
||||
forceUpdateSelection(0, 0, -1, -1)
|
||||
} else {
|
||||
notifySelectionIfChanged(0, 0, -1, -1)
|
||||
}
|
||||
} else {
|
||||
lastSentText = currentText
|
||||
val selStart = maxOf(0, Selection.getSelectionStart(sharedEditable))
|
||||
val selEnd = maxOf(0, Selection.getSelectionEnd(sharedEditable))
|
||||
notifySelectionIfChanged(selStart, selEnd, compStart, compEnd)
|
||||
}
|
||||
|
||||
if (out.isNotEmpty()) {
|
||||
onInput(out.toString())
|
||||
}
|
||||
}
|
||||
|
||||
private fun flushAndClear() {
|
||||
batchEditDepth = 0
|
||||
val hadText = sharedEditable.isNotEmpty()
|
||||
val out = StringBuilder()
|
||||
if (pendingBackspaces > 0) {
|
||||
repeat(pendingBackspaces) { out.append('\u007f') }
|
||||
pendingBackspaces = 0
|
||||
}
|
||||
val currentText = sharedEditable.toString()
|
||||
val diff = computeDiff(lastSentText, currentText)
|
||||
if (diff.isNotEmpty()) {
|
||||
out.append(normalizeLineEndings(diff))
|
||||
}
|
||||
if (hadText || getComposingSpanStart(sharedEditable) >= 0) {
|
||||
clearEditableSilently()
|
||||
}
|
||||
lastSentText = ""
|
||||
if (hadText || lastSelStart != 0 || lastSelEnd != 0 || lastCompStart != -1 || lastCompEnd != -1) {
|
||||
forceUpdateSelection(0, 0, -1, -1)
|
||||
}
|
||||
if (out.isNotEmpty()) {
|
||||
onInput(out.toString())
|
||||
}
|
||||
}
|
||||
|
||||
private fun clearEditableSilently() {
|
||||
removeComposingSpans(sharedEditable)
|
||||
sharedEditable.clear()
|
||||
Selection.setSelection(sharedEditable, 0)
|
||||
}
|
||||
|
||||
private fun notifySelectionIfChanged(selStart: Int, selEnd: Int, compStart: Int, compEnd: Int) {
|
||||
if (
|
||||
selStart == lastSelStart &&
|
||||
selEnd == lastSelEnd &&
|
||||
compStart == lastCompStart &&
|
||||
compEnd == lastCompEnd
|
||||
) {
|
||||
return
|
||||
}
|
||||
forceUpdateSelection(selStart, selEnd, compStart, compEnd)
|
||||
}
|
||||
|
||||
private fun forceUpdateSelection(selStart: Int, selEnd: Int, compStart: Int, compEnd: Int) {
|
||||
lastSelStart = selStart
|
||||
lastSelEnd = selEnd
|
||||
lastCompStart = compStart
|
||||
lastCompEnd = compEnd
|
||||
val imm = targetView.context.getSystemService(InputMethodManager::class.java) ?: return
|
||||
if (imm.isActive(targetView)) {
|
||||
imm.updateSelection(targetView, selStart, selEnd, compStart, compEnd)
|
||||
}
|
||||
}
|
||||
|
||||
companion object {
|
||||
internal fun configureEditorInfo(outAttrs: EditorInfo) {
|
||||
outAttrs.inputType = InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
|
||||
outAttrs.imeOptions =
|
||||
EditorInfo.IME_ACTION_NONE or
|
||||
EditorInfo.IME_FLAG_NO_FULLSCREEN or
|
||||
EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||
outAttrs.initialSelStart = 0
|
||||
outAttrs.initialSelEnd = 0
|
||||
}
|
||||
|
||||
private fun normalizeLineEndings(text: String): String =
|
||||
text.replace("\r\n", "\r").replace("\n", "\r")
|
||||
|
||||
private fun computeDiff(previous: String, next: String): String {
|
||||
if (previous == next) return ""
|
||||
val prevCps = previous.toCodePoints()
|
||||
val nextCps = next.toCodePoints()
|
||||
var common = 0
|
||||
val limit = minOf(prevCps.size, nextCps.size)
|
||||
while (common < limit && prevCps[common] == nextCps[common]) {
|
||||
common += 1
|
||||
}
|
||||
val removed = prevCps.size - common
|
||||
val out = StringBuilder(removed + (nextCps.size - common))
|
||||
repeat(removed) { out.append('\u007f') }
|
||||
for (i in common until nextCps.size) {
|
||||
out.appendCodePoint(nextCps[i])
|
||||
}
|
||||
return out.toString()
|
||||
}
|
||||
|
||||
private fun String.toCodePoints(): IntArray {
|
||||
val count = codePointCount(0, length)
|
||||
val result = IntArray(count)
|
||||
var offset = 0
|
||||
var index = 0
|
||||
while (offset < length) {
|
||||
val cp = codePointAt(offset)
|
||||
result[index++] = cp
|
||||
offset += Character.charCount(cp)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
private fun encodeCtrlKey(keyCode: Int, event: KeyEvent): String? {
|
||||
val unctrlMeta =
|
||||
event.metaState and
|
||||
KeyEvent.META_CTRL_MASK.inv() and
|
||||
KeyEvent.META_ALT_MASK.inv() and
|
||||
KeyEvent.META_META_MASK.inv()
|
||||
val unicode = event.getUnicodeChar(unctrlMeta)
|
||||
val ch = when {
|
||||
unicode != 0 -> unicode.toChar()
|
||||
keyCode in KeyEvent.KEYCODE_A..KeyEvent.KEYCODE_Z ->
|
||||
('a'.code + keyCode - KeyEvent.KEYCODE_A).toChar()
|
||||
keyCode == KeyEvent.KEYCODE_SPACE -> ' '
|
||||
else -> return null
|
||||
}
|
||||
val upper = ch.uppercaseChar()
|
||||
return when {
|
||||
upper in 'A'..'Z' -> (upper.code - 64).toChar().toString()
|
||||
ch == ' ' || ch == '@' || ch == '2' -> "\u0000"
|
||||
ch == '[' || ch == '3' -> "\u001b"
|
||||
ch == '\\' || ch == '4' -> "\u001c"
|
||||
ch == ']' || ch == '5' -> "\u001d"
|
||||
ch == '^' || ch == '6' -> "\u001e"
|
||||
ch == '_' || ch == '/' || ch == '7' -> "\u001f"
|
||||
ch == '8' || ch == '?' -> "\u007f"
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import android.widget.TextView
|
||||
import com.facebook.react.bridge.UiThreadUtil
|
||||
import com.facebook.react.uimanager.util.ReactFindViewUtil
|
||||
|
||||
// Matched against the hidden terminal input's `nativeID`
|
||||
// (TERMINAL_INPUT_NATIVE_ID in terminal-input.native.tsx).
|
||||
private const val TERMINAL_INPUT_NATIVE_ID = "paseo-terminal-input"
|
||||
|
||||
/**
|
||||
* Keeps what is typed at a terminal prompt, such as a `sudo` password, out of the keyboard's
|
||||
* learned words. React Native's TextInput has no prop for IME_FLAG_NO_PERSONALIZED_LEARNING, so the
|
||||
* flag is added when the input receives its `nativeID`, before it can take focus.
|
||||
*
|
||||
* React Native replaces `imeOptions` when `returnKeyType` or `disableFullscreenUI` is set, so the
|
||||
* terminal input sets neither.
|
||||
*/
|
||||
internal object TerminalInputKeyboard : ReactFindViewUtil.OnMultipleViewsFoundListener {
|
||||
fun install() {
|
||||
UiThreadUtil.runOnUiThread {
|
||||
ReactFindViewUtil.addViewsListener(this, setOf(TERMINAL_INPUT_NATIVE_ID))
|
||||
}
|
||||
}
|
||||
|
||||
override fun onViewFound(view: View, nativeId: String) {
|
||||
val input = view as? TextView ?: return
|
||||
input.imeOptions = input.imeOptions or EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
import { requireNativeView } from "expo";
|
||||
import { forwardRef, useCallback, type Ref } from "react";
|
||||
import type { ViewProps } from "react-native";
|
||||
import type {
|
||||
PaseoTerminalInputKeyEvent,
|
||||
PaseoTerminalInputViewHandle,
|
||||
PaseoTerminalInputViewProps,
|
||||
} from "./terminal-input-view";
|
||||
|
||||
export type {
|
||||
PaseoTerminalInputKeyEvent,
|
||||
PaseoTerminalInputViewHandle,
|
||||
PaseoTerminalInputViewProps,
|
||||
};
|
||||
|
||||
interface NativePaseoTerminalInputViewProps extends ViewProps {
|
||||
ref?: Ref<PaseoTerminalInputViewHandle>;
|
||||
onTerminalInput?: (event: { nativeEvent: { data: string } }) => void;
|
||||
onTerminalKey?: (event: { nativeEvent: PaseoTerminalInputKeyEvent }) => void;
|
||||
onFocusChange?: (event: { nativeEvent: { focused: boolean } }) => void;
|
||||
}
|
||||
|
||||
const NativePaseoTerminalInputView = requireNativeView<NativePaseoTerminalInputViewProps>(
|
||||
"PaseoTerminal",
|
||||
"PaseoTerminalInputView",
|
||||
);
|
||||
|
||||
export const PaseoTerminalInputView = forwardRef<
|
||||
PaseoTerminalInputViewHandle,
|
||||
PaseoTerminalInputViewProps
|
||||
>(function PaseoTerminalInputView(
|
||||
{ onTerminalInput, onTerminalKey, onFocusChange, ...props },
|
||||
ref,
|
||||
) {
|
||||
const handleTerminalInput = useCallback(
|
||||
(event: { nativeEvent: { data: string } }) => onTerminalInput?.(event.nativeEvent.data),
|
||||
[onTerminalInput],
|
||||
);
|
||||
const handleTerminalKey = useCallback(
|
||||
(event: { nativeEvent: PaseoTerminalInputKeyEvent }) => onTerminalKey?.(event.nativeEvent),
|
||||
[onTerminalKey],
|
||||
);
|
||||
const handleFocusChange = useCallback(
|
||||
(event: { nativeEvent: { focused: boolean } }) => onFocusChange?.(event.nativeEvent.focused),
|
||||
[onFocusChange],
|
||||
);
|
||||
|
||||
return (
|
||||
<NativePaseoTerminalInputView
|
||||
{...props}
|
||||
ref={ref}
|
||||
onTerminalInput={handleTerminalInput}
|
||||
onTerminalKey={handleTerminalKey}
|
||||
onFocusChange={handleFocusChange}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -1,32 +0,0 @@
|
||||
import { forwardRef, type Ref } from "react";
|
||||
import type { ViewProps } from "react-native";
|
||||
|
||||
export interface PaseoTerminalInputViewHandle {
|
||||
focusInput: () => Promise<void>;
|
||||
showKeyboard: () => Promise<void>;
|
||||
blurInput: () => Promise<void>;
|
||||
}
|
||||
|
||||
export interface PaseoTerminalInputKeyEvent {
|
||||
key: string;
|
||||
ctrl: boolean;
|
||||
shift: boolean;
|
||||
alt: boolean;
|
||||
meta: boolean;
|
||||
}
|
||||
|
||||
export interface PaseoTerminalInputViewProps extends ViewProps {
|
||||
onTerminalInput?: (data: string) => void;
|
||||
onTerminalKey?: (event: PaseoTerminalInputKeyEvent) => void;
|
||||
onFocusChange?: (focused: boolean) => void;
|
||||
}
|
||||
|
||||
export const PaseoTerminalInputView = forwardRef<
|
||||
PaseoTerminalInputViewHandle,
|
||||
PaseoTerminalInputViewProps
|
||||
>(function PaseoTerminalInputView(
|
||||
_props: PaseoTerminalInputViewProps,
|
||||
_ref: Ref<PaseoTerminalInputViewHandle>,
|
||||
) {
|
||||
return null;
|
||||
});
|
||||
@@ -1,70 +0,0 @@
|
||||
const { withMainActivity } = require("expo/config-plugins");
|
||||
|
||||
// Android 12+ "Bold text" sets Configuration.fontWeightAdjustment, and TextView
|
||||
// applies it when drawing text that has no explicit fontWeight or fontFamily.
|
||||
// React Native's TextLayoutManager measures that text without the adjustment, so
|
||||
// the wider glyphs overflow the measured box and trailing words or lines are
|
||||
// clipped (#4057, #10152, #10850).
|
||||
//
|
||||
// Override only fontWeightAdjustment on an empty sparse Configuration() so
|
||||
// unrelated configuration fields (uiMode, densityDpi, orientation,
|
||||
// screenWidthDp, fontScale, locales) keep flowing through onConfigurationChanged.
|
||||
//
|
||||
// Remove this plugin once upstream React Native's TextLayoutManager measures
|
||||
// with Configuration.fontWeightAdjustment.
|
||||
const IMPORTS = [
|
||||
"android.content.Context",
|
||||
"android.content.res.Configuration",
|
||||
"android.os.Build",
|
||||
];
|
||||
|
||||
const MARKER = "// paseo-ignore-bold-text";
|
||||
|
||||
const ATTACH_BASE_CONTEXT = ` ${MARKER}
|
||||
override fun attachBaseContext(newBase: Context) {
|
||||
val configuration = newBase.resources.configuration
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S && configuration.fontWeightAdjustment != 0) {
|
||||
val override = Configuration()
|
||||
override.fontWeightAdjustment = 0
|
||||
super.attachBaseContext(newBase.createConfigurationContext(override))
|
||||
return
|
||||
}
|
||||
super.attachBaseContext(newBase)
|
||||
}
|
||||
`;
|
||||
|
||||
const CLASS_DECLARATION = /class MainActivity : ReactActivity\(\) \{\n/;
|
||||
|
||||
function configureIgnoreBoldTextMainActivity(source) {
|
||||
if (source.includes(MARKER)) {
|
||||
return source;
|
||||
}
|
||||
if (!CLASS_DECLARATION.test(source)) {
|
||||
throw new Error("withAndroidIgnoreBoldText could not find the MainActivity class declaration");
|
||||
}
|
||||
if (/override fun attachBaseContext\(/.test(source)) {
|
||||
throw new Error("withAndroidIgnoreBoldText found an existing attachBaseContext override");
|
||||
}
|
||||
let contents = source;
|
||||
for (const name of IMPORTS) {
|
||||
if (!contents.includes(`import ${name}\n`)) {
|
||||
contents = contents.replace(/^package .*\n/m, (line) => `${line}import ${name}\n`);
|
||||
}
|
||||
}
|
||||
return contents.replace(CLASS_DECLARATION, (line) => `${line}${ATTACH_BASE_CONTEXT}\n`);
|
||||
}
|
||||
|
||||
function withAndroidIgnoreBoldText(config) {
|
||||
return withMainActivity(config, (modConfig) => {
|
||||
if (modConfig.modResults.language !== "kt") {
|
||||
throw new Error("withAndroidIgnoreBoldText expects a Kotlin MainActivity");
|
||||
}
|
||||
modConfig.modResults.contents = configureIgnoreBoldTextMainActivity(
|
||||
modConfig.modResults.contents,
|
||||
);
|
||||
return modConfig;
|
||||
});
|
||||
}
|
||||
|
||||
module.exports = withAndroidIgnoreBoldText;
|
||||
module.exports.configureIgnoreBoldTextMainActivity = configureIgnoreBoldTextMainActivity;
|
||||
@@ -783,56 +783,6 @@ it("presents received agent messages as attributed bubbles with the original tur
|
||||
});
|
||||
});
|
||||
|
||||
it("presents a finished notification as a compact tool call, not a received message", () => {
|
||||
const call = toolCall("notice", "agent_finished");
|
||||
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
|
||||
call.payload.data.detail = {
|
||||
type: "plain_text",
|
||||
label: "Child",
|
||||
text: "Agent child (Child) finished.",
|
||||
icon: "bot",
|
||||
};
|
||||
const result = createStreamPresentation()({
|
||||
...presentationOptions,
|
||||
transform: undefined,
|
||||
tail: [call],
|
||||
head: [],
|
||||
});
|
||||
expect(result.tail).toEqual([call]);
|
||||
});
|
||||
|
||||
// COMPAT(agentNotificationMetadata): rows from daemons that sent notification metadata.
|
||||
it("presents a legacy notification as the plain tool call current daemons send", () => {
|
||||
const call = toolCall("legacy", "agent_message");
|
||||
if (call.payload.source !== "agent") throw new Error("Expected agent tool");
|
||||
call.turnId = "turn";
|
||||
call.payload.data.detail = { type: "plain_text", text: "Done", icon: "bot" };
|
||||
call.payload.data.agentMessage = {
|
||||
event: "finished",
|
||||
sender: { id: "child", title: "Child" },
|
||||
text: "Done",
|
||||
};
|
||||
const result = createStreamPresentation()({
|
||||
...presentationOptions,
|
||||
transform: undefined,
|
||||
tail: [call],
|
||||
head: [],
|
||||
});
|
||||
expect(result.tail).toHaveLength(1);
|
||||
const [presented] = result.tail;
|
||||
if (presented?.kind !== "tool_call" || presented.payload.source !== "agent")
|
||||
throw new Error("Expected agent tool");
|
||||
expect(presented).toMatchObject({ id: call.id, turnId: "turn" });
|
||||
expect(presented.payload.data).toEqual({
|
||||
provider: "codex",
|
||||
callId: "legacy",
|
||||
name: "agent_finished",
|
||||
status: "completed",
|
||||
error: null,
|
||||
detail: { type: "plain_text", label: "Child", text: "Done", icon: "bot" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not reopen the previous turn while a new run waits for its first row", () => {
|
||||
const timestamp = new Date();
|
||||
const tail: StreamItem[] = [
|
||||
|
||||
@@ -9,14 +9,7 @@ import {
|
||||
type ToolCallDetailLevel,
|
||||
type ToolCallDetailProjection,
|
||||
} from "@/tool-calls/detail-level/projection";
|
||||
import type { AgentMessage } from "@getpaseo/protocol/agent-message";
|
||||
import { legacyAgentNotificationToolCall } from "@getpaseo/protocol/paseo-tool-presentation/index";
|
||||
import {
|
||||
isAgentToolCallItem,
|
||||
type AgentToolCallItem,
|
||||
type StreamItem,
|
||||
type UserMessageItem,
|
||||
} from "@/types/stream";
|
||||
import type { StreamItem, UserMessageItem } from "@/types/stream";
|
||||
import { collapseTurns, type TurnCollapse } from "./turn-collapse/model";
|
||||
import type { ReadingRowReplacements } from "./reading-anchor";
|
||||
|
||||
@@ -63,7 +56,6 @@ const NO_COLLAPSED_TURNS: StreamPresentation["turns"] = collapseTurns({
|
||||
/** Source messages reach plugins before display projection. */
|
||||
export function createStreamPresentation() {
|
||||
const userMessageCache = new WeakMap<UserMessageItem, UserMessageItem>();
|
||||
const legacyNotificationCache = new WeakMap<AgentToolCallItem, AgentToolCallItem>();
|
||||
|
||||
function presentUserMessage(item: UserMessageItem): UserMessageItem {
|
||||
const cached = userMessageCache.get(item);
|
||||
@@ -80,19 +72,6 @@ export function createStreamPresentation() {
|
||||
return projected;
|
||||
}
|
||||
|
||||
// COMPAT(agentNotificationMetadata): added in v0.18.1, remove after 2027-06-01.
|
||||
function presentLegacyNotification(item: AgentToolCallItem, message: AgentMessage): StreamItem {
|
||||
const cached = legacyNotificationCache.get(item);
|
||||
if (cached) return cached;
|
||||
const { agentMessage: _legacy, ...data } = item.payload.data;
|
||||
const presented: AgentToolCallItem = {
|
||||
...item,
|
||||
payload: { source: "agent", data: { ...data, ...legacyAgentNotificationToolCall(message) } },
|
||||
};
|
||||
legacyNotificationCache.set(item, presented);
|
||||
return presented;
|
||||
}
|
||||
|
||||
let historySource: StreamItem[] | undefined;
|
||||
let historyTransform: TimelineItemTransform | undefined;
|
||||
let historyRows: StreamItem[] = [];
|
||||
@@ -107,7 +86,7 @@ export function createStreamPresentation() {
|
||||
let collapsed: TurnCollapse | undefined;
|
||||
|
||||
function presentRows(item: StreamItem): StreamItem[] {
|
||||
if (isAgentToolCallItem(item)) {
|
||||
if (item.kind === "tool_call" && item.payload.source === "agent") {
|
||||
const message = item.payload.data.agentMessage;
|
||||
if (message?.event === "message") {
|
||||
return [
|
||||
@@ -122,7 +101,6 @@ export function createStreamPresentation() {
|
||||
},
|
||||
];
|
||||
}
|
||||
if (message) return [presentLegacyNotification(item, message)];
|
||||
}
|
||||
return [item.kind === "user_message" ? presentUserMessage(item) : item];
|
||||
}
|
||||
|
||||
@@ -22,35 +22,10 @@ function row(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "u
|
||||
};
|
||||
}
|
||||
|
||||
function assistantRow(
|
||||
index: number,
|
||||
height = ROW_HEIGHT,
|
||||
): Extract<StreamItem, { kind: "assistant_message" }> {
|
||||
return {
|
||||
kind: "assistant_message",
|
||||
id: `assistant-${index}`,
|
||||
text: String(height),
|
||||
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
|
||||
};
|
||||
}
|
||||
|
||||
function thoughtRow(index: number, height = ROW_HEIGHT): Extract<StreamItem, { kind: "thought" }> {
|
||||
return {
|
||||
kind: "thought",
|
||||
id: `thought-${index}`,
|
||||
text: String(height),
|
||||
status: "ready",
|
||||
timestamp: new Date(`2026-04-20T00:00:${String(index % 60).padStart(2, "0")}.000Z`),
|
||||
};
|
||||
}
|
||||
|
||||
const rowStyleByHeight = new Map<number, { height: number }>();
|
||||
|
||||
function renderRow(item: StreamItem) {
|
||||
const height =
|
||||
item.kind === "user_message" || item.kind === "assistant_message" || item.kind === "thought"
|
||||
? Number(item.text)
|
||||
: ROW_HEIGHT;
|
||||
const height = item.kind === "user_message" ? Number(item.text) : ROW_HEIGHT;
|
||||
let style = rowStyleByHeight.get(height);
|
||||
if (!style) {
|
||||
style = { height };
|
||||
@@ -82,30 +57,18 @@ type OlderHistoryInput = Pick<
|
||||
interface MountTimelineOptions {
|
||||
olderHistory?: OlderHistoryInput;
|
||||
isMobileBreakpoint?: boolean;
|
||||
historyVirtualized?: StreamItem[];
|
||||
viewportHeight?: number;
|
||||
}
|
||||
|
||||
function mountTimeline(
|
||||
historyMounted: StreamItem[],
|
||||
{
|
||||
olderHistory,
|
||||
isMobileBreakpoint = true,
|
||||
historyVirtualized = [],
|
||||
viewportHeight = VIEWPORT_HEIGHT,
|
||||
}: MountTimelineOptions = {},
|
||||
{ olderHistory, isMobileBreakpoint = true }: MountTimelineOptions = {},
|
||||
) {
|
||||
host.style.height = `${viewportHeight}px`;
|
||||
const strategy = createWebStreamStrategy({ isMobileBreakpoint });
|
||||
const viewportRef = React.createRef<StreamViewportHandle>();
|
||||
let currentInput: StreamRenderInput = {
|
||||
const input: StreamRenderInput = {
|
||||
agentId: "agent",
|
||||
segments: { historyVirtualized, historyMounted, liveHead: [] },
|
||||
boundary: {
|
||||
hasVirtualizedHistory: historyVirtualized.length > 0,
|
||||
hasMountedHistory: historyMounted.length > 0,
|
||||
hasLiveHead: false,
|
||||
},
|
||||
segments: { historyVirtualized: [], historyMounted, liveHead: [] },
|
||||
boundary: { hasVirtualizedHistory: false, hasMountedHistory: true, hasLiveHead: false },
|
||||
renderers: {
|
||||
renderHistoryVirtualizedRow: renderRow,
|
||||
renderHistoryMountedRow: renderRow,
|
||||
@@ -128,23 +91,8 @@ function mountTimeline(
|
||||
contentMaxWidth: DEFAULT_CONTENT_MAX_WIDTH,
|
||||
...olderHistory,
|
||||
};
|
||||
const render = (
|
||||
segments: Partial<StreamRenderInput["segments"]>,
|
||||
overrides: Partial<Omit<StreamRenderInput, "segments">> = {},
|
||||
) => {
|
||||
const nextSegments = { ...currentInput.segments, ...segments };
|
||||
currentInput = {
|
||||
...currentInput,
|
||||
...overrides,
|
||||
segments: nextSegments,
|
||||
boundary: {
|
||||
hasVirtualizedHistory: nextSegments.historyVirtualized.length > 0,
|
||||
hasMountedHistory: nextSegments.historyMounted.length > 0,
|
||||
hasLiveHead: nextSegments.liveHead.length > 0,
|
||||
},
|
||||
};
|
||||
root.render(strategy.render(currentInput));
|
||||
};
|
||||
const render = (segments: Partial<StreamRenderInput["segments"]>) =>
|
||||
root.render(strategy.render({ ...input, segments: { ...input.segments, ...segments } }));
|
||||
act(() => render({}));
|
||||
|
||||
const scrollContainer = host.querySelector<HTMLElement>('[data-testid="agent-chat-scroll"]');
|
||||
@@ -156,10 +104,7 @@ function mountTimeline(
|
||||
};
|
||||
|
||||
return {
|
||||
render: (
|
||||
segments: Partial<StreamRenderInput["segments"]>,
|
||||
overrides?: Partial<Omit<StreamRenderInput, "segments">>,
|
||||
) => act(() => render(segments, overrides)),
|
||||
render: (segments: Partial<StreamRenderInput["segments"]>) => act(() => render(segments)),
|
||||
hold: (rowId: string, apply: () => void, triggerEdge: DisclosureTriggerEdge = "top") =>
|
||||
act(() => viewportRef.current!.holdRow(rowId, apply, triggerEdge)),
|
||||
rowTop: (id: string) =>
|
||||
@@ -184,9 +129,9 @@ function mountTimeline(
|
||||
scrollContainer.dispatchEvent(new Event("scroll"));
|
||||
}),
|
||||
// Resize observers and the hold's settle run on animation frames.
|
||||
settle: (frames = 4) =>
|
||||
settle: () =>
|
||||
act(async () => {
|
||||
for (let frame = 0; frame < frames; frame += 1) {
|
||||
for (let frame = 0; frame < 4; frame += 1) {
|
||||
await new Promise((resolve) => requestAnimationFrame(resolve));
|
||||
}
|
||||
}),
|
||||
@@ -365,148 +310,3 @@ describe("web history start", () => {
|
||||
expect(olderHistoryLoads).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("web virtualizer reconcile stability", () => {
|
||||
it("settles without nested update loops when virtualized rows grow far past estimates above a mounted anchor", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(500 + index));
|
||||
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(200);
|
||||
await timeline.settle();
|
||||
const readingTop = timeline.rowTop("message-500");
|
||||
|
||||
const virtualized = Array.from({ length: 500 }, (_, index) => thoughtRow(index, 800));
|
||||
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.rowTop("message-500")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("thought-499")).toBe(readingTop);
|
||||
});
|
||||
|
||||
it("does not overflow React update depth via reconcileReadingPosition when growing virtualized rows reach the start on desktop", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(400 + index));
|
||||
const timeline = mountTimeline(mounted, {
|
||||
viewportHeight: 200,
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(200);
|
||||
await timeline.settle();
|
||||
const readingTop = timeline.rowTop("message-400");
|
||||
|
||||
const virtualized = Array.from({ length: 170 }, (_, index) => thoughtRow(index, 800));
|
||||
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.rowTop("message-400")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("thought-169")).toBe(readingTop);
|
||||
});
|
||||
|
||||
it("does not runaway-loop when unmeasured virtualized rows shrink near the bottom of a long chat", async () => {
|
||||
const virtualized = Array.from({ length: 2000 }, (_, index) => assistantRow(index, 20));
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(2000 + index, 40));
|
||||
const timeline = mountTimeline(mounted, {
|
||||
historyVirtualized: virtualized,
|
||||
viewportHeight: 600,
|
||||
});
|
||||
await timeline.settle(10);
|
||||
timeline.scrollUp(120);
|
||||
await timeline.settle(10);
|
||||
|
||||
const readingTop = timeline.rowTop("message-2000");
|
||||
timeline.render({}, { contentMaxWidth: 360 });
|
||||
await timeline.settle(10);
|
||||
|
||||
expect(timeline.rowTop("message-2000")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("assistant-1999")).toBe(readingTop);
|
||||
expect(timeline.rowTop("assistant-1990")).toBe(readingTop - 200);
|
||||
});
|
||||
|
||||
it("keeps a mounted anchor near the bottom when prepended virtualized rows shrink below estimate", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(40 + index, 40));
|
||||
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(60);
|
||||
await timeline.settle();
|
||||
const readingTop = timeline.rowTop("message-44");
|
||||
|
||||
const virtualized = Array.from({ length: 40 }, (_, index) => assistantRow(index, 40));
|
||||
timeline.render({ historyVirtualized: virtualized, historyMounted: mounted });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.rowTop("message-44")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("assistant-39")).toBe(timeline.rowTop("message-40"));
|
||||
});
|
||||
|
||||
it("settles across frames without hitting React update depth limits for hundreds of tiny virtualized rows", async () => {
|
||||
const mounted = Array.from({ length: 4 }, (_, index) => row(800 + index, 40));
|
||||
const virtualized = Array.from({ length: 800 }, (_, index) => assistantRow(index, 2));
|
||||
const timeline = mountTimeline(mounted, {
|
||||
historyVirtualized: virtualized,
|
||||
viewportHeight: 1200,
|
||||
});
|
||||
await timeline.settle(16);
|
||||
expect(timeline.distanceFromEnd()).toBeLessThanOrEqual(1);
|
||||
|
||||
const readingTop = timeline.rowTop("message-800");
|
||||
timeline.hold("message-800", () => timeline.render({}, { contentMaxWidth: 360 }));
|
||||
await timeline.settle(16);
|
||||
|
||||
expect(timeline.rowTop("message-800")).toBe(readingTop);
|
||||
expect(timeline.rowBottom("assistant-799")).toBe(readingTop);
|
||||
expect(timeline.rowTop("assistant-700")).toBe(readingTop - 200);
|
||||
});
|
||||
|
||||
it("resumes following when a layout commit precedes the scroll event at the bottom", async () => {
|
||||
const mounted = Array.from({ length: 10 }, (_, index) => row(index, 40));
|
||||
const timeline = mountTimeline(mounted, { viewportHeight: 200 });
|
||||
await timeline.settle();
|
||||
timeline.scrollUp(120);
|
||||
await timeline.settle();
|
||||
|
||||
timeline.scrollTo(1000);
|
||||
timeline.render({ historyMounted: [...mounted] });
|
||||
await timeline.settle();
|
||||
|
||||
timeline.render({ liveHead: [row(10, 40)] });
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.distanceFromEnd()).toBe(0);
|
||||
});
|
||||
|
||||
it("mounts the top of a newly virtualized block when all history fits in the viewport", async () => {
|
||||
const timeline = mountTimeline([row(99, 40)], {
|
||||
viewportHeight: 1200,
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
await timeline.settle();
|
||||
|
||||
timeline.render({
|
||||
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
|
||||
});
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.scrollTop()).toBe(0);
|
||||
expect(timeline.rowTop("thought-0")).toBe(48);
|
||||
expect(timeline.rowTop("message-99")).toBe(48 + 24 * 40);
|
||||
});
|
||||
|
||||
it("mounts the top of a newly virtualized block when a mounted row shrinks in the same commit", async () => {
|
||||
const timeline = mountTimeline([row(99, 1100)], {
|
||||
viewportHeight: 1200,
|
||||
isMobileBreakpoint: false,
|
||||
});
|
||||
await timeline.settle();
|
||||
expect(timeline.scrollTop()).toBe(0);
|
||||
|
||||
timeline.render({
|
||||
historyVirtualized: Array.from({ length: 24 }, (_, index) => thoughtRow(index, 40)),
|
||||
historyMounted: [row(99, 40)],
|
||||
});
|
||||
await timeline.settle();
|
||||
|
||||
expect(timeline.scrollTop()).toBe(0);
|
||||
expect(timeline.rowTop("message-99")).toBe(1008);
|
||||
expect(timeline.rowTop("thought-0")).toBe(48);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -57,10 +57,8 @@ const AUTO_SCROLL_RESUME_THRESHOLD_PX = 1;
|
||||
const HISTORY_START_SETTLE_FRAMES = 2;
|
||||
const HISTORY_START_SLOT_HEIGHT_PX = 32;
|
||||
const CONTENT_PADDING_TOP_PX = 16;
|
||||
const CONTENT_PADDING_BOTTOM_PX = 16;
|
||||
const UPWARD_INPUT_EVIDENCE_TIMEOUT_MS = 100;
|
||||
const VIRTUALIZER_SCROLL_MARGIN_PX = HISTORY_START_SLOT_HEIGHT_PX + CONTENT_PADDING_TOP_PX;
|
||||
const MAX_SYNC_LAYOUT_PASSES = 16;
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
@@ -120,127 +118,6 @@ function isScrollContainerMeasurable(
|
||||
return scrollContainer.clientHeight > 0 && scrollContainer.scrollHeight > 0;
|
||||
}
|
||||
|
||||
function getUnclampedScrollTop(
|
||||
scrollContainer: Pick<HTMLElement, "scrollTop" | "clientHeight" | "scrollHeight">,
|
||||
lastKnownScrollTop: number,
|
||||
): number {
|
||||
if (!isScrollContainerMeasurable(scrollContainer)) {
|
||||
return scrollContainer.scrollTop;
|
||||
}
|
||||
const maxScrollTop = Math.max(0, scrollContainer.scrollHeight - scrollContainer.clientHeight);
|
||||
const isBrowserClamped =
|
||||
maxScrollTop < lastKnownScrollTop - 0.5 &&
|
||||
Math.abs(scrollContainer.scrollTop - maxScrollTop) <= 1;
|
||||
return isBrowserClamped ? lastKnownScrollTop : scrollContainer.scrollTop;
|
||||
}
|
||||
|
||||
interface MountedRowOffset {
|
||||
topWithoutVirtual: number;
|
||||
height: number;
|
||||
mountedIndex: number;
|
||||
}
|
||||
|
||||
interface MountedRowSnapshot {
|
||||
firstRowId: string | null;
|
||||
offsets: Map<string, MountedRowOffset>;
|
||||
}
|
||||
|
||||
function findNonVirtualizedRowIndex(
|
||||
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">,
|
||||
rowId: string,
|
||||
): number {
|
||||
const mountedIndex = segments.historyMounted.findIndex((row) => row.id === rowId);
|
||||
if (mountedIndex >= 0) {
|
||||
return mountedIndex;
|
||||
}
|
||||
const liveHeadIndex = segments.liveHead.findIndex((row) => row.id === rowId);
|
||||
return liveHeadIndex >= 0 ? segments.historyMounted.length + liveHeadIndex : -1;
|
||||
}
|
||||
|
||||
interface CommittedLayoutMetrics {
|
||||
hasCommittedFlowHeight: boolean;
|
||||
virtualSpacerHeight: number;
|
||||
nonVirtualFlowHeight: number;
|
||||
nonVirtualRowCount: number;
|
||||
}
|
||||
|
||||
interface ProjectRangeOffsetInput {
|
||||
container: HTMLElement;
|
||||
virtualizer: Virtualizer<HTMLElement, Element>;
|
||||
followOutput: boolean;
|
||||
isJumpSettling: boolean;
|
||||
lastClampedBaselineScrollTop: number;
|
||||
committedLayoutMetrics: CommittedLayoutMetrics;
|
||||
anchorId: string | null;
|
||||
anchorIndex: number;
|
||||
segments: Pick<StreamRenderInput["segments"], "historyMounted" | "liveHead">;
|
||||
mountedSnapshot: MountedRowSnapshot;
|
||||
readingAnchor: ReturnType<typeof createReadingAnchor>;
|
||||
readingRowReplacements: StreamRenderInput["readingRowReplacements"];
|
||||
}
|
||||
|
||||
function projectRangeOffset(input: ProjectRangeOffsetInput): number {
|
||||
const { container, virtualizer } = input;
|
||||
if (input.isJumpSettling) {
|
||||
return container.scrollTop;
|
||||
}
|
||||
const baseScrollTop = getUnclampedScrollTop(container, input.lastClampedBaselineScrollTop);
|
||||
if (input.followOutput && isScrollContainerMeasurable(container)) {
|
||||
const { committedLayoutMetrics } = input;
|
||||
const currentNonVirtualRowCount =
|
||||
input.segments.historyMounted.length + input.segments.liveHead.length;
|
||||
if (
|
||||
!committedLayoutMetrics.hasCommittedFlowHeight ||
|
||||
currentNonVirtualRowCount < committedLayoutMetrics.nonVirtualRowCount
|
||||
) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
const projectedFlowHeight =
|
||||
committedLayoutMetrics.nonVirtualFlowHeight + virtualizer.getTotalSize();
|
||||
return Math.max(0, projectedFlowHeight - container.clientHeight);
|
||||
}
|
||||
if (input.anchorIndex >= 0) {
|
||||
const measurement = virtualizer.measurementsCache[input.anchorIndex];
|
||||
if (!measurement) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
return input.readingAnchor.project(
|
||||
baseScrollTop,
|
||||
{
|
||||
id: String(measurement.key),
|
||||
top: measurement.start,
|
||||
height: measurement.size,
|
||||
},
|
||||
input.readingRowReplacements,
|
||||
);
|
||||
}
|
||||
if (!input.anchorId) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
const mountedAnchor = input.mountedSnapshot.offsets.get(input.anchorId);
|
||||
if (!mountedAnchor) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
const currentMountedIndex = findNonVirtualizedRowIndex(input.segments, input.anchorId);
|
||||
const currentFirstMountedId =
|
||||
input.segments.historyMounted[0]?.id ?? input.segments.liveHead[0]?.id ?? null;
|
||||
if (
|
||||
currentMountedIndex !== mountedAnchor.mountedIndex ||
|
||||
currentFirstMountedId !== input.mountedSnapshot.firstRowId
|
||||
) {
|
||||
return baseScrollTop;
|
||||
}
|
||||
return input.readingAnchor.project(
|
||||
baseScrollTop,
|
||||
{
|
||||
id: input.anchorId,
|
||||
top: mountedAnchor.topWithoutVirtual + virtualizer.getTotalSize(),
|
||||
height: mountedAnchor.height,
|
||||
},
|
||||
input.readingRowReplacements,
|
||||
);
|
||||
}
|
||||
|
||||
function isEditableEventTarget(target: EventTarget | null): boolean {
|
||||
if (!(target instanceof Element)) {
|
||||
return false;
|
||||
@@ -453,7 +330,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const isActive = useRetainedPanelActive();
|
||||
const { t } = useTranslation();
|
||||
const rowsHostRef = useRef<HTMLDivElement | null>(null);
|
||||
const virtualSpacerRef = useRef<HTMLDivElement | null>(null);
|
||||
const auxiliaryRef = useRef<HTMLDivElement | null>(null);
|
||||
const isActiveRef = useRef(isActive);
|
||||
const scrollContainerRef = useRef<HTMLElement | null>(null);
|
||||
@@ -465,7 +341,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
contentRef.current = node;
|
||||
}, []);
|
||||
const [followOutput, setFollowOutputr] = useState(true);
|
||||
const [rangeProjectionEpoch, setRangeProjectionEpoch] = useState(0);
|
||||
const followOutputRef = useRef(followOutput);
|
||||
const setFollowOutput = (value: boolean) => {
|
||||
followOutputRef.current = value;
|
||||
@@ -473,10 +348,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
return value;
|
||||
};
|
||||
const lastKnownScrollTopRef = useRef(0);
|
||||
const lastClampedBaselineScrollTopRef = useRef(0);
|
||||
const segmentsRef = useRef(segments);
|
||||
segmentsRef.current = segments;
|
||||
const isJumpSettlingRef = useRef<() => boolean>(() => false);
|
||||
const mouseScrollGestureRef = useRef<
|
||||
| { kind: "scrollbar"; pointerId: number }
|
||||
| {
|
||||
@@ -492,23 +363,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const lastTouchClientYRef = useRef<number | null>(null);
|
||||
const pendingAutoScrollFrameRef = useRef<number | null>(null);
|
||||
const pendingAutoScrollTimeoutRef = useRef<number | null>(null);
|
||||
const deferredLayoutFrameRef = useRef<number | null>(null);
|
||||
const lastProjectedRangeOffsetRef = useRef<number | null>(null);
|
||||
const syncLayoutPassesRef = useRef(0);
|
||||
const syncLayoutResetScheduledRef = useRef(false);
|
||||
const historyStartReadyRef = useRef(false);
|
||||
const readingAnchor = useMemo(createReadingAnchor, []);
|
||||
const measuredRowHeights = useRef(new Map<string, { width: number; height: number }>());
|
||||
const mountedRowSnapshotRef = useRef<MountedRowSnapshot>({
|
||||
firstRowId: null,
|
||||
offsets: new Map(),
|
||||
});
|
||||
const committedLayoutMetricsRef = useRef<CommittedLayoutMetrics>({
|
||||
hasCommittedFlowHeight: false,
|
||||
virtualSpacerHeight: 0,
|
||||
nonVirtualFlowHeight: 0,
|
||||
nonVirtualRowCount: 0,
|
||||
});
|
||||
const historyStartSettleSchedulerRef = useRef<HistoryStartSettleScheduler | null>(null);
|
||||
const lastActiveFollowOutputLayoutRef = useRef<ActiveFollowOutputLayout | null>(null);
|
||||
const lastObservedViewportGeometryRef = useRef<ObservedViewportGeometry | null>(null);
|
||||
@@ -547,50 +404,38 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const rowVirtualizerRef = useRef<Virtualizer<HTMLElement, Element> | null>(null);
|
||||
const rangeExtractor = useCallback(
|
||||
(range: VirtualRange): number[] => {
|
||||
// Busts TanStack's getVirtualIndexes memo when a post-commit check detects a stale projection.
|
||||
void rangeProjectionEpoch;
|
||||
const anchorId = readingAnchor.getRowId(props.readingRowReplacements);
|
||||
const anchorIndex = anchorId
|
||||
? segments.historyVirtualized.findIndex((row) => row.id === anchorId)
|
||||
: -1;
|
||||
const anchorIndex = segments.historyVirtualized.findIndex(
|
||||
(row) => row.id === readingAnchor.getRowId(props.readingRowReplacements),
|
||||
);
|
||||
const container = scrollContainerRef.current;
|
||||
// TanStack has computed the new measurements before calling the extractor.
|
||||
// Select against the pending anchor correction, before mounting any rows at
|
||||
// the stale pre-prepend offset. The DOM correction still belongs to commit.
|
||||
const virtualizer = rowVirtualizerRef.current!;
|
||||
const virtualizerOffset = virtualizer.scrollOffset ?? 0;
|
||||
const correctedOffset = container
|
||||
? projectRangeOffset({
|
||||
container,
|
||||
virtualizer,
|
||||
followOutput: followOutputRef.current,
|
||||
isJumpSettling: isJumpSettlingRef.current(),
|
||||
lastClampedBaselineScrollTop: lastClampedBaselineScrollTopRef.current,
|
||||
committedLayoutMetrics: committedLayoutMetricsRef.current,
|
||||
anchorId,
|
||||
anchorIndex,
|
||||
segments: segmentsRef.current,
|
||||
mountedSnapshot: mountedRowSnapshotRef.current,
|
||||
readingAnchor,
|
||||
readingRowReplacements: props.readingRowReplacements,
|
||||
})
|
||||
: undefined;
|
||||
const measurement = virtualizer.measurementsCache[anchorIndex];
|
||||
const correctedOffset =
|
||||
container && measurement
|
||||
? readingAnchor.project(
|
||||
container.scrollTop,
|
||||
{
|
||||
id: String(measurement.key),
|
||||
top: measurement.start,
|
||||
height: measurement.size,
|
||||
},
|
||||
props.readingRowReplacements,
|
||||
)
|
||||
: container?.scrollTop;
|
||||
let visibleRange = range;
|
||||
let projectedRangeOffset: number | null = null;
|
||||
if (
|
||||
container &&
|
||||
correctedOffset !== undefined &&
|
||||
Math.abs(correctedOffset - virtualizerOffset) > 0.5
|
||||
Math.abs(correctedOffset - container.scrollTop) > 0.5
|
||||
) {
|
||||
const projectedOffset = Math.max(0, correctedOffset);
|
||||
const first = virtualizer.getVirtualItemForOffset(projectedOffset);
|
||||
const last = virtualizer.getVirtualItemForOffset(projectedOffset + container.clientHeight);
|
||||
if (first && last) {
|
||||
const first = virtualizer.getVirtualItemForOffset(correctedOffset);
|
||||
const last = virtualizer.getVirtualItemForOffset(correctedOffset + container.clientHeight);
|
||||
if (first && last)
|
||||
visibleRange = { ...range, startIndex: first.index, endIndex: last.index };
|
||||
projectedRangeOffset = projectedOffset;
|
||||
}
|
||||
}
|
||||
lastProjectedRangeOffsetRef.current = projectedRangeOffset;
|
||||
return [
|
||||
...new Set([
|
||||
...defaultRangeExtractor(visibleRange),
|
||||
@@ -599,13 +444,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
]),
|
||||
].sort((left, right) => left - right);
|
||||
},
|
||||
[
|
||||
chatFindRowIndexes,
|
||||
rangeProjectionEpoch,
|
||||
readingAnchor,
|
||||
segments.historyVirtualized,
|
||||
props.readingRowReplacements,
|
||||
],
|
||||
[chatFindRowIndexes, readingAnchor, segments.historyVirtualized, props.readingRowReplacements],
|
||||
);
|
||||
const virtualOffsetListener = useRef<((offset: number, scrolling: boolean) => void) | null>(null);
|
||||
const observeVirtualOffset = useCallback<typeof observeElementOffset>((instance, onOffset) => {
|
||||
@@ -724,10 +563,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
"[data-history-row-id][data-index]",
|
||||
) ?? []) {
|
||||
const index = Number(element.dataset.index);
|
||||
const measurement = rowVirtualizer.measurementsCache[index];
|
||||
if (!measurement) continue;
|
||||
const height = measureVirtualElement(element, undefined, rowVirtualizer);
|
||||
if (measurement.size === height) continue;
|
||||
if (rowVirtualizer.measurementsCache[index]?.size === height) continue;
|
||||
rowVirtualizer.resizeItem(index, height);
|
||||
resized = true;
|
||||
}
|
||||
@@ -756,22 +593,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
);
|
||||
useEffect(() => () => virtualRowObserver.disconnect(), [virtualRowObserver]);
|
||||
|
||||
const cancelDeferredLayoutPass = useCallback(() => {
|
||||
const pendingFrame = deferredLayoutFrameRef.current;
|
||||
if (pendingFrame !== null) {
|
||||
deferredLayoutFrameRef.current = null;
|
||||
window.cancelAnimationFrame(pendingFrame);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(
|
||||
() => () => {
|
||||
cancelDeferredLayoutPass();
|
||||
syncLayoutPassesRef.current = 0;
|
||||
},
|
||||
[cancelDeferredLayoutPass],
|
||||
);
|
||||
|
||||
const cancelPendingStickToBottom = useCallback(() => {
|
||||
const pendingFrame = pendingAutoScrollFrameRef.current;
|
||||
if (pendingFrame !== null) {
|
||||
@@ -817,20 +638,11 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
return;
|
||||
}
|
||||
cancelPendingStickToBottom();
|
||||
cancelDeferredLayoutPass();
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
historyStartSettleSchedulerRef.current?.cancel();
|
||||
clearMouseScrollGesture();
|
||||
clearUpwardInputEvidence();
|
||||
lastTouchClientYRef.current = null;
|
||||
}, [
|
||||
cancelDeferredLayoutPass,
|
||||
cancelPendingStickToBottom,
|
||||
clearMouseScrollGesture,
|
||||
clearUpwardInputEvidence,
|
||||
isActive,
|
||||
]);
|
||||
}, [cancelPendingStickToBottom, clearMouseScrollGesture, clearUpwardInputEvidence, isActive]);
|
||||
|
||||
const scrollMessagesToBottom = useCallback(
|
||||
(behavior: ScrollBehaviorLike = "auto") => {
|
||||
@@ -847,7 +659,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
}
|
||||
scrollElementToBottom(scrollContainer, behavior);
|
||||
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
|
||||
lastClampedBaselineScrollTopRef.current = scrollContainer.scrollTop;
|
||||
syncNearBottom(scrollContainer, onNearBottomChange);
|
||||
evaluateHistoryStart();
|
||||
},
|
||||
@@ -920,7 +731,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
setFollowOutput,
|
||||
onNearBottomChange,
|
||||
});
|
||||
isJumpSettlingRef.current = isJumpSettling;
|
||||
|
||||
// Row tops in content coordinates, which survive scrolling.
|
||||
const measureRows = useStableEvent(() => {
|
||||
@@ -930,89 +740,14 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
const viewportTop = container.getBoundingClientRect().top;
|
||||
const scrollTop = container.scrollTop;
|
||||
const width = readContentWidth() ?? 0;
|
||||
const virtualSpacerHeight = virtualSpacerRef.current?.getBoundingClientRect().height ?? 0;
|
||||
const rowsHostHeight = rowsHostRef.current?.getBoundingClientRect().height ?? 0;
|
||||
const auxiliaryHeight = auxiliaryRef.current?.getBoundingClientRect().height ?? 0;
|
||||
const shouldTrackMountedOffsets = !followOutputRef.current;
|
||||
const mountedOffsets = mountedRowSnapshotRef.current.offsets;
|
||||
mountedOffsets.clear();
|
||||
let firstRowId: string | null = null;
|
||||
let mountedIndex = 0;
|
||||
const rows = Array.from(
|
||||
content.querySelectorAll<HTMLElement>("[data-history-row-id]"),
|
||||
(element) => {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
const id = element.dataset.historyRowId!;
|
||||
const top = bounds.top - viewportTop + scrollTop;
|
||||
measuredRowHeights.current.set(id, { width, height: bounds.height });
|
||||
if (!element.hasAttribute("data-index")) {
|
||||
if (shouldTrackMountedOffsets) {
|
||||
if (firstRowId === null) {
|
||||
firstRowId = id;
|
||||
}
|
||||
mountedOffsets.set(id, {
|
||||
topWithoutVirtual: top - virtualSpacerHeight,
|
||||
height: bounds.height,
|
||||
mountedIndex,
|
||||
});
|
||||
}
|
||||
mountedIndex += 1;
|
||||
}
|
||||
return { id, top, height: bounds.height };
|
||||
},
|
||||
);
|
||||
mountedRowSnapshotRef.current.firstRowId = firstRowId;
|
||||
committedLayoutMetricsRef.current = {
|
||||
hasCommittedFlowHeight: true,
|
||||
virtualSpacerHeight,
|
||||
nonVirtualFlowHeight:
|
||||
VIRTUALIZER_SCROLL_MARGIN_PX +
|
||||
Math.max(0, rowsHostHeight - virtualSpacerHeight) +
|
||||
auxiliaryHeight +
|
||||
CONTENT_PADDING_BOTTOM_PX,
|
||||
nonVirtualRowCount: mountedIndex,
|
||||
};
|
||||
return rows;
|
||||
});
|
||||
|
||||
const scheduleDeferredLayoutPass = useStableEvent(() => {
|
||||
if (deferredLayoutFrameRef.current !== null || !isActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
deferredLayoutFrameRef.current = window.requestAnimationFrame(() => {
|
||||
deferredLayoutFrameRef.current = null;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
if (!isActiveRef.current) {
|
||||
return;
|
||||
}
|
||||
if (measureVirtualizedRows()) {
|
||||
return;
|
||||
}
|
||||
reconcileReadingPosition();
|
||||
if (followOutputRef.current && scrollContainerRef.current) {
|
||||
reconcileProjectedRange(scrollContainerRef.current);
|
||||
}
|
||||
return Array.from(content.querySelectorAll<HTMLElement>("[data-history-row-id]"), (element) => {
|
||||
const bounds = element.getBoundingClientRect();
|
||||
const id = element.dataset.historyRowId!;
|
||||
measuredRowHeights.current.set(id, { width, height: bounds.height });
|
||||
return { id, top: bounds.top - viewportTop + scrollTop, height: bounds.height };
|
||||
});
|
||||
});
|
||||
|
||||
const reconcileProjectedRange = useStableEvent((container: HTMLElement): boolean => {
|
||||
const projectedOffset = lastProjectedRangeOffsetRef.current;
|
||||
if (projectedOffset === null) {
|
||||
return false;
|
||||
}
|
||||
if (Math.abs(container.scrollTop - projectedOffset) <= 0.5) {
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
return false;
|
||||
}
|
||||
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
|
||||
scheduleDeferredLayoutPass();
|
||||
return true;
|
||||
}
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
setRangeProjectionEpoch((value) => value + 1);
|
||||
return true;
|
||||
});
|
||||
|
||||
const reconcileReadingPosition = useStableEvent(() => {
|
||||
const container = scrollContainerRef.current;
|
||||
if (!isActiveRef.current || !container) return;
|
||||
@@ -1020,11 +755,8 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
if (!rows) return;
|
||||
const shouldAnchor = !followOutputRef.current && !isJumpSettling();
|
||||
if (!shouldAnchor) readingAnchor.reset();
|
||||
const anchorScrollTop = shouldAnchor
|
||||
? getUnclampedScrollTop(container, lastClampedBaselineScrollTopRef.current)
|
||||
: container.scrollTop;
|
||||
const correctedTop = readingAnchor.reconcile(
|
||||
anchorScrollTop,
|
||||
container.scrollTop,
|
||||
rows,
|
||||
false,
|
||||
props.readingRowReplacements,
|
||||
@@ -1036,20 +768,9 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
if (Math.abs(correctedTop - container.scrollTop) > 0.5) {
|
||||
container.scrollTop = correctedTop;
|
||||
lastKnownScrollTopRef.current = container.scrollTop;
|
||||
}
|
||||
lastClampedBaselineScrollTopRef.current = container.scrollTop;
|
||||
const virtualizerOffset = rowVirtualizer.scrollOffset ?? 0;
|
||||
if (virtualOffsetListener.current && Math.abs(container.scrollTop - virtualizerOffset) > 0.5) {
|
||||
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
|
||||
scheduleDeferredLayoutPass();
|
||||
return;
|
||||
}
|
||||
// The DOM scroll event arrives later. Fill the corrected virtual range in
|
||||
// this layout so the reader does not get a frame containing only the pin.
|
||||
virtualOffsetListener.current(container.scrollTop, false);
|
||||
}
|
||||
if (reconcileProjectedRange(container)) {
|
||||
return;
|
||||
virtualOffsetListener.current?.(container.scrollTop, false);
|
||||
}
|
||||
// A disclosure that closes back to the end of the list rejoins the output.
|
||||
if (disclosurePendingRef.current) {
|
||||
@@ -1061,38 +782,17 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
// Apply row positions and their scroll correction in the same paint, including
|
||||
// the ordinary-to-virtualized handoff and measurements of newly mounted rows.
|
||||
useLayoutEffect(() => {
|
||||
if (!isActive) {
|
||||
cancelDeferredLayoutPass();
|
||||
lastProjectedRangeOffsetRef.current = null;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
return;
|
||||
}
|
||||
if (syncLayoutPassesRef.current >= MAX_SYNC_LAYOUT_PASSES) {
|
||||
scheduleDeferredLayoutPass();
|
||||
return;
|
||||
}
|
||||
syncLayoutPassesRef.current += 1;
|
||||
if (!syncLayoutResetScheduledRef.current) {
|
||||
syncLayoutResetScheduledRef.current = true;
|
||||
queueMicrotask(() => {
|
||||
syncLayoutResetScheduledRef.current = false;
|
||||
syncLayoutPassesRef.current = 0;
|
||||
});
|
||||
}
|
||||
// Commit positions for every resized row before accepting reading geometry.
|
||||
// Child layout can change during this commit, ahead of ResizeObserver delivery.
|
||||
if (measureVirtualizedRows()) return;
|
||||
cancelDeferredLayoutPass();
|
||||
if (!isActive || measureVirtualizedRows()) return;
|
||||
reconcileReadingPosition();
|
||||
}, [
|
||||
cancelDeferredLayoutPass,
|
||||
contentWidth,
|
||||
isActive,
|
||||
segments,
|
||||
virtualRows,
|
||||
measureVirtualizedRows,
|
||||
reconcileReadingPosition,
|
||||
scheduleDeferredLayoutPass,
|
||||
]);
|
||||
|
||||
const stopFollowingOutputFromUserIntent = useStableEvent(() => {
|
||||
@@ -1132,7 +832,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
}
|
||||
|
||||
lastKnownScrollTopRef.current = currentScrollTop;
|
||||
lastClampedBaselineScrollTopRef.current = currentScrollTop;
|
||||
if (!followOutputRef.current && !isJumpSettling() && (scrolledUp || scrolledDown)) {
|
||||
readingAnchor.scroll(currentScrollTop);
|
||||
}
|
||||
@@ -1226,15 +925,11 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
if (!followOutputRef.current || resumedUnchangedLayout) return;
|
||||
cancelPendingStickToBottom();
|
||||
scrollMessagesToBottom("auto");
|
||||
if (scrollContainerRef.current) {
|
||||
reconcileProjectedRange(scrollContainerRef.current);
|
||||
}
|
||||
}, [
|
||||
activationKey,
|
||||
cancelPendingStickToBottom,
|
||||
isActive,
|
||||
isActivationReady,
|
||||
reconcileProjectedRange,
|
||||
renderLiveAuxiliary,
|
||||
scrollMessagesToBottom,
|
||||
segments.historyMounted,
|
||||
@@ -1302,9 +997,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
} else {
|
||||
lastObservedViewportGeometryRef.current = nextGeometry;
|
||||
}
|
||||
if (deferredLayoutFrameRef.current === null) {
|
||||
reconcileReadingPosition();
|
||||
}
|
||||
reconcileReadingPosition();
|
||||
if (isHistoryStartSettling()) {
|
||||
scheduleHistoryStartPrependSettle();
|
||||
}
|
||||
@@ -1515,9 +1208,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
setFollowOutput(false);
|
||||
const row = measureRows()?.find((candidate) => candidate.id === rowId);
|
||||
const scrollTop = scrollContainerRef.current?.scrollTop;
|
||||
if (scrollTop !== undefined) {
|
||||
lastClampedBaselineScrollTopRef.current = scrollTop;
|
||||
}
|
||||
if (row && scrollTop !== undefined) readingAnchor.pin(row, triggerEdge, scrollTop);
|
||||
disclosurePendingRef.current = true;
|
||||
apply();
|
||||
@@ -1553,7 +1243,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
flexDirection: "column",
|
||||
minHeight: "100%",
|
||||
paddingTop: CONTENT_PADDING_TOP_PX,
|
||||
paddingBottom: CONTENT_PADDING_BOTTOM_PX,
|
||||
paddingBottom: 16,
|
||||
paddingLeft,
|
||||
paddingRight,
|
||||
boxSizing: "border-box",
|
||||
@@ -1685,7 +1375,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
<div ref={handleContentRef} style={contentContainerStyle}>
|
||||
{historyStartSlot}
|
||||
<div ref={rowsHostRef} style={streamRowsHostStyle}>
|
||||
<div ref={virtualSpacerRef} style={virtualRowsContainerStyle} />
|
||||
<div style={virtualRowsContainerStyle} />
|
||||
{[
|
||||
...virtualRows.map((virtualRow) => {
|
||||
const item = segments.historyVirtualized[virtualRow.index];
|
||||
|
||||
@@ -12,7 +12,6 @@ import {
|
||||
TEXT_REVEAL_FRAME_INTERVAL_MS,
|
||||
TEXT_REVEAL_HORIZON_MS,
|
||||
visibleRevealedText,
|
||||
withholdPartialClosingFence,
|
||||
} from "./text-reveal";
|
||||
|
||||
describe("computeRevealStep", () => {
|
||||
@@ -276,127 +275,3 @@ describe("trailing fragments from arrival boundaries", () => {
|
||||
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
|
||||
});
|
||||
});
|
||||
|
||||
describe("a closing fence still being typed", () => {
|
||||
const code = "Intro\n\n```ts\nconst a = 1;\n";
|
||||
|
||||
it("holds back one or two backticks that can only become the closing fence", () => {
|
||||
expect(withholdPartialClosingFence(`${code}\``)).toBe(code);
|
||||
expect(withholdPartialClosingFence(`${code}\`\``)).toBe(code);
|
||||
expect(withholdPartialClosingFence(`${code} \`\``)).toBe(code);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ char: "`", length: 3, whitespace: " " },
|
||||
{ char: "`", length: 3, whitespace: "\t" },
|
||||
{ char: "`", length: 4, whitespace: " " },
|
||||
{ char: "`", length: 4, whitespace: "\t" },
|
||||
{ char: "~", length: 3, whitespace: " " },
|
||||
{ char: "~", length: 3, whitespace: "\t" },
|
||||
{ char: "~", length: 5, whitespace: " " },
|
||||
{ char: "~", length: 5, whitespace: "\t" },
|
||||
])(
|
||||
"paints real code after whitespace ends a $length $char run ($whitespace)",
|
||||
({ char, length, whitespace }) => {
|
||||
const prefix = `${char.repeat(length)}\ncode\n`;
|
||||
const run = char.repeat(length - 1);
|
||||
expect(withholdPartialClosingFence(prefix + run)).toBe(prefix);
|
||||
const text = prefix + run + whitespace;
|
||||
expect(withholdPartialClosingFence(text)).toBe(text);
|
||||
expect(visibleRevealedText(beginTextReveal(text), { streaming: true })).toBe(text);
|
||||
},
|
||||
);
|
||||
|
||||
it("paints the fence once it closes the block", () => {
|
||||
expect(withholdPartialClosingFence(`${code}\`\`\``)).toBe(`${code}\`\`\``);
|
||||
expect(withholdPartialClosingFence(`${code}\`\`\`\n\nAfter`)).toBe(`${code}\`\`\`\n\nAfter`);
|
||||
});
|
||||
|
||||
it("needs a run as long as the opener and of the same character", () => {
|
||||
const long = "````md\nInside\n";
|
||||
expect(withholdPartialClosingFence(`${long}\`\`\``)).toBe(long);
|
||||
expect(withholdPartialClosingFence(`${long}\`\`\`\``)).toBe(`${long}\`\`\`\``);
|
||||
const tilde = "~~~\ncode\n";
|
||||
expect(withholdPartialClosingFence(`${tilde}~~`)).toBe(tilde);
|
||||
expect(withholdPartialClosingFence(`${tilde}\``)).toBe(`${tilde}\``);
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ lineEnding: "LF", newline: "\n", closer: "```" },
|
||||
{ lineEnding: "CRLF", newline: "\r\n", closer: "```" },
|
||||
{ lineEnding: "LF", newline: "\n", closer: "``` \t" },
|
||||
{ lineEnding: "CRLF", newline: "\r\n", closer: "``` \t" },
|
||||
])(
|
||||
"recognizes completed closers before a tilde block with $lineEnding ($closer)",
|
||||
({ newline, closer }) => {
|
||||
const backtickBlock = ["Intro", "```ts", "const a = 1;", closer, ""].join(newline);
|
||||
const tildeBlock = backtickBlock + ["~~~md", "code", ""].join(newline);
|
||||
|
||||
expect(withholdPartialClosingFence(tildeBlock + "~~")).toBe(tildeBlock);
|
||||
expect(withholdPartialClosingFence(tildeBlock + "~~~")).toBe(tildeBlock + "~~~");
|
||||
expect(withholdPartialClosingFence(tildeBlock + "~~ not a closer")).toBe(
|
||||
tildeBlock + "~~ not a closer",
|
||||
);
|
||||
|
||||
const closedTildeBlock = tildeBlock + "~~~" + newline;
|
||||
expect(withholdPartialClosingFence(closedTildeBlock + "`")).toBe(closedTildeBlock + "`");
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
{ marker: "-", fence: "```", newline: "\n" },
|
||||
{ marker: "1.", fence: "~~~", newline: "\n" },
|
||||
{ marker: "-", fence: "~~~", newline: "\r\n" },
|
||||
{ marker: "1.", fence: "```", newline: "\r\n" },
|
||||
])(
|
||||
"keeps prose after a closed $marker list fence ($fence, $newline)",
|
||||
({ marker, fence, newline }) => {
|
||||
const indent = " ".repeat(marker.length + 1);
|
||||
const closed = [`${marker} ${fence}`, `${indent}code`, `${indent}${fence}`, "", ""].join(
|
||||
newline,
|
||||
);
|
||||
const prose = closed + fence[0];
|
||||
expect(withholdPartialClosingFence(prose)).toBe(prose);
|
||||
expect(visibleRevealedText(beginTextReveal(prose), { streaming: true })).toBe(prose);
|
||||
const open = [`${marker} ${fence}`, `${indent}code`, ""].join(newline);
|
||||
expect(withholdPartialClosingFence(open + indent + fence[0])).toBe(open);
|
||||
},
|
||||
);
|
||||
|
||||
it("does not take an indented code block's fence for a top-level opener", () => {
|
||||
const text = " code\n ```\n\n`";
|
||||
expect(withholdPartialClosingFence(text)).toBe(text);
|
||||
});
|
||||
|
||||
it("leaves backticks alone outside a code block", () => {
|
||||
expect(withholdPartialClosingFence("Prose\n`")).toBe("Prose\n`");
|
||||
const closed = "```\na\n```\n";
|
||||
expect(withholdPartialClosingFence(`${closed}\``)).toBe(`${closed}\``);
|
||||
expect(withholdPartialClosingFence("`` inline ``\n`")).toBe("`` inline ``\n`");
|
||||
});
|
||||
|
||||
it("leaves a code line that only starts with backticks alone", () => {
|
||||
expect(withholdPartialClosingFence(`${code}\`x`)).toBe(`${code}\`x`);
|
||||
});
|
||||
|
||||
it("never paints a lone backtick line while a paced reveal crosses the closing fence", () => {
|
||||
const full = `${code}\`\`\`\n\nAfter the block.`;
|
||||
let state = retargetTextReveal(beginTextReveal(code), full);
|
||||
const painted: string[] = [];
|
||||
for (let frame = 0; frame < 120 && !isTextRevealSettled(state); frame += 1) {
|
||||
state = advanceTextReveal(state, 16, 1_000);
|
||||
painted.push(visibleRevealedText(state, { streaming: true }));
|
||||
}
|
||||
expect(painted.at(-1)).toBe(full);
|
||||
for (const text of painted) {
|
||||
expect(full.startsWith(text)).toBe(true);
|
||||
expect(text.endsWith("\n`") || text.endsWith("\n``")).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it("holds the fence back when an arrival ends inside it, and paints it once the turn ends", () => {
|
||||
const state = beginTextReveal(`${code}\``);
|
||||
expect(visibleRevealedText(state, { streaming: true })).toBe(code);
|
||||
expect(visibleRevealedText(state, { streaming: false })).toBe(`${code}\``);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { createMarkdownParser } from "@/utils/markdown-parser";
|
||||
|
||||
/**
|
||||
* Paced reveal for streaming assistant text.
|
||||
*
|
||||
@@ -209,41 +207,6 @@ function trimIncompleteTrailingCluster(text: string): string {
|
||||
return text;
|
||||
}
|
||||
|
||||
// Only parse block context when the current line can still become a closer.
|
||||
const UNFINISHED_FENCE_RUN = /^ {0,3}(`+|~+)$/;
|
||||
const fenceParser = createMarkdownParser({ linkify: false }).disable("inline");
|
||||
|
||||
/**
|
||||
* Hold back the closing fence of a code block while it is still being typed.
|
||||
*
|
||||
* Inside an open fence, a last line holding one or two backticks is code until
|
||||
* the third one arrives and closes the block. Painted, it adds a line of code
|
||||
* that vanishes a frame later, so the block grows and shrinks and every row
|
||||
* below it shifts twice. A paced reveal hands out these prefixes one character
|
||||
* at a time, and an arrival boundary can end on one too. The line waits until it
|
||||
* either closes the block or turns out to be code.
|
||||
*/
|
||||
export function withholdPartialClosingFence(text: string): string {
|
||||
const lineStart = text.lastIndexOf("\n") + 1;
|
||||
if (lineStart === 0) return text;
|
||||
const run = UNFINISHED_FENCE_RUN.exec(text.slice(lineStart))?.[1];
|
||||
if (!run) return text;
|
||||
// Source maps include container boundaries: a list closer must not become a
|
||||
// new top-level opener, and a fence-looking line in indented code is not one.
|
||||
const lastLine = text.split("\n").length - 1;
|
||||
const open = fenceParser
|
||||
.parse(text, {})
|
||||
.findLast(
|
||||
(token) =>
|
||||
token.type === "fence" &&
|
||||
token.map !== null &&
|
||||
token.map[0] < lastLine &&
|
||||
token.map[1] === lastLine + 1,
|
||||
);
|
||||
if (!open || open.markup[0] !== run[0] || run.length >= open.markup.length) return text;
|
||||
return text.slice(0, lineStart);
|
||||
}
|
||||
|
||||
/** Number of regional indicators at the end of `text`. A flag is a pair. */
|
||||
function countTrailingRegionalIndicators(text: string): number {
|
||||
let count = 0;
|
||||
@@ -271,12 +234,7 @@ export function visibleRevealedText(
|
||||
options?: { streaming?: boolean },
|
||||
): string {
|
||||
if (state.revealed >= state.target.length) {
|
||||
return options?.streaming
|
||||
? withholdPartialClosingFence(trimIncompleteTrailingCluster(state.target))
|
||||
: state.target;
|
||||
return options?.streaming ? trimIncompleteTrailingCluster(state.target) : state.target;
|
||||
}
|
||||
// More text is already here, so a partial fence at the cut is certainly unfinished.
|
||||
return withholdPartialClosingFence(
|
||||
state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed)),
|
||||
);
|
||||
return state.target.slice(0, clampToSafeRevealBoundary(state.target, state.revealed));
|
||||
}
|
||||
|
||||
@@ -162,12 +162,11 @@ describe("collapseTurns", () => {
|
||||
create.payload.data.detail = { type: "unknown", input: { title: "Side fix" }, output: null };
|
||||
const finished = shell("finished");
|
||||
if (finished.payload.source !== "agent") throw new Error("Expected agent tool");
|
||||
finished.payload.data.name = "agent_finished";
|
||||
finished.payload.data.detail = {
|
||||
type: "plain_text",
|
||||
label: "PR helper",
|
||||
finished.payload.data.name = "agent_notification";
|
||||
finished.payload.data.agentMessage = {
|
||||
event: "finished",
|
||||
sender: { id: "worker", title: "PR helper" },
|
||||
text: "Finished",
|
||||
icon: "bot",
|
||||
};
|
||||
const items: StreamItem[] = [
|
||||
user("u1"),
|
||||
|
||||
@@ -77,8 +77,11 @@ describe("canonical turn membership", () => {
|
||||
delete trigger.turnId;
|
||||
expect(continuesTurn(previous, trigger)).toBe(false);
|
||||
trigger.payload.data.name = "agent_message";
|
||||
expect(continuesTurn(previous, trigger)).toBe(false);
|
||||
trigger.payload.data.name = "agent_finished";
|
||||
trigger.payload.data.agentMessage = {
|
||||
event: "finished",
|
||||
sender: { id: "worker" },
|
||||
text: "Done",
|
||||
};
|
||||
expect(continuesTurn(previous, trigger)).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -744,7 +744,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
<AssistantFileLinkResolverProvider
|
||||
client={client}
|
||||
serverId={resolvedServerId}
|
||||
workspaceId={context.workspaceId}
|
||||
workspaceRoot={workspaceRoot}
|
||||
onOpenWorkspaceFile={handleInlinePathPress}
|
||||
toast={toast}
|
||||
@@ -767,15 +766,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
</AssistantFileLinkResolverProvider>
|
||||
);
|
||||
},
|
||||
[
|
||||
agentId,
|
||||
client,
|
||||
context.workspaceId,
|
||||
handleInlinePathPress,
|
||||
resolvedServerId,
|
||||
toast,
|
||||
workspaceRoot,
|
||||
],
|
||||
[agentId, client, handleInlinePathPress, resolvedServerId, toast, workspaceRoot],
|
||||
);
|
||||
|
||||
const renderThoughtItem = useCallback(
|
||||
@@ -827,6 +818,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
cwd={context.cwd}
|
||||
serverId={resolvedServerId}
|
||||
metadata={data.metadata}
|
||||
agentMessage={data.agentMessage}
|
||||
isLastInSequence={isLastInSequence}
|
||||
onOpenFilePath={handleToolCallOpenFile}
|
||||
standalone={options.standalone}
|
||||
|
||||
@@ -108,7 +108,6 @@ import { useGlobalNewWorkspaceAction } from "@/hooks/use-global-new-workspace-ac
|
||||
import { useLatchedBoolean } from "@/hooks/use-latched-boolean";
|
||||
import { useFaviconStatus } from "@/hooks/use-favicon-status";
|
||||
import { useKeyboardShortcuts } from "@/keyboard/use-shortcuts";
|
||||
import { reportNativeUserActivity } from "@/hooks/native-user-activity";
|
||||
import { KeyboardShiftProvider } from "@/keyboard/shift";
|
||||
import { useCompactWebViewportZoomLock } from "@/hooks/use-compact-web-viewport-zoom-lock";
|
||||
import { useOpenProject } from "@/hooks/use-open-project";
|
||||
@@ -1027,11 +1026,7 @@ function RootProviders({ children }: { children: ReactNode }) {
|
||||
|
||||
function RootAppTree() {
|
||||
return (
|
||||
<GestureHandlerRootView
|
||||
style={flexStyle}
|
||||
onTouchStart={reportNativeUserActivity}
|
||||
onTouchEnd={reportNativeUserActivity}
|
||||
>
|
||||
<GestureHandlerRootView style={flexStyle}>
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
<LucideProvider strokeWidth={ICON_STROKE_WIDTH}>
|
||||
<AddHostProvider>
|
||||
|
||||
@@ -7,7 +7,6 @@ export const ASSISTANT_FILE_EXTENSIONS: ReadonlySet<string> = new Set([
|
||||
"cpp",
|
||||
"cs",
|
||||
"css",
|
||||
"csv",
|
||||
"cts",
|
||||
"cxx",
|
||||
"env",
|
||||
|
||||
@@ -10,11 +10,6 @@ export {
|
||||
type AssistantFileLinkResolverProviderProps,
|
||||
} from "./provider";
|
||||
export type { AssistantFileLinkSource } from "./resolver";
|
||||
export {
|
||||
useAssistantFileLinkActions,
|
||||
useFileLink,
|
||||
type AssistantFileLinkInspection,
|
||||
type AssistantFileLinkPath,
|
||||
} from "./use-file-link";
|
||||
export { useAssistantFileLinkActions, useFileLink } from "./use-file-link";
|
||||
|
||||
export { createInlinePathOpener } from "./path-open";
|
||||
|
||||
@@ -169,15 +169,6 @@ describe("classifyAssistantFileLink", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("classifies a bare CSV filename as a workspace candidate", () => {
|
||||
expect(
|
||||
classifyAssistantFileLink("report.csv", { workspaceRoot: "/Users/test/project" }),
|
||||
).toMatchObject({
|
||||
kind: "ambiguousFileCandidate",
|
||||
target: { path: "/Users/test/project/report.csv" },
|
||||
});
|
||||
});
|
||||
|
||||
it("does not classify normal bare domains as file candidates", () => {
|
||||
expect(
|
||||
classifyAssistantFileLink("google.com", {
|
||||
|
||||
@@ -49,52 +49,6 @@ export async function resolveInlinePathOpen(input: PathOpenInput): Promise<PathO
|
||||
return { kind: "directory", directoryPath: input.file };
|
||||
}
|
||||
|
||||
export type InlinePathDestination =
|
||||
| { kind: "file"; location: WorkspaceFileLocation }
|
||||
| { kind: "directory"; path: string }
|
||||
| { kind: "outsideDirectory"; path: string };
|
||||
|
||||
/** What a path reference points at, as opening it would find it. */
|
||||
export async function resolveInlinePathDestination(input: {
|
||||
target: InlinePathTarget;
|
||||
workspaceRoot: string;
|
||||
client: {
|
||||
listDirectory(root: string, path: string): Promise<unknown>;
|
||||
getDirectorySuggestions: GetDirectorySuggestions;
|
||||
} | null;
|
||||
resolveRelativeFiles?: boolean;
|
||||
}): Promise<InlinePathDestination | null> {
|
||||
const { target, workspaceRoot, client } = input;
|
||||
const normalized = normalizeInlinePathTarget(target.path, workspaceRoot);
|
||||
if (!normalized) return null;
|
||||
const destination = await resolveInlinePathOpen({
|
||||
...normalized,
|
||||
lineStart: target.lineStart,
|
||||
workspaceRoot,
|
||||
client,
|
||||
});
|
||||
if (destination.kind !== "file") {
|
||||
return { kind: destination.kind, path: destination.directoryPath };
|
||||
}
|
||||
if (!normalized.file) return null;
|
||||
const resolvedTarget =
|
||||
input.resolveRelativeFiles && client
|
||||
? await resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot,
|
||||
getDirectorySuggestions: client.getDirectorySuggestions.bind(client),
|
||||
})
|
||||
: target;
|
||||
const resolved = normalizeInlinePathTarget(resolvedTarget.path, workspaceRoot);
|
||||
if (!resolved?.file) return null;
|
||||
const location = normalizeWorkspaceFileLocation({
|
||||
path: resolved.file,
|
||||
lineStart: resolvedTarget.lineStart,
|
||||
lineEnd: resolvedTarget.lineEnd,
|
||||
});
|
||||
return location ? { kind: "file", location } : null;
|
||||
}
|
||||
|
||||
export function createInlinePathOpener(input: {
|
||||
workspaceRoot: string;
|
||||
client: {
|
||||
@@ -110,19 +64,37 @@ export function createInlinePathOpener(input: {
|
||||
return {
|
||||
async open(target: InlinePathTarget, disposition: OpenFileDisposition) {
|
||||
const ownGeneration = ++generation;
|
||||
const destination = await resolveInlinePathDestination({
|
||||
target,
|
||||
const normalized = normalizeInlinePathTarget(target.path, input.workspaceRoot);
|
||||
if (!normalized) return;
|
||||
const destination = await resolveInlinePathOpen({
|
||||
...normalized,
|
||||
lineStart: target.lineStart,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
client: input.client,
|
||||
resolveRelativeFiles: input.resolveRelativeFiles,
|
||||
});
|
||||
if (!destination || ownGeneration !== generation) return;
|
||||
if (ownGeneration !== generation) return;
|
||||
if (destination.kind === "directory") {
|
||||
input.openDirectory(destination.path);
|
||||
input.openDirectory(destination.directoryPath);
|
||||
} else if (destination.kind === "outsideDirectory") {
|
||||
input.openOutsideDirectory(destination.path);
|
||||
} else {
|
||||
input.openFile(destination.location, disposition);
|
||||
input.openOutsideDirectory(destination.directoryPath);
|
||||
} else if (normalized.file) {
|
||||
const resolvedTarget =
|
||||
input.resolveRelativeFiles && input.client
|
||||
? await resolveMissingNestedRelativeFile({
|
||||
target,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
getDirectorySuggestions: input.client.getDirectorySuggestions.bind(input.client),
|
||||
})
|
||||
: target;
|
||||
if (ownGeneration !== generation) return;
|
||||
const resolved = normalizeInlinePathTarget(resolvedTarget.path, input.workspaceRoot);
|
||||
if (!resolved?.file) return;
|
||||
const location = normalizeWorkspaceFileLocation({
|
||||
path: resolved.file,
|
||||
lineStart: resolvedTarget.lineStart,
|
||||
lineEnd: resolvedTarget.lineEnd,
|
||||
});
|
||||
if (location) input.openFile(location, disposition);
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
|
||||
@@ -16,15 +16,11 @@ import type { AssistantFileLinkContext, GetDirectorySuggestions } from "./resolv
|
||||
export interface AssistantFileLinkDaemonClient {
|
||||
readFile?: import("@getpaseo/client/internal/daemon-client").DaemonClient["readFile"];
|
||||
getDirectorySuggestions: GetDirectorySuggestions;
|
||||
/** Without it, a link to a folder is taken for a file. */
|
||||
listDirectory?: (root: string, path: string) => Promise<unknown>;
|
||||
}
|
||||
|
||||
export interface AssistantFileLinkResolverConfig {
|
||||
client?: AssistantFileLinkDaemonClient | null;
|
||||
serverId?: string;
|
||||
/** The workspace the Markdown belongs to, for actions that change its panes. */
|
||||
workspaceId?: string;
|
||||
workspaceRoot?: string;
|
||||
relativePathBase?: string;
|
||||
onOpenWorkspaceFile?: (target: InlinePathTarget, disposition: OpenFileDisposition) => void;
|
||||
@@ -59,7 +55,6 @@ export function useAssistantFileLinkEnvironmentBridge() {
|
||||
export function AssistantFileLinkResolverProvider({
|
||||
client,
|
||||
serverId,
|
||||
workspaceId,
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
@@ -70,7 +65,6 @@ export function AssistantFileLinkResolverProvider({
|
||||
const configRef = useRef<AssistantFileLinkResolverConfig>({
|
||||
client,
|
||||
serverId,
|
||||
workspaceId,
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
@@ -80,7 +74,6 @@ export function AssistantFileLinkResolverProvider({
|
||||
configRef.current = {
|
||||
client,
|
||||
serverId,
|
||||
workspaceId,
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
|
||||
@@ -9,7 +9,7 @@ import type { ToastApi } from "@/components/toast-host";
|
||||
import type { InlinePathTarget } from "./parse";
|
||||
import { AssistantFileLinkResolverProvider } from "./provider";
|
||||
import type { DirectorySuggestionResult } from "./resolver";
|
||||
import { useAssistantFileLinkActions, useFileLink } from "./use-file-link";
|
||||
import { useFileLink } from "./use-file-link";
|
||||
import type { OpenFileDisposition } from "@/workspace/file-open";
|
||||
|
||||
vi.mock("@/utils/open-external-url", () => ({
|
||||
@@ -68,7 +68,6 @@ interface TestClient {
|
||||
matchMode: "suffix";
|
||||
limit: number;
|
||||
}) => Promise<DirectorySuggestionResult>;
|
||||
listDirectory?: (root: string, path: string) => Promise<unknown>;
|
||||
}
|
||||
|
||||
function createQueryClient(): QueryClient {
|
||||
@@ -348,80 +347,4 @@ describe("useFileLink", () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe("inspecting a link before acting on it", () => {
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
});
|
||||
|
||||
/** A workspace holding `docs/notes.md` and the folder `src/utils`. */
|
||||
function inspectLinks(toast?: ToastApi) {
|
||||
const client: TestClient = {
|
||||
getDirectorySuggestions: async ({ query }) =>
|
||||
resolvedSuggestions(query === "notes.md" ? [{ path: "docs/notes.md", kind: "file" }] : []),
|
||||
listDirectory: async (_root, path) => {
|
||||
if (path !== "src/utils") throw new Error("not a directory");
|
||||
return {};
|
||||
},
|
||||
};
|
||||
return renderHook(() => useAssistantFileLinkActions(), {
|
||||
wrapper: createWrapper({ client, openedFiles: [], toast }),
|
||||
}).result.current;
|
||||
}
|
||||
|
||||
function pathInspection(inspection: ReturnType<ReturnType<typeof inspectLinks>["inspect"]>) {
|
||||
if (inspection?.kind !== "path") throw new Error("Expected a path link");
|
||||
return inspection;
|
||||
}
|
||||
|
||||
it("reports a web link by its URL", () => {
|
||||
const links = inspectLinks();
|
||||
|
||||
expect(links.inspect({ href: "https://example.test/doc" })).toEqual({
|
||||
kind: "url",
|
||||
url: "https://example.test/doc",
|
||||
});
|
||||
});
|
||||
|
||||
it("finds the file a bare name refers to without opening it", async () => {
|
||||
const links = inspectLinks();
|
||||
const report = pathInspection(
|
||||
links.inspect({ href: "notes.md", text: "notes.md", markup: "linkify" }),
|
||||
);
|
||||
|
||||
expect(report.written.kind).toBe("file");
|
||||
await expect(report.lookup()).resolves.toEqual({ path: "docs/notes.md", kind: "file" });
|
||||
});
|
||||
|
||||
it("tells a folder from a file by asking the host", async () => {
|
||||
const links = inspectLinks();
|
||||
|
||||
await expect(pathInspection(links.inspect({ href: "src/utils" })).lookup()).resolves.toEqual({
|
||||
path: "src/utils",
|
||||
kind: "directory",
|
||||
});
|
||||
});
|
||||
|
||||
it("knows a trailing slash names a folder before asking", () => {
|
||||
const links = inspectLinks();
|
||||
|
||||
expect(pathInspection(links.inspect({ href: "src/utils/" })).written.kind).toBe("directory");
|
||||
});
|
||||
|
||||
it("says a name was not found only when asked to", async () => {
|
||||
const toast = createToast();
|
||||
const missing = pathInspection(
|
||||
inspectLinks(toast).inspect({ href: "gone.md", text: "gone.md", markup: "linkify" }),
|
||||
);
|
||||
|
||||
await expect(missing.lookup()).resolves.toBeNull();
|
||||
expect(toast.show).not.toHaveBeenCalled();
|
||||
|
||||
missing.reportNotFound();
|
||||
expect(toast.show).toHaveBeenCalledWith(expect.stringContaining("gone.md"), {
|
||||
variant: "error",
|
||||
testID: "assistant-file-link-not-found-toast",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
const WorkspaceSwitchContext = React.createContext<(workspaceRoot: string) => void>(() => {});
|
||||
|
||||
@@ -6,8 +6,7 @@ import type { OpenFileDisposition } from "@/workspace/file-open";
|
||||
import { shouldRouteWorkspaceUrlToProxiedBrowser } from "@/desktop/browser/proxy";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { formatFileLinkTooltipPath } from "./tooltip-path";
|
||||
import { normalizeInlinePathTarget, type InlinePathTarget } from "./parse";
|
||||
import { resolveInlinePathDestination } from "./path-open";
|
||||
import type { InlinePathTarget } from "./parse";
|
||||
import {
|
||||
useAssistantFileLinkResolverContext,
|
||||
type AssistantFileLinkResolverContextValue,
|
||||
@@ -32,28 +31,8 @@ export interface AssistantFileLinkActions {
|
||||
open(source: AssistantFileLinkSource, disposition: OpenFileDisposition): void;
|
||||
canOpen(source: AssistantFileLinkSource): boolean;
|
||||
canResolveFile(source: AssistantFileLinkSource): boolean;
|
||||
/** What a link names, for offering actions on it. Null when Paseo does nothing with it. */
|
||||
inspect(source: AssistantFileLinkSource): AssistantFileLinkInspection | null;
|
||||
}
|
||||
|
||||
export interface AssistantFileLinkPath {
|
||||
/** Workspace-relative inside the workspace, absolute or `~/` outside it. */
|
||||
path: string;
|
||||
kind: "file" | "directory";
|
||||
}
|
||||
|
||||
export type AssistantFileLinkInspection =
|
||||
| { kind: "url"; url: string }
|
||||
| {
|
||||
kind: "path";
|
||||
/** What the link says, before the host has been asked. */
|
||||
written: AssistantFileLinkPath;
|
||||
/** Where it actually leads, or null when nothing matches. */
|
||||
lookup(): Promise<AssistantFileLinkPath | null>;
|
||||
/** Tells the user `lookup` found nothing. */
|
||||
reportNotFound(): void;
|
||||
};
|
||||
|
||||
interface AssistantFileLinkLookupKey {
|
||||
query: string;
|
||||
path: string;
|
||||
@@ -188,116 +167,7 @@ export function useAssistantFileLinkActions(): AssistantFileLinkActions {
|
||||
[context.configRef],
|
||||
);
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useTranslation();
|
||||
const inspect = useStableEvent((source: AssistantFileLinkSource) =>
|
||||
inspectAssistantFileLink({
|
||||
source,
|
||||
context,
|
||||
queryClient,
|
||||
formatNoFileFoundMessage: (token) => t("common.errors.noFileFound", { token }),
|
||||
}),
|
||||
);
|
||||
|
||||
return useMemo(
|
||||
() => ({ open, canOpen, canResolveFile, inspect }),
|
||||
[open, canOpen, canResolveFile, inspect],
|
||||
);
|
||||
}
|
||||
|
||||
function inspectAssistantFileLink(input: {
|
||||
source: AssistantFileLinkSource;
|
||||
context: AssistantFileLinkResolverContextValue;
|
||||
queryClient: ReturnType<typeof useQueryClient>;
|
||||
formatNoFileFoundMessage: (token: string) => string;
|
||||
}): AssistantFileLinkInspection | null {
|
||||
const { serverId, workspaceRoot, relativePathBase, client } = input.context.configRef.current;
|
||||
const resolution = classifyForResolution(input.source, { workspaceRoot, relativePathBase });
|
||||
if (resolution.kind === "resolved" && resolution.value.kind !== "file") {
|
||||
return resolution.value.kind === "external" ? { kind: "url", url: resolution.value.url } : null;
|
||||
}
|
||||
const target =
|
||||
resolution.kind === "needsLookup"
|
||||
? resolution.target
|
||||
: (resolution.value as { kind: "file"; target: InlinePathTarget }).target;
|
||||
const written = normalizeInlinePathTarget(target.path, workspaceRoot);
|
||||
if (!written) return null;
|
||||
|
||||
const lookup = async (): Promise<AssistantFileLinkPath | null> => {
|
||||
try {
|
||||
const found =
|
||||
resolution.kind === "needsLookup"
|
||||
? await fetchLookup({
|
||||
resolution,
|
||||
serverId,
|
||||
workspaceRoot,
|
||||
context: input.context,
|
||||
queryClient: input.queryClient,
|
||||
})
|
||||
: target;
|
||||
const destination = await resolveInlinePathDestination({
|
||||
target: found,
|
||||
workspaceRoot: workspaceRoot ?? "",
|
||||
resolveRelativeFiles: true,
|
||||
client: client?.listDirectory
|
||||
? {
|
||||
listDirectory: client.listDirectory.bind(client),
|
||||
getDirectorySuggestions: input.context.getDirectorySuggestions,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
if (!destination) return null;
|
||||
return destination.kind === "file"
|
||||
? { path: destination.location.path, kind: "file" }
|
||||
: { path: destination.path, kind: "directory" };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
kind: "path",
|
||||
// Parsing drops a trailing slash from the path; the link as written still has it.
|
||||
written: {
|
||||
path: written.file ?? written.directory,
|
||||
kind: written.file && !target.raw.endsWith("/") ? "file" : "directory",
|
||||
},
|
||||
lookup,
|
||||
reportNotFound: () => {
|
||||
void dispatchUnresolvedError({
|
||||
error: null,
|
||||
noFileFoundMessage: input.formatNoFileFoundMessage(
|
||||
resolution.kind === "needsLookup" ? resolution.token : target.raw,
|
||||
),
|
||||
capturedServerId: serverId,
|
||||
capturedWorkspaceRoot: workspaceRoot,
|
||||
context: input.context,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fetchLookup(input: {
|
||||
resolution: Extract<AssistantFileLinkResolution, { kind: "needsLookup" }>;
|
||||
serverId?: string;
|
||||
workspaceRoot?: string;
|
||||
context: AssistantFileLinkResolverContextValue;
|
||||
queryClient: ReturnType<typeof useQueryClient>;
|
||||
}): Promise<InlinePathTarget> {
|
||||
const { resolution, serverId, workspaceRoot } = input;
|
||||
return input.queryClient.fetchQuery({
|
||||
queryKey: assistantFileLinkQueryKey({ serverId, workspaceRoot, resolution }),
|
||||
queryFn: () =>
|
||||
fetchDaemonResolution({
|
||||
ambiguousQuery: resolution.ambiguousQuery,
|
||||
token: resolution.token,
|
||||
target: resolution.target,
|
||||
workspaceRoot,
|
||||
getDirectorySuggestions: input.context.getDirectorySuggestions,
|
||||
}),
|
||||
retry: 0,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
return useMemo(() => ({ open, canOpen, canResolveFile }), [open, canOpen, canResolveFile]);
|
||||
}
|
||||
|
||||
function openAssistantFileLink(input: {
|
||||
@@ -324,14 +194,26 @@ function openAssistantFileLink(input: {
|
||||
return;
|
||||
}
|
||||
|
||||
const capturedQueryKey = assistantFileLinkQueryKey({
|
||||
serverId: capturedConfig.serverId,
|
||||
workspaceRoot: capturedConfig.workspaceRoot,
|
||||
resolution: capturedResolution,
|
||||
});
|
||||
|
||||
const run = async () => {
|
||||
try {
|
||||
const target = await fetchLookup({
|
||||
resolution: capturedResolution,
|
||||
serverId: capturedConfig.serverId,
|
||||
workspaceRoot: capturedConfig.workspaceRoot,
|
||||
context: input.context,
|
||||
queryClient: input.queryClient,
|
||||
const target = await input.queryClient.fetchQuery({
|
||||
queryKey: capturedQueryKey,
|
||||
queryFn: () =>
|
||||
fetchDaemonResolution({
|
||||
ambiguousQuery: capturedResolution.ambiguousQuery,
|
||||
token: capturedResolution.token,
|
||||
target: capturedResolution.target,
|
||||
workspaceRoot: capturedConfig.workspaceRoot,
|
||||
getDirectorySuggestions: input.context.getDirectorySuggestions,
|
||||
}),
|
||||
retry: 0,
|
||||
staleTime: Infinity,
|
||||
});
|
||||
await dispatchFileTarget({
|
||||
target,
|
||||
|
||||
@@ -12,7 +12,6 @@ export interface AttachmentFileSystem {
|
||||
writeBytes(uri: string, bytes: Uint8Array): Promise<void>;
|
||||
copy(input: { from: string; to: string }): Promise<void>;
|
||||
readAsBase64(uri: string): Promise<string>;
|
||||
readBytes(uri: string): Promise<Uint8Array>;
|
||||
delete(uri: string, options: { idempotent: boolean }): Promise<void>;
|
||||
listDirectory(uri: string): Promise<string[]>;
|
||||
}
|
||||
@@ -45,9 +44,6 @@ export function createExpoAttachmentFileSystem(): AttachmentFileSystem {
|
||||
encoding: FileSystem.EncodingType.Base64,
|
||||
});
|
||||
},
|
||||
async readBytes(uri) {
|
||||
return await new File(uri).bytes();
|
||||
},
|
||||
async delete(uri, options) {
|
||||
await FileSystem.deleteAsync(uri, options);
|
||||
},
|
||||
|
||||
@@ -166,10 +166,6 @@ export function createLocalFileAttachmentStore(params: {
|
||||
return await fileSystem.readAsBase64(attachmentUri(attachment));
|
||||
},
|
||||
|
||||
async readBytes({ attachment }): Promise<Uint8Array> {
|
||||
return await fileSystem.readBytes(attachmentUri(attachment));
|
||||
},
|
||||
|
||||
async resolvePreviewUrl({ attachment }): Promise<string> {
|
||||
return await params.resolvePreviewUrl(attachment);
|
||||
},
|
||||
|
||||
@@ -5,7 +5,6 @@ import {
|
||||
encodeAttachmentsForSend,
|
||||
garbageCollectAttachments,
|
||||
persistAttachmentFromBytes,
|
||||
uploadImageAttachments,
|
||||
} from "./service";
|
||||
|
||||
function createAttachment(input: Partial<AttachmentMetadata> = {}): AttachmentMetadata {
|
||||
@@ -43,9 +42,6 @@ function createRecordingStore(): AttachmentStore & {
|
||||
async encodeBase64({ attachment }) {
|
||||
return `${attachment.id}:base64`;
|
||||
},
|
||||
async readBytes({ attachment }) {
|
||||
return new TextEncoder().encode(`${attachment.id}:bytes`);
|
||||
},
|
||||
async resolvePreviewUrl({ attachment }) {
|
||||
return `blob:${attachment.id}`;
|
||||
},
|
||||
@@ -144,80 +140,4 @@ describe("attachment service", () => {
|
||||
|
||||
expect(garbageCollections).toEqual([["assistant-preview"]]);
|
||||
});
|
||||
|
||||
it("uploads image attachments sequentially via uploadFile without inlining base64", async () => {
|
||||
const store = createRecordingStore();
|
||||
__setAttachmentStoreForTests(store);
|
||||
|
||||
const events: string[] = [];
|
||||
const firstGate = (() => {
|
||||
let release: () => void = () => {};
|
||||
const promise = new Promise<void>((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
return { promise, release };
|
||||
})();
|
||||
const client = {
|
||||
uploadFile: async (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => {
|
||||
events.push(`start:${input.fileName}`);
|
||||
if (input.fileName === "first.jpg") {
|
||||
await firstGate.promise;
|
||||
}
|
||||
events.push(`end:${input.fileName}`);
|
||||
return {
|
||||
requestId: `req-${input.fileName}`,
|
||||
file: {
|
||||
type: "uploaded_file" as const,
|
||||
id: `upload_${input.fileName}`,
|
||||
fileName: input.fileName,
|
||||
mimeType: input.mimeType,
|
||||
size: input.bytes.byteLength,
|
||||
path: `/home/user/.paseo/uploads/upload_${input.fileName}/${input.fileName}`,
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const uploadPromise = uploadImageAttachments({
|
||||
client,
|
||||
images: [
|
||||
createAttachment({ id: "img-1", fileName: "first.jpg", mimeType: "image/jpeg" }),
|
||||
createAttachment({ id: "img-2", fileName: "second.png", mimeType: "image/png" }),
|
||||
],
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
// Second photo must NOT start uploading until first photo's response has resolved.
|
||||
expect(events).toEqual(["start:first.jpg"]);
|
||||
firstGate.release();
|
||||
|
||||
const uploaded = await uploadPromise;
|
||||
expect(events).toEqual([
|
||||
"start:first.jpg",
|
||||
"end:first.jpg",
|
||||
"start:second.png",
|
||||
"end:second.png",
|
||||
]);
|
||||
expect(uploaded).toEqual([
|
||||
{
|
||||
type: "uploaded_file",
|
||||
id: "upload_first.jpg",
|
||||
fileName: "first.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
size: new TextEncoder().encode("img-1:bytes").byteLength,
|
||||
path: "/home/user/.paseo/uploads/upload_first.jpg/first.jpg",
|
||||
role: "image",
|
||||
},
|
||||
{
|
||||
type: "uploaded_file",
|
||||
id: "upload_second.png",
|
||||
fileName: "second.png",
|
||||
mimeType: "image/png",
|
||||
size: new TextEncoder().encode("img-2:bytes").byteLength,
|
||||
path: "/home/user/.paseo/uploads/upload_second.png/second.png",
|
||||
role: "image",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import type { UploadedFileAttachment } from "@getpaseo/protocol/messages";
|
||||
import { collectRetainedAttachmentIds } from "@/attachments/gc-retention";
|
||||
import { getAttachmentStore } from "@/attachments/store";
|
||||
import type { AttachmentMetadata, SaveAttachmentInput } from "@/attachments/types";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
|
||||
const activePersistence = new Set<Promise<AttachmentMetadata>>();
|
||||
const persistedDuringGarbageCollection = new Set<string>();
|
||||
@@ -127,75 +124,6 @@ export async function encodeAttachmentsForSend(
|
||||
return valid.length > 0 ? valid : undefined;
|
||||
}
|
||||
|
||||
const DEFAULT_UPLOAD_EXTENSION_BY_MIME: Record<string, string> = {
|
||||
"image/jpeg": ".jpg",
|
||||
"image/jpg": ".jpg",
|
||||
"image/png": ".png",
|
||||
"image/gif": ".gif",
|
||||
"image/webp": ".webp",
|
||||
};
|
||||
|
||||
function resolveUploadedImageFileName(attachment: AttachmentMetadata): string {
|
||||
const existing = attachment.fileName?.trim();
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
const ext = DEFAULT_UPLOAD_EXTENSION_BY_MIME[attachment.mimeType.toLowerCase()] ?? ".img";
|
||||
return `${attachment.id}${ext}`;
|
||||
}
|
||||
|
||||
export interface ImageUploadClient {
|
||||
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
|
||||
requestId: string;
|
||||
file: UploadedFileAttachment | null;
|
||||
error: string | null;
|
||||
}>;
|
||||
}
|
||||
|
||||
export async function readAttachmentBytes(attachment: AttachmentMetadata): Promise<Uint8Array> {
|
||||
const store = await getAttachmentStore();
|
||||
return await store.readBytes({ attachment });
|
||||
}
|
||||
|
||||
/**
|
||||
* Uploads persisted image attachments sequentially via `file.upload.request` so multi-photo
|
||||
* batches drain cleanly between files instead of queueing concurrently on mobile sockets.
|
||||
* Each uploaded image is marked with `role: "image"` inside `uploaded_file` so current daemons
|
||||
* resolve it into a native vision block + timeline thumbnail, while older daemons (v0.1.91-v0.18.1)
|
||||
* strip the unknown `role` field and still deliver the uploaded file path instead of dropping it.
|
||||
*/
|
||||
export async function uploadImageAttachments(input: {
|
||||
client: ImageUploadClient;
|
||||
images: readonly AttachmentMetadata[] | undefined;
|
||||
}): Promise<UploadedFileAttachment[] | undefined> {
|
||||
if (!input.images || input.images.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const uploaded: UploadedFileAttachment[] = [];
|
||||
for (const attachment of input.images) {
|
||||
const fileName = resolveUploadedImageFileName(attachment);
|
||||
const bytes = await readAttachmentBytes(attachment);
|
||||
if (bytes.byteLength > FILE_UPLOAD_MAX_BYTES) {
|
||||
throw new Error(i18n.t("composer.errors.fileTooLarge", { size: "50MB", fileName }));
|
||||
}
|
||||
const response = await input.client.uploadFile({
|
||||
fileName,
|
||||
mimeType: attachment.mimeType,
|
||||
bytes,
|
||||
});
|
||||
if (response.error || !response.file) {
|
||||
throw new Error(response.error ?? "Upload failed.");
|
||||
}
|
||||
uploaded.push({
|
||||
...response.file,
|
||||
role: "image",
|
||||
});
|
||||
}
|
||||
|
||||
return uploaded;
|
||||
}
|
||||
|
||||
export async function resolveAttachmentPreviewUrl(attachment: AttachmentMetadata): Promise<string> {
|
||||
const store = await getAttachmentStore();
|
||||
return await store.resolvePreviewUrl({ attachment });
|
||||
|
||||
@@ -61,13 +61,6 @@ export function createTestAttachmentFileSystem(options?: {
|
||||
}
|
||||
return toBase64(bytes);
|
||||
},
|
||||
async readBytes(uri) {
|
||||
const bytes = files.get(uri);
|
||||
if (!bytes) {
|
||||
throw new Error(`readBytes: file does not exist: ${uri}`);
|
||||
}
|
||||
return new Uint8Array(bytes);
|
||||
},
|
||||
async delete(uri, deleteOptions) {
|
||||
if (!files.delete(uri) && !deleteOptions.idempotent) {
|
||||
throw new Error(`delete: file does not exist: ${uri}`);
|
||||
|
||||
@@ -178,7 +178,6 @@ export interface AttachmentStore {
|
||||
readonly storageType: AttachmentStorageType;
|
||||
save(input: SaveAttachmentInput): Promise<AttachmentMetadata>;
|
||||
encodeBase64(input: EncodeAttachmentInput): Promise<string>;
|
||||
readBytes(input: EncodeAttachmentInput): Promise<Uint8Array>;
|
||||
resolvePreviewUrl(input: ResolvePreviewUrlInput): Promise<string>;
|
||||
releasePreviewUrl?(input: ReleasePreviewUrlInput): Promise<void>;
|
||||
delete(input: DeleteAttachmentInput): Promise<void>;
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
// @vitest-environment jsdom
|
||||
import { cleanup, renderHook, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { FileReadResult } from "@getpaseo/client/internal/daemon-client";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import type { AttachmentStore } from "@/attachments/types";
|
||||
import { useDaemonUploadedImage } from "./use-daemon-uploaded-image";
|
||||
|
||||
function createMemoryStore(): AttachmentStore {
|
||||
const bytesById = new Map<string, Uint8Array>();
|
||||
return {
|
||||
storageType: "web-indexeddb",
|
||||
async save(input) {
|
||||
const id = input.id ?? "saved";
|
||||
const bytes = input.source.kind === "bytes" ? input.source.bytes : new Uint8Array();
|
||||
bytesById.set(id, bytes);
|
||||
return {
|
||||
id,
|
||||
mimeType: input.mimeType ?? "image/png",
|
||||
storageType: "web-indexeddb",
|
||||
storageKey: id,
|
||||
fileName: input.fileName ?? null,
|
||||
byteSize: bytes.byteLength,
|
||||
createdAt: 1,
|
||||
};
|
||||
},
|
||||
async encodeBase64() {
|
||||
return "";
|
||||
},
|
||||
async readBytes({ attachment }) {
|
||||
return bytesById.get(attachment.id) ?? new Uint8Array();
|
||||
},
|
||||
async resolvePreviewUrl({ attachment }) {
|
||||
return `blob:${attachment.id}`;
|
||||
},
|
||||
async delete() {},
|
||||
async garbageCollect() {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("useDaemonUploadedImage", () => {
|
||||
beforeEach(() => {
|
||||
__setAttachmentStoreForTests(createMemoryStore());
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
__setAttachmentStoreForTests(null);
|
||||
});
|
||||
|
||||
it("loads an uploaded image from the daemon via readFile and persists local AttachmentMetadata", async () => {
|
||||
const readFile = vi.fn(
|
||||
async (cwd: string, path: string): Promise<FileReadResult> => ({
|
||||
kind: "image",
|
||||
path,
|
||||
mime: "image/jpeg",
|
||||
size: 4,
|
||||
modifiedAt: "2026-11-28T00:00:00.000Z",
|
||||
bytes: new Uint8Array([0xff, 0xd8, 0xff, 0xd9]),
|
||||
}),
|
||||
);
|
||||
|
||||
const { result } = renderHook(() =>
|
||||
useDaemonUploadedImage({
|
||||
image: {
|
||||
storageType: "daemon-upload",
|
||||
id: "upload_reload_1",
|
||||
fileName: "photo.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
size: 4,
|
||||
path: "/home/user/.paseo/uploads/upload_reload_1/photo.jpg",
|
||||
},
|
||||
client: { readFile },
|
||||
serverId: "srv-1",
|
||||
}),
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current).not.toBeNull();
|
||||
});
|
||||
expect(readFile).toHaveBeenCalledWith(
|
||||
"/",
|
||||
"/home/user/.paseo/uploads/upload_reload_1/photo.jpg",
|
||||
);
|
||||
expect(result.current).toMatchObject({
|
||||
mimeType: "image/jpeg",
|
||||
fileName: "photo.jpg",
|
||||
byteSize: 4,
|
||||
storageType: "web-indexeddb",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,83 +0,0 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { createAssistantImageAcquisitionCache } from "@/assistant-image/acquisition-cache";
|
||||
import { retainAttachmentForGarbageCollection } from "@/attachments/gc-retention";
|
||||
import { persistAttachmentFromBytes } from "@/attachments/service";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import { resolveFilePreviewReadTarget } from "@/file-explorer/preview-target";
|
||||
import type { DaemonUploadedImageAttachment } from "@/types/stream";
|
||||
|
||||
const uploadedImageCache = createAssistantImageAcquisitionCache<AttachmentMetadata>({
|
||||
capacity: 200,
|
||||
onRetain: (attachment) => retainAttachmentForGarbageCollection(attachment.id),
|
||||
});
|
||||
|
||||
function buildCacheKey(serverId: string | undefined, image: DaemonUploadedImageAttachment): string {
|
||||
return [serverId ?? "local", image.id, image.path].join("\u0000");
|
||||
}
|
||||
|
||||
function buildLocalAttachmentId(serverId: string | undefined, uploadId: string): string {
|
||||
const safeServer = (serverId ?? "local").replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
const safeUpload = uploadId.replace(/[^a-zA-Z0-9_-]/g, "_");
|
||||
return `daemon-upload-${safeServer}-${safeUpload}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads a daemon-stored uploaded image through `client.readFile` (binary chunked stream),
|
||||
* persists it into the local attachment store, and retains it in a bounded LRU cache so
|
||||
* timeline reloads and cross-device views render thumbnails and lightbox previews cleanly.
|
||||
*/
|
||||
export function useDaemonUploadedImage(input: {
|
||||
image: DaemonUploadedImageAttachment;
|
||||
client?: Pick<DaemonClient, "readFile"> | null;
|
||||
serverId?: string;
|
||||
}): AttachmentMetadata | null {
|
||||
const { image, client, serverId } = input;
|
||||
const cacheKey = buildCacheKey(serverId, image);
|
||||
const [resolved, setResolved] = useState<{ key: string; metadata: AttachmentMetadata } | null>(
|
||||
null,
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!client) {
|
||||
return;
|
||||
}
|
||||
const target = resolveFilePreviewReadTarget({ path: image.path });
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
const retained = uploadedImageCache.acquireRetained(cacheKey, async () => {
|
||||
const file = await client.readFile(target.cwd, target.path);
|
||||
return await persistAttachmentFromBytes({
|
||||
id: buildLocalAttachmentId(serverId, image.id),
|
||||
bytes: file.bytes,
|
||||
mimeType: image.mimeType || file.mime,
|
||||
fileName: image.fileName,
|
||||
});
|
||||
});
|
||||
|
||||
void retained.promise
|
||||
.then((metadata) => {
|
||||
if (!cancelled) {
|
||||
setResolved({ key: cacheKey, metadata });
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn("[attachments] Failed to load uploaded user message image", {
|
||||
id: image.id,
|
||||
path: image.path,
|
||||
error,
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
retained.release();
|
||||
};
|
||||
}, [cacheKey, client, image.fileName, image.id, image.mimeType, image.path, serverId]);
|
||||
|
||||
return resolved?.key === cacheKey ? resolved.metadata : null;
|
||||
}
|
||||
@@ -165,16 +165,6 @@ export function createIndexedDbAttachmentStore(): AttachmentStore {
|
||||
}
|
||||
},
|
||||
|
||||
async readBytes({ attachment }): Promise<Uint8Array> {
|
||||
const db = await openAttachmentDb();
|
||||
try {
|
||||
const blob = await loadBlob(db, attachment.storageKey);
|
||||
return new Uint8Array(await blob.arrayBuffer());
|
||||
} finally {
|
||||
db.close();
|
||||
}
|
||||
},
|
||||
|
||||
async resolvePreviewUrl({ attachment }): Promise<string> {
|
||||
const db = await openAttachmentDb();
|
||||
try {
|
||||
|
||||
@@ -56,7 +56,6 @@ function source(gitActions: GitActions): {
|
||||
copyAgentId: "Copy agent id",
|
||||
copyTerminalId: "Copy terminal id",
|
||||
copyFilePath: "Copy file path",
|
||||
revealInFiles: "Reveal in Files",
|
||||
closeTabsLeft: "Close tabs left",
|
||||
closeTabsRight: "Close tabs right",
|
||||
closeOtherTabs: "Close other tabs",
|
||||
@@ -140,21 +139,6 @@ describe("workspace command center contributions", () => {
|
||||
expect(fixture.dispatched).toEqual([]);
|
||||
});
|
||||
|
||||
it("reveals the active file tab in Files", () => {
|
||||
const fixture = source({ primary: null, secondary: [], menu: [] });
|
||||
fixture.value.activeTabKind = "file";
|
||||
fixture.value.activeTabIndex = 0;
|
||||
fixture.value.activeTabCount = 1;
|
||||
|
||||
buildWorkspaceCommandCenterContributions(fixture.value)
|
||||
.find((item) => item.id === "tab:reveal-in-files")
|
||||
?.run();
|
||||
|
||||
expect(fixture.dispatched).toEqual([
|
||||
{ id: "workspace.tab.reveal-in-files", scope: "workspace" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("omits archive while the workspace cannot be archived", () => {
|
||||
const fixture = source({ primary: null, secondary: [], menu: [] });
|
||||
fixture.value.archiveWorkspace = null;
|
||||
|
||||
@@ -36,7 +36,6 @@ export interface WorkspaceCommandCenterLabels {
|
||||
copyAgentId: string;
|
||||
copyTerminalId: string;
|
||||
copyFilePath: string;
|
||||
revealInFiles: string;
|
||||
closeTabsLeft: string;
|
||||
closeTabsRight: string;
|
||||
closeOtherTabs: string;
|
||||
@@ -352,14 +351,6 @@ function buildActiveTabContributions(
|
||||
icon: source.icons.copy,
|
||||
action: { id: "workspace.tab.copy-file-path", scope: "workspace" },
|
||||
}),
|
||||
buildQueryAction(source, {
|
||||
id: "tab:reveal-in-files",
|
||||
rank: 37,
|
||||
title: source.labels.revealInFiles,
|
||||
keywords: ["tab", "file", "reveal", "files", "explorer"],
|
||||
icon: source.icons.files,
|
||||
action: { id: "workspace.tab.reveal-in-files", scope: "workspace" },
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (source.activeTabIndex > 0) {
|
||||
|
||||
@@ -256,7 +256,6 @@ export function useWorkspaceCommandCenterActions(): void {
|
||||
copyAgentId: t("workspace.tabs.menu.copyAgentId"),
|
||||
copyTerminalId: t("workspace.tabs.menu.copyTerminalId"),
|
||||
copyFilePath: t("workspace.tabs.menu.copyFilePath"),
|
||||
revealInFiles: t("workspace.fileActions.revealInFiles"),
|
||||
closeTabsLeft: t("workspace.tabs.menu.closeLeft"),
|
||||
closeTabsRight: t("workspace.tabs.menu.closeRight"),
|
||||
closeOtherTabs: t("workspace.tabs.menu.closeOthers"),
|
||||
|
||||
@@ -412,29 +412,6 @@ export function SheetHeaderIconButton({
|
||||
);
|
||||
}
|
||||
|
||||
/** The header's overflow trigger. Place it inside the `DropdownMenu` that holds its rows. */
|
||||
export function SheetHeaderMenuButton({
|
||||
icon,
|
||||
label,
|
||||
testID,
|
||||
}: {
|
||||
icon: LucideIcon;
|
||||
/** The accessible name, also shown as the desktop tooltip. */
|
||||
label: string;
|
||||
testID?: string;
|
||||
}) {
|
||||
const compact = useIsCompactFormFactor();
|
||||
return (
|
||||
<ToolbarButton kind="menu" label={label} compact={compact} testID={testID}>
|
||||
<ThemedHeaderGlyph
|
||||
icon={icon}
|
||||
size={iconButtonChromeGlyphSize("large", compact)}
|
||||
uniProps={mutedIconColorMapping}
|
||||
/>
|
||||
</ToolbarButton>
|
||||
);
|
||||
}
|
||||
|
||||
function SheetHeaderBackButton({ back }: { back: SheetHeaderBack }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
@@ -624,8 +601,8 @@ export interface AdaptiveModalSheetProps {
|
||||
/** Re-establishes caller-owned contexts inside the native or compact sheet portal. */
|
||||
contextBridge?: ContextBridge | null;
|
||||
/**
|
||||
* Keys the body handles while the sheet is the top overlay, such as list navigation. Return true
|
||||
* from `onKeyDown` to claim the key. Escape closes the sheet unless the body lists it and claims it.
|
||||
* Keys the body handles while the sheet is the top overlay, such as list navigation. Escape
|
||||
* always closes the sheet. Return true from `onKeyDown` to claim the key.
|
||||
*/
|
||||
keyboard?: SheetKeyboard;
|
||||
}
|
||||
@@ -783,18 +760,12 @@ export function AdaptiveModalSheet({
|
||||
}
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
// A body that lists Escape among its keys undoes its own step first, such as a page that
|
||||
// returns to the one before it; Escape closes the sheet when the body has nothing to undo.
|
||||
if (keyboard?.keys.includes("Escape") && keyboard.onKeyDown(event)) return true;
|
||||
onClose();
|
||||
return true;
|
||||
},
|
||||
[keyboard, onClose],
|
||||
);
|
||||
const overlayKeys = useMemo(
|
||||
() => ["Escape", ...(keyboard?.keys ?? []).filter((key) => key !== "Escape")],
|
||||
[keyboard?.keys],
|
||||
);
|
||||
const overlayKeys = useMemo(() => ["Escape", ...(keyboard?.keys ?? [])], [keyboard?.keys]);
|
||||
const setOverlayScope = useOverlayRegistration({
|
||||
keys: overlayKeys,
|
||||
active: visible,
|
||||
|
||||
@@ -1,26 +1,18 @@
|
||||
import { useCallback, useMemo, useRef, useState, type ReactNode, type RefObject } from "react";
|
||||
import { Keyboard, Pressable, Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactNode } from "react";
|
||||
import { Pressable, Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { AgentProvider } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentProfile, AgentProfilePicker, AgentProfileSeed } from "@/agent-profiles";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import type { ComboboxProps } from "@/components/ui/combobox";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
type SheetHeader,
|
||||
type SheetKeyboard,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { ModelProviderGlyph, useSelectedModelLabels } from "@/components/model-browser";
|
||||
import { DesktopModelPicker, type ModelPickerActions } from "@/components/model-browser-panes";
|
||||
import {
|
||||
MobileModelPageView,
|
||||
SheetSearchDock,
|
||||
useMobileModelPage,
|
||||
} from "@/components/mobile-model-page";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { Combobox, type ComboboxOption, type ComboboxProps } from "@/components/ui/combobox";
|
||||
import { ModelBrowser, ModelProviderGlyph, useModelBrowser } from "@/components/model-browser";
|
||||
import { resolveModelBrowserScrolling } from "@/components/model-browser-view";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import {
|
||||
TOOLBAR_GLYPH_SIZES,
|
||||
toolbarContentSlot,
|
||||
@@ -29,9 +21,15 @@ import {
|
||||
|
||||
import { useKeyboardToggle, type KeyboardToggleAction } from "@/hooks/use-keyboard-toggle";
|
||||
|
||||
const EMPTY_COMBOBOX_OPTIONS: ComboboxOption[] = [];
|
||||
const DEFAULT_TRIGGER_DECORATION = { showCaret: true, tooltip: undefined };
|
||||
const SHEET_SNAP_POINTS = ["80%", "90%"];
|
||||
const ESCAPE_KEYS = ["Escape"] as const;
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
const foregroundMutedMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
function noop() {}
|
||||
|
||||
interface CombinedModelSelectorProps {
|
||||
providers: ProviderSelectorProvider[];
|
||||
@@ -60,6 +58,7 @@ interface CombinedModelSelectorProps {
|
||||
disabled?: boolean;
|
||||
serverId?: string | null;
|
||||
desktopPlacement?: ComboboxProps["desktopPlacement"];
|
||||
desktopMinWidth?: number;
|
||||
/**
|
||||
* Render the custom trigger as a full-width form field: the outer Pressable
|
||||
* becomes a transparent passthrough that stretches its child edge-to-edge and
|
||||
@@ -76,17 +75,7 @@ interface CombinedModelSelectorProps {
|
||||
};
|
||||
}
|
||||
|
||||
export function CombinedModelSelector(props: CombinedModelSelectorProps) {
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
// One frame per form factor: a sheet that drills into providers, or a two-pane popover.
|
||||
return isCompact ? (
|
||||
<CompactCombinedModelSelector {...props} />
|
||||
) : (
|
||||
<DesktopCombinedModelSelector {...props} />
|
||||
);
|
||||
}
|
||||
|
||||
function DesktopCombinedModelSelector({
|
||||
export function CombinedModelSelector({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
@@ -106,127 +95,60 @@ function DesktopCombinedModelSelector({
|
||||
disabled = false,
|
||||
serverId = null,
|
||||
desktopPlacement,
|
||||
triggerFill = false,
|
||||
toolbar,
|
||||
}: CombinedModelSelectorProps) {
|
||||
const anchorRef = useRef<View>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsOpen(open);
|
||||
if (open) onOpen?.();
|
||||
else onClose?.();
|
||||
},
|
||||
[onClose, onOpen],
|
||||
);
|
||||
const handleTriggerPress = useCallback(() => {
|
||||
handleOpenChange(!isOpen);
|
||||
}, [handleOpenChange, isOpen]);
|
||||
const actions = useModelSelectorActions({
|
||||
onOpenChange: handleOpenChange,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
});
|
||||
|
||||
useKeyboardToggle({
|
||||
action: toggleAction,
|
||||
disabled,
|
||||
open: isOpen,
|
||||
// The search field holds focus for as long as the popover is open.
|
||||
searchFocused: isOpen,
|
||||
onToggle: handleTriggerPress,
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModelSelectorTrigger
|
||||
anchorRef={anchorRef}
|
||||
isOpen={isOpen}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
labels={labels}
|
||||
selectedProvider={selectedProvider}
|
||||
serverId={serverId}
|
||||
renderTrigger={renderTrigger}
|
||||
triggerFill={triggerFill}
|
||||
toolbar={toolbar}
|
||||
/>
|
||||
<DesktopModelPicker
|
||||
open={isOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
providers={providers}
|
||||
selectedProvider={selectedProvider}
|
||||
selectedModel={selectedModel}
|
||||
profiles={profiles}
|
||||
serverId={serverId}
|
||||
onSelect={actions.handleSelect}
|
||||
onApplyProfile={actions.handleApplyProfile}
|
||||
onEditProfiles={onEditProfiles ? actions.handleEditProfiles : undefined}
|
||||
onCreateProfile={onCreateProfile ? actions.handleCreateProfile : undefined}
|
||||
onEditProfile={onEditProfile ? actions.handleEditProfile : undefined}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function CompactCombinedModelSelector({
|
||||
providers,
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
onSelect,
|
||||
isLoading,
|
||||
profiles = null,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
renderTrigger,
|
||||
toggleAction,
|
||||
onOpen,
|
||||
onClose,
|
||||
onRetryProvider,
|
||||
isRetryingProvider = false,
|
||||
disabled = false,
|
||||
serverId = null,
|
||||
desktopMinWidth,
|
||||
triggerFill = false,
|
||||
toolbar,
|
||||
}: CombinedModelSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const modelBrowserScrolling = resolveModelBrowserScrolling({ isNative, isCompact });
|
||||
const anchorRef = useRef<View>(null);
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const labels = useSelectedModelLabels({ providers, selectedProvider, selectedModel, isLoading });
|
||||
const page = useMobileModelPage({
|
||||
const [isContentReady, setIsContentReady] = useState(isWeb);
|
||||
const browser = useModelBrowser({
|
||||
providers,
|
||||
profiles: profiles?.rows ?? null,
|
||||
canCreateProfile: Boolean(onEditProfiles),
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
const { reset, clearQuery } = page;
|
||||
const { prepareToOpen, reset } = browser;
|
||||
|
||||
const handleOpenChange = useCallback(
|
||||
(open: boolean) => {
|
||||
setIsOpen(open);
|
||||
if (open) {
|
||||
reset();
|
||||
prepareToOpen();
|
||||
onOpen?.();
|
||||
return;
|
||||
}
|
||||
Keyboard.dismiss();
|
||||
reset();
|
||||
onClose?.();
|
||||
},
|
||||
[onClose, onOpen, reset],
|
||||
[onClose, onOpen, prepareToOpen, reset],
|
||||
);
|
||||
const handleClose = useCallback(() => handleOpenChange(false), [handleOpenChange]);
|
||||
|
||||
const handleSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
handleOpenChange(false);
|
||||
},
|
||||
[handleOpenChange, onSelect],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (isWeb) return () => {};
|
||||
if (!isOpen) {
|
||||
setIsContentReady(false);
|
||||
return () => {};
|
||||
}
|
||||
const frame = requestAnimationFrame(() => {
|
||||
setIsContentReady(true);
|
||||
});
|
||||
return () => cancelAnimationFrame(frame);
|
||||
}, [isOpen]);
|
||||
|
||||
const handleTriggerPress = useCallback(() => {
|
||||
handleOpenChange(!isOpen);
|
||||
}, [handleOpenChange, isOpen]);
|
||||
@@ -235,184 +157,10 @@ function CompactCombinedModelSelector({
|
||||
action: toggleAction,
|
||||
disabled,
|
||||
open: isOpen,
|
||||
searchFocused: false,
|
||||
searchFocused: browser.isSearchFocused,
|
||||
onToggle: handleTriggerPress,
|
||||
});
|
||||
|
||||
const actions = useModelSelectorActions({
|
||||
onOpenChange: handleOpenChange,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
});
|
||||
const pickerActions = useMemo<ModelPickerActions>(
|
||||
() => ({
|
||||
onSelect: actions.handleSelect,
|
||||
onApplyProfile: actions.handleApplyProfile,
|
||||
onEditProfiles: onEditProfiles ? actions.handleEditProfiles : undefined,
|
||||
onCreateProfile: onCreateProfile ? actions.handleCreateProfile : undefined,
|
||||
onEditProfile: onEditProfile ? actions.handleEditProfile : undefined,
|
||||
onRetryProvider,
|
||||
isRetryingProvider,
|
||||
}),
|
||||
[actions, isRetryingProvider, onCreateProfile, onEditProfile, onEditProfiles, onRetryProvider],
|
||||
);
|
||||
|
||||
// Escape clears the search first, then closes the sheet.
|
||||
const query = page.query;
|
||||
const keyboard = useMemo<SheetKeyboard>(
|
||||
() => ({
|
||||
keys: ESCAPE_KEYS,
|
||||
onKeyDown: (event) => {
|
||||
if (event.key !== "Escape" || query.trim().length === 0) return false;
|
||||
clearQuery();
|
||||
return true;
|
||||
},
|
||||
}),
|
||||
[clearQuery, query],
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("modelSelector.selectModel") }), [t]);
|
||||
const footer = useMemo(() => {
|
||||
let placeholder = t("modelSelector.searchPlaceholder");
|
||||
if (profiles && profiles.rows.length > 0) {
|
||||
placeholder = t("modelSelector.searchModelsAndProfilesPlaceholder");
|
||||
} else if (providers.length > 1) {
|
||||
placeholder = t("modelSelector.searchAllPlaceholder");
|
||||
}
|
||||
return (
|
||||
<SheetSearchDock
|
||||
query={page.query}
|
||||
searchKey={page.searchKey}
|
||||
onChangeText={page.setQuery}
|
||||
placeholder={placeholder}
|
||||
testID="model-search-all-input"
|
||||
/>
|
||||
);
|
||||
}, [page.query, page.searchKey, page.setQuery, profiles, providers.length, t]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<ModelSelectorTrigger
|
||||
anchorRef={anchorRef}
|
||||
isOpen={isOpen}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
labels={labels}
|
||||
selectedProvider={selectedProvider}
|
||||
serverId={serverId}
|
||||
renderTrigger={renderTrigger}
|
||||
triggerFill={triggerFill}
|
||||
toolbar={toolbar}
|
||||
/>
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={isOpen}
|
||||
onClose={handleClose}
|
||||
snapPoints={SHEET_SNAP_POINTS}
|
||||
scrollable={false}
|
||||
footer={footer}
|
||||
keyboard={keyboard}
|
||||
contentStyle={styles.sheetBody}
|
||||
testID="model-selector-sheet"
|
||||
>
|
||||
<MobileModelPageView
|
||||
page={page}
|
||||
selectedProvider={selectedProvider}
|
||||
selectedModel={selectedModel}
|
||||
serverId={serverId}
|
||||
profiles={profiles?.rows ?? null}
|
||||
actions={pickerActions}
|
||||
/>
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every pick resolves the selector and closes it. A 1-tap `+` saves the profile, selects its model
|
||||
* immediately, and closes the picker; useAgentProfileEditor surfaces a toast with Edit and Undo.
|
||||
*/
|
||||
function useModelSelectorActions({
|
||||
onOpenChange,
|
||||
onSelect,
|
||||
onApplyProfile,
|
||||
onEditProfiles,
|
||||
onCreateProfile,
|
||||
onEditProfile,
|
||||
}: Pick<
|
||||
CombinedModelSelectorProps,
|
||||
"onSelect" | "onApplyProfile" | "onEditProfiles" | "onCreateProfile" | "onEditProfile"
|
||||
> & { onOpenChange: (open: boolean) => void }) {
|
||||
const handleSelect = useCallback(
|
||||
(provider: string, modelId: string) => {
|
||||
onSelect(provider, modelId);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onOpenChange, onSelect],
|
||||
);
|
||||
const handleApplyProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onApplyProfile?.(profileId);
|
||||
onOpenChange(false);
|
||||
},
|
||||
[onApplyProfile, onOpenChange],
|
||||
);
|
||||
const handleEditProfiles = useCallback(() => {
|
||||
onOpenChange(false);
|
||||
onEditProfiles?.();
|
||||
}, [onEditProfiles, onOpenChange]);
|
||||
const handleCreateProfile = useCallback(
|
||||
(seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
onOpenChange(false);
|
||||
void onCreateProfile?.(seed);
|
||||
},
|
||||
[onCreateProfile, onOpenChange, onSelect],
|
||||
);
|
||||
const handleEditProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onOpenChange(false);
|
||||
onEditProfile?.(profileId);
|
||||
},
|
||||
[onEditProfile, onOpenChange],
|
||||
);
|
||||
return {
|
||||
handleSelect,
|
||||
handleApplyProfile,
|
||||
handleEditProfiles,
|
||||
handleCreateProfile,
|
||||
handleEditProfile,
|
||||
};
|
||||
}
|
||||
|
||||
function ModelSelectorTrigger({
|
||||
anchorRef,
|
||||
isOpen,
|
||||
disabled,
|
||||
onPress,
|
||||
labels,
|
||||
selectedProvider,
|
||||
serverId,
|
||||
renderTrigger,
|
||||
triggerFill,
|
||||
toolbar,
|
||||
}: {
|
||||
anchorRef: RefObject<View | null>;
|
||||
isOpen: boolean;
|
||||
disabled: boolean;
|
||||
onPress: () => void;
|
||||
labels: { selectedModelLabel: string; triggerLabel: string };
|
||||
selectedProvider: string;
|
||||
serverId: string | null;
|
||||
renderTrigger: CombinedModelSelectorProps["renderTrigger"];
|
||||
triggerFill: boolean;
|
||||
toolbar: CombinedModelSelectorProps["toolbar"];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const triggerStyle = useCallback(
|
||||
({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) => {
|
||||
if (triggerFill) {
|
||||
@@ -433,73 +181,145 @@ function ModelSelectorTrigger({
|
||||
},
|
||||
[disabled, isOpen, renderTrigger, triggerFill],
|
||||
);
|
||||
const accessibilityLabel = t("modelSelector.selectedModel", {
|
||||
model: labels.selectedModelLabel,
|
||||
});
|
||||
|
||||
const handleApplyProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
onApplyProfile?.(profileId);
|
||||
handleOpenChange(false);
|
||||
},
|
||||
[handleOpenChange, onApplyProfile],
|
||||
);
|
||||
|
||||
const handleEditProfiles = useCallback(() => {
|
||||
handleOpenChange(false);
|
||||
onEditProfiles?.();
|
||||
}, [handleOpenChange, onEditProfiles]);
|
||||
|
||||
// 1-tap `+` saves the profile, selects the model immediately, and closes the picker;
|
||||
// useAgentProfileEditor surfaces a toast with Edit and Undo actions.
|
||||
const handleCreateProfile = useCallback(
|
||||
(seed: AgentProfileSeed) => {
|
||||
if (seed.modelId) {
|
||||
onSelect(seed.provider, seed.modelId);
|
||||
}
|
||||
handleOpenChange(false);
|
||||
void onCreateProfile?.(seed);
|
||||
},
|
||||
[handleOpenChange, onCreateProfile, onSelect],
|
||||
);
|
||||
|
||||
const handleEditProfile = useCallback(
|
||||
(profileId: string) => {
|
||||
handleOpenChange(false);
|
||||
onEditProfile?.(profileId);
|
||||
},
|
||||
[handleOpenChange, onEditProfile],
|
||||
);
|
||||
|
||||
const selectorBody = isContentReady ? (
|
||||
<ModelBrowser
|
||||
state={browser}
|
||||
onSelect={handleSelect}
|
||||
onApplyProfile={handleApplyProfile}
|
||||
onEditProfiles={onEditProfiles ? handleEditProfiles : undefined}
|
||||
onCreateProfile={onCreateProfile ? handleCreateProfile : undefined}
|
||||
onEditProfile={onEditProfile ? handleEditProfile : undefined}
|
||||
onRetryProvider={onRetryProvider}
|
||||
isRetryingProvider={isRetryingProvider}
|
||||
scrolling={modelBrowserScrolling}
|
||||
/>
|
||||
) : (
|
||||
<View style={styles.sheetLoadingState}>
|
||||
<ThemedLoadingSpinner size={ICON_SIZE.sm} uniProps={foregroundMutedMapping} />
|
||||
<Text style={styles.sheetLoadingText}>{t("modelSelector.loadingSelector")}</Text>
|
||||
</View>
|
||||
);
|
||||
|
||||
const { showCaret, tooltip } = toolbar ?? DEFAULT_TRIGGER_DECORATION;
|
||||
|
||||
if (renderTrigger) {
|
||||
return (
|
||||
<Pressable
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
testID="combined-model-selector"
|
||||
>
|
||||
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
|
||||
renderTrigger({
|
||||
selectedModelLabel: labels.triggerLabel,
|
||||
onPress,
|
||||
disabled,
|
||||
isOpen,
|
||||
hovered: Boolean(hovered),
|
||||
pressed,
|
||||
})
|
||||
}
|
||||
</Pressable>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<ComboboxTrigger
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={onPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
testID="combined-model-selector"
|
||||
chevron={showCaret === false ? null : undefined}
|
||||
tooltip={tooltip}
|
||||
>
|
||||
{selectedProvider.trim().length > 0 ? (
|
||||
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
|
||||
<ModelProviderGlyph
|
||||
provider={selectedProvider}
|
||||
serverId={serverId}
|
||||
size={toolbar?.glyph.size ?? ICON_SIZE.md}
|
||||
strokeWidth={toolbar?.glyph.strokeWidth}
|
||||
tone={toolbar?.glyph.tone}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
|
||||
{labels.triggerLabel}
|
||||
</Text>
|
||||
</ComboboxTrigger>
|
||||
<>
|
||||
{renderTrigger ? (
|
||||
<Pressable
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t("modelSelector.selectedModel", {
|
||||
model: browser.selectedModelLabel,
|
||||
})}
|
||||
testID="combined-model-selector"
|
||||
>
|
||||
{({ pressed, hovered }: PressableStateCallbackType & { hovered?: boolean }) =>
|
||||
renderTrigger({
|
||||
selectedModelLabel: browser.triggerLabel,
|
||||
onPress: handleTriggerPress,
|
||||
disabled,
|
||||
isOpen,
|
||||
hovered: Boolean(hovered),
|
||||
pressed,
|
||||
})
|
||||
}
|
||||
</Pressable>
|
||||
) : (
|
||||
<ComboboxTrigger
|
||||
ref={anchorRef}
|
||||
collapsable={false}
|
||||
disabled={disabled}
|
||||
onPress={handleTriggerPress}
|
||||
style={triggerStyle}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={t("modelSelector.selectedModel", {
|
||||
model: browser.selectedModelLabel,
|
||||
})}
|
||||
testID="combined-model-selector"
|
||||
chevron={showCaret === false ? null : undefined}
|
||||
tooltip={tooltip}
|
||||
>
|
||||
{selectedProvider.trim().length > 0 ? (
|
||||
<View style={toolbar ? styles.toolbarGlyph : styles.glyph}>
|
||||
<ModelProviderGlyph
|
||||
provider={selectedProvider}
|
||||
serverId={serverId}
|
||||
size={toolbar?.glyph.size ?? ICON_SIZE.md}
|
||||
strokeWidth={toolbar?.glyph.strokeWidth}
|
||||
tone={toolbar?.glyph.tone}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
<Text style={styles.triggerText} numberOfLines={1} ellipsizeMode="tail">
|
||||
{browser.triggerLabel}
|
||||
</Text>
|
||||
</ComboboxTrigger>
|
||||
)}
|
||||
<Combobox
|
||||
options={EMPTY_COMBOBOX_OPTIONS}
|
||||
value=""
|
||||
onSelect={noop}
|
||||
open={isOpen}
|
||||
onOpenChange={handleOpenChange}
|
||||
anchorRef={anchorRef}
|
||||
desktopPlacement={desktopPlacement}
|
||||
desktopMinWidth={desktopMinWidth}
|
||||
desktopLockWidth
|
||||
desktopFixedHeight={browser.desktopFixedHeight}
|
||||
desktopChildrenScrollEnabled={false}
|
||||
header={browser.header}
|
||||
keyboard={browser.keyboard}
|
||||
mobileChildrenScrollEnabled={!browser.isProviderView || !isNative}
|
||||
mobileChildrenContentContainerStyle={styles.mobileBrowserContent}
|
||||
>
|
||||
{selectorBody}
|
||||
</Combobox>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
sheetBody: {
|
||||
mobileBrowserContent: {
|
||||
paddingHorizontal: 0,
|
||||
paddingTop: 0,
|
||||
paddingBottom: 0,
|
||||
gap: 0,
|
||||
},
|
||||
trigger: {
|
||||
minWidth: 0,
|
||||
@@ -551,4 +371,14 @@ const styles = StyleSheet.create((theme) => ({
|
||||
backgroundColor: "transparent",
|
||||
borderRadius: 0,
|
||||
},
|
||||
sheetLoadingState: {
|
||||
minHeight: 160,
|
||||
justifyContent: "center",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
sheetLoadingText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
}));
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user