mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-28 11:15:58 +00:00
Compare commits
30
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b261d207c2 | ||
|
|
9933a302bf | ||
|
|
af8601d060 | ||
|
|
82415b7c15 | ||
|
|
1f2a88e58a | ||
|
|
af4bfad1e2 | ||
|
|
4011199370 | ||
|
|
a6054adb97 | ||
|
|
6fc22514ed | ||
|
|
ea1f2ffab5 | ||
|
|
d9497fb1e4 | ||
|
|
8c18b1558b | ||
|
|
2c2393f0ad | ||
|
|
f786001454 | ||
|
|
43aaf62c7d | ||
|
|
bf23004852 | ||
|
|
3680a4a185 | ||
|
|
9808fd4198 | ||
|
|
5d4793ddc1 | ||
|
|
cb5bcb5a60 | ||
|
|
73fab19166 | ||
|
|
4842f7e24d | ||
|
|
ada93c7a1a | ||
|
|
e05d39bdde | ||
|
|
5e568571ba | ||
|
|
3b5cf28cae | ||
|
|
feb0d74ab5 | ||
|
|
cd5b713a1b | ||
|
|
fef4530e4a | ||
|
|
d77356210e |
@@ -60,7 +60,6 @@ sdk:
|
||||
- "packages/client/**"
|
||||
- "packages/highlight/**"
|
||||
- "packages/protocol/**"
|
||||
- "packages/workflows/**"
|
||||
|
||||
browser:
|
||||
- "packages/server/src/server/agent/provider-snapshot-manager.ts"
|
||||
|
||||
@@ -127,14 +127,6 @@ 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
|
||||
|
||||
@@ -86,6 +86,7 @@ packages/server/src/server/fixtures/dictation/dictation-debug-largest.wav
|
||||
packages/server/src/server/fixtures/dictation/dictation-debug-largest.transcript.txt
|
||||
packages/protocol/src/generated/validation/*.aot.ts
|
||||
packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts
|
||||
packages/protocol/src/generated/validation/message-defaults.ts
|
||||
packages/protocol/codegen/generated/
|
||||
|
||||
/artifacts
|
||||
|
||||
+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>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo のスポンサーになる</a></td>
|
||||
</tr>
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr valign="top">
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Paseo 스폰서 되기</a></td>
|
||||
</tr>
|
||||
|
||||
@@ -57,7 +57,7 @@ Paseo is an open source agentic development environment for desktop, mobile, web
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr valign="top">
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="56"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="56"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/sponsor">Become a sponsor</a></td>
|
||||
</tr>
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@
|
||||
<!-- Sponsors: one cell per sponsor in the order of packages/website/src/data/sponsors.ts, then "become a sponsor" cells up to three. -->
|
||||
<table>
|
||||
<tr valign="top">
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Cloud coding agents</sub></td>
|
||||
<td align="center" width="33%"><a href="https://hoplite.sh/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/hoplite-on-dark.svg"><img src="packages/website/public/sponsors/hoplite-on-light.svg" alt="Hoplite" height="40"></picture></a><br><sub>Hoplite runs swarms of coding agents in the cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://encore.dev/?utm_source=paseo&utm_medium=readme&utm_campaign=sponsor"><picture><source media="(prefers-color-scheme: dark)" srcset="packages/website/public/sponsors/encore-on-dark.svg"><img src="packages/website/public/sponsors/encore-on-light.svg" alt="Encore" height="40"></picture></a><br><sub>Encore lets AI agents ship to production safely, at scale, in your own cloud.</sub></td>
|
||||
<td align="center" width="33%"><a href="https://paseo.sh/zh-CN/sponsor">成为 Paseo 赞助商</a></td>
|
||||
</tr>
|
||||
|
||||
@@ -154,17 +154,17 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. A queued receipt acknowledges admission before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
An agent sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. `steer` and `interrupt` mean what they mean for a person. A person's send has no `queue`. Each kind of prompt is released this way:
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
|
||||
|
||||
- **`queue`** (the agent default) waits. An idle recipient gets the queue after two quiet seconds; steady arrivals cannot hold that window open past ten seconds. While the recipient has a running or starting turn (including compaction), the queue waits and is delivered together when that turn ends on its own or fails. The daemon releases it when it observes the recipient settle; a two-second timer also retries. Finish notifications and change-request updates always queue.
|
||||
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages. Finish notifications and change-request updates always queue.
|
||||
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
|
||||
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
|
||||
- **A person's prompt** (app, CLI, top-level MCP) is dispatched directly with its existing steer or interrupt behavior and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
|
||||
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) is dispatched directly and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
|
||||
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`.
|
||||
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`. A new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
|
||||
|
||||
A command the provider accepts out of band is the one exception to admission order: it runs alone without ending the turn. A queued command runs ahead of older messages, and a `steer` or `interrupt` that runs this way takes no queued message along. A person's command leaves the queue where it is. A prompt is a command when it starts with a slash and a name that has no second slash, so `/compact` is one and `/tmp/build.log is stale` is plain text.
|
||||
|
||||
|
||||
+1
-3
@@ -72,9 +72,7 @@ hashes, never prompts, environment values, or credentials.
|
||||
|
||||
Before messaging an archived workspace, call `workspace.recovery.inspect.request`, then
|
||||
`workspace.recovery.restore.request` and await success. The native message handler unarchives the
|
||||
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so
|
||||
`activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn
|
||||
when that provider cannot steer. The daemon rejects `queue` on a direct send.
|
||||
agent and loads its persisted provider session. A Hub message is a direct send (no `sourceAgentId`), so `activeTurnBehavior: "steer"` uses the provider's native steering and interrupts the running turn when that provider cannot steer, and `activeTurnBehavior: "queue"` waits for the running turn to end when the host advertises `server_info.features.nonAgentMessageQueue`.
|
||||
Execution completion and arrival-specific output authority remain Hub responsibilities.
|
||||
|
||||
The older `hub.execution.*` RPCs remain accepted for existing clients. Their execution ownership
|
||||
|
||||
@@ -95,9 +95,9 @@ A focused terminal excludes that binding. The source leaves terminal Escape alon
|
||||
terminal Escape/Ctrl forwarding is a separate feature.
|
||||
|
||||
Terminal arrows never pass through the shortcut pipeline. The Android hardware
|
||||
module claims them while the terminal's hidden input (`nativeID`) owns the focus.
|
||||
`TextInput.onKeyPress` only sees IME keys, and an arrow that falls through moves
|
||||
the hidden caret and desyncs the next text change, so the pipeline cannot own them.
|
||||
module claims them while the terminal's native input (`nativeID`) owns the focus,
|
||||
so Android DPAD focus search cannot move focus away from the terminal view, while
|
||||
leaving active IME composition spans untouched for candidate navigation.
|
||||
|
||||
## Keys shared with text editing
|
||||
|
||||
|
||||
@@ -12,6 +12,8 @@ Every block is separated by one gap, `density.blockGap`: 12 on compact layouts,
|
||||
|
||||
Workspace file links use the shared file-link resolver. The workspace supplies its client, root and open-file action once; chat can supply the agent's more specific context. URLs use the same link press path. Recognized inline-code paths stay tappable. The library callback carries the tapped occurrence’s syntax context. Preserve it when opening files: explicit Markdown links decode URL escapes, while recognized inline-code paths preserve literal percent characters and use suffix lookup. Identical URL strings in different occurrences must stay distinct. Explicit absolute workspace links receive a relative hover title; existing authored titles remain intact. Inside a workspace, forge references such as `#12` and `owner/repo#12` are recognized in prose (not code) and open the workspace forge; the reference pattern comes before path recognition so `group/project#12` is not read as a path. See [forge providers](forge-providers.md#gotchas).
|
||||
|
||||
Right-click on web and long press on native open one link menu per rendered part (`components/markdown/link-menu`), not one per link: a menu root cannot sit inside a paragraph without producing invalid markup on web. The native long-press event carries only the URL, with no position and no syntax context. The menu takes the position from the touch that started the press, and treats a URL that is no `](destination)` in the source as recognized text.
|
||||
|
||||
Pass `external` for author-controlled Markdown from outside the host, such as a plugin README. It follows the registry's overview contract in `packages/protocol/src/plugin-overview.ts`, which the website also uses: only absolute https links and images work, and any other destination renders as its label or alt text. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only https. None of the workspace recognition above applies, so `Node.js` is prose, not a file. The lines of a paragraph join, as they do on the README's forge.
|
||||
|
||||
Resolve workspace image paths over the existing session RPC, then give the library a cached native file URL or web blob URL. HTTP(S) images pass through unchanged. This preserves relay, SSH and local socket connections, which do not expose a daemon HTTP endpoint. Each mounted renderer owns its image acquisition identity, so a later reply reads a rewritten path again while the earlier mounted reply retains its snapshot. Image taps open the attachment lightbox. File previews resolve relative images against the Markdown file's directory. An image alone on its line becomes its own paragraph before the library sees it, so it renders as a block on every platform; the library only treats sole-child paragraph images as blocks, and with hard soft breaks every newline is a break node, which left own-line images inline on iOS and web. Images that share a line with text stay inline at line height and keep their aspect ratio. A linked image counts as an image, so review-bot badges such as `[](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,6 +63,8 @@ An arbitrary Activity launch with data extras does not exercise Expo's FCM path.
|
||||
Foreground pushes remain in Notification Center without a banner or sound.
|
||||
This preserves notifications sent with stale presence information.
|
||||
|
||||
Native clients have no DOM events, so presence comes from `@/hooks/native-user-activity`: touches on the root `GestureHandlerRootView` and edits in the native `EditingTextInput` refresh `lastActivityAt`. Touches inside a native `Modal` open a separate window and do not reach the root.
|
||||
|
||||
## Startup and verification
|
||||
|
||||
Wait for the root navigator, host registry, remembered selection, and startup
|
||||
|
||||
@@ -103,6 +103,13 @@ The `worktree-include` built-in copies gitignored files selected by
|
||||
[`.worktreeinclude`](../public-docs/worktrees.md#copy-local-files-with-worktreeinclude)
|
||||
before setup and agents, through `worktree.create.after`.
|
||||
|
||||
The `cloudflared-tunnel` and `tailscale-funnel` built-ins register tunnel providers through
|
||||
`server.registerTunnelProvider()`. Both start without installed binaries or credentials and report
|
||||
availability through `status()`. `cloudflared-tunnel` runs quick tunnels only, with `--url` set to
|
||||
the exposure target. Named Cloudflare tunnels are not supported: the Cloudflare dashboard sets
|
||||
their routing, so their URL does not serve the exposure target. `tailscale-funnel` runs `tailscale funnel` in the foreground: with
|
||||
`--bg`, tailscaled keeps the Funnel public after a crash with no owner.
|
||||
|
||||
Desktop packaging ships the entire built-in plugin directory as an external resource,
|
||||
including declarations. The external esbuild compiler cannot read Electron's `app.asar`
|
||||
filesystem, and packaging dependencies excludes `.d.ts` files needed for import validation.
|
||||
|
||||
@@ -21,7 +21,7 @@ The protocol package owns generation.
|
||||
- `packages/protocol/src/validation/ws-outbound-envelope.ts` defines the tag-only envelope schema and exposes the session message schemas that get their own validators.
|
||||
- `packages/protocol/scripts/generate-validation-aot.mjs` writes the zod-aot discovery entry and the runtime schema metadata, runs the exact-pinned compiler, and applies the small local compiler patches before generation. It also emits the `type` → validator map the boundary dispatches through.
|
||||
- `packages/protocol/scripts/watch-validation-aot.mjs` reruns generation while editing protocol sources.
|
||||
- `packages/protocol/codegen/generated/ws-outbound.compile.ts`, `packages/protocol/src/generated/validation/ws-outbound.aot.ts`, and `packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts` are generated and gitignored. The metadata module lets generated code reach schema fallback/default values.
|
||||
- `packages/protocol/codegen/generated/ws-outbound.compile.ts`, `packages/protocol/src/generated/validation/ws-outbound.aot.ts`, `packages/protocol/src/generated/validation/ws-outbound-schema-metadata.ts`, and `packages/protocol/src/generated/validation/message-defaults.ts` are generated and gitignored. The metadata module lets generated code reach schema fallback/default values, and `message-defaults.ts` lets zero-Zod clients (`packages/protocol/src/validation/message-defaults.ts`) apply every schema `.default()` without loading Zod or `ws-outbound.aot.ts`.
|
||||
|
||||
Generation runs from protocol-owned lifecycle hooks: `prebuild`, `pretypecheck`, `pretest`, and `watch`. Installs do not run generation: published packages consume protocol from prebuilt `dist`, and local build/typecheck/test flows generate the source file at the point it is actually needed.
|
||||
|
||||
|
||||
@@ -47,8 +47,14 @@
|
||||
"ignore": ["android/**", "ios/**", ".expo/**", "dist/**", "scripts/reset-project.js"]
|
||||
},
|
||||
"packages/cli": {
|
||||
"entry": ["src/index.ts", "bin/paseo", "src/**/*.test.{ts,tsx}", "tests/**/*.{ts,tsx}"],
|
||||
"project": ["src/**/*.{ts,tsx}", "tests/**/*.{ts,tsx}"]
|
||||
"entry": [
|
||||
"src/index.ts",
|
||||
"bin/paseo",
|
||||
"scripts/**/*.mjs",
|
||||
"src/**/*.test.{ts,tsx}",
|
||||
"tests/**/*.{ts,tsx}"
|
||||
],
|
||||
"project": ["src/**/*.{ts,tsx}", "scripts/**/*.mjs", "tests/**/*.{ts,tsx}"]
|
||||
},
|
||||
"packages/relay": {
|
||||
"entry": ["src/index.ts", "src/e2ee.ts", "src/cloudflare-adapter.ts", "src/**/*.test.ts"],
|
||||
@@ -67,17 +73,6 @@
|
||||
"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
+3
-20
@@ -16,7 +16,6 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -6710,10 +6709,6 @@
|
||||
"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",
|
||||
@@ -14929,6 +14924,7 @@
|
||||
"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",
|
||||
@@ -31402,6 +31398,7 @@
|
||||
"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"
|
||||
@@ -36231,6 +36228,7 @@
|
||||
"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"
|
||||
@@ -43161,21 +43159,6 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"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,7 +27,6 @@
|
||||
"packages/highlight",
|
||||
"packages/plugin",
|
||||
"packages/protocol",
|
||||
"packages/workflows",
|
||||
"packages/client",
|
||||
"packages/server",
|
||||
"packages/app",
|
||||
@@ -61,8 +60,6 @@
|
||||
"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,6 +2,7 @@ const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
const pkg = require("./package.json");
|
||||
const withAndroidAsyncStorageSize = require("./plugins/with-android-async-storage-size");
|
||||
const withAndroidIgnoreBoldText = require("./plugins/with-android-ignore-bold-text");
|
||||
const withAndroidOptionalCamera = require("./plugins/with-android-optional-camera");
|
||||
const withAndroidProfileable = require("./plugins/with-android-profileable");
|
||||
const withFdroidAutolinking = require("./plugins/with-fdroid-autolinking");
|
||||
@@ -148,6 +149,7 @@ export default {
|
||||
withPasteInput,
|
||||
withAndroidScroll,
|
||||
withAndroidDisplayMetrics,
|
||||
withAndroidIgnoreBoldText,
|
||||
[withAndroidAsyncStorageSize, 64],
|
||||
...buildProfile.cameraPlugins,
|
||||
withAndroidOptionalCamera,
|
||||
|
||||
@@ -112,3 +112,92 @@ describe("hardware keyboard scene integration", () => {
|
||||
expect(configureHardwareKeyboardAppDelegate(configured)).toBe(configured);
|
||||
});
|
||||
});
|
||||
|
||||
// Android Bold text bolds unstyled text at draw time after React Native measured it
|
||||
// unbolded, which clips trailing words (#4057, #10152, #10850). The activity must opt out
|
||||
// with a sparse Configuration() so other configuration fields still update live.
|
||||
describe("Android Bold text opt-out", () => {
|
||||
const {
|
||||
configureIgnoreBoldTextMainActivity,
|
||||
} = require("./plugins/with-android-ignore-bold-text.js");
|
||||
const {
|
||||
configureDisplayMetricsActivity,
|
||||
} = require("./modules/paseo-display-metrics/app.plugin.js");
|
||||
const mainActivity = [
|
||||
"package sh.paseo",
|
||||
"import expo.modules.splashscreen.SplashScreenManager",
|
||||
"",
|
||||
"import android.os.Build",
|
||||
"import android.os.Bundle",
|
||||
"",
|
||||
"import com.facebook.react.ReactActivity",
|
||||
"",
|
||||
"class MainActivity : ReactActivity() {",
|
||||
" override fun onCreate(savedInstanceState: Bundle?) {",
|
||||
" super.onCreate(null)",
|
||||
" }",
|
||||
"}",
|
||||
"",
|
||||
].join("\n");
|
||||
|
||||
it("zeroes fontWeightAdjustment on a sparse Configuration before attaching and is idempotent", () => {
|
||||
const configured = configureIgnoreBoldTextMainActivity(mainActivity);
|
||||
expect(configured).toMatch(/^import android\.content\.Context$/m);
|
||||
expect(configured).toMatch(/^import android\.content\.res\.Configuration$/m);
|
||||
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
|
||||
expect(configured).toContain("val override = Configuration()");
|
||||
expect(configured).not.toContain("Configuration(configuration)");
|
||||
expect(configured).toContain("override.fontWeightAdjustment = 0");
|
||||
expect(configured).toContain(
|
||||
"super.attachBaseContext(newBase.createConfigurationContext(override))",
|
||||
);
|
||||
expect(configured.indexOf("attachBaseContext")).toBeLessThan(configured.indexOf("onCreate"));
|
||||
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
|
||||
});
|
||||
|
||||
it("composes cleanly with withAndroidDisplayMetrics in both plugin orders", () => {
|
||||
const displayFirst = configureIgnoreBoldTextMainActivity(
|
||||
configureDisplayMetricsActivity(mainActivity),
|
||||
);
|
||||
const boldFirst = configureDisplayMetricsActivity(
|
||||
configureIgnoreBoldTextMainActivity(mainActivity),
|
||||
);
|
||||
|
||||
for (const configured of [displayFirst, boldFirst]) {
|
||||
expect(configured).toContain("override fun attachBaseContext(newBase: Context)");
|
||||
expect(configured).toContain("val override = Configuration()");
|
||||
expect(configured).toContain("override.fontWeightAdjustment = 0");
|
||||
expect(configured).toContain("override fun onContentChanged()");
|
||||
expect(configured).toContain(
|
||||
"override fun onConfigurationChanged(newConfig: android.content.res.Configuration)",
|
||||
);
|
||||
expect(configured).toContain(
|
||||
"sh.paseo.displaymetrics.PaseoDisplayMetrics.syncWithWindow(this)",
|
||||
);
|
||||
expect(configureIgnoreBoldTextMainActivity(configured)).toBe(configured);
|
||||
expect(configureDisplayMetricsActivity(configured)).toBe(configured);
|
||||
}
|
||||
});
|
||||
|
||||
it("fails the prebuild when the MainActivity template changes shape", () => {
|
||||
expect(() => configureIgnoreBoldTextMainActivity("package sh.paseo\n")).toThrow(
|
||||
/MainActivity class declaration/,
|
||||
);
|
||||
});
|
||||
|
||||
it("fails the prebuild rather than duplicate an existing attachBaseContext override", () => {
|
||||
const withExistingOverride = mainActivity.replace(
|
||||
"override fun onCreate",
|
||||
"override fun attachBaseContext(newBase: Context) { super.attachBaseContext(newBase) }\n\n override fun onCreate",
|
||||
);
|
||||
expect(() => configureIgnoreBoldTextMainActivity(withExistingOverride)).toThrow(
|
||||
/existing attachBaseContext override/,
|
||||
);
|
||||
});
|
||||
|
||||
it("is registered in the app config", async () => {
|
||||
const { exp } = await getPrebuildConfigAsync(__dirname, { platforms: ["android"] });
|
||||
// Expo records function plugins by name.
|
||||
expect(exp.plugins).toContain("withAndroidIgnoreBoldText");
|
||||
}, 30_000);
|
||||
});
|
||||
|
||||
@@ -1042,7 +1042,7 @@ test("changes context menu recursively collapses descendant folders", async ({ p
|
||||
nestedLabel.boundingBox(),
|
||||
]);
|
||||
if (!rootBounds || !nestedBounds) throw new Error("Changes tree rows have no bounds");
|
||||
expect(nestedBounds.x - rootBounds.x).toBe(12);
|
||||
expect(nestedBounds.x - rootBounds.x).toBe(16);
|
||||
|
||||
await tree.getByTestId("diff-folder-src-toggle").click({ button: "right" });
|
||||
await page.getByTestId("diff-folder-src-collapse-folder").click();
|
||||
|
||||
@@ -3,6 +3,7 @@ import path from "node:path";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import {
|
||||
expectSubagentRowGone,
|
||||
@@ -29,6 +30,89 @@ import {
|
||||
|
||||
const FILE_LINK = "linked.ts:3";
|
||||
|
||||
test("compact offers file actions from a link and from the file sheet", async ({ page }) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "compact-file-actions-",
|
||||
title: "File actions",
|
||||
initialPrompt: promptMentioning(FILE_LINK),
|
||||
});
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
|
||||
const fileLink = page.getByText(FILE_LINK, { exact: true });
|
||||
await expect(fileLink).toBeVisible({ timeout: 15_000 });
|
||||
|
||||
// Native opens the same sheet from a long press.
|
||||
await fileLink.click({ button: "right" });
|
||||
const linkMenu = page.getByTestId("markdown-link-menu-content");
|
||||
await expect(linkMenu.getByRole("menuitem")).toHaveText([
|
||||
"Open file",
|
||||
"Reveal in Files",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
await linkMenu.getByRole("menuitem", { name: "Open file" }).click();
|
||||
|
||||
await expect(sheet(page, "linked.ts")).toBeVisible();
|
||||
await page.getByTestId("sheet-file-menu-trigger").click();
|
||||
const sheetMenu = page.getByTestId("sheet-file-menu-content");
|
||||
await expect(sheetMenu.getByRole("menuitem")).toHaveText([
|
||||
"Reveal in Files",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
await expect(sheetMenu.getByRole("menuitem").last()).toBeInViewport({ ratio: 1 });
|
||||
await page.screenshot({
|
||||
path: test.info().outputPath("compact-file-sheet-menu.png"),
|
||||
animations: "disabled",
|
||||
});
|
||||
await sheetMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
|
||||
await expectNoSheetOpen(page);
|
||||
await expect(
|
||||
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
|
||||
).toContainText("linked.ts");
|
||||
await page.screenshot({
|
||||
path: test.info().outputPath("compact-reveal-in-files.png"),
|
||||
animations: "disabled",
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("a narrow desktop window keeps the desktop actions in the file sheet menu", async ({
|
||||
page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
const workspace = await seedMockAgentWorkspace({
|
||||
repoPrefix: "narrow-desktop-file-actions-",
|
||||
title: "File actions",
|
||||
initialPrompt: promptMentioning(FILE_LINK),
|
||||
});
|
||||
try {
|
||||
await writeFile(path.join(workspace.cwd, "linked.ts"), "one\ntwo\nthree\n", "utf8");
|
||||
await installLocalDesktopHost(page, workspace.cwd, { fileManager: "Dolphin" });
|
||||
await openAgentRoute(page, { workspaceId: workspace.workspaceId, agentId: workspace.agentId });
|
||||
await page.getByText(FILE_LINK, { exact: true }).click();
|
||||
|
||||
await expect(sheet(page, "linked.ts")).toBeVisible({ timeout: 15_000 });
|
||||
await page.getByTestId("sheet-file-menu-trigger").click();
|
||||
await expect(page.getByTestId("sheet-file-menu-content").getByRole("menuitem")).toHaveText([
|
||||
"Reveal in Files",
|
||||
"Reveal in Dolphin",
|
||||
"Open in default app",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("compact opens files and subagents in a sheet, leaving the tabs for agents", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { test } from "../support/fixtures";
|
||||
import {
|
||||
expectExplorerEntryHidden,
|
||||
expectExplorerEntryVisible,
|
||||
expandFolder,
|
||||
expectFileTabOpen,
|
||||
openFileExplorer,
|
||||
} from "../support/helpers/file-explorer";
|
||||
import { gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { seedWorkspace, type SeededWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
let workspace: SeededWorkspace;
|
||||
|
||||
test.beforeEach(async () => {
|
||||
workspace = await seedWorkspace({ repoPrefix: "file-explorer-filter-" });
|
||||
await mkdir(path.join(workspace.repoPath, "data/nested"), { recursive: true });
|
||||
await writeFile(path.join(workspace.repoPath, "data/nested/report.csv"), "name,total\n");
|
||||
await mkdir(path.join(workspace.repoPath, "docs"), { recursive: true });
|
||||
await writeFile(path.join(workspace.repoPath, "docs/guide.md"), "# Guide\n");
|
||||
});
|
||||
|
||||
test.afterEach(async () => {
|
||||
await workspace?.cleanup();
|
||||
});
|
||||
|
||||
function filterInput(page: Page) {
|
||||
return page.getByTestId("files-filter-input");
|
||||
}
|
||||
|
||||
function matches(page: Page) {
|
||||
return page.locator('[data-testid^="file-filter-row-"][aria-selected]');
|
||||
}
|
||||
|
||||
function match(page: Page, name: string) {
|
||||
return matches(page).filter({ hasText: name });
|
||||
}
|
||||
|
||||
test("finds files in collapsed folders and acts on them", async ({ page }) => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openFileExplorer(page);
|
||||
await expandFolder(page, "docs");
|
||||
await expectExplorerEntryVisible(page, "guide.md");
|
||||
|
||||
await filterInput(page).fill("report");
|
||||
await expect(matches(page)).toHaveCount(1);
|
||||
await expect(match(page, "report.csv")).toContainText("data/nested");
|
||||
// Draggable onto the chat, like a tree row.
|
||||
await expect(match(page, "report.csv").locator('[draggable="true"]')).toHaveCount(1);
|
||||
|
||||
await match(page, "report.csv").click({ button: "right" });
|
||||
const menu = page.getByTestId(/file-filter-row-\d+-context-menu$/);
|
||||
for (const name of [
|
||||
"Reveal in Files",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
"Download",
|
||||
"Rename",
|
||||
"Delete",
|
||||
]) {
|
||||
await expect(menu.getByRole("menuitem", { name, exact: true })).toBeVisible();
|
||||
}
|
||||
await expect(menu.getByRole("menuitem", { name: "New file", exact: true })).toHaveCount(0);
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(menu).toHaveCount(0);
|
||||
|
||||
await match(page, "report.csv").click();
|
||||
await expectFileTabOpen(page, "data/nested/report.csv");
|
||||
|
||||
// Escape restores the tree with its expanded folders.
|
||||
await filterInput(page).press("Escape");
|
||||
await expect(filterInput(page)).toHaveValue("");
|
||||
await expectExplorerEntryVisible(page, "guide.md");
|
||||
await expectExplorerEntryHidden(page, "report.csv");
|
||||
|
||||
// So does the clear button.
|
||||
await filterInput(page).fill("zzz-no-such-file");
|
||||
await expect(page.getByText("No matching files", { exact: true })).toBeVisible();
|
||||
await page.getByTestId("files-filter-clear").click();
|
||||
await expect(filterInput(page)).toHaveValue("");
|
||||
await expectExplorerEntryVisible(page, "guide.md");
|
||||
|
||||
// Revealing a match leaves the filter and selects the file in the tree.
|
||||
await filterInput(page).fill("report");
|
||||
await match(page, "report.csv").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Reveal in Files", exact: true }).click();
|
||||
await expect(filterInput(page)).toHaveValue("");
|
||||
await expect(
|
||||
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
|
||||
).toContainText("report.csv");
|
||||
});
|
||||
|
||||
/** The directory listings the app asks the host for, by path. */
|
||||
function recordDirectoryListings(page: Page): string[] {
|
||||
const listed: string[] = [];
|
||||
page.on("websocket", (socket) => {
|
||||
socket.on("framesent", ({ payload }) => {
|
||||
if (typeof payload !== "string") return;
|
||||
const { message } = JSON.parse(payload);
|
||||
if (message?.type === "file_explorer_request" && message.mode === "list") {
|
||||
listed.push(message.path);
|
||||
}
|
||||
});
|
||||
});
|
||||
return listed;
|
||||
}
|
||||
|
||||
test("opens a matching folder in the tree", async ({ page }) => {
|
||||
const listed = recordDirectoryListings(page);
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openFileExplorer(page);
|
||||
|
||||
await filterInput(page).fill("nested");
|
||||
await match(page, "nested").first().click();
|
||||
|
||||
await expect(filterInput(page)).toHaveValue("");
|
||||
await expectExplorerEntryVisible(page, "report.csv");
|
||||
await expect(
|
||||
page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]'),
|
||||
).toContainText("nested");
|
||||
// One walk down to the folder: its collapsed parent is listed once.
|
||||
expect(listed.filter((directory) => directory === "data")).toEqual(["data"]);
|
||||
});
|
||||
|
||||
test("renames and deletes a match without leaving the filter", async ({ page }) => {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openFileExplorer(page);
|
||||
|
||||
await filterInput(page).fill("guide");
|
||||
await match(page, "guide.md").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Rename", exact: true }).click();
|
||||
const nameInput = page.getByTestId("file-explorer-name-input");
|
||||
await nameInput.fill("guide-v2.md");
|
||||
await nameInput.press("Enter");
|
||||
await expect(match(page, "guide-v2.md")).toBeVisible();
|
||||
|
||||
page.once("dialog", (dialog) => void dialog.accept());
|
||||
await match(page, "guide-v2.md").click({ button: "right" });
|
||||
await page.getByRole("menuitem", { name: "Delete", exact: true }).click();
|
||||
await expect(page.getByText("No matching files", { exact: true })).toBeVisible();
|
||||
});
|
||||
@@ -0,0 +1,135 @@
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { commandCenterSection, openCommandCenter } from "../support/helpers/command-center";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
|
||||
const REPLY = [
|
||||
"Read [the report](data/report.csv), the [settings](.config/nested/file-55.json),",
|
||||
"the [data folder](data) or the [website](https://example.test/docs).",
|
||||
"Nothing is at gone.md.",
|
||||
].join(" ");
|
||||
|
||||
async function seedLinkedFiles() {
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "file-link-menu-",
|
||||
title: "File link actions",
|
||||
initialPrompt: "Show the links",
|
||||
featureValues: { mockAssistantResponse: REPLY },
|
||||
});
|
||||
await mkdir(path.join(agent.cwd, "data"), { recursive: true });
|
||||
await writeFile(path.join(agent.cwd, "data/report.csv"), "name,total\nalpha,1\n");
|
||||
await mkdir(path.join(agent.cwd, ".config/nested"), { recursive: true });
|
||||
// Enough siblings that the target row starts outside the tree's viewport.
|
||||
await Promise.all(
|
||||
Array.from({ length: 60 }, (_, index) =>
|
||||
writeFile(
|
||||
path.join(agent.cwd, `.config/nested/file-${String(index).padStart(2, "0")}.json`),
|
||||
"{}\n",
|
||||
),
|
||||
),
|
||||
);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
return agent;
|
||||
}
|
||||
|
||||
function replyLink(page: Page, name: string) {
|
||||
return page.getByTestId("assistant-message").getByRole("link", { name, exact: true });
|
||||
}
|
||||
|
||||
function linkMenu(page: Page) {
|
||||
return page.getByTestId("markdown-link-menu");
|
||||
}
|
||||
|
||||
function selectedTreeRow(page: Page) {
|
||||
return page.locator('[data-testid^="file-explorer-row-"][aria-selected="true"]');
|
||||
}
|
||||
|
||||
async function expectMenuItems(page: Page, names: string[]) {
|
||||
await expect(linkMenu(page).getByRole("menuitem")).toHaveText(names);
|
||||
}
|
||||
|
||||
async function dismissMenu(page: Page) {
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(linkMenu(page)).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function screenshot(page: Page, name: string) {
|
||||
await page.screenshot({
|
||||
path: test.info().outputPath(`${name}.png`),
|
||||
animations: "disabled",
|
||||
});
|
||||
}
|
||||
|
||||
test("links in chat and file tabs offer file actions and reveal the file in Files", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
testInfo.setTimeout(180_000);
|
||||
const agent = await seedLinkedFiles();
|
||||
try {
|
||||
await page.addInitScript(() => {
|
||||
localStorage.setItem(
|
||||
"panel-state",
|
||||
JSON.stringify({ state: { explorerShowHiddenFiles: false }, version: 0 }),
|
||||
);
|
||||
});
|
||||
await openAgentRoute(page, agent);
|
||||
|
||||
await replyLink(page, "the report").click({ button: "right" });
|
||||
await expectMenuItems(page, [
|
||||
"Open file",
|
||||
"Open to the side",
|
||||
"Reveal in Files",
|
||||
"Download",
|
||||
"Copy path",
|
||||
"Copy relative path",
|
||||
]);
|
||||
await screenshot(page, "chat-file-link-menu");
|
||||
await dismissMenu(page);
|
||||
|
||||
await replyLink(page, "data folder").click({ button: "right" });
|
||||
await expectMenuItems(page, ["Reveal in Files", "Copy path", "Copy relative path"]);
|
||||
await dismissMenu(page);
|
||||
|
||||
await replyLink(page, "website").click({ button: "right" });
|
||||
await expectMenuItems(page, ["Open in default browser", "Copy link"]);
|
||||
await screenshot(page, "chat-web-link-menu");
|
||||
await dismissMenu(page);
|
||||
|
||||
// A bare name is looked up while the menu is open; acting on one that matches nothing says so.
|
||||
await replyLink(page, "gone.md").click({ button: "right" });
|
||||
await linkMenu(page).getByRole("menuitem", { name: "Download" }).click();
|
||||
await expect(page.getByTestId("assistant-file-link-not-found-toast")).toContainText("gone.md");
|
||||
|
||||
await replyLink(page, "the report").click({ button: "right" });
|
||||
await linkMenu(page).getByRole("menuitem", { name: "Reveal in Files" }).click();
|
||||
await expect(selectedTreeRow(page)).toContainText("report.csv");
|
||||
await expect(replyLink(page, "the report")).toBeVisible();
|
||||
await screenshot(page, "reveal-in-files-from-chat-link");
|
||||
|
||||
// A hidden folder, a freshly expanded tree and a row far below the fold.
|
||||
await replyLink(page, "settings").click();
|
||||
const fileTab = page.getByTestId("workspace-tab-file_.config/nested/file-55.json").first();
|
||||
await expect(fileTab).toBeVisible();
|
||||
await fileTab.click({ button: "right" });
|
||||
const tabMenu = page.getByTestId("workspace-tab-context-file_.config/nested/file-55.json");
|
||||
await expect(tabMenu.getByRole("menuitem", { name: "Reveal in Files" })).toBeVisible();
|
||||
await expect(tabMenu.getByRole("menuitem", { name: "Copy relative path" })).toBeVisible();
|
||||
await screenshot(page, "file-tab-menu");
|
||||
await tabMenu.getByRole("menuitem", { name: "Reveal in Files" }).click();
|
||||
await expect(selectedTreeRow(page)).toContainText("file-55.json");
|
||||
await expect(selectedTreeRow(page)).toBeInViewport();
|
||||
await screenshot(page, "reveal-in-files-from-file-tab");
|
||||
|
||||
// The tree is already mounted and scrolled elsewhere. Command Center reveals the active tab.
|
||||
await page.getByTestId("file-explorer-tree-scroll").hover();
|
||||
await page.mouse.wheel(0, -100_000);
|
||||
await expect(selectedTreeRow(page)).not.toBeInViewport();
|
||||
const commandCenter = await openCommandCenter(page);
|
||||
await commandCenter.getByTestId("command-center-input").fill("Reveal in Files");
|
||||
await commandCenterSection(commandCenter, "Reveal in Files").click();
|
||||
await expect(selectedTreeRow(page)).toBeInViewport();
|
||||
} finally {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -13,11 +13,17 @@ import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import type { Locator } from "@playwright/test";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
|
||||
const PLUGIN_ID = "plugin-host-ui-e2e";
|
||||
const TINY_PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||
"base64",
|
||||
);
|
||||
|
||||
const PLUGIN_SOURCE = `import { usePaseo } from "@getpaseo/plugin/client";
|
||||
import { Icon, Modal, useToast, Markdown } from "@getpaseo/plugin/client/ui";
|
||||
@@ -39,6 +45,7 @@ function ModalBody({ onSaved }) {
|
||||
<Text>Plugin modal contexts ready</Text>
|
||||
<Markdown>{"## Plugin report"}</Markdown>
|
||||
<Markdown>{"Checks **passed**. [Documentation](https://paseo.sh/docs/plugins)"}</Markdown>
|
||||
<Markdown>{""}</Markdown>
|
||||
<Markdown>{""}</Markdown>
|
||||
<Pressable accessibilityRole="button" onPress={save}>
|
||||
<Text>Save issue</Text>
|
||||
@@ -56,6 +63,7 @@ function Surface({ playAudio }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
return <View>
|
||||
<Text>{audioStatus}</Text>
|
||||
<Markdown>{"\\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)}>
|
||||
@@ -105,20 +113,39 @@ async function openPluginModal(page: Page): Promise<void> {
|
||||
await page.getByRole("button", { name: "Open plugin modal", exact: true }).click();
|
||||
}
|
||||
|
||||
async function expectPluginMarkdown(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("heading", { name: "Plugin report" })).toBeVisible();
|
||||
await expect(page.getByText("Checks passed.", { exact: false })).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "Documentation", exact: true })).toHaveAttribute(
|
||||
async function expectLoadedMarkdownImage(scope: Page | Locator, alt: string): Promise<void> {
|
||||
const image = scope.getByAltText(alt, { exact: true });
|
||||
await expect(image).toBeVisible();
|
||||
await expect
|
||||
.poll(() =>
|
||||
image.evaluate((node) => {
|
||||
const img = node as HTMLImageElement;
|
||||
return {
|
||||
isBlob: img.src.startsWith("blob:"),
|
||||
complete: img.complete,
|
||||
naturalWidth: img.naturalWidth,
|
||||
};
|
||||
}),
|
||||
)
|
||||
.toEqual({ isBlob: true, complete: true, naturalWidth: 1 });
|
||||
}
|
||||
|
||||
async function expectPluginMarkdown(scope: Page | Locator): Promise<void> {
|
||||
await expect(scope.getByRole("heading", { name: "Plugin report" })).toBeVisible();
|
||||
await expect(scope.getByText("Checks passed.", { exact: false })).toBeVisible();
|
||||
await expect(scope.getByRole("link", { name: "Documentation", exact: true })).toHaveAttribute(
|
||||
"href",
|
||||
"https://paseo.sh/docs/plugins",
|
||||
);
|
||||
await expectLoadedMarkdownImage(scope, "Modal preview");
|
||||
await expect(scope.getByText("Image unavailable")).toHaveCount(0);
|
||||
}
|
||||
|
||||
async function expectCenteredPluginDialog(page: Page): Promise<void> {
|
||||
const dialog = page.getByRole("dialog");
|
||||
await expect(dialog.getByText("Edit plugin issue", { exact: true })).toBeVisible();
|
||||
await expect(dialog.getByText("Plugin modal contexts ready", { exact: true })).toBeVisible();
|
||||
await expectPluginMarkdown(page);
|
||||
await expectPluginMarkdown(dialog);
|
||||
}
|
||||
|
||||
async function closeCenteredPluginDialog(page: Page): Promise<void> {
|
||||
@@ -147,10 +174,15 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
|
||||
);
|
||||
const beforePath = path.join(directory, "before.png");
|
||||
const afterPath = path.join(directory, "after.png");
|
||||
const afterFileUrl = pathToFileURL(afterPath).href;
|
||||
await writeFile(beforePath, TINY_PNG);
|
||||
await writeFile(afterPath, TINY_PNG);
|
||||
const audio = await readFile(path.resolve(__dirname, "../../assets/audio/thinking-tone.wav"));
|
||||
await writeFile(
|
||||
path.join(directory, "index.client.tsx"),
|
||||
`const AUDIO_BASE64 = ${JSON.stringify(audio.toString("base64"))};\n${PLUGIN_SOURCE}`,
|
||||
`const AUDIO_BASE64 = ${JSON.stringify(audio.toString("base64"))};\nconst SCREENSHOT_PATH = ${JSON.stringify(beforePath)};\nconst SCREENSHOT_FILE_URL = ${JSON.stringify(afterFileUrl)};\n${PLUGIN_SOURCE}`,
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -159,6 +191,12 @@ test("plugin modal adapts its presentation and preserves host contexts", async (
|
||||
await useNonCompactLayout(page);
|
||||
await openHostUiPlugin(page);
|
||||
|
||||
await test.step("plugin screen Markdown renders local absolute and file:// PNG images inline", async () => {
|
||||
await expectLoadedMarkdownImage(page, "Before");
|
||||
await expectLoadedMarkdownImage(page, "After");
|
||||
await expect(page.getByText("Image unavailable")).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("plugin audio finishes, rejects corrupt files, and recovers", async () => {
|
||||
await playPluginAudio(page, "Play plugin audio", "Audio finished");
|
||||
await playPluginAudio(page, "Play invalid audio", "Audio rejected");
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { TerminalE2EHarness, withTerminalInApp } from "../support/helpers/terminal-dsl";
|
||||
import { waitForTerminalContent } from "../support/helpers/terminal-perf";
|
||||
|
||||
const CODE_FONT = "monospace";
|
||||
const INTERFACE_FONT = "serif";
|
||||
|
||||
test("terminal text keeps the code font when an interface font is set", async ({ page }) => {
|
||||
// Without WebGL2 the terminal falls back to xterm's DOM renderer, whose rows are
|
||||
// styled by CSS and so can inherit the interface font.
|
||||
await page.addInitScript(() => {
|
||||
const getContext = HTMLCanvasElement.prototype.getContext;
|
||||
HTMLCanvasElement.prototype.getContext = function (
|
||||
this: HTMLCanvasElement,
|
||||
type: string,
|
||||
...rest: unknown[]
|
||||
) {
|
||||
if (type === "webgl2") return null;
|
||||
return (getContext as (...args: unknown[]) => unknown).call(this, type, ...rest);
|
||||
} as typeof getContext;
|
||||
});
|
||||
await page.addInitScript(
|
||||
(fonts) => {
|
||||
const saved = JSON.parse(localStorage.getItem("@paseo:app-settings") ?? "{}");
|
||||
localStorage.setItem("@paseo:app-settings", JSON.stringify({ ...saved, ...fonts }));
|
||||
},
|
||||
{ monoFontFamily: CODE_FONT, uiFontFamily: INTERFACE_FONT },
|
||||
);
|
||||
|
||||
const harness = await TerminalE2EHarness.create({ tempPrefix: "terminal-font-family-" });
|
||||
try {
|
||||
await withTerminalInApp(page, harness, { name: "font-family" }, async () => {
|
||||
await harness.setupPrompt(page);
|
||||
await harness
|
||||
.terminalSurface(page)
|
||||
.pressSequentially("clear; printf 'iiiiiiiiii\\nWWWWWWWWWW\\n'\n", { delay: 0 });
|
||||
await waitForTerminalContent(page, (text) => text.includes("WWWWWWWWWW"), 10_000);
|
||||
|
||||
await harness
|
||||
.terminalSurface(page)
|
||||
.screenshot({ path: test.info().outputPath("terminal-font-family.png") });
|
||||
|
||||
const rowFont = await page
|
||||
.locator(".xterm-rows")
|
||||
.evaluate((rows) => getComputedStyle(rows).fontFamily);
|
||||
expect(rowFont).toBe(CODE_FONT);
|
||||
});
|
||||
} finally {
|
||||
await harness.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -4,7 +4,9 @@ import path from "node:path";
|
||||
import type { Page } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { holdFileUploadResponse } from "../support/helpers/file-upload-gate";
|
||||
import { clickNewTerminal, gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { installLocalDesktopHost } from "../support/helpers/local-desktop-host";
|
||||
import { clickSettingsBackToWorkspace, openSettingsSection } from "../support/helpers/settings";
|
||||
import { TerminalE2EHarness } from "../support/helpers/terminal-dsl";
|
||||
import { getTerminalBufferText, waitForTerminalContent } from "../support/helpers/terminal-perf";
|
||||
|
||||
@@ -23,13 +25,134 @@ if (process.stdin.isTTY) {
|
||||
process.stdin.resume();
|
||||
process.stdin.on("data", (chunk) => {
|
||||
captured = Buffer.concat([captured, chunk]);
|
||||
if (captured.includes(Buffer.from("rgb:"))) {
|
||||
finish();
|
||||
}
|
||||
});
|
||||
setTimeout(finish, 700);
|
||||
`;
|
||||
|
||||
const TERMINAL_PALETTE_PROBE_SCRIPT = `
|
||||
process.stdin.setRawMode(true);
|
||||
process.stdin.resume();
|
||||
const mode = process.argv[2];
|
||||
let buf = "";
|
||||
const timer = setTimeout(() => {
|
||||
process.stdout.write("PROBE_TIMEOUT:" + mode + ":" + buf.replace(/\\x1b/g, "ESC") + "\\n");
|
||||
process.exit(2);
|
||||
}, 5000);
|
||||
|
||||
if (mode === "osc") {
|
||||
const code = process.argv[3];
|
||||
process.stdin.on("data", (chunk) => {
|
||||
buf += chunk.toString("binary");
|
||||
const match = buf.match(new RegExp("\\\\x1b\\\\]" + code + ";rgb:[0-9a-f/]+\\\\x1b\\\\\\\\"));
|
||||
if (!match) return;
|
||||
clearTimeout(timer);
|
||||
process.stdout.write("OSC_COLOR_OK:" + code + ":" + match[0].replace(/\\x1b/g, "ESC") + "\\n");
|
||||
process.exit(0);
|
||||
});
|
||||
process.stdout.write("\\x1b]" + code + ";?\\x07");
|
||||
} else if (mode === "dsr996") {
|
||||
process.stdin.on("data", (chunk) => {
|
||||
buf += chunk.toString("binary");
|
||||
const match = buf.match(/\\x1b\\[\\?997;([12])n/);
|
||||
if (!match) return;
|
||||
clearTimeout(timer);
|
||||
process.stdout.write("DSR996_OK:" + match[1] + "\\n");
|
||||
process.exit(0);
|
||||
});
|
||||
process.stdout.write("\\x1b[?996n");
|
||||
} else if (mode === "watch2031") {
|
||||
clearTimeout(timer);
|
||||
process.stdin.on("data", (chunk) => {
|
||||
buf += chunk.toString("binary");
|
||||
if (buf.includes("Q")) {
|
||||
process.stdout.write("\\x1b[?2031lWATCH2031_DONE\\n");
|
||||
process.exit(0);
|
||||
}
|
||||
let match;
|
||||
while ((match = buf.match(/\\x1b\\[\\?997;([12])n/))) {
|
||||
process.stdout.write("WATCH2031_EVENT:" + match[1] + "\\n");
|
||||
buf = buf.slice(match.index + match[0].length);
|
||||
}
|
||||
});
|
||||
process.stdout.write("\\x1b[?2031hWATCH2031_READY\\n");
|
||||
}
|
||||
`;
|
||||
|
||||
const TERMINAL_PALETTE_SCENARIOS = {
|
||||
light: {
|
||||
label: "Light",
|
||||
colorFgBg: "0;15",
|
||||
schemeCode: "2",
|
||||
colors: {
|
||||
10: "rgb:1a1a/1a1a/1e1e",
|
||||
11: "rgb:ffff/ffff/ffff",
|
||||
12: "rgb:1a1a/1a1a/1e1e",
|
||||
},
|
||||
},
|
||||
dark: {
|
||||
label: "Dark",
|
||||
colorFgBg: "15;0",
|
||||
schemeCode: "1",
|
||||
colors: {
|
||||
10: "rgb:fafa/fafa/fafa",
|
||||
11: "rgb:1818/1b1b/1a1a",
|
||||
12: "rgb:fafa/fafa/fafa",
|
||||
},
|
||||
},
|
||||
} as const;
|
||||
|
||||
type TerminalPaletteScenario =
|
||||
(typeof TERMINAL_PALETTE_SCENARIOS)[keyof typeof TERMINAL_PALETTE_SCENARIOS];
|
||||
|
||||
async function selectAppThemeInApp(
|
||||
page: Page,
|
||||
label: TerminalPaletteScenario["label"],
|
||||
): Promise<void> {
|
||||
await page.getByRole("button", { name: "Settings", exact: true }).click();
|
||||
await expect(page.getByTestId("settings-sidebar")).toBeVisible();
|
||||
await openSettingsSection(page, "appearance");
|
||||
|
||||
const themeRadio = page.getByRole("radio", { name: label, exact: true });
|
||||
await themeRadio.click();
|
||||
await expect(themeRadio).toBeChecked();
|
||||
await clickSettingsBackToWorkspace(page);
|
||||
}
|
||||
|
||||
function collectBrowserOsc11Replies(page: Page): string[] {
|
||||
const replies: string[] = [];
|
||||
page.on("websocket", (ws) => {
|
||||
ws.on("framesent", ({ payload }) => {
|
||||
const text = typeof payload === "string" ? payload : payload.toString("latin1");
|
||||
if (text.includes("]11;rgb:")) {
|
||||
replies.push(text);
|
||||
}
|
||||
});
|
||||
});
|
||||
return replies;
|
||||
}
|
||||
|
||||
async function waitForCreatedTerminal(
|
||||
harness: TerminalE2EHarness,
|
||||
knownTerminalIds: Set<string>,
|
||||
): Promise<string> {
|
||||
let createdTerminalId: string | undefined;
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const result = await harness.client.listTerminals(harness.tempRepo.path, undefined, {
|
||||
workspaceId: harness.workspaceId,
|
||||
});
|
||||
createdTerminalId = result.terminals.find(
|
||||
(terminal) => !knownTerminalIds.has(terminal.id),
|
||||
)?.id;
|
||||
return createdTerminalId;
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
)
|
||||
.toBeTruthy();
|
||||
return createdTerminalId!;
|
||||
}
|
||||
|
||||
// A TUI stand-in: turns on bracketed paste, reads every quoted path in each
|
||||
// bracketed paste, and echoes typed lines, so the PTY output proves what reached
|
||||
// the terminal and where the file was read from.
|
||||
@@ -158,6 +281,10 @@ test.describe("Terminal protocol queries", () => {
|
||||
test.beforeAll(async () => {
|
||||
harness = await TerminalE2EHarness.create({ tempPrefix: "terminal-protocol-query-" });
|
||||
await writeFile(path.join(harness.tempRepo.path, "osc11-capture.cjs"), OSC11_CAPTURE_SCRIPT);
|
||||
await writeFile(
|
||||
path.join(harness.tempRepo.path, "palette-probe.cjs"),
|
||||
TERMINAL_PALETTE_PROBE_SCRIPT,
|
||||
);
|
||||
await writeFile(path.join(harness.tempRepo.path, "file-receiver.cjs"), FILE_RECEIVER_SCRIPT);
|
||||
});
|
||||
|
||||
@@ -166,6 +293,8 @@ test.describe("Terminal protocol queries", () => {
|
||||
});
|
||||
|
||||
test("does not send browser OSC 11 color-query replies back to the PTY", async ({ page }) => {
|
||||
const browserOscReplies = collectBrowserOsc11Replies(page);
|
||||
|
||||
const terminalInstance = await harness.createTerminal({ name: "osc11-query" });
|
||||
try {
|
||||
await harness.openTerminal(page, { terminalId: terminalInstance.id });
|
||||
@@ -178,14 +307,110 @@ test.describe("Terminal protocol queries", () => {
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
const text = await getTerminalBufferText(page);
|
||||
const captureLine =
|
||||
text.split("\n").find((line) => line.includes("PASEO_OSC11_CAPTURE:")) ?? "";
|
||||
const capturedMatches = captureLine.match(/\]11;rgb:[0-9a-f/]+/g) ?? [];
|
||||
|
||||
expect(text).toContain("rgb:0b0b/0b0b/0b0b");
|
||||
expect(text).not.toContain("rgb:ffff/ffff/ffff");
|
||||
expect(capturedMatches).toHaveLength(1);
|
||||
expect(browserOscReplies).toEqual([]);
|
||||
const afterCapture = text.slice(text.indexOf("PASEO_OSC11_CAPTURE:") + captureLine.length);
|
||||
expect(afterCapture).not.toContain("rgb:");
|
||||
} finally {
|
||||
await harness.killTerminal(terminalInstance.id);
|
||||
}
|
||||
});
|
||||
|
||||
test("reports Light and Dark palettes through OSC 10/11/12, COLORFGBG, DSR 996/997, and live DEC 2031 toggles", async ({
|
||||
page,
|
||||
}) => {
|
||||
const createAppTerminal = async (): Promise<string> => {
|
||||
const existing = await harness.client.listTerminals(harness.tempRepo.path, undefined, {
|
||||
workspaceId: harness.workspaceId,
|
||||
});
|
||||
const knownIds = new Set(existing.terminals.map((entry) => entry.id));
|
||||
await clickNewTerminal(page);
|
||||
const terminalId = await waitForCreatedTerminal(harness, knownIds);
|
||||
const surface = terminalSurface(page);
|
||||
await expect(surface).toBeVisible({ timeout: 20_000 });
|
||||
await surface.click();
|
||||
const readyTag = `READY_${Date.now()}`;
|
||||
await surface.pressSequentially(`echo ${readyTag}\n`, { delay: 0 });
|
||||
await expectTerminalOutput(terminalId, readyTag);
|
||||
return terminalId;
|
||||
};
|
||||
|
||||
const runPaletteChecks = async (
|
||||
terminalId: string,
|
||||
scenario: TerminalPaletteScenario,
|
||||
options: { checkColorFgBg: boolean },
|
||||
): Promise<void> => {
|
||||
const surface = terminalSurface(page);
|
||||
await surface.click();
|
||||
if (options.checkColorFgBg) {
|
||||
await surface.pressSequentially('echo "CFGBG=$COLORFGBG"\n', { delay: 0 });
|
||||
await expectTerminalOutput(terminalId, `CFGBG=${scenario.colorFgBg}`);
|
||||
}
|
||||
for (const code of [10, 11, 12] as const) {
|
||||
await surface.pressSequentially(`${process.execPath} palette-probe.cjs osc ${code}\n`, {
|
||||
delay: 0,
|
||||
});
|
||||
await expectTerminalOutput(
|
||||
terminalId,
|
||||
`OSC_COLOR_OK:${code}:ESC]${code};${scenario.colors[code]}ESC\\`,
|
||||
);
|
||||
}
|
||||
await surface.pressSequentially(`${process.execPath} palette-probe.cjs dsr996\n`, {
|
||||
delay: 0,
|
||||
});
|
||||
await expectTerminalOutput(terminalId, `DSR996_OK:${scenario.schemeCode}`);
|
||||
};
|
||||
|
||||
// 1. Open workspace once, switch to Light in-app, and create a fresh Light terminal.
|
||||
await gotoWorkspace(page, harness.workspaceId);
|
||||
await selectAppThemeInApp(page, "Light");
|
||||
const lightTerminalId = await createAppTerminal();
|
||||
let darkTerminalId: string | null = null;
|
||||
try {
|
||||
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.light, {
|
||||
checkColorFgBg: true,
|
||||
});
|
||||
|
||||
// 2. Start DEC 2031 watcher in that running Light terminal, then toggle Light -> Dark -> Light.
|
||||
await terminalSurface(page).pressSequentially(
|
||||
`${process.execPath} palette-probe.cjs watch2031\n`,
|
||||
{ delay: 0 },
|
||||
);
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_READY");
|
||||
|
||||
await selectAppThemeInApp(page, "Dark");
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:1");
|
||||
|
||||
await selectAppThemeInApp(page, "Light");
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_EVENT:2");
|
||||
|
||||
// Stop watcher, toggle to Dark, and verify live OSC 10/11/12 + DSR 996 update on the same PTY.
|
||||
await terminalSurface(page).click();
|
||||
await terminalSurface(page).pressSequentially("Q", { delay: 0 });
|
||||
await expectTerminalOutput(lightTerminalId, "WATCH2031_DONE");
|
||||
|
||||
await selectAppThemeInApp(page, "Dark");
|
||||
await runPaletteChecks(lightTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
|
||||
checkColorFgBg: false,
|
||||
});
|
||||
|
||||
// 3. Fresh Dark terminal reports Dark OSC 10/11/12, COLORFGBG=15;0, and DSR 996 -> dark (1).
|
||||
darkTerminalId = await createAppTerminal();
|
||||
await runPaletteChecks(darkTerminalId, TERMINAL_PALETTE_SCENARIOS.dark, {
|
||||
checkColorFgBg: true,
|
||||
});
|
||||
} finally {
|
||||
await harness.killTerminal(lightTerminalId);
|
||||
if (darkTerminalId) {
|
||||
await harness.killTerminal(darkTerminalId);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
async function openFileReceiver(page: Page, name: string) {
|
||||
const terminal = await harness.createTerminal({
|
||||
name,
|
||||
|
||||
@@ -668,3 +668,186 @@ test("sidebar usage falls back to period shorthands before dropping all labels",
|
||||
await dragSidebarTo(300);
|
||||
await expectPinnedUsage(page, ["6%", "20%", "100%", "14%", "22%", "97%"]);
|
||||
});
|
||||
|
||||
test("pushed status.usage_report_changed updates sidebar summary and open Usage modal without polling", async ({
|
||||
page,
|
||||
}) => {
|
||||
const [claude] = claudeAndCodexReports();
|
||||
const initialFetchedAt = new Date(Date.now() - 60_000).toISOString();
|
||||
const usage = await installUsageReportsFixture(page, {
|
||||
lists: [
|
||||
() => [
|
||||
{
|
||||
...claude!,
|
||||
fetchedAt: initialFetchedAt,
|
||||
successfulAt: initialFetchedAt,
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 31 },
|
||||
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 54 },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
});
|
||||
await page.setViewportSize(WIDE);
|
||||
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||
await gotoAppShell(page);
|
||||
await expectPinnedUsage(page, ["31% 5h", "54% wk"]);
|
||||
await usage.waitForUsageReportSubscription();
|
||||
|
||||
await openUsageFromItem(page);
|
||||
const modal = usageModal(page);
|
||||
await expect(modal.getByText("31% used")).toBeVisible();
|
||||
const requestsBeforePush = usage.listRequests();
|
||||
|
||||
const updatedAt = new Date().toISOString();
|
||||
usage.pushReportUpdate({
|
||||
...claude!,
|
||||
fetchedAt: updatedAt,
|
||||
successfulAt: updatedAt,
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 64 },
|
||||
{ id: "weekly", label: "Weekly", shortLabel: "wk", summary: true, usedPct: 54 },
|
||||
],
|
||||
},
|
||||
});
|
||||
await expectPinnedUsage(page, ["64% 5h", "54% wk"]);
|
||||
await expect(modal.getByText("64% used")).toBeVisible();
|
||||
expect(usage.listRequests()).toEqual(requestsBeforePush);
|
||||
});
|
||||
|
||||
test("a pushed report for one source does not postpone the five-minute poll of other sources", async ({
|
||||
page,
|
||||
}) => {
|
||||
const [claude, codex] = claudeAndCodexReports();
|
||||
let codexUsedPct = 7;
|
||||
let listFetchedAt = "2026-11-28T10:00:00.000Z";
|
||||
const usage = await installUsageReportsFixture(page, {
|
||||
lists: [
|
||||
() => [
|
||||
{
|
||||
...claude!,
|
||||
fetchedAt: listFetchedAt,
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 31 },
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
...codex!,
|
||||
fetchedAt: listFetchedAt,
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{
|
||||
id: "five_hour",
|
||||
label: "Session",
|
||||
shortLabel: "5h",
|
||||
summary: true,
|
||||
usedPct: codexUsedPct,
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
});
|
||||
await page.clock.install();
|
||||
await page.setViewportSize(WIDE);
|
||||
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||
await gotoAppShell(page);
|
||||
await expectPinnedUsage(page, ["31% 5h", "7% 5h"]);
|
||||
await usage.waitForUsageReportSubscription();
|
||||
const initialRequests = usage.listRequests();
|
||||
|
||||
// Push a Claude update 2 minutes into the 5-minute poll window.
|
||||
await page.clock.fastForward(2 * 60_000);
|
||||
const pushedAt = "2026-11-28T10:02:00.000Z";
|
||||
usage.pushReportUpdate({
|
||||
...claude!,
|
||||
fetchedAt: pushedAt,
|
||||
successfulAt: pushedAt,
|
||||
report: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct: 64 },
|
||||
],
|
||||
},
|
||||
});
|
||||
await expectPinnedUsage(page, ["64% 5h", "7% 5h"]);
|
||||
expect(usage.listRequests()).toEqual(initialRequests);
|
||||
|
||||
// Only 3 minutes later (t = 5m from initial fetch), the scheduled poll still runs for Codex.
|
||||
codexUsedPct = 19;
|
||||
listFetchedAt = "2026-11-28T10:05:00.000Z";
|
||||
await page.clock.fastForward(3 * 60_000);
|
||||
await expectPinnedUsage(page, ["31% 5h", "19% 5h"]);
|
||||
expect(usage.listRequests()).toHaveLength(initialRequests.length + 1);
|
||||
});
|
||||
|
||||
test("hiding and showing the sidebar preserves the five-minute poll schedule and failed reports retry after one minute", async ({
|
||||
page,
|
||||
}) => {
|
||||
const [claude] = claudeAndCodexReports();
|
||||
let mode: "ok" | "error" = "ok";
|
||||
let usedPct = 31;
|
||||
const usage = await installUsageReportsFixture(page, {
|
||||
lists: [
|
||||
() => [
|
||||
{
|
||||
...claude!,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
report:
|
||||
mode === "error"
|
||||
? { status: "error", error: "Temporary 503" }
|
||||
: {
|
||||
status: "available",
|
||||
windows: [
|
||||
{ id: "five_hour", label: "Session", shortLabel: "5h", summary: true, usedPct },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
],
|
||||
});
|
||||
await page.clock.install();
|
||||
await page.setViewportSize(WIDE);
|
||||
await seedSidebarFooterPreferences(page, [{ key: "usage", visible: true }]);
|
||||
await gotoAppShell(page);
|
||||
await expectPinnedUsage(page, ["31% 5h"]);
|
||||
const initialRequests = usage.listRequests();
|
||||
|
||||
// Hide and reopen the sidebar within the stale window: no extra fetch starts on remount,
|
||||
// and the original 5-minute poll slot fires on time rather than restarting from zero.
|
||||
await page.clock.fastForward(20_000);
|
||||
await page.setViewportSize(COMPACT);
|
||||
await expect(usageItem(page)).toHaveCount(0);
|
||||
await page.clock.fastForward(15_000);
|
||||
await openCompactSidebar(page);
|
||||
await expectPinnedUsage(page, ["31% 5h"]);
|
||||
expect(usage.listRequests()).toEqual(initialRequests);
|
||||
|
||||
usedPct = 44;
|
||||
await page.clock.fastForward(4 * 60_000 + 25_000);
|
||||
await expectPinnedUsage(page, ["44% 5h"]);
|
||||
expect(usage.listRequests()).toHaveLength(initialRequests.length + 1);
|
||||
|
||||
// When a report enters error state, the app retries after 1 minute instead of waiting 5 minutes.
|
||||
mode = "error";
|
||||
await page.clock.fastForward(5 * 60_000);
|
||||
const requestsAfterError = usage.listRequests();
|
||||
expect(requestsAfterError).toHaveLength(initialRequests.length + 2);
|
||||
|
||||
mode = "ok";
|
||||
usedPct = 58;
|
||||
await page.clock.fastForward(60_000);
|
||||
await expectPinnedUsage(page, ["58% 5h"]);
|
||||
expect(usage.listRequests()).toHaveLength(requestsAfterError.length + 1);
|
||||
});
|
||||
|
||||
@@ -31,7 +31,7 @@ function keyboardState() {
|
||||
return {
|
||||
shown: /^ mInputShown=true$/m.test(state),
|
||||
// The native object identity survives layout/flag changes but not a remount.
|
||||
input: view.match(/ReactEditText\{(\w+)/)?.[1] ?? null,
|
||||
input: view.match(/PaseoTerminalInputView\{(\w+)/)?.[1] ?? null,
|
||||
};
|
||||
}
|
||||
async function waitForKeyboard(shown) {
|
||||
|
||||
@@ -3,15 +3,35 @@ import type { Page } from "@playwright/test";
|
||||
// Poses as the desktop app running the e2e daemon as its own managed daemon, so
|
||||
// `useIsLocalDaemon` reports the host as this machine. `directory` is where the
|
||||
// desktop bridge claims dropped files live on disk.
|
||||
export async function installLocalDesktopHost(page: Page, directory: string): Promise<void> {
|
||||
export async function installLocalDesktopHost(
|
||||
page: Page,
|
||||
directory: string,
|
||||
// `fileManager` adds the editor bridge: a file manager of that name, and the default-app opener.
|
||||
{ fileManager = null }: { fileManager?: string | null } = {},
|
||||
): Promise<void> {
|
||||
const serverId = process.env.E2E_SERVER_ID;
|
||||
if (!serverId) {
|
||||
throw new Error("E2E_SERVER_ID is not set");
|
||||
}
|
||||
await page.addInitScript(
|
||||
(localHost: { serverId: string; directory: string }) => {
|
||||
(localHost: { serverId: string; directory: string; fileManager: string | null }) => {
|
||||
const editor = localHost.fileManager
|
||||
? {
|
||||
listTargets: async () => [
|
||||
{
|
||||
id: "file-manager",
|
||||
label: localHost.fileManager,
|
||||
kind: "file-manager",
|
||||
icon: { kind: "symbol", name: "folder" },
|
||||
},
|
||||
],
|
||||
openTarget: async () => undefined,
|
||||
openDefaultApp: async () => undefined,
|
||||
}
|
||||
: undefined;
|
||||
(window as unknown as { paseoDesktop: unknown }).paseoDesktop = {
|
||||
platform: "linux",
|
||||
editor,
|
||||
invoke: async (command: string) => {
|
||||
if (command === "desktop_daemon_status") {
|
||||
return {
|
||||
@@ -33,6 +53,6 @@ export async function installLocalDesktopHost(page: Page, directory: string): Pr
|
||||
webUtils: { getPathForFile: (file: File) => `${localHost.directory}/${file.name}` },
|
||||
};
|
||||
},
|
||||
{ serverId, directory },
|
||||
{ serverId, directory, fileManager },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import path from "node:path";
|
||||
import { readFileSync } from "node:fs";
|
||||
import type { TerminalDefaultColors } from "@getpaseo/protocol/messages";
|
||||
import type { TerminalActivity } from "@getpaseo/protocol/terminal-activity";
|
||||
import { connectDaemonClient } from "./daemon-client-loader";
|
||||
import { withProjectOwnership } from "./project-ownership";
|
||||
@@ -94,7 +95,13 @@ export interface SeedDaemonClient {
|
||||
cwd: string,
|
||||
name?: string,
|
||||
requestId?: string,
|
||||
options?: { agentId?: string; command?: string; args?: string[]; workspaceId?: string },
|
||||
options?: {
|
||||
agentId?: string;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
workspaceId?: string;
|
||||
defaultColors?: TerminalDefaultColors;
|
||||
},
|
||||
): Promise<{
|
||||
terminal: { id: string; name: string; cwd: string; activity?: TerminalActivity | null } | null;
|
||||
error: string | null;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Page } from "@playwright/test";
|
||||
import type { TerminalDefaultColors } from "@getpaseo/protocol/messages";
|
||||
import type { TerminalActivity, TerminalActivityState } from "@getpaseo/protocol/terminal-activity";
|
||||
import { createTempGitRepo } from "./workspace";
|
||||
import { navigateToTerminal, setupDeterministicPrompt } from "./terminal-perf";
|
||||
@@ -19,6 +20,7 @@ interface CreateTerminalInput {
|
||||
name: string;
|
||||
command?: string;
|
||||
args?: string[];
|
||||
defaultColors?: TerminalDefaultColors;
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
@@ -69,14 +71,11 @@ export class TerminalE2EHarness {
|
||||
}
|
||||
|
||||
async createTerminal(input: CreateTerminalInput): Promise<TerminalInstance> {
|
||||
const options =
|
||||
input.command || input.args
|
||||
? {
|
||||
command: input.command,
|
||||
args: input.args,
|
||||
workspaceId: this.workspaceId,
|
||||
}
|
||||
: { workspaceId: this.workspaceId };
|
||||
const options = {
|
||||
...(input.command || input.args ? { command: input.command, args: input.args } : {}),
|
||||
workspaceId: this.workspaceId,
|
||||
...(input.defaultColors ? { defaultColors: input.defaultColors } : {}),
|
||||
};
|
||||
const result = await this.client.createTerminal(
|
||||
this.tempRepo.path,
|
||||
input.name,
|
||||
|
||||
@@ -11,6 +11,10 @@ export interface UsageListRequest {
|
||||
export interface UsageReportsFixture {
|
||||
listRequests(): UsageListRequest[];
|
||||
waitForListRequests(count: number): Promise<void>;
|
||||
/** Waits until the app holds an active `status.usage_report_changed` subscription. */
|
||||
waitForUsageReportSubscription(): Promise<void>;
|
||||
/** Pushes a `status.usage_report_changed` update to every active app subscription. */
|
||||
pushReportUpdate(report: UsageReportEntry): void;
|
||||
/** Runs `action`, then waits until the app has received the agent's next usage scope. */
|
||||
untilUsageScopeChanges(agentId: string, action: () => Promise<unknown>): Promise<void>;
|
||||
}
|
||||
@@ -28,6 +32,8 @@ interface UsageReportsFixtureOptions {
|
||||
*/
|
||||
usageSupported?: boolean | (() => boolean);
|
||||
usageSettingSupported?: boolean;
|
||||
/** Overrides `server_info.features.usageReportUpdates` when set. */
|
||||
usageReportUpdates?: boolean;
|
||||
/** Released hosts expose provider.usage.list with no source icons. */
|
||||
providerUsageListOnly?: boolean;
|
||||
/** The host daemon's port; defaults to the E2E daemon. */
|
||||
@@ -67,6 +73,7 @@ function withUsageSupportFeature(
|
||||
enabled: boolean,
|
||||
providerUsageListOnly: boolean,
|
||||
usageSettingSupported: boolean,
|
||||
usageReportUpdates?: boolean,
|
||||
): string | null {
|
||||
const envelope = parseJson(message) as {
|
||||
type?: unknown;
|
||||
@@ -93,6 +100,7 @@ function withUsageSupportFeature(
|
||||
usageSetting: usageSettingSupported ? true : undefined,
|
||||
usageSources: enabled && !providerUsageListOnly,
|
||||
providerUsageList: enabled,
|
||||
...(usageReportUpdates !== undefined ? { usageReportUpdates } : {}),
|
||||
},
|
||||
},
|
||||
},
|
||||
@@ -143,12 +151,37 @@ function createCounter() {
|
||||
};
|
||||
}
|
||||
|
||||
function trackUsageReportSubscriptionMessage(
|
||||
request: Record<string, unknown> | null,
|
||||
pendingUsageSubRequestIds: Set<string>,
|
||||
usageReportSubscriptions: Map<string, { send: (payload: string) => void }>,
|
||||
socketSubIds: Set<string>,
|
||||
): void {
|
||||
if (
|
||||
request?.type === "session.events.set_subscription.request" &&
|
||||
typeof request.requestId === "string" &&
|
||||
Array.isArray(request.events) &&
|
||||
request.events.includes("status.usage_report_changed")
|
||||
) {
|
||||
pendingUsageSubRequestIds.add(request.requestId);
|
||||
}
|
||||
if (
|
||||
request?.type === "subscription.release.request" &&
|
||||
typeof request.subscriptionId === "string"
|
||||
) {
|
||||
usageReportSubscriptions.delete(request.subscriptionId);
|
||||
socketSubIds.delete(request.subscriptionId);
|
||||
}
|
||||
}
|
||||
|
||||
export async function installUsageReportsFixture(
|
||||
page: Page,
|
||||
options: UsageReportsFixtureOptions,
|
||||
): Promise<UsageReportsFixture> {
|
||||
const listRequests: UsageListRequest[] = [];
|
||||
const listCounter = createCounter();
|
||||
const usageReportSubscriptions = new Map<string, { send: (payload: string) => void }>();
|
||||
const usageReportSubCounter = createCounter();
|
||||
const usageScopes = new Map<string, string>();
|
||||
const usageScopeChanges = new Map<string, ReturnType<typeof createCounter>>();
|
||||
const usageScopeCounts = new Map<string, number>();
|
||||
@@ -171,10 +204,23 @@ export async function installUsageReportsFixture(
|
||||
options.port === undefined ? daemonWsRoutePattern() : wsRoutePatternForPort(`${options.port}`);
|
||||
await page.routeWebSocket(route, (ws) => {
|
||||
const server = ws.connectToServer();
|
||||
const pendingUsageSubRequestIds = new Set<string>();
|
||||
const socketSubIds = new Set<string>();
|
||||
|
||||
ws.onClose(() => {
|
||||
for (const id of socketSubIds) usageReportSubscriptions.delete(id);
|
||||
socketSubIds.clear();
|
||||
});
|
||||
|
||||
ws.onMessage((message) => {
|
||||
const request = getSessionMessage(message);
|
||||
const requestId = request?.requestId;
|
||||
trackUsageReportSubscriptionMessage(
|
||||
request,
|
||||
pendingUsageSubRequestIds,
|
||||
usageReportSubscriptions,
|
||||
socketSubIds,
|
||||
);
|
||||
if (request?.type === requestType && typeof requestId === "string") {
|
||||
const listRequest: UsageListRequest = {
|
||||
forceRefresh: request.forceRefresh === true,
|
||||
@@ -262,6 +308,26 @@ export async function installUsageReportsFixture(
|
||||
});
|
||||
|
||||
server.onMessage((message) => {
|
||||
const sessionMessage = getSessionMessage(message);
|
||||
const subPayload =
|
||||
sessionMessage?.type === "session.events.set_subscription.response"
|
||||
? (sessionMessage.payload as
|
||||
| { requestId?: unknown; subscriptionId?: unknown }
|
||||
| undefined)
|
||||
: undefined;
|
||||
if (
|
||||
typeof subPayload?.requestId === "string" &&
|
||||
pendingUsageSubRequestIds.delete(subPayload.requestId) &&
|
||||
typeof subPayload.subscriptionId === "string"
|
||||
) {
|
||||
usageReportSubscriptions.set(subPayload.subscriptionId, {
|
||||
send: (payload) => ws.send(payload),
|
||||
});
|
||||
socketSubIds.add(subPayload.subscriptionId);
|
||||
ws.send(message);
|
||||
usageReportSubCounter.increment();
|
||||
return;
|
||||
}
|
||||
const serverInfo =
|
||||
typeof message === "string"
|
||||
? withUsageSupportFeature(
|
||||
@@ -269,6 +335,7 @@ export async function installUsageReportsFixture(
|
||||
isUsageSupported(),
|
||||
providerUsageListOnly,
|
||||
options.usageSettingSupported ?? true,
|
||||
options.usageReportUpdates,
|
||||
)
|
||||
: null;
|
||||
const scope = agentUsageScope(message);
|
||||
@@ -287,6 +354,24 @@ export async function installUsageReportsFixture(
|
||||
return {
|
||||
listRequests: () => [...listRequests],
|
||||
waitForListRequests: (count) => listCounter.waitFor(count),
|
||||
waitForUsageReportSubscription: () => usageReportSubCounter.waitFor(1),
|
||||
pushReportUpdate: (report) => {
|
||||
for (const [subscriptionId, target] of usageReportSubscriptions) {
|
||||
target.send(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "usage_report_changed",
|
||||
subscriptionId,
|
||||
report,
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
},
|
||||
untilUsageScopeChanges: async (agentId, action) => {
|
||||
const next = (usageScopeCounts.get(agentId) ?? 0) + 1;
|
||||
await action();
|
||||
|
||||
+42
@@ -2,12 +2,16 @@ package sh.paseo.keyboard
|
||||
|
||||
import android.app.Activity
|
||||
import android.content.Intent
|
||||
import android.text.SpannableStringBuilder
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.inputmethod.BaseInputConnection
|
||||
import android.widget.EditText
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.After
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertSame
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
@@ -57,6 +61,44 @@ class TerminalArrowTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test fun customTerminalViewExposesComposingStateToHardwareArrows() {
|
||||
val host = instrumentation.startActivitySync(
|
||||
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
)
|
||||
activity = host
|
||||
val editable = SpannableStringBuilder("한")
|
||||
lateinit var view: View
|
||||
instrumentation.runOnMainSync {
|
||||
view = object : View(host), ComposingTextOwner {
|
||||
init {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
setTag(com.facebook.react.R.id.view_tag_native_id, "paseo-terminal-input")
|
||||
// Mirrors React Native BaseViewManager.setTestId, which overwrites the unkeyed View tag.
|
||||
setTag("terminal-native-input")
|
||||
}
|
||||
|
||||
override fun isComposingText(): Boolean =
|
||||
BaseInputConnection.getComposingSpanStart(editable) >= 0
|
||||
}
|
||||
host.setContentView(view)
|
||||
view.requestFocus()
|
||||
HardwareKeyboard.observe(host.window)
|
||||
}
|
||||
instrumentation.waitForIdleSync()
|
||||
instrumentation.runOnMainSync {
|
||||
assertSame(view, host.window.currentFocus)
|
||||
// When not composing, hardware arrows are claimed for the terminal.
|
||||
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)))
|
||||
assertTrue(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)))
|
||||
|
||||
// While composing, hardware arrows must NOT be claimed so IME candidate navigation still works.
|
||||
BaseInputConnection.setComposingSpans(editable)
|
||||
assertFalse(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DPAD_LEFT)))
|
||||
assertFalse(host.window.callback.dispatchKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DPAD_LEFT)))
|
||||
}
|
||||
}
|
||||
|
||||
private fun withInput(terminal: Boolean, check: (EditText, Activity) -> Unit) {
|
||||
val host = instrumentation.startActivitySync(
|
||||
Intent(instrumentation.targetContext, Activity::class.java).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
|
||||
|
||||
+14
-2
@@ -115,11 +115,23 @@ internal object HardwareKeyboard {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Implemented by custom non-EditText editor views so window-level hardware key dispatch can
|
||||
* detect active IME composition without depending on `View.getTag()` (which React Native's
|
||||
* `BaseViewManager.setTestId` overwrites with the string `testID`).
|
||||
*/
|
||||
interface ComposingTextOwner {
|
||||
fun isComposingText(): Boolean
|
||||
}
|
||||
|
||||
private class KeyboardWindowCallback(private val window: Window, val previous: Window.Callback) : Window.Callback by previous {
|
||||
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
|
||||
val focus = window.currentFocus
|
||||
val editable = (focus as? EditText)?.text
|
||||
val composing = editable != null && BaseInputConnection.getComposingSpanStart(editable) >= 0
|
||||
val composing = when (focus) {
|
||||
is ComposingTextOwner -> focus.isComposingText()
|
||||
is EditText -> focus.text != null && BaseInputConnection.getComposingSpanStart(focus.text) >= 0
|
||||
else -> false
|
||||
}
|
||||
val terminalFocused = focus?.getTag(R.id.view_tag_native_id) == TERMINAL_INPUT_NATIVE_ID
|
||||
return HardwareKeyboard.dispatcher.dispatch(
|
||||
event,
|
||||
|
||||
@@ -18,6 +18,7 @@ android {
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation project(":paseo-hardware-keyboard")
|
||||
implementation "androidx.customview:customview:1.1.0"
|
||||
implementation "com.facebook.react:react-android"
|
||||
testImplementation "junit:junit:4.13.2"
|
||||
|
||||
+337
@@ -0,0 +1,337 @@
|
||||
package sh.paseo.terminal
|
||||
|
||||
import android.text.InputType
|
||||
import android.view.KeyCharacterMap
|
||||
import android.view.KeyEvent
|
||||
import android.view.View
|
||||
import android.view.inputmethod.EditorInfo
|
||||
import androidx.test.ext.junit.runners.AndroidJUnit4
|
||||
import androidx.test.platform.app.InstrumentationRegistry
|
||||
import org.junit.Assert.assertEquals
|
||||
import org.junit.Assert.assertFalse
|
||||
import org.junit.Assert.assertNotEquals
|
||||
import org.junit.Assert.assertTrue
|
||||
import org.junit.Test
|
||||
import org.junit.runner.RunWith
|
||||
|
||||
/**
|
||||
* Exercises `TerminalInputConnection` and `PaseoTerminalInputView` against real Android
|
||||
* `SpannableStringBuilder`, `BaseInputConnection`, `EditorInfo`, and `KeyEvent` instances.
|
||||
*/
|
||||
@RunWith(AndroidJUnit4::class)
|
||||
class TerminalInputConnectionTest {
|
||||
private val instrumentation = InstrumentationRegistry.getInstrumentation()
|
||||
|
||||
private class RecordedTerminal {
|
||||
val chunks = mutableListOf<String>()
|
||||
val keys = mutableListOf<TerminalKeyPayload>()
|
||||
|
||||
fun write(data: String) {
|
||||
chunks.add(data)
|
||||
}
|
||||
|
||||
fun key(payload: TerminalKeyPayload) {
|
||||
keys.add(payload)
|
||||
}
|
||||
|
||||
val rawStream: String
|
||||
get() = chunks.joinToString("")
|
||||
|
||||
/** Applies `\x7f` rubouts onto a simulated terminal line buffer to verify visible text. */
|
||||
fun applyToLine(initial: String = ""): String {
|
||||
val codePoints = mutableListOf<Int>()
|
||||
initial.codePoints().forEach { codePoints.add(it) }
|
||||
rawStream.codePoints().forEach { cp ->
|
||||
if (cp == 0x7f) {
|
||||
if (codePoints.isNotEmpty()) codePoints.removeAt(codePoints.lastIndex)
|
||||
} else {
|
||||
codePoints.add(cp)
|
||||
}
|
||||
}
|
||||
val sb = StringBuilder()
|
||||
codePoints.forEach { sb.appendCodePoint(it) }
|
||||
return sb.toString()
|
||||
}
|
||||
}
|
||||
|
||||
private fun withInputHarness(
|
||||
block: (View, TerminalInputConnection, EditorInfo, RecordedTerminal) -> Unit,
|
||||
) {
|
||||
instrumentation.runOnMainSync {
|
||||
val context = instrumentation.targetContext
|
||||
val terminal = RecordedTerminal()
|
||||
val view = object : View(context) {
|
||||
init {
|
||||
isFocusable = true
|
||||
isFocusableInTouchMode = true
|
||||
}
|
||||
}
|
||||
val editorInfo = EditorInfo()
|
||||
val connection = TerminalInputConnection(
|
||||
targetView = view,
|
||||
onInput = terminal::write,
|
||||
onTerminalKey = terminal::key,
|
||||
)
|
||||
TerminalInputConnection.configureEditorInfo(editorInfo)
|
||||
block(view, connection, editorInfo, terminal)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun editorInfoDisablesSuggestionsFullscreenAndPersonalizedLearning() {
|
||||
instrumentation.runOnMainSync {
|
||||
val context = instrumentation.targetContext
|
||||
val editorInfo = EditorInfo()
|
||||
val view = PaseoTerminalInputView.createForTest(context)
|
||||
assertTrue("Terminal input view must declare itself as a text editor", view.onCheckIsTextEditor())
|
||||
assertTrue("Terminal input view must be focusable", view.isFocusable && view.isFocusableInTouchMode)
|
||||
val connection = view.onCreateInputConnection(editorInfo)
|
||||
assertTrue("onCreateInputConnection must return TerminalInputConnection", connection is TerminalInputConnection)
|
||||
assertEquals(
|
||||
InputType.TYPE_CLASS_TEXT or InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS,
|
||||
editorInfo.inputType,
|
||||
)
|
||||
assertEquals(EditorInfo.IME_ACTION_NONE, editorInfo.imeOptions and EditorInfo.IME_MASK_ACTION)
|
||||
assertNotEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_FULLSCREEN)
|
||||
assertNotEquals(0, editorInfo.imeOptions and EditorInfo.IME_FLAG_NO_PERSONALIZED_LEARNING)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun batchedCommitTextAndSetComposingTextDoNotDoubleCharacters() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
for (ch in listOf("a", "b", "c", "d")) {
|
||||
ic.beginBatchEdit()
|
||||
ic.commitText(ch, 1)
|
||||
ic.endBatchEdit()
|
||||
}
|
||||
assertEquals("abcd", terminal.rawStream)
|
||||
assertEquals("", ic.editable.toString())
|
||||
|
||||
// Coalesced setComposingText + finishComposingText inside one batch emits once.
|
||||
ic.beginBatchEdit()
|
||||
ic.setComposingText("ef", 1)
|
||||
ic.finishComposingText()
|
||||
ic.endBatchEdit()
|
||||
assertEquals("abcdef", terminal.rawStream)
|
||||
assertEquals("", ic.editable.toString())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun backspaceWorksAcrossAllThreeImePaths() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
ic.commitText("abcd", 1)
|
||||
assertEquals("abcd", terminal.applyToLine())
|
||||
|
||||
// Path 1: deleteSurroundingText (empty editable after commit)
|
||||
ic.deleteSurroundingText(0, 0)
|
||||
assertEquals("abcd", terminal.applyToLine())
|
||||
ic.deleteSurroundingText(1, 0)
|
||||
assertEquals("abc", terminal.applyToLine())
|
||||
|
||||
// Path 2: deleteSurroundingTextInCodePoints (empty editable)
|
||||
ic.deleteSurroundingTextInCodePoints(1, 0)
|
||||
assertEquals("ab", terminal.applyToLine())
|
||||
|
||||
// Path 2b: deleteSurroundingTextInCodePoints on surrogate-pair emoji in composing buffer
|
||||
ic.setComposingText("😀", 1)
|
||||
assertEquals("ab😀", terminal.applyToLine())
|
||||
ic.deleteSurroundingTextInCodePoints(1, 0)
|
||||
assertEquals("ab", terminal.applyToLine())
|
||||
|
||||
// Path 3: sendKeyEvent(KEYCODE_DEL) emits on ACTION_DOWN only, not ACTION_UP
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL))
|
||||
assertEquals("a", terminal.applyToLine())
|
||||
|
||||
// Multi-char deleteSurroundingText on empty buffer
|
||||
ic.commitText("xyz", 1)
|
||||
ic.deleteSurroundingText(2, 0)
|
||||
assertEquals("ax", terminal.applyToLine())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun hangulCompositionSyllableMigrationBackspaceAndPostEnter() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
// ㅎ -> 하 -> 한
|
||||
ic.setComposingText("ㅎ", 1)
|
||||
ic.setComposingText("하", 1)
|
||||
ic.setComposingText("한", 1)
|
||||
assertEquals("한", terminal.applyToLine())
|
||||
|
||||
// Final consonant migration: 한 + ㅏ -> commit 하 + compose 나 in one batch
|
||||
ic.beginBatchEdit()
|
||||
ic.commitText("하", 1)
|
||||
ic.setComposingText("나", 1)
|
||||
ic.endBatchEdit()
|
||||
assertEquals("하나", terminal.applyToLine())
|
||||
|
||||
// Continue composing second syllable: 나 -> 난
|
||||
ic.setComposingText("난", 1)
|
||||
assertEquals("하난", terminal.applyToLine())
|
||||
|
||||
// Backspace decomposes 난 -> 나 -> ㄴ -> "" (leaving 하) -> ""
|
||||
ic.setComposingText("나", 1)
|
||||
assertEquals("하나", terminal.applyToLine())
|
||||
ic.setComposingText("ㄴ", 1)
|
||||
assertEquals("하ㄴ", terminal.applyToLine())
|
||||
ic.commitText("", 1)
|
||||
assertEquals("하", terminal.applyToLine())
|
||||
ic.deleteSurroundingText(1, 0)
|
||||
assertEquals("", terminal.applyToLine())
|
||||
|
||||
// Submit via Enter, then immediately type 한글 with zero stale newline residue (#7164)
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
|
||||
ic.setComposingText("ㅎ", 1)
|
||||
ic.setComposingText("하", 1)
|
||||
ic.setComposingText("한", 1)
|
||||
ic.beginBatchEdit()
|
||||
ic.commitText("한", 1)
|
||||
ic.setComposingText("ㄱ", 1)
|
||||
ic.endBatchEdit()
|
||||
ic.setComposingText("그", 1)
|
||||
ic.setComposingText("글", 1)
|
||||
ic.finishComposingText()
|
||||
|
||||
assertEquals("\r한글", terminal.applyToLine())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun pinyinCompositionAndMixedChineseThenLatinCandidate() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
// Pinyin reading: nihao -> ni hao -> 你好
|
||||
ic.setComposingText("n", 1)
|
||||
ic.setComposingText("ni", 1)
|
||||
ic.setComposingText("nih", 1)
|
||||
ic.setComposingText("niha", 1)
|
||||
ic.setComposingText("ni hao", 1)
|
||||
ic.beginBatchEdit()
|
||||
ic.commitText("你好", 1)
|
||||
ic.endBatchEdit()
|
||||
assertEquals("你好", terminal.applyToLine())
|
||||
|
||||
// WeChat Keyboard #9121: immediately compose English and pick 2nd suggestion `hello`
|
||||
ic.setComposingText("h", 1)
|
||||
ic.setComposingText("he", 1)
|
||||
ic.setComposingText("hel", 1)
|
||||
ic.beginBatchEdit()
|
||||
ic.commitText("hello", 1)
|
||||
ic.endBatchEdit()
|
||||
assertEquals("你好hello", terminal.applyToLine())
|
||||
|
||||
// Backspace right after Latin candidate deletes from terminal visibly
|
||||
ic.deleteSurroundingText(1, 0)
|
||||
assertEquals("你好hell", terminal.applyToLine())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun latinCandidatesAutocorrectAndRepeatedClipboardCommit() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
// Candidate completion: hel -> hello
|
||||
ic.setComposingText("hel", 1)
|
||||
ic.commitText("hello", 1)
|
||||
assertEquals("hello", terminal.applyToLine())
|
||||
|
||||
// Autocorrect replacement inside composing span: teh -> the
|
||||
ic.setComposingText("teh", 1)
|
||||
ic.commitText("the", 1)
|
||||
assertEquals("hellothe", terminal.applyToLine())
|
||||
|
||||
// Repeated clipboard paste of identical text works because editable clears after commit
|
||||
ic.commitText("echo ok", 1)
|
||||
ic.commitText("echo ok", 1)
|
||||
assertEquals("hellotheecho okecho ok", terminal.applyToLine())
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun enterKeyAndEditorActionEmitSingleCarriageReturn() {
|
||||
withInputHarness { _, ic, _, terminal ->
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER))
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER))
|
||||
assertEquals("\r", terminal.rawStream)
|
||||
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER))
|
||||
ic.sendKeyEvent(KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_NUMPAD_ENTER))
|
||||
assertEquals("\r\r", terminal.rawStream)
|
||||
|
||||
ic.performEditorAction(EditorInfo.IME_ACTION_NONE)
|
||||
assertEquals("\r\r\r", terminal.rawStream)
|
||||
|
||||
ic.commitText("\n", 1)
|
||||
assertEquals("\r\r\r\r", terminal.rawStream)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun physicalKeyboardKeysAndDeadKeyAccents() {
|
||||
instrumentation.runOnMainSync {
|
||||
val context = instrumentation.targetContext
|
||||
val terminal = RecordedTerminal()
|
||||
val view = PaseoTerminalInputView.createForTest(
|
||||
context = context,
|
||||
onInput = terminal::write,
|
||||
onTerminalKey = terminal::key,
|
||||
)
|
||||
view.onCreateInputConnection(EditorInfo())
|
||||
|
||||
// Enter & Numpad Enter: ACTION_DOWN + ACTION_UP -> single \r each
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_ENTER, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ENTER)))
|
||||
assertTrue(view.onKeyUp(KeyEvent.KEYCODE_ENTER, KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_ENTER)))
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_NUMPAD_ENTER)))
|
||||
assertTrue(view.onKeyUp(KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_NUMPAD_ENTER)))
|
||||
assertEquals("\r\r", terminal.rawStream)
|
||||
|
||||
// Tab, Shift+Tab, Escape, Del
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB)))
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, 0, KeyEvent.META_SHIFT_ON)))
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_ESCAPE, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_ESCAPE)))
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_DEL, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL)))
|
||||
assertEquals("\r\r\t\u001b[Z\u001b\u007f", terminal.rawStream)
|
||||
|
||||
// Ctrl+C and Alt+B
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_C, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_C, 0, KeyEvent.META_CTRL_ON)))
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_B, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_B, 0, KeyEvent.META_ALT_ON)))
|
||||
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bb", terminal.rawStream)
|
||||
|
||||
// Printable key
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_A, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_A)))
|
||||
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bba", terminal.rawStream)
|
||||
|
||||
// Dead key accent (acute + e -> é)
|
||||
val deadAcuteEvent = object : KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E) {
|
||||
override fun getUnicodeChar(metaState: Int): Int =
|
||||
KeyCharacterMap.COMBINING_ACCENT or '\u00b4'.code
|
||||
}
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_E, deadAcuteEvent))
|
||||
assertTrue(view.onKeyDown(KeyEvent.KEYCODE_E, KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_E)))
|
||||
assertEquals("\r\r\t\u001b[Z\u001b\u007f\u0003\u001bbaé", terminal.rawStream)
|
||||
|
||||
// Meta shortcuts pass through unhandled
|
||||
assertFalse(view.onKeyDown(KeyEvent.KEYCODE_TAB, KeyEvent(0, 0, KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_TAB, 0, KeyEvent.META_META_ON)))
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
fun composingStateIsExposedOnViewForHardwareKeyboardModule() {
|
||||
instrumentation.runOnMainSync {
|
||||
val context = instrumentation.targetContext
|
||||
val view = PaseoTerminalInputView.createForTest(context)
|
||||
// Mirrors React Native BaseViewManager.setTestId, which overwrites the unkeyed View tag.
|
||||
view.setTag("terminal-native-input")
|
||||
val ic = checkNotNull(view.onCreateInputConnection(EditorInfo()))
|
||||
assertFalse(view.isComposingText())
|
||||
|
||||
ic.setComposingText("한", 1)
|
||||
assertTrue(view.isComposingText())
|
||||
|
||||
ic.commitText("한", 1)
|
||||
assertFalse(view.isComposingText())
|
||||
}
|
||||
}
|
||||
}
|
||||
-69
@@ -1,69 +0,0 @@
|
||||
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
@@ -0,0 +1,168 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
}
|
||||
+8
-2
@@ -7,8 +7,6 @@ class PaseoTerminalModule : Module() {
|
||||
override fun definition() = ModuleDefinition {
|
||||
Name("PaseoTerminal")
|
||||
|
||||
OnCreate { TerminalInputKeyboard.install() }
|
||||
|
||||
View(PaseoTerminalView::class) {
|
||||
Events("onCellMetrics")
|
||||
|
||||
@@ -22,5 +20,13 @@ 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
@@ -0,0 +1,501 @@
|
||||
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
@@ -1,32 +0,0 @@
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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}
|
||||
/>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,32 @@
|
||||
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;
|
||||
});
|
||||
@@ -0,0 +1,70 @@
|
||||
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;
|
||||
@@ -744,6 +744,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
<AssistantFileLinkResolverProvider
|
||||
client={client}
|
||||
serverId={resolvedServerId}
|
||||
workspaceId={context.workspaceId}
|
||||
workspaceRoot={workspaceRoot}
|
||||
onOpenWorkspaceFile={handleInlinePathPress}
|
||||
toast={toast}
|
||||
@@ -766,7 +767,15 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
</AssistantFileLinkResolverProvider>
|
||||
);
|
||||
},
|
||||
[agentId, client, handleInlinePathPress, resolvedServerId, toast, workspaceRoot],
|
||||
[
|
||||
agentId,
|
||||
client,
|
||||
context.workspaceId,
|
||||
handleInlinePathPress,
|
||||
resolvedServerId,
|
||||
toast,
|
||||
workspaceRoot,
|
||||
],
|
||||
);
|
||||
|
||||
const renderThoughtItem = useCallback(
|
||||
|
||||
@@ -108,6 +108,7 @@ 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";
|
||||
@@ -1026,7 +1027,11 @@ function RootProviders({ children }: { children: ReactNode }) {
|
||||
|
||||
function RootAppTree() {
|
||||
return (
|
||||
<GestureHandlerRootView style={flexStyle}>
|
||||
<GestureHandlerRootView
|
||||
style={flexStyle}
|
||||
onTouchStart={reportNativeUserActivity}
|
||||
onTouchEnd={reportNativeUserActivity}
|
||||
>
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
<LucideProvider strokeWidth={ICON_STROKE_WIDTH}>
|
||||
<AddHostProvider>
|
||||
|
||||
@@ -7,6 +7,7 @@ export const ASSISTANT_FILE_EXTENSIONS: ReadonlySet<string> = new Set([
|
||||
"cpp",
|
||||
"cs",
|
||||
"css",
|
||||
"csv",
|
||||
"cts",
|
||||
"cxx",
|
||||
"env",
|
||||
|
||||
@@ -10,6 +10,11 @@ export {
|
||||
type AssistantFileLinkResolverProviderProps,
|
||||
} from "./provider";
|
||||
export type { AssistantFileLinkSource } from "./resolver";
|
||||
export { useAssistantFileLinkActions, useFileLink } from "./use-file-link";
|
||||
export {
|
||||
useAssistantFileLinkActions,
|
||||
useFileLink,
|
||||
type AssistantFileLinkInspection,
|
||||
type AssistantFileLinkPath,
|
||||
} from "./use-file-link";
|
||||
|
||||
export { createInlinePathOpener } from "./path-open";
|
||||
|
||||
@@ -169,6 +169,15 @@ 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,6 +49,52 @@ 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: {
|
||||
@@ -64,37 +110,19 @@ export function createInlinePathOpener(input: {
|
||||
return {
|
||||
async open(target: InlinePathTarget, disposition: OpenFileDisposition) {
|
||||
const ownGeneration = ++generation;
|
||||
const normalized = normalizeInlinePathTarget(target.path, input.workspaceRoot);
|
||||
if (!normalized) return;
|
||||
const destination = await resolveInlinePathOpen({
|
||||
...normalized,
|
||||
lineStart: target.lineStart,
|
||||
const destination = await resolveInlinePathDestination({
|
||||
target,
|
||||
workspaceRoot: input.workspaceRoot,
|
||||
client: input.client,
|
||||
resolveRelativeFiles: input.resolveRelativeFiles,
|
||||
});
|
||||
if (ownGeneration !== generation) return;
|
||||
if (!destination || ownGeneration !== generation) return;
|
||||
if (destination.kind === "directory") {
|
||||
input.openDirectory(destination.directoryPath);
|
||||
input.openDirectory(destination.path);
|
||||
} else if (destination.kind === "outsideDirectory") {
|
||||
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);
|
||||
input.openOutsideDirectory(destination.path);
|
||||
} else {
|
||||
input.openFile(destination.location, disposition);
|
||||
}
|
||||
},
|
||||
cancel() {
|
||||
|
||||
@@ -16,11 +16,15 @@ 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;
|
||||
@@ -55,6 +59,7 @@ export function useAssistantFileLinkEnvironmentBridge() {
|
||||
export function AssistantFileLinkResolverProvider({
|
||||
client,
|
||||
serverId,
|
||||
workspaceId,
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
@@ -65,6 +70,7 @@ export function AssistantFileLinkResolverProvider({
|
||||
const configRef = useRef<AssistantFileLinkResolverConfig>({
|
||||
client,
|
||||
serverId,
|
||||
workspaceId,
|
||||
workspaceRoot,
|
||||
relativePathBase,
|
||||
onOpenWorkspaceFile,
|
||||
@@ -74,6 +80,7 @@ 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 { useFileLink } from "./use-file-link";
|
||||
import { useAssistantFileLinkActions, useFileLink } from "./use-file-link";
|
||||
import type { OpenFileDisposition } from "@/workspace/file-open";
|
||||
|
||||
vi.mock("@/utils/open-external-url", () => ({
|
||||
@@ -68,6 +68,7 @@ interface TestClient {
|
||||
matchMode: "suffix";
|
||||
limit: number;
|
||||
}) => Promise<DirectorySuggestionResult>;
|
||||
listDirectory?: (root: string, path: string) => Promise<unknown>;
|
||||
}
|
||||
|
||||
function createQueryClient(): QueryClient {
|
||||
@@ -347,4 +348,80 @@ 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,7 +6,8 @@ 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 type { InlinePathTarget } from "./parse";
|
||||
import { normalizeInlinePathTarget, type InlinePathTarget } from "./parse";
|
||||
import { resolveInlinePathDestination } from "./path-open";
|
||||
import {
|
||||
useAssistantFileLinkResolverContext,
|
||||
type AssistantFileLinkResolverContextValue,
|
||||
@@ -31,8 +32,28 @@ 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;
|
||||
@@ -167,7 +188,116 @@ export function useAssistantFileLinkActions(): AssistantFileLinkActions {
|
||||
[context.configRef],
|
||||
);
|
||||
|
||||
return useMemo(() => ({ open, canOpen, canResolveFile }), [open, canOpen, canResolveFile]);
|
||||
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,
|
||||
});
|
||||
}
|
||||
|
||||
function openAssistantFileLink(input: {
|
||||
@@ -194,26 +324,14 @@ function openAssistantFileLink(input: {
|
||||
return;
|
||||
}
|
||||
|
||||
const capturedQueryKey = assistantFileLinkQueryKey({
|
||||
serverId: capturedConfig.serverId,
|
||||
workspaceRoot: capturedConfig.workspaceRoot,
|
||||
resolution: capturedResolution,
|
||||
});
|
||||
|
||||
const run = async () => {
|
||||
try {
|
||||
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,
|
||||
const target = await fetchLookup({
|
||||
resolution: capturedResolution,
|
||||
serverId: capturedConfig.serverId,
|
||||
workspaceRoot: capturedConfig.workspaceRoot,
|
||||
context: input.context,
|
||||
queryClient: input.queryClient,
|
||||
});
|
||||
await dispatchFileTarget({
|
||||
target,
|
||||
|
||||
@@ -12,6 +12,7 @@ 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[]>;
|
||||
}
|
||||
@@ -44,6 +45,9 @@ 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,6 +166,10 @@ 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,6 +5,7 @@ import {
|
||||
encodeAttachmentsForSend,
|
||||
garbageCollectAttachments,
|
||||
persistAttachmentFromBytes,
|
||||
uploadImageAttachments,
|
||||
} from "./service";
|
||||
|
||||
function createAttachment(input: Partial<AttachmentMetadata> = {}): AttachmentMetadata {
|
||||
@@ -42,6 +43,9 @@ 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}`;
|
||||
},
|
||||
@@ -140,4 +144,80 @@ 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,6 +1,9 @@
|
||||
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>();
|
||||
@@ -124,6 +127,75 @@ 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,6 +61,13 @@ 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,6 +178,7 @@ 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>;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// @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",
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
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,6 +165,16 @@ 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,6 +56,7 @@ 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",
|
||||
@@ -139,6 +140,21 @@ 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,6 +36,7 @@ export interface WorkspaceCommandCenterLabels {
|
||||
copyAgentId: string;
|
||||
copyTerminalId: string;
|
||||
copyFilePath: string;
|
||||
revealInFiles: string;
|
||||
closeTabsLeft: string;
|
||||
closeTabsRight: string;
|
||||
closeOtherTabs: string;
|
||||
@@ -351,6 +352,14 @@ 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,6 +256,7 @@ 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,6 +412,29 @@ 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 (
|
||||
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
FolderMinus,
|
||||
FolderOpen,
|
||||
FolderPlus,
|
||||
FolderTree,
|
||||
MessageSquarePlus,
|
||||
Pencil,
|
||||
Trash2,
|
||||
@@ -55,6 +56,8 @@ interface FileActionsContextMenuContentProps {
|
||||
onOpenInEditor?: () => void;
|
||||
editorTargetName?: string;
|
||||
onOpenToSide?: () => void;
|
||||
/** Only for a row listed outside the tree, such as a filter match. */
|
||||
onRevealInFiles?: () => void;
|
||||
onCopyPath?: () => void;
|
||||
onCopyRelativePath?: () => void;
|
||||
onReveal?: () => void;
|
||||
@@ -82,6 +85,7 @@ export function FileActionsContextMenuContent({
|
||||
onOpenInEditor,
|
||||
editorTargetName,
|
||||
onOpenToSide,
|
||||
onRevealInFiles,
|
||||
onCopyPath,
|
||||
onCopyRelativePath,
|
||||
onReveal,
|
||||
@@ -157,6 +161,12 @@ export function FileActionsContextMenuContent({
|
||||
label: t("workspace.fileActions.openToSide"),
|
||||
icon: ArrowRightToLine,
|
||||
}),
|
||||
optionalFileAction(true, onRevealInFiles, {
|
||||
key: "reveal-in-files",
|
||||
group: "open",
|
||||
label: t("workspace.fileActions.revealInFiles"),
|
||||
icon: FolderTree,
|
||||
}),
|
||||
onCopyPath
|
||||
? {
|
||||
key: "copy-path",
|
||||
@@ -265,6 +275,7 @@ export function FileActionsContextMenuContent({
|
||||
onOpenToSide,
|
||||
onRename,
|
||||
onReveal,
|
||||
onRevealInFiles,
|
||||
onRevert,
|
||||
revealTargetName,
|
||||
t,
|
||||
|
||||
@@ -12,6 +12,7 @@ import { useQuery } from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
FlatList,
|
||||
type LayoutChangeEvent,
|
||||
ListRenderItemInfo,
|
||||
Pressable,
|
||||
Text,
|
||||
@@ -26,11 +27,19 @@ import { EditingTextInput as TextInput } from "@/components/ui/text-input";
|
||||
import { StyleSheet, useUnistyles, withUnistyles } from "react-native-unistyles";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { ChevronDown, Eye, EyeOff, FilePlus, FolderPlus, RotateCw } from "lucide-react-native";
|
||||
import {
|
||||
ChevronDown,
|
||||
Eye,
|
||||
EyeOff,
|
||||
FilePlus,
|
||||
Folder,
|
||||
FolderPlus,
|
||||
RotateCw,
|
||||
} from "lucide-react-native";
|
||||
import { MaterialFileIcon } from "@/components/material-file-icon";
|
||||
import {
|
||||
TreeChevron,
|
||||
TreeIndentGuides,
|
||||
treeRowPaddingLeft,
|
||||
workspaceTreeRowStyles,
|
||||
WORKSPACE_TREE_ICON_LABEL_GAP,
|
||||
@@ -58,12 +67,17 @@ import type {
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { FileActionsContextMenuContent } from "@/components/file-actions-menu";
|
||||
import { ContextMenu, ContextMenuTrigger, useContextMenu } from "@/components/ui/context-menu";
|
||||
import { useFileDownload } from "@/hooks/use-file-download";
|
||||
import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
|
||||
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
||||
import { buildWorkspaceExplorerStateKey } from "@/hooks/use-file-explorer-actions";
|
||||
import {
|
||||
clearFileFilter,
|
||||
FileFilterField,
|
||||
FileFilterResults,
|
||||
useFileFilterQuery,
|
||||
useRefreshFileFilterResults,
|
||||
type FileFilterMatch,
|
||||
} from "@/file-explorer/filter";
|
||||
import { usePanelStore, type ExpandedPathsUpdate, type SortOption } from "@/stores/panel-store";
|
||||
import { buildAbsoluteExplorerPath } from "@/utils/explorer-paths";
|
||||
import {
|
||||
DIRECTORY_LISTING_INVALIDATED,
|
||||
type DirectoryListingResult,
|
||||
@@ -81,9 +95,10 @@ import {
|
||||
import { useWorkspaceFileDragSource } from "@/attachments/use-workspace-file-drag-source";
|
||||
import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { openDesktopTarget, useDesktopOpenTargets } from "@/workspace/desktop-open-targets";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import { useOpenDirectoryInEditor } from "@/workspace/open-in-editor/directory";
|
||||
import { useWorkspaceFileActions } from "@/workspace/file-actions";
|
||||
import { useScrollToRevealedEntry } from "@/file-explorer/use-scroll-to-revealed-entry";
|
||||
|
||||
const SORT_OPTIONS: { value: SortOption }[] = [
|
||||
{ value: "name" },
|
||||
@@ -92,6 +107,7 @@ const SORT_OPTIONS: { value: SortOption }[] = [
|
||||
];
|
||||
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
const ThemedFolder = withUnistyles(Folder);
|
||||
const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
@@ -108,33 +124,64 @@ function DirectoryChevronIcon({ loading, expanded }: { loading: boolean; expande
|
||||
return <TreeChevron expanded={expanded} />;
|
||||
}
|
||||
|
||||
interface TreeRowItemProps {
|
||||
/** What a row needs to know about its entry; tree entries and filter matches both have it. */
|
||||
type ExplorerEntryRef = Pick<ExplorerEntry, "kind" | "name" | "path">;
|
||||
|
||||
/** What every row can do with its entry, whether the tree or the filter lists it. */
|
||||
interface EntryRowActions {
|
||||
onEntryPress: (entry: ExplorerEntryRef) => void;
|
||||
onSelectEntry: (entry: ExplorerEntryRef) => void;
|
||||
onCopyPath: (path: string) => void;
|
||||
onCopyRelativePath: (path: string) => void;
|
||||
onOpenInEditor?: (entry: ExplorerEntryRef) => void;
|
||||
editorTargetName?: string;
|
||||
onRevealEntry?: (entry: ExplorerEntryRef) => void;
|
||||
revealTargetName?: string;
|
||||
onDownloadEntry: (entry: ExplorerEntryRef) => void;
|
||||
onAddToChat?: (path: string) => void;
|
||||
onOpenFileToSide?: (path: string) => void;
|
||||
onNewEntry?: (parentPath: string, kind: "file" | "directory") => void;
|
||||
onRenameEntry?: (entry: ExplorerEntryRef) => void;
|
||||
onDuplicateEntry?: (entry: ExplorerEntryRef) => void;
|
||||
onDeleteEntry?: (entry: ExplorerEntryRef) => void;
|
||||
}
|
||||
|
||||
interface TreeRowItemProps extends EntryRowActions {
|
||||
serverId: string;
|
||||
workspaceId?: string | null;
|
||||
entry: ExplorerEntry;
|
||||
entry: ExplorerEntryRef;
|
||||
depth: number;
|
||||
isExpanded: boolean;
|
||||
isSelected: boolean;
|
||||
loading: boolean;
|
||||
onEntryPress: (entry: ExplorerEntry) => void;
|
||||
onSelectEntry: (entry: ExplorerEntry) => void;
|
||||
onCopyPath: (path: string) => void;
|
||||
onCopyRelativePath: (path: string) => void;
|
||||
onOpenInEditor?: (entry: ExplorerEntry) => void;
|
||||
editorTargetName?: string;
|
||||
onRevealEntry?: (entry: ExplorerEntry) => void;
|
||||
revealTargetName?: string;
|
||||
onDownloadEntry: (entry: ExplorerEntry) => void;
|
||||
onAddToChat?: (path: string) => void;
|
||||
onOpenFileToSide?: (path: string) => void;
|
||||
onNewEntry?: (parentPath: string, kind: "file" | "directory") => void;
|
||||
/** Set on a filter match, which names the folder it is in instead of sitting under it. */
|
||||
parentDirectory?: string;
|
||||
onRevealInFiles?: (path: string) => void;
|
||||
onCollapseDirectory?: (path: string) => void;
|
||||
onRenameEntry?: (entry: ExplorerEntry) => void;
|
||||
onDuplicateEntry?: (entry: ExplorerEntry) => void;
|
||||
onDeleteEntry?: (entry: ExplorerEntry) => void;
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
function EntryIcon({
|
||||
entry,
|
||||
loading,
|
||||
isExpanded,
|
||||
isMatch,
|
||||
}: {
|
||||
entry: ExplorerEntryRef;
|
||||
loading: boolean;
|
||||
isExpanded: boolean;
|
||||
isMatch: boolean;
|
||||
}) {
|
||||
if (entry.kind === "file") {
|
||||
return <MaterialFileIcon fileName={entry.name} size={WORKSPACE_TREE_ICON_SIZE} />;
|
||||
}
|
||||
// A match does not expand in place, so it carries no disclosure chevron.
|
||||
if (isMatch) {
|
||||
return <ThemedFolder size={WORKSPACE_TREE_ICON_SIZE} uniProps={foregroundMutedColorMapping} />;
|
||||
}
|
||||
return <DirectoryChevronIcon loading={loading} expanded={isExpanded} />;
|
||||
}
|
||||
|
||||
function sortTriggerStyle({
|
||||
hovered,
|
||||
pressed,
|
||||
@@ -145,11 +192,16 @@ function sortTriggerStyle({
|
||||
type ExplorerListRow =
|
||||
| { type: "entry"; row: ExplorerTreeRow }
|
||||
| { type: "draft"; parentPath: string; kind: "file" | "directory"; depth: number }
|
||||
| { type: "rename"; entry: ExplorerEntry; depth: number };
|
||||
| { type: "rename"; entry: ExplorerEntryRef; depth: number };
|
||||
|
||||
type ExplorerPendingEdit =
|
||||
| { type: "create"; parentPath: string; kind: "file" | "directory" }
|
||||
| { type: "rename"; entry: ExplorerEntry };
|
||||
| { type: "rename"; entry: ExplorerEntryRef };
|
||||
|
||||
function listRowPath(row: ExplorerListRow): string | null {
|
||||
if (row.type === "entry") return row.row.entry.path;
|
||||
return row.type === "rename" ? row.entry.path : null;
|
||||
}
|
||||
|
||||
function listRowKeyExtractor(row: ExplorerListRow) {
|
||||
if (row.type === "entry") {
|
||||
@@ -202,6 +254,7 @@ function EntryNameInputRow({
|
||||
|
||||
return (
|
||||
<View style={[workspaceTreeRowStyles.row, { paddingLeft: treeRowPaddingLeft(depth) }]}>
|
||||
<TreeIndentGuides depth={depth} />
|
||||
<View style={styles.entryInfo}>
|
||||
<View style={styles.entryIcon}>
|
||||
{kind === "directory" ? (
|
||||
@@ -242,6 +295,8 @@ function TreeRowItem({
|
||||
isExpanded,
|
||||
isSelected,
|
||||
loading,
|
||||
parentDirectory,
|
||||
onRevealInFiles,
|
||||
onEntryPress,
|
||||
onSelectEntry,
|
||||
onCopyPath,
|
||||
@@ -264,6 +319,7 @@ function TreeRowItem({
|
||||
const showNameHover = useCallback(() => setIsHovered(true), []);
|
||||
const hideNameHover = useCallback(() => setIsHovered(false), []);
|
||||
const isDirectory = entry.kind === "directory";
|
||||
const isMatch = parentDirectory !== undefined;
|
||||
const dragSourceRef = useWorkspaceFileDragSource({
|
||||
enabled: !isDirectory,
|
||||
serverId,
|
||||
@@ -317,6 +373,10 @@ function TreeRowItem({
|
||||
onAddToChat?.(entry.path);
|
||||
}, [onAddToChat, entry.path]);
|
||||
|
||||
const handleRevealInFiles = useCallback(() => {
|
||||
onRevealInFiles?.(entry.path);
|
||||
}, [entry.path, onRevealInFiles]);
|
||||
|
||||
const handleOpenToSide = useCallback(() => {
|
||||
onOpenFileToSide?.(entry.path);
|
||||
}, [entry.path, onOpenFileToSide]);
|
||||
@@ -358,17 +418,14 @@ function TreeRowItem({
|
||||
aria-selected={isSelected}
|
||||
testID={testID}
|
||||
>
|
||||
<TreeIndentGuides depth={depth} />
|
||||
<View ref={dragSourceRef} style={styles.entryInfo}>
|
||||
<View style={styles.entryIcon}>
|
||||
{isDirectory ? (
|
||||
<DirectoryChevronIcon loading={loading} expanded={isExpanded} />
|
||||
) : (
|
||||
<MaterialFileIcon fileName={entry.name} size={WORKSPACE_TREE_ICON_SIZE} />
|
||||
)}
|
||||
<EntryIcon entry={entry} loading={loading} isExpanded={isExpanded} isMatch={isMatch} />
|
||||
</View>
|
||||
<Text
|
||||
style={[
|
||||
styles.entryName,
|
||||
isMatch ? styles.matchName : styles.entryName,
|
||||
workspaceTreeRowStyles.name,
|
||||
isHovered && workspaceTreeRowStyles.nameHovered,
|
||||
]}
|
||||
@@ -377,6 +434,11 @@ function TreeRowItem({
|
||||
>
|
||||
{entry.name}
|
||||
</Text>
|
||||
{parentDirectory ? (
|
||||
<Text style={styles.matchDirectory} numberOfLines={1} ellipsizeMode="head">
|
||||
{parentDirectory}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</ContextMenuTrigger>
|
||||
<FileActionsContextMenuContent
|
||||
@@ -390,6 +452,7 @@ function TreeRowItem({
|
||||
onDownload={handleDownload}
|
||||
onAddToChat={onAddToChat ? handleAddToChat : undefined}
|
||||
onOpenToSide={!isDirectory && onOpenFileToSide ? handleOpenToSide : undefined}
|
||||
onRevealInFiles={onRevealInFiles ? handleRevealInFiles : undefined}
|
||||
onNewFile={onNewEntry ? handleNewFile : undefined}
|
||||
onNewFolder={onNewEntry ? handleNewFolder : undefined}
|
||||
onCollapseFolder={isDirectory && isExpanded ? handleCollapseDirectory : undefined}
|
||||
@@ -439,6 +502,7 @@ export function FileExplorerPane({
|
||||
);
|
||||
|
||||
const {
|
||||
revealDirectory,
|
||||
requestDirectoryListing,
|
||||
invalidateDirectoryListings,
|
||||
createEntry,
|
||||
@@ -452,11 +516,11 @@ export function FileExplorerPane({
|
||||
workspaceRoot: normalizedWorkspaceRoot,
|
||||
});
|
||||
const toast = useToast();
|
||||
const isLocalDaemon = useIsLocalDaemon(serverId);
|
||||
const { targets: desktopOpenTargets } = useDesktopOpenTargets({
|
||||
isLocalExecution: isLocalDaemon,
|
||||
const fileActions = useWorkspaceFileActions({
|
||||
serverId,
|
||||
workspaceId,
|
||||
workspaceRoot: normalizedWorkspaceRoot,
|
||||
});
|
||||
const fileManagerTarget = desktopOpenTargets.find((target) => target.kind === "file-manager");
|
||||
const projectId = useWorkspaceFields(
|
||||
serverId,
|
||||
workspaceId ?? null,
|
||||
@@ -476,11 +540,8 @@ export function FileExplorerPane({
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.fsEntryDuplicate === true,
|
||||
);
|
||||
const [pendingEdit, setPendingEdit] = useState<ExplorerPendingEdit | null>(null);
|
||||
const downloadFile = useFileDownload({
|
||||
serverId,
|
||||
workspaceId,
|
||||
workspaceRoot: normalizedWorkspaceRoot,
|
||||
});
|
||||
const filterQuery = useFileFilterQuery(workspaceStateKey);
|
||||
const refreshFilterResults = useRefreshFileFilterResults(serverId);
|
||||
const sortOption = usePanelStore((state) => state.explorerSortOption);
|
||||
const showHiddenFiles = usePanelStore((state) => state.explorerShowHiddenFiles);
|
||||
const setSortOption = usePanelStore((state) => state.setExplorerSortOption);
|
||||
@@ -534,7 +595,7 @@ export function FileExplorerPane({
|
||||
]);
|
||||
|
||||
const handleToggleDirectory = useCallback(
|
||||
(entry: ExplorerEntry) =>
|
||||
(entry: ExplorerEntryRef) =>
|
||||
toggleDirectory({
|
||||
entry,
|
||||
workspaceStateKey,
|
||||
@@ -555,7 +616,7 @@ export function FileExplorerPane({
|
||||
// Selection is intentionally separate from opening/expansion so future keyboard actions
|
||||
// (for example, pressing R to rename) have one stable file-or-folder target.
|
||||
const handleSelectEntry = useCallback(
|
||||
(entry: ExplorerEntry) => {
|
||||
(entry: ExplorerEntryRef) => {
|
||||
if (hasWorkspaceScope) {
|
||||
selectExplorerEntry(entry.path);
|
||||
}
|
||||
@@ -564,7 +625,7 @@ export function FileExplorerPane({
|
||||
);
|
||||
|
||||
const handleOpenFile = useCallback(
|
||||
(entry: ExplorerEntry) => {
|
||||
(entry: ExplorerEntryRef) => {
|
||||
if (!hasWorkspaceScope) {
|
||||
return;
|
||||
}
|
||||
@@ -574,7 +635,7 @@ export function FileExplorerPane({
|
||||
);
|
||||
|
||||
const handleEntryPress = useCallback(
|
||||
(entry: ExplorerEntry) => {
|
||||
(entry: ExplorerEntryRef) => {
|
||||
handleSelectEntry(entry);
|
||||
if (entry.kind === "directory") {
|
||||
handleToggleDirectory(entry);
|
||||
@@ -597,58 +658,37 @@ export function FileExplorerPane({
|
||||
[setExpandedPathsForWorkspace, workspaceStateKey],
|
||||
);
|
||||
|
||||
const handleCopyPath = useCallback(
|
||||
async (path: string) => {
|
||||
await Clipboard.setStringAsync(
|
||||
buildAbsoluteExplorerPath({
|
||||
workspaceRoot: normalizedWorkspaceRoot,
|
||||
entryPath: path,
|
||||
}),
|
||||
);
|
||||
},
|
||||
[normalizedWorkspaceRoot],
|
||||
);
|
||||
|
||||
const handleCopyRelativePath = useCallback(async (path: string) => {
|
||||
await Clipboard.setStringAsync(path);
|
||||
}, []);
|
||||
|
||||
const handleRevealEntry = useCallback(
|
||||
async (entry: ExplorerEntry) => {
|
||||
if (!fileManagerTarget) {
|
||||
const handleMatchPress = useCallback(
|
||||
async (entry: ExplorerEntryRef) => {
|
||||
handleSelectEntry(entry);
|
||||
if (entry.kind === "file") {
|
||||
handleOpenFile(entry);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await openDesktopTarget({
|
||||
editorId: fileManagerTarget.id,
|
||||
workspacePath: normalizedWorkspaceRoot,
|
||||
filePath: buildAbsoluteExplorerPath({
|
||||
workspaceRoot: normalizedWorkspaceRoot,
|
||||
entryPath: entry.path,
|
||||
}),
|
||||
});
|
||||
} catch (cause) {
|
||||
toast.error(
|
||||
cause instanceof Error ? cause.message : t("workspace.fileExplorer.errors.revealFailed"),
|
||||
);
|
||||
}
|
||||
// A folder has no tab to open: show it, expanded, in the tree.
|
||||
await revealDirectory(entry.path, { select: true });
|
||||
},
|
||||
[fileManagerTarget, normalizedWorkspaceRoot, t, toast],
|
||||
[handleOpenFile, handleSelectEntry, revealDirectory],
|
||||
);
|
||||
|
||||
const handleRevealEntry = useCallback(
|
||||
(entry: ExplorerEntryRef) => void fileActions.revealInFileManager(entry.path),
|
||||
[fileActions],
|
||||
);
|
||||
|
||||
const handleOpenDirectoryInEditor = useCallback(
|
||||
(entry: ExplorerEntry) => openDirectoryInEditor?.open(entry.path),
|
||||
(entry: ExplorerEntryRef) => openDirectoryInEditor?.open(entry.path),
|
||||
[openDirectoryInEditor],
|
||||
);
|
||||
|
||||
const handleDownloadEntry = useCallback(
|
||||
(entry: ExplorerEntry) => {
|
||||
(entry: ExplorerEntryRef) => {
|
||||
if (entry.kind !== "file") {
|
||||
return;
|
||||
}
|
||||
downloadFile({ fileName: entry.name, path: entry.path });
|
||||
fileActions.download(entry.path);
|
||||
},
|
||||
[downloadFile],
|
||||
[fileActions],
|
||||
);
|
||||
|
||||
const handleNewEntry = useCallback(
|
||||
@@ -656,6 +696,8 @@ export function FileExplorerPane({
|
||||
if (!workspaceStateKey) {
|
||||
return;
|
||||
}
|
||||
// The name is typed into a draft row in the tree.
|
||||
clearFileFilter(workspaceStateKey);
|
||||
if (parentPath !== ".") {
|
||||
setExpandedPathsForWorkspace(workspaceStateKey, (currentPaths) =>
|
||||
setExpandedDirectoryPath({
|
||||
@@ -680,7 +722,7 @@ export function FileExplorerPane({
|
||||
setPendingEdit(null);
|
||||
}, []);
|
||||
|
||||
const handleRenameEntry = useCallback((entry: ExplorerEntry) => {
|
||||
const handleRenameEntry = useCallback((entry: ExplorerEntryRef) => {
|
||||
setPendingEdit({ type: "rename", entry });
|
||||
}, []);
|
||||
|
||||
@@ -737,6 +779,7 @@ export function FileExplorerPane({
|
||||
}
|
||||
|
||||
const renamedPath = payload.renamedPath;
|
||||
void refreshFilterResults();
|
||||
if (workspaceStateKey && entry.kind === "directory") {
|
||||
const expandedRenamedPaths = Array.from(expandedPaths)
|
||||
.filter((expandedPath) => isExplorerPathWithin(expandedPath, entry.path))
|
||||
@@ -778,6 +821,7 @@ export function FileExplorerPane({
|
||||
expandedPaths,
|
||||
onOpenFile,
|
||||
pendingEdit,
|
||||
refreshFilterResults,
|
||||
requestDirectoryListing,
|
||||
renameEntry,
|
||||
selectExplorerEntry,
|
||||
@@ -790,7 +834,7 @@ export function FileExplorerPane({
|
||||
);
|
||||
|
||||
const handleDuplicateEntry = useCallback(
|
||||
async (entry: ExplorerEntry) => {
|
||||
async (entry: ExplorerEntryRef) => {
|
||||
try {
|
||||
const payload = await duplicateEntry(entry.path);
|
||||
if (!payload) {
|
||||
@@ -801,15 +845,16 @@ export function FileExplorerPane({
|
||||
return;
|
||||
}
|
||||
selectExplorerEntry(payload.duplicatedPath);
|
||||
void refreshFilterResults();
|
||||
} catch (cause) {
|
||||
toast.error(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
},
|
||||
[duplicateEntry, selectExplorerEntry, t, toast],
|
||||
[duplicateEntry, refreshFilterResults, selectExplorerEntry, t, toast],
|
||||
);
|
||||
|
||||
const handleDeleteEntry = useCallback(
|
||||
async (entry: ExplorerEntry) => {
|
||||
async (entry: ExplorerEntryRef) => {
|
||||
const confirmed = await confirmDialog({
|
||||
title:
|
||||
entry.kind === "directory"
|
||||
@@ -835,11 +880,12 @@ export function FileExplorerPane({
|
||||
if (selectedEntryPath === entry.path) {
|
||||
selectExplorerEntry(null);
|
||||
}
|
||||
void refreshFilterResults();
|
||||
} catch (cause) {
|
||||
toast.error(cause instanceof Error ? cause.message : String(cause));
|
||||
}
|
||||
},
|
||||
[deleteEntry, selectExplorerEntry, selectedEntryPath, t, toast],
|
||||
[deleteEntry, refreshFilterResults, selectExplorerEntry, selectedEntryPath, t, toast],
|
||||
);
|
||||
|
||||
const handleSortCycle = useCallback(() => {
|
||||
@@ -906,7 +952,8 @@ export function FileExplorerPane({
|
||||
|
||||
const handleRefresh = useCallback(() => {
|
||||
void refetchExplorer();
|
||||
}, [refetchExplorer]);
|
||||
void refreshFilterResults();
|
||||
}, [refetchExplorer, refreshFilterResults]);
|
||||
|
||||
const sortLabels = useMemo(
|
||||
() => ({
|
||||
@@ -950,6 +997,13 @@ export function FileExplorerPane({
|
||||
return rows;
|
||||
}, [pendingEdit, treeRows]);
|
||||
|
||||
const revealScroll = useScrollToRevealedEntry({
|
||||
stateKey: workspaceStateKey,
|
||||
listRef: treeListRef,
|
||||
rowPaths: useMemo(() => listRows.map(listRowPath), [listRows]),
|
||||
onLayout: scrollbar.onLayout,
|
||||
});
|
||||
|
||||
const showInitialLoading = resolveShowInitialLoading({
|
||||
directories,
|
||||
isExplorerLoading,
|
||||
@@ -958,6 +1012,43 @@ export function FileExplorerPane({
|
||||
const showBackFromError = Boolean(error && selectedEntryPath);
|
||||
const errorRecoveryPath = useMemo(() => getErrorRecoveryPath(explorerState), [explorerState]);
|
||||
|
||||
const rowActions = useMemo<EntryRowActions>(
|
||||
() => ({
|
||||
onEntryPress: handleEntryPress,
|
||||
onSelectEntry: handleSelectEntry,
|
||||
onCopyPath: fileActions.copyPath,
|
||||
onCopyRelativePath: fileActions.copyRelativePath,
|
||||
onOpenInEditor: openDirectoryInEditor ? handleOpenDirectoryInEditor : undefined,
|
||||
editorTargetName: openDirectoryInEditor?.targetName,
|
||||
onRevealEntry: fileActions.revealTargetName ? handleRevealEntry : undefined,
|
||||
revealTargetName: fileActions.revealTargetName ?? undefined,
|
||||
onDownloadEntry: handleDownloadEntry,
|
||||
onAddToChat,
|
||||
onOpenFileToSide,
|
||||
onNewEntry: fsEntryOpsEnabled ? handleNewEntry : undefined,
|
||||
onRenameEntry: fsEntryOpsEnabled ? handleRenameEntry : undefined,
|
||||
onDuplicateEntry: fsEntryDuplicateEnabled ? handleDuplicateEntry : undefined,
|
||||
onDeleteEntry: fsEntryOpsEnabled ? handleDeleteEntry : undefined,
|
||||
}),
|
||||
[
|
||||
fileActions,
|
||||
fsEntryDuplicateEnabled,
|
||||
fsEntryOpsEnabled,
|
||||
handleDeleteEntry,
|
||||
handleDownloadEntry,
|
||||
handleDuplicateEntry,
|
||||
handleEntryPress,
|
||||
handleNewEntry,
|
||||
handleOpenDirectoryInEditor,
|
||||
handleRenameEntry,
|
||||
handleRevealEntry,
|
||||
handleSelectEntry,
|
||||
onAddToChat,
|
||||
onOpenFileToSide,
|
||||
openDirectoryInEditor,
|
||||
],
|
||||
);
|
||||
|
||||
const renderTreeRow = useCallback(
|
||||
(info: ListRenderItemInfo<ExplorerListRow>) => {
|
||||
if (info.item.type === "draft") {
|
||||
@@ -990,50 +1081,67 @@ export function FileExplorerPane({
|
||||
expandedPaths={expandedPaths}
|
||||
selectedEntryPath={selectedEntryPath}
|
||||
isDirectoryLoading={isDirectoryLoading}
|
||||
onEntryPress={handleEntryPress}
|
||||
onSelectEntry={handleSelectEntry}
|
||||
onCopyPath={handleCopyPath}
|
||||
onCopyRelativePath={handleCopyRelativePath}
|
||||
onOpenInEditor={openDirectoryInEditor ? handleOpenDirectoryInEditor : undefined}
|
||||
editorTargetName={openDirectoryInEditor?.targetName}
|
||||
onRevealEntry={fileManagerTarget ? handleRevealEntry : undefined}
|
||||
revealTargetName={fileManagerTarget?.label}
|
||||
onDownloadEntry={handleDownloadEntry}
|
||||
onAddToChat={onAddToChat}
|
||||
onOpenFileToSide={onOpenFileToSide}
|
||||
onNewEntry={fsEntryOpsEnabled ? handleNewEntry : undefined}
|
||||
actions={rowActions}
|
||||
onCollapseDirectory={handleCollapseDirectory}
|
||||
onRenameEntry={fsEntryOpsEnabled ? handleRenameEntry : undefined}
|
||||
onDuplicateEntry={fsEntryDuplicateEnabled ? handleDuplicateEntry : undefined}
|
||||
onDeleteEntry={fsEntryOpsEnabled ? handleDeleteEntry : undefined}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
expandedPaths,
|
||||
fsEntryDuplicateEnabled,
|
||||
fsEntryOpsEnabled,
|
||||
handleCollapseDirectory,
|
||||
handleCopyPath,
|
||||
handleCopyRelativePath,
|
||||
handleOpenDirectoryInEditor,
|
||||
handleDeleteEntry,
|
||||
handleDownloadEntry,
|
||||
handleDraftCommit,
|
||||
handleDuplicateEntry,
|
||||
handleEditCancel,
|
||||
handleEntryPress,
|
||||
handleNewEntry,
|
||||
handleRenameCommit,
|
||||
handleRenameEntry,
|
||||
handleRevealEntry,
|
||||
handleSelectEntry,
|
||||
isDirectoryLoading,
|
||||
fileManagerTarget,
|
||||
openDirectoryInEditor,
|
||||
rowActions,
|
||||
selectedEntryPath,
|
||||
serverId,
|
||||
workspaceId,
|
||||
],
|
||||
);
|
||||
|
||||
const matchActions = useMemo<EntryRowActions>(
|
||||
// Creating inside a hit would put the draft row somewhere the user cannot see.
|
||||
() => ({ ...rowActions, onEntryPress: handleMatchPress, onNewEntry: undefined }),
|
||||
[handleMatchPress, rowActions],
|
||||
);
|
||||
|
||||
const renderMatch = useCallback(
|
||||
(match: FileFilterMatch, index: number) => {
|
||||
if (pendingEdit?.type === "rename" && pendingEdit.entry.path === match.path) {
|
||||
return (
|
||||
<EntryNameInputRow
|
||||
depth={0}
|
||||
kind={match.kind}
|
||||
initialName={match.name}
|
||||
onCommit={handleRenameCommit}
|
||||
onCancel={handleEditCancel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<TreeRowItem
|
||||
{...matchActions}
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
entry={match}
|
||||
parentDirectory={match.directory}
|
||||
onRevealInFiles={fileActions.revealInFiles}
|
||||
depth={0}
|
||||
isExpanded={false}
|
||||
isSelected={selectedEntryPath === match.path}
|
||||
loading={false}
|
||||
testID={`file-filter-row-${index}`}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[
|
||||
fileActions,
|
||||
handleEditCancel,
|
||||
handleRenameCommit,
|
||||
matchActions,
|
||||
pendingEdit,
|
||||
selectedEntryPath,
|
||||
onAddToChat,
|
||||
onOpenFileToSide,
|
||||
serverId,
|
||||
workspaceId,
|
||||
],
|
||||
@@ -1057,7 +1165,7 @@ export function FileExplorerPane({
|
||||
});
|
||||
}, [requestDirectoryListing]);
|
||||
|
||||
if (!hasWorkspaceScope) {
|
||||
if (!workspaceStateKey || !hasWorkspaceScope) {
|
||||
return (
|
||||
<View style={styles.centerState}>
|
||||
<Text style={styles.errorText}>{t("workspace.fileExplorer.states.unavailable")}</Text>
|
||||
@@ -1075,6 +1183,11 @@ export function FileExplorerPane({
|
||||
<FileExplorerPaneContent
|
||||
error={error}
|
||||
isCompact={isCompact}
|
||||
serverId={serverId}
|
||||
workspaceRoot={normalizedWorkspaceRoot}
|
||||
filterStateKey={workspaceStateKey}
|
||||
filterQuery={filterQuery}
|
||||
renderMatch={renderMatch}
|
||||
showInitialLoading={showInitialLoading}
|
||||
showBackFromError={showBackFromError}
|
||||
listRows={listRows}
|
||||
@@ -1083,6 +1196,8 @@ export function FileExplorerPane({
|
||||
isRefreshFetching={isRefreshFetching}
|
||||
treeListRef={treeListRef}
|
||||
scrollbar={scrollbar}
|
||||
onListLayout={revealScroll.onLayout}
|
||||
onScrollToIndexFailed={revealScroll.onScrollToIndexFailed}
|
||||
renderTreeRow={renderTreeRow}
|
||||
handleSortCycle={handleSortCycle}
|
||||
handleToggleHiddenFiles={handleToggleHiddenFiles}
|
||||
@@ -1149,6 +1264,12 @@ function RootCreationContextTarget({
|
||||
interface FileExplorerPaneContentProps {
|
||||
error: string | null;
|
||||
isCompact: boolean;
|
||||
serverId: string;
|
||||
workspaceRoot: string;
|
||||
filterStateKey: string;
|
||||
/** While this is not empty, matches show in place of the tree. */
|
||||
filterQuery: string;
|
||||
renderMatch: (match: FileFilterMatch, index: number) => ReactElement;
|
||||
showInitialLoading: boolean;
|
||||
showBackFromError: boolean;
|
||||
listRows: ExplorerListRow[];
|
||||
@@ -1157,6 +1278,8 @@ interface FileExplorerPaneContentProps {
|
||||
isRefreshFetching: boolean;
|
||||
treeListRef: RefObject<FlatList<ExplorerListRow> | null>;
|
||||
scrollbar: OverlayFlatListScrollbar;
|
||||
onListLayout: (event: LayoutChangeEvent) => void;
|
||||
onScrollToIndexFailed: (info: { index: number; averageItemLength: number }) => void;
|
||||
renderTreeRow: (info: ListRenderItemInfo<ExplorerListRow>) => ReactElement;
|
||||
handleSortCycle: () => void;
|
||||
handleToggleHiddenFiles: () => void;
|
||||
@@ -1172,6 +1295,11 @@ function FileExplorerPaneContent(props: FileExplorerPaneContentProps) {
|
||||
const {
|
||||
error,
|
||||
isCompact,
|
||||
serverId,
|
||||
workspaceRoot,
|
||||
filterStateKey,
|
||||
filterQuery,
|
||||
renderMatch,
|
||||
showInitialLoading,
|
||||
showBackFromError,
|
||||
listRows,
|
||||
@@ -1180,6 +1308,8 @@ function FileExplorerPaneContent(props: FileExplorerPaneContentProps) {
|
||||
isRefreshFetching,
|
||||
treeListRef,
|
||||
scrollbar,
|
||||
onListLayout,
|
||||
onScrollToIndexFailed,
|
||||
renderTreeRow,
|
||||
handleSortCycle,
|
||||
handleToggleHiddenFiles,
|
||||
@@ -1328,46 +1458,67 @@ function FileExplorerPaneContent(props: FileExplorerPaneContentProps) {
|
||||
</ToolbarButton>
|
||||
</ToolbarControls>
|
||||
</PaneContentToolbar>
|
||||
<ContextMenu>
|
||||
<RootCreationContextTarget enabled={Boolean(onNewEntryAtRoot)}>
|
||||
{listRows.length === 0 ? (
|
||||
<View style={styles.centerState}>
|
||||
<Text style={styles.emptyText}>{emptyLabel}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<FlatList
|
||||
ref={treeListRef}
|
||||
style={styles.treeList}
|
||||
data={listRows}
|
||||
renderItem={renderTreeRow}
|
||||
keyExtractor={listRowKeyExtractor}
|
||||
testID="file-explorer-tree-scroll"
|
||||
contentContainerStyle={styles.entriesContent}
|
||||
onLayout={scrollbar.onLayout}
|
||||
onScroll={scrollbar.onScroll}
|
||||
onContentSizeChange={scrollbar.onContentSizeChange}
|
||||
scrollEventThrottle={16}
|
||||
showsVerticalScrollIndicator={!scrollbar.enabled}
|
||||
initialNumToRender={24}
|
||||
maxToRenderPerBatch={40}
|
||||
windowSize={12}
|
||||
<View {...{ onContextMenu: keepBrowserContextMenu }} style={styles.filterRow}>
|
||||
<FileFilterField key={filterStateKey} stateKey={filterStateKey} />
|
||||
</View>
|
||||
{filterQuery ? (
|
||||
<FileFilterResults
|
||||
key={filterStateKey}
|
||||
serverId={serverId}
|
||||
workspaceRoot={workspaceRoot}
|
||||
query={filterQuery}
|
||||
showHiddenFiles={showHiddenFiles}
|
||||
isCompact={isCompact}
|
||||
renderMatch={renderMatch}
|
||||
/>
|
||||
) : (
|
||||
<ContextMenu>
|
||||
<RootCreationContextTarget enabled={Boolean(onNewEntryAtRoot)}>
|
||||
{listRows.length === 0 ? (
|
||||
<View style={styles.centerState}>
|
||||
<Text style={styles.emptyText}>{emptyLabel}</Text>
|
||||
</View>
|
||||
) : (
|
||||
<FlatList
|
||||
ref={treeListRef}
|
||||
style={styles.treeList}
|
||||
data={listRows}
|
||||
renderItem={renderTreeRow}
|
||||
keyExtractor={listRowKeyExtractor}
|
||||
testID="file-explorer-tree-scroll"
|
||||
contentContainerStyle={styles.entriesContent}
|
||||
onLayout={onListLayout}
|
||||
onScrollToIndexFailed={onScrollToIndexFailed}
|
||||
onScroll={scrollbar.onScroll}
|
||||
onContentSizeChange={scrollbar.onContentSizeChange}
|
||||
scrollEventThrottle={16}
|
||||
showsVerticalScrollIndicator={!scrollbar.enabled}
|
||||
initialNumToRender={24}
|
||||
maxToRenderPerBatch={40}
|
||||
windowSize={12}
|
||||
/>
|
||||
)}
|
||||
{listRows.length > 0 ? scrollbar.overlay : null}
|
||||
</RootCreationContextTarget>
|
||||
{onNewEntryAtRoot ? (
|
||||
<FileActionsContextMenuContent
|
||||
fileKind="directory"
|
||||
onNewFile={handleNewFileAtRoot}
|
||||
onNewFolder={handleNewFolderAtRoot}
|
||||
testIDPrefix="files-empty-area"
|
||||
/>
|
||||
)}
|
||||
{listRows.length > 0 ? scrollbar.overlay : null}
|
||||
</RootCreationContextTarget>
|
||||
{onNewEntryAtRoot ? (
|
||||
<FileActionsContextMenuContent
|
||||
fileKind="directory"
|
||||
onNewFile={handleNewFileAtRoot}
|
||||
onNewFolder={handleNewFolderAtRoot}
|
||||
testIDPrefix="files-empty-area"
|
||||
/>
|
||||
) : null}
|
||||
</ContextMenu>
|
||||
) : null}
|
||||
</ContextMenu>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
// The pane suppresses the browser menu; the filter input wants it back for paste.
|
||||
function keepBrowserContextMenu(event: { stopPropagation: () => void }) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
|
||||
function deriveExplorerFields(state: AgentFileExplorerState | undefined) {
|
||||
return {
|
||||
directories:
|
||||
@@ -1425,7 +1576,7 @@ function toggleDirectory({
|
||||
requestDirectoryListing,
|
||||
setExpandedPathsForWorkspace,
|
||||
}: {
|
||||
entry: ExplorerEntry;
|
||||
entry: ExplorerEntryRef;
|
||||
workspaceStateKey: string | null;
|
||||
expandedPaths: Set<string>;
|
||||
directories: Map<string, ExplorerDirectory>;
|
||||
@@ -1462,22 +1613,8 @@ function TreeRowDispatcher({
|
||||
expandedPaths,
|
||||
selectedEntryPath,
|
||||
isDirectoryLoading,
|
||||
onEntryPress,
|
||||
onSelectEntry,
|
||||
onCopyPath,
|
||||
onCopyRelativePath,
|
||||
onOpenInEditor,
|
||||
editorTargetName,
|
||||
onRevealEntry,
|
||||
revealTargetName,
|
||||
onDownloadEntry,
|
||||
onAddToChat,
|
||||
onOpenFileToSide,
|
||||
onNewEntry,
|
||||
actions,
|
||||
onCollapseDirectory,
|
||||
onRenameEntry,
|
||||
onDuplicateEntry,
|
||||
onDeleteEntry,
|
||||
}: {
|
||||
serverId: string;
|
||||
workspaceId?: string | null;
|
||||
@@ -1486,55 +1623,23 @@ function TreeRowDispatcher({
|
||||
expandedPaths: Set<string>;
|
||||
selectedEntryPath: string | null;
|
||||
isDirectoryLoading: (path: string) => boolean;
|
||||
onEntryPress: (entry: ExplorerEntry) => void;
|
||||
onSelectEntry: (entry: ExplorerEntry) => void;
|
||||
onCopyPath: (path: string) => void | Promise<void>;
|
||||
onCopyRelativePath: (path: string) => void | Promise<void>;
|
||||
onOpenInEditor?: (entry: ExplorerEntry) => void;
|
||||
editorTargetName?: string;
|
||||
onRevealEntry?: (entry: ExplorerEntry) => void;
|
||||
revealTargetName?: string;
|
||||
onDownloadEntry: (entry: ExplorerEntry) => void;
|
||||
onAddToChat?: (path: string) => void;
|
||||
onOpenFileToSide?: (path: string) => void;
|
||||
onNewEntry?: (parentPath: string, kind: "file" | "directory") => void;
|
||||
onCollapseDirectory?: (path: string) => void;
|
||||
onRenameEntry?: (entry: ExplorerEntry) => void;
|
||||
onDuplicateEntry?: (entry: ExplorerEntry) => void;
|
||||
onDeleteEntry?: (entry: ExplorerEntry) => void;
|
||||
actions: EntryRowActions;
|
||||
onCollapseDirectory: (path: string) => void;
|
||||
}) {
|
||||
const entry = row.entry;
|
||||
const depth = row.depth;
|
||||
const isDirectory = entry.kind === "directory";
|
||||
const isExpanded = isDirectory && expandedPaths.has(entry.path);
|
||||
const isSelected = selectedEntryPath === entry.path;
|
||||
const loading = isDirectory && isDirectoryLoading(entry.path);
|
||||
|
||||
return (
|
||||
<TreeRowItem
|
||||
{...actions}
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
entry={entry}
|
||||
depth={depth}
|
||||
isExpanded={isExpanded}
|
||||
isSelected={isSelected}
|
||||
loading={loading}
|
||||
onEntryPress={onEntryPress}
|
||||
onSelectEntry={onSelectEntry}
|
||||
onCopyPath={onCopyPath}
|
||||
onCopyRelativePath={onCopyRelativePath}
|
||||
onOpenInEditor={onOpenInEditor}
|
||||
editorTargetName={editorTargetName}
|
||||
onRevealEntry={onRevealEntry}
|
||||
revealTargetName={revealTargetName}
|
||||
onDownloadEntry={onDownloadEntry}
|
||||
onAddToChat={onAddToChat}
|
||||
onOpenFileToSide={onOpenFileToSide}
|
||||
onNewEntry={onNewEntry}
|
||||
depth={row.depth}
|
||||
isExpanded={isDirectory && expandedPaths.has(entry.path)}
|
||||
isSelected={selectedEntryPath === entry.path}
|
||||
loading={isDirectory && isDirectoryLoading(entry.path)}
|
||||
onCollapseDirectory={onCollapseDirectory}
|
||||
onRenameEntry={onRenameEntry}
|
||||
onDuplicateEntry={onDuplicateEntry}
|
||||
onDeleteEntry={onDeleteEntry}
|
||||
testID={`file-explorer-row-${index}`}
|
||||
/>
|
||||
);
|
||||
@@ -1767,6 +1872,25 @@ const styles = StyleSheet.create((theme) => ({
|
||||
fontSize: theme.fontSize.base,
|
||||
userSelect: "none",
|
||||
},
|
||||
matchName: {
|
||||
flexShrink: 1,
|
||||
minWidth: 0,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
userSelect: "none",
|
||||
},
|
||||
matchDirectory: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
userSelect: "none",
|
||||
},
|
||||
filterRow: {
|
||||
flexDirection: "row",
|
||||
paddingHorizontal: theme.spacing[1.5],
|
||||
paddingTop: theme.spacing[2],
|
||||
},
|
||||
draftInput: {
|
||||
flex: 1,
|
||||
color: theme.colors.foreground,
|
||||
|
||||
@@ -24,6 +24,9 @@ const memoryStore: AttachmentStore = {
|
||||
async encodeBase64() {
|
||||
return "";
|
||||
},
|
||||
async readBytes() {
|
||||
return new Uint8Array();
|
||||
},
|
||||
async resolvePreviewUrl() {
|
||||
return "blob:chart";
|
||||
},
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import {
|
||||
createContext,
|
||||
useContext,
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type Dispatch,
|
||||
type ReactNode,
|
||||
type SetStateAction,
|
||||
} from "react";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import { ContextMenu, useContextMenu } from "@/components/ui/context-menu";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { LinkMenuSurface } from "./internal/surface";
|
||||
import type { LinkMenuLink, LinkMenuSubject, OpenedLink, Point } from "./internal/types";
|
||||
|
||||
export type { LinkMenuSubject } from "./internal/types";
|
||||
|
||||
/** Opens the menu for a link. False when the link has none, so the platform's own menu stays. */
|
||||
type OpenLinkMenu = (link: LinkMenuLink, point: Point) => boolean;
|
||||
|
||||
const LinkMenuContext = createContext<OpenLinkMenu | null>(null);
|
||||
|
||||
export function useOpenLinkMenu(): OpenLinkMenu | null {
|
||||
return useContext(LinkMenuContext);
|
||||
}
|
||||
|
||||
/** One menu for every link in a piece of Markdown. Adds no view of its own. */
|
||||
export function LinkMenu({
|
||||
describeLink,
|
||||
children,
|
||||
}: {
|
||||
describeLink: (link: LinkMenuLink) => LinkMenuSubject | null;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const [opened, setOpened] = useState<OpenedLink | null>(null);
|
||||
// The surface holds its workspace's hooks, so it lives only as long as the menu is open.
|
||||
const handleOpenChange = useStableEvent((open: boolean) => {
|
||||
if (!open) setOpened(null);
|
||||
});
|
||||
return (
|
||||
<ContextMenu onOpenChange={handleOpenChange}>
|
||||
<LinkMenuHost describeLink={describeLink} setOpened={setOpened}>
|
||||
{children}
|
||||
</LinkMenuHost>
|
||||
{opened ? <LinkMenuSurface link={opened} /> : null}
|
||||
</ContextMenu>
|
||||
);
|
||||
}
|
||||
|
||||
function LinkMenuHost({
|
||||
describeLink,
|
||||
setOpened,
|
||||
children,
|
||||
}: {
|
||||
describeLink: (link: LinkMenuLink) => LinkMenuSubject | null;
|
||||
setOpened: Dispatch<SetStateAction<OpenedLink | null>>;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const menu = useContextMenu();
|
||||
|
||||
const open = useStableEvent((link: LinkMenuLink, point: Point) => {
|
||||
const subject = describeLink(link);
|
||||
if (!subject) return false;
|
||||
if (subject.kind === "web") {
|
||||
setOpened(subject);
|
||||
} else {
|
||||
// The menu opens on what the link says and settles on what the host finds.
|
||||
const lookup = subject.inspection.lookup();
|
||||
setOpened({ ...subject, lookup, found: null });
|
||||
void lookup.then((found) =>
|
||||
setOpened((current) =>
|
||||
current?.kind === "path" && current.lookup === lookup ? { ...current, found } : current,
|
||||
),
|
||||
);
|
||||
}
|
||||
menu.setAnchorRect({ ...point, width: 0, height: 0 });
|
||||
menu.setOpen(true);
|
||||
return true;
|
||||
});
|
||||
|
||||
return <LinkMenuContext.Provider value={open}>{children}</LinkMenuContext.Provider>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Long press on a link, for the native text view. Web links open the menu themselves, from their
|
||||
* own right click.
|
||||
*/
|
||||
export function useLinkMenuLongPress(markdown: string) {
|
||||
const open = useOpenLinkMenu();
|
||||
// The native event carries no position; the touch that started the press does.
|
||||
const touch = useRef<Point>({ x: 0, y: 0 });
|
||||
const onTouchStart = useStableEvent((event: GestureResponderEvent) => {
|
||||
touch.current = { x: event.nativeEvent.pageX, y: event.nativeEvent.pageY };
|
||||
});
|
||||
const onLinkLongPress = useStableEvent(({ url }: { url: string }) => {
|
||||
// Nor does it say how the link was written. One that is no `](destination)` was recognized
|
||||
// in the text.
|
||||
open?.({ url, sourceType: markdown.includes(`](${url}`) ? "markdown" : "text" }, touch.current);
|
||||
});
|
||||
return useMemo(
|
||||
() => (isWeb ? null : { onTouchStart, onLinkLongPress }),
|
||||
[onTouchStart, onLinkLongPress],
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import * as Clipboard from "expo-clipboard";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
ArrowRightToLine,
|
||||
Copy,
|
||||
ExternalLink,
|
||||
FileText,
|
||||
Globe,
|
||||
type LucideIcon,
|
||||
} from "lucide-react-native";
|
||||
import {
|
||||
useAssistantFileLinkActions,
|
||||
useAssistantFileLinkEnvironment,
|
||||
} from "@/assistant-file-links";
|
||||
import {
|
||||
ContextMenuContent,
|
||||
ContextMenuItem,
|
||||
ContextMenuSeparator,
|
||||
} from "@/components/ui/context-menu";
|
||||
import { supportsDesktopPaneSplits, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { useToast } from "@/contexts/toast-context";
|
||||
import { openUrlInWorkspaceBrowser } from "@/desktop/browser/open-url-in-workspace";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { useWorkspaceFileActions, WorkspaceFileActionItems } from "@/workspace/file-actions";
|
||||
import type { OpenedLink } from "./types";
|
||||
|
||||
const TEST_ID = "markdown-link-menu";
|
||||
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const ThemedFileText = withUnistyles(FileText);
|
||||
const ThemedArrowRightToLine = withUnistyles(ArrowRightToLine);
|
||||
const ThemedGlobe = withUnistyles(Globe);
|
||||
const ThemedExternalLink = withUnistyles(ExternalLink);
|
||||
const ThemedCopy = withUnistyles(Copy);
|
||||
|
||||
export function LinkMenuSurface({ link }: { link: OpenedLink }): ReactElement {
|
||||
return link.kind === "web" ? <WebLinkMenu link={link} /> : <PathLinkMenu link={link} />;
|
||||
}
|
||||
|
||||
function WebLinkMenu({ link }: { link: Extract<OpenedLink, { kind: "web" }> }): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const { url, workspace } = link;
|
||||
const openInPaseo = useMemo(() => {
|
||||
const workspaceId = workspace?.workspaceId;
|
||||
if (!getIsElectron() || !workspace || !workspaceId) return null;
|
||||
return () => openUrlInWorkspaceBrowser({ serverId: workspace.serverId, workspaceId, url });
|
||||
}, [url, workspace]);
|
||||
const openInBrowser = useCallback(() => void openExternalUrl(url), [url]);
|
||||
const copy = useCallback(() => {
|
||||
void Clipboard.setStringAsync(url).then(
|
||||
() => toast.copied(t("workspace.linkActions.linkCopiedLabel")),
|
||||
() => toast.error(t("workspace.tabs.toasts.copyFailed")),
|
||||
);
|
||||
}, [t, toast, url]);
|
||||
|
||||
return (
|
||||
<ContextMenuContent testID={TEST_ID} sheetTitle={url}>
|
||||
{openInPaseo ? (
|
||||
<LinkItem icon={ThemedGlobe} onSelect={openInPaseo} testID={`${TEST_ID}-open-in-paseo`}>
|
||||
{t("workspace.linkActions.openInPaseo")}
|
||||
</LinkItem>
|
||||
) : null}
|
||||
<LinkItem icon={ThemedExternalLink} onSelect={openInBrowser} testID={`${TEST_ID}-open`}>
|
||||
{t("workspace.linkActions.openInDefaultBrowser")}
|
||||
</LinkItem>
|
||||
<LinkItem icon={ThemedCopy} onSelect={copy} testID={`${TEST_ID}-copy`}>
|
||||
{t("workspace.linkActions.copyLink")}
|
||||
</LinkItem>
|
||||
</ContextMenuContent>
|
||||
);
|
||||
}
|
||||
|
||||
function PathLinkMenu({ link }: { link: Extract<OpenedLink, { kind: "path" }> }): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const links = useAssistantFileLinkActions();
|
||||
const { onOpenWorkspaceFile } = useAssistantFileLinkEnvironment();
|
||||
const fileActions = useWorkspaceFileActions(link.workspace);
|
||||
const { source, lookup, inspection } = link;
|
||||
const shown = link.found ?? inspection.written;
|
||||
|
||||
const actions = fileActions.actionsFor(shown.path, shown.kind).map(({ id }) => ({
|
||||
id,
|
||||
// Chosen before the host has answered, an action waits for the real path.
|
||||
run: () =>
|
||||
void lookup.then((found) => {
|
||||
if (!found) return inspection.reportNotFound();
|
||||
return fileActions
|
||||
.actionsFor(found.path, found.kind)
|
||||
.find((action) => action.id === id)
|
||||
?.run();
|
||||
}),
|
||||
}));
|
||||
|
||||
const open = useCallback(() => links.open(source, "preferred"), [links, source]);
|
||||
const openToSide = useCallback(() => links.open(source, "side"), [links, source]);
|
||||
const canOpen = shown.kind === "file" && Boolean(onOpenWorkspaceFile);
|
||||
|
||||
return (
|
||||
<ContextMenuContent testID={TEST_ID} sheetTitle={shown.path}>
|
||||
{canOpen ? (
|
||||
<>
|
||||
<LinkItem icon={ThemedFileText} onSelect={open} testID={`${TEST_ID}-open`}>
|
||||
{t("workspace.fileActions.openFile")}
|
||||
</LinkItem>
|
||||
{supportsDesktopPaneSplits() && !isCompact ? (
|
||||
<LinkItem
|
||||
icon={ThemedArrowRightToLine}
|
||||
onSelect={openToSide}
|
||||
testID={`${TEST_ID}-open-to-side`}
|
||||
>
|
||||
{t("workspace.fileActions.openToSide")}
|
||||
</LinkItem>
|
||||
) : null}
|
||||
<ContextMenuSeparator />
|
||||
</>
|
||||
) : null}
|
||||
<WorkspaceFileActionItems
|
||||
actions={actions}
|
||||
revealTargetName={fileActions.revealTargetName}
|
||||
testIDBase={TEST_ID}
|
||||
/>
|
||||
</ContextMenuContent>
|
||||
);
|
||||
}
|
||||
|
||||
function LinkItem({
|
||||
icon: Icon,
|
||||
onSelect,
|
||||
testID,
|
||||
children,
|
||||
}: {
|
||||
icon: ReturnType<typeof withUnistyles<LucideIcon, object>>;
|
||||
onSelect: () => void;
|
||||
testID: string;
|
||||
children: string;
|
||||
}): ReactElement {
|
||||
const leading = useMemo(() => <Icon size={ICON_SIZE.sm} uniProps={mutedIconMapping} />, [Icon]);
|
||||
return (
|
||||
<ContextMenuItem leading={leading} onSelect={onSelect} testID={testID}>
|
||||
{children}
|
||||
</ContextMenuItem>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import type {
|
||||
AssistantFileLinkInspection,
|
||||
AssistantFileLinkPath,
|
||||
AssistantFileLinkSource,
|
||||
} from "@/assistant-file-links";
|
||||
|
||||
export interface Point {
|
||||
x: number;
|
||||
y: number;
|
||||
}
|
||||
|
||||
export interface LinkMenuLink {
|
||||
url: string;
|
||||
sourceType?: "markdown" | "text" | "inline-code";
|
||||
}
|
||||
|
||||
export interface LinkMenuWorkspace {
|
||||
serverId: string;
|
||||
workspaceId?: string;
|
||||
workspaceRoot: string;
|
||||
}
|
||||
|
||||
type PathInspection = Extract<AssistantFileLinkInspection, { kind: "path" }>;
|
||||
|
||||
/** What a link in Markdown leads to. */
|
||||
export type LinkMenuSubject =
|
||||
| { kind: "web"; url: string; workspace: LinkMenuWorkspace | null }
|
||||
| {
|
||||
kind: "path";
|
||||
source: AssistantFileLinkSource;
|
||||
inspection: PathInspection;
|
||||
workspace: LinkMenuWorkspace;
|
||||
};
|
||||
|
||||
export type OpenedLink =
|
||||
| Extract<LinkMenuSubject, { kind: "web" }>
|
||||
| (Extract<LinkMenuSubject, { kind: "path" }> & {
|
||||
lookup: Promise<AssistantFileLinkPath | null>;
|
||||
/** Null while the host is being asked, and when nothing matches. */
|
||||
found: AssistantFileLinkPath | null;
|
||||
});
|
||||
@@ -1,20 +1,23 @@
|
||||
import { memo, useMemo, useState } from "react";
|
||||
import { memo, useMemo, useState, type ComponentProps } from "react";
|
||||
import { EnrichedMarkdownText, type LinkPressEvent } from "react-native-enriched-markdown";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
useAssistantFileLinkActions,
|
||||
useAssistantFileLinkEnvironment,
|
||||
type AssistantFileLinkSource,
|
||||
} from "@/assistant-file-links";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { matchCommandLink, useAgentCommandHints, type CommandHints } from "@/agent-commands";
|
||||
import { useForgeShorthand } from "@/git/forge-shorthand";
|
||||
import { pluginOverviewUrl } from "@getpaseo/protocol/plugin-overview";
|
||||
import { isHttpUrl } from "@/utils/http-url";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { density, resolveDensity } from "@/styles/density";
|
||||
import { MarkdownBlockStack } from "./block-stack";
|
||||
import { LinkMenu, useLinkMenuLongPress, type LinkMenuSubject } from "./link-menu";
|
||||
import { WEB_RENDERERS } from "./renderers";
|
||||
import { createMarkdownStyles } from "./styles";
|
||||
import { PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
@@ -87,6 +90,18 @@ const CommandMarkdownPart = memo(function CommandMarkdownPart(props: MarkdownRen
|
||||
return <MarkdownPart {...props} commandHints={commandHints} />;
|
||||
});
|
||||
|
||||
type ReadMarkdownLink =
|
||||
| { kind: "web"; url: string }
|
||||
| { kind: "command"; command: string }
|
||||
| { kind: "source"; source: AssistantFileLinkSource }
|
||||
| { kind: "inert" };
|
||||
|
||||
/** The text view, with the long press its menu needs on native. */
|
||||
function MarkdownText(props: ComponentProps<typeof ThemedMarkdown> & { markdown: string }) {
|
||||
const longPress = useLinkMenuLongPress(props.markdown);
|
||||
return <ThemedMarkdown {...props} {...longPress} />;
|
||||
}
|
||||
|
||||
const MarkdownPart = memo(function MarkdownPart({
|
||||
text,
|
||||
compact = false,
|
||||
@@ -103,15 +118,17 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
const actions = useAssistantFileLinkActions();
|
||||
const workspaceForgeShorthand = useForgeShorthand();
|
||||
const forgeShorthand = external ? null : workspaceForgeShorthand;
|
||||
const environmentMatchesHost =
|
||||
!imageContext.serverId || imageContext.serverId === environment.serverId;
|
||||
const client =
|
||||
imageContext.client ??
|
||||
(environment.client?.readFile
|
||||
(environmentMatchesHost && environment.client?.readFile
|
||||
? { readFile: environment.client.readFile.bind(environment.client) }
|
||||
: undefined);
|
||||
const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(
|
||||
text,
|
||||
{
|
||||
workspaceRoot: environment.workspaceRoot,
|
||||
workspaceRoot: environmentMatchesHost ? environment.workspaceRoot : undefined,
|
||||
serverId: environment.serverId,
|
||||
...imageContext,
|
||||
client,
|
||||
@@ -123,26 +140,43 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
},
|
||||
);
|
||||
const [image, setImage] = useState<ImageLightboxSource | null>(null);
|
||||
const pressLink = useStableEvent(({ url, sourceType }: LinkPressEvent) => {
|
||||
// What a link is, for pressing it and for its menu alike.
|
||||
const readLink = useStableEvent(({ url, sourceType }: LinkPressEvent): ReadMarkdownLink => {
|
||||
if (external) {
|
||||
// The parser still autolinks bare http, www and email text; only https links open.
|
||||
const safe = pluginOverviewUrl(url);
|
||||
if (safe) void openExternalUrl(safe);
|
||||
return;
|
||||
return safe ? { kind: "web", url: safe } : { kind: "inert" };
|
||||
}
|
||||
const command = commandHints && matchCommandLink(url, sourceType, commandHints.names);
|
||||
if (command) {
|
||||
commandHints.insert(command);
|
||||
return;
|
||||
}
|
||||
if (command) return { kind: "command", command };
|
||||
const forgeUrl = sourceType === "text" ? forgeShorthand?.resolve(url) : null;
|
||||
if (forgeUrl) {
|
||||
void openExternalUrl(forgeUrl);
|
||||
return;
|
||||
if (forgeUrl) return { kind: "web", url: forgeUrl };
|
||||
return { kind: "source", source: linkSource(url, sourceType) };
|
||||
});
|
||||
const pressLink = useStableEvent((event: LinkPressEvent) => {
|
||||
const link = readLink(event);
|
||||
if (link.kind === "web") {
|
||||
void openExternalUrl(link.url);
|
||||
} else if (link.kind === "command") {
|
||||
commandHints?.insert(link.command);
|
||||
} else if (link.kind === "source") {
|
||||
if (onLinkPress && !actions.canResolveFile(link.source)) onLinkPress(event.url);
|
||||
else actions.open(link.source, "preferred");
|
||||
}
|
||||
const source = linkSource(url, sourceType);
|
||||
if (onLinkPress && !actions.canResolveFile(source)) onLinkPress(url);
|
||||
else actions.open(source, "preferred");
|
||||
});
|
||||
const describeLink = useStableEvent((pressed: LinkPressEvent): LinkMenuSubject | null => {
|
||||
const link = readLink(pressed);
|
||||
const { serverId, workspaceId, workspaceRoot } = environment;
|
||||
const workspace =
|
||||
!external && serverId && workspaceRoot ? { serverId, workspaceId, workspaceRoot } : null;
|
||||
const web = (url: string) =>
|
||||
isHttpUrl(url) ? ({ kind: "web", url, workspace } as const) : null;
|
||||
if (link.kind === "web") return web(link.url);
|
||||
if (link.kind !== "source") return null;
|
||||
const inspection = actions.inspect(link.source);
|
||||
if (inspection?.kind === "url") return web(inspection.url);
|
||||
if (!inspection || !workspace) return null;
|
||||
return { kind: "path", source: link.source, inspection, workspace };
|
||||
});
|
||||
const pressImage = useStableEvent(({ url }: { url: string }) => {
|
||||
if (url !== PENDING_MARKDOWN_IMAGE) setImage({ type: "uri", uri: url });
|
||||
@@ -155,31 +189,33 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
);
|
||||
return (
|
||||
<MermaidStreamingContext.Provider value={streaming}>
|
||||
<MarkdownBlockStack imageSources={imageSources}>
|
||||
{segments.map((segment) =>
|
||||
segment.kind === "mermaid" ? (
|
||||
<MermaidFence key={`${segment.kind}:${segment.id}`} code={segment.source} />
|
||||
) : (
|
||||
<ThemedMarkdown
|
||||
key={`${segment.kind}:${segment.id}`}
|
||||
markdown={segment.source}
|
||||
uniProps={pickMarkdownStyle(compact, muted)}
|
||||
flavor="github"
|
||||
selectable={selectable}
|
||||
md4cFlags={external ? EXTERNAL_MD4C_FLAGS : MD4C_FLAGS}
|
||||
linkRecognition={linkRecognition}
|
||||
enableTaskListItemToggle={false}
|
||||
enableLinkPreview={false}
|
||||
enableBlockContextMenu={false}
|
||||
// JS reveal owns pacing; native fade animation is a separate experiment.
|
||||
streamingAnimation={false}
|
||||
onLinkPress={pressLink}
|
||||
onImagePress={pressImage}
|
||||
renderers={isWeb ? WEB_RENDERERS : undefined}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</MarkdownBlockStack>
|
||||
<LinkMenu describeLink={describeLink}>
|
||||
<MarkdownBlockStack imageSources={imageSources}>
|
||||
{segments.map((segment) =>
|
||||
segment.kind === "mermaid" ? (
|
||||
<MermaidFence key={`${segment.kind}:${segment.id}`} code={segment.source} />
|
||||
) : (
|
||||
<MarkdownText
|
||||
key={`${segment.kind}:${segment.id}`}
|
||||
markdown={segment.source}
|
||||
uniProps={pickMarkdownStyle(compact, muted)}
|
||||
flavor="github"
|
||||
selectable={selectable}
|
||||
md4cFlags={external ? EXTERNAL_MD4C_FLAGS : MD4C_FLAGS}
|
||||
linkRecognition={linkRecognition}
|
||||
enableTaskListItemToggle={false}
|
||||
enableLinkPreview={false}
|
||||
enableBlockContextMenu={false}
|
||||
// JS reveal owns pacing; native fade animation is a separate experiment.
|
||||
streamingAnimation={false}
|
||||
onLinkPress={pressLink}
|
||||
onImagePress={pressImage}
|
||||
renderers={isWeb ? WEB_RENDERERS : undefined}
|
||||
/>
|
||||
),
|
||||
)}
|
||||
</MarkdownBlockStack>
|
||||
</LinkMenu>
|
||||
{image ? <AttachmentLightbox source={image} onClose={closeImage} /> : null}
|
||||
</MermaidStreamingContext.Provider>
|
||||
);
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
import { Text } from "react-native";
|
||||
import { forwardRef, useCallback, useMemo, useState, type ComponentProps } from "react";
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useMemo,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import type {
|
||||
CodeBlockRendererProps,
|
||||
LinkRendererProps,
|
||||
@@ -12,6 +19,8 @@ import { useForgeShorthand } from "@/git/forge-shorthand";
|
||||
import { Tooltip, TooltipTrigger, TooltipContent } from "@/components/ui/tooltip";
|
||||
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useOpenLinkMenu } from "./link-menu";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { WebBlockquote } from "./quote-block.web";
|
||||
@@ -61,6 +70,13 @@ function WebLink({ link, anchorProps, children }: LinkRendererProps) {
|
||||
: anchorProps,
|
||||
[anchorProps, recognized],
|
||||
);
|
||||
const openLinkMenu = useOpenLinkMenu();
|
||||
const handleContextMenu = useStableEvent((event: MouseEvent) => {
|
||||
const point = { x: event.pageX, y: event.pageY };
|
||||
if (!openLinkMenu?.({ url: link.url, sourceType: link.sourceType }, point)) return;
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
});
|
||||
const anchor = (
|
||||
<a
|
||||
{...copyAnchorProps}
|
||||
@@ -68,6 +84,7 @@ function WebLink({ link, anchorProps, children }: LinkRendererProps) {
|
||||
style={anchorStyle}
|
||||
onMouseEnter={handleMouseEnter}
|
||||
onMouseLeave={handleMouseLeave}
|
||||
onContextMenu={handleContextMenu}
|
||||
>
|
||||
{children}
|
||||
</a>
|
||||
|
||||
@@ -2,6 +2,8 @@ import { useDisclosureHold } from "@/agent-stream/disclosure";
|
||||
import { MessagePreview, MessageSender } from "@/components/user-message";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { getAgentAttachmentPillContent } from "@/attachments/attachment-pill-content";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import { useDaemonUploadedImage } from "@/attachments/use-daemon-uploaded-image";
|
||||
import { AssistantForkMenu, type AssistantForkTarget } from "@/components/assistant-fork-menu";
|
||||
import { TurnMetricsButton } from "@/components/turn-metrics";
|
||||
import { AttachmentLightbox, type ImageLightboxSource } from "@/components/attachment-lightbox";
|
||||
@@ -26,7 +28,12 @@ import { useRevealedText, type MarkdownPhase } from "@/hooks/use-revealed-text";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
import { buildToolCallPresentation } from "@/tool-calls/presentation";
|
||||
import type { TaskActivity, TodoEntry, UserMessageImageAttachment } from "@/types/stream";
|
||||
import type {
|
||||
DaemonUploadedImageAttachment,
|
||||
TaskActivity,
|
||||
TodoEntry,
|
||||
UserMessageImageAttachment,
|
||||
} from "@/types/stream";
|
||||
import { setAssistantMessageHeight } from "@/utils/assistant-message-height-estimate";
|
||||
import { isRenderProfileEnabled } from "@/utils/render-profiler";
|
||||
import { writeMarkdownToRichClipboard } from "@/utils/rich-clipboard";
|
||||
@@ -355,6 +362,11 @@ const userMessageStylesheet = StyleSheet.create((theme) => ({
|
||||
imagePreviewSpacing: {
|
||||
marginBottom: theme.spacing[2],
|
||||
},
|
||||
daemonImagePlaceholder: {
|
||||
width: 48,
|
||||
height: 48,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
},
|
||||
copyButton: {
|
||||
alignSelf: "center",
|
||||
padding: theme.spacing[1],
|
||||
@@ -382,13 +394,17 @@ const userMessageStylesheet = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
interface UserMessageImagePillProps {
|
||||
image: UserMessageImageAttachment;
|
||||
onOpen: (image: UserMessageImageAttachment) => void;
|
||||
interface LocalUserMessageImagePillProps {
|
||||
image: AttachmentMetadata;
|
||||
onOpen: (image: AttachmentMetadata) => void;
|
||||
accessibilityLabel: string;
|
||||
}
|
||||
|
||||
function UserMessageImagePill({ image, onOpen, accessibilityLabel }: UserMessageImagePillProps) {
|
||||
function LocalUserMessageImagePill({
|
||||
image,
|
||||
onOpen,
|
||||
accessibilityLabel,
|
||||
}: LocalUserMessageImagePillProps) {
|
||||
const handlePress = useCallback(() => {
|
||||
onOpen(image);
|
||||
}, [onOpen, image]);
|
||||
@@ -399,6 +415,76 @@ function UserMessageImagePill({ image, onOpen, accessibilityLabel }: UserMessage
|
||||
);
|
||||
}
|
||||
|
||||
interface DaemonUserMessageImagePillProps {
|
||||
image: DaemonUploadedImageAttachment;
|
||||
client?: DaemonClient | null;
|
||||
serverId?: string;
|
||||
onOpen: (image: AttachmentMetadata) => void;
|
||||
accessibilityLabel: string;
|
||||
}
|
||||
|
||||
function DaemonUserMessageImagePill({
|
||||
image,
|
||||
client,
|
||||
serverId,
|
||||
onOpen,
|
||||
accessibilityLabel,
|
||||
}: DaemonUserMessageImagePillProps) {
|
||||
const resolved = useDaemonUploadedImage({ image, client, serverId });
|
||||
const handlePress = useCallback(() => {
|
||||
if (resolved) {
|
||||
onOpen(resolved);
|
||||
}
|
||||
}, [onOpen, resolved]);
|
||||
if (!resolved) {
|
||||
return (
|
||||
<AttachmentFrame accessibilityLabel={accessibilityLabel}>
|
||||
<View style={userMessageStylesheet.daemonImagePlaceholder} />
|
||||
</AttachmentFrame>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<AttachmentFrame onPress={handlePress} accessibilityLabel={accessibilityLabel}>
|
||||
<AttachmentThumbnail metadata={resolved} />
|
||||
</AttachmentFrame>
|
||||
);
|
||||
}
|
||||
|
||||
interface UserMessageImagePillProps {
|
||||
image: UserMessageImageAttachment;
|
||||
client?: DaemonClient | null;
|
||||
serverId?: string;
|
||||
onOpen: (image: AttachmentMetadata) => void;
|
||||
accessibilityLabel: string;
|
||||
}
|
||||
|
||||
function UserMessageImagePill({
|
||||
image,
|
||||
client,
|
||||
serverId,
|
||||
onOpen,
|
||||
accessibilityLabel,
|
||||
}: UserMessageImagePillProps) {
|
||||
if (image.storageType === "daemon-upload") {
|
||||
return (
|
||||
<DaemonUserMessageImagePill
|
||||
image={image}
|
||||
client={client}
|
||||
serverId={serverId}
|
||||
onOpen={onOpen}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<LocalUserMessageImagePill
|
||||
image={image}
|
||||
onOpen={onOpen}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const MESSAGE_TEXT_DATASET = { messageText: "true" };
|
||||
|
||||
export const UserMessage = memo(function UserMessage({
|
||||
@@ -421,7 +507,7 @@ export const UserMessage = memo(function UserMessage({
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const { t } = useTranslation();
|
||||
const [isHovered, setIsHovered] = useState(false);
|
||||
const [lightboxMetadata, setLightboxMetadata] = useState<UserMessageImageAttachment | null>(null);
|
||||
const [lightboxMetadata, setLightboxMetadata] = useState<AttachmentMetadata | null>(null);
|
||||
const handleLightboxClose = useCallback(() => setLightboxMetadata(null), []);
|
||||
const lightboxSource = useMemo<ImageLightboxSource | null>(
|
||||
() => (lightboxMetadata ? { type: "attachment", metadata: lightboxMetadata } : null),
|
||||
@@ -499,6 +585,8 @@ export const UserMessage = memo(function UserMessage({
|
||||
<UserMessageImagePill
|
||||
key={image.id}
|
||||
image={image}
|
||||
client={client}
|
||||
serverId={serverId}
|
||||
onOpen={setLightboxMetadata}
|
||||
accessibilityLabel={t("composer.attachments.openImage")}
|
||||
/>
|
||||
|
||||
@@ -86,7 +86,6 @@ interface SplitContainerProps {
|
||||
onCopyResumeCommand: (agentId: string) => Promise<void> | void;
|
||||
onCopyAgentId: (agentId: string) => Promise<void> | void;
|
||||
onCopyTerminalId: (terminalId: string) => Promise<void> | void;
|
||||
onCopyFilePath: (path: string) => Promise<void> | void;
|
||||
onReloadAgent: (agentId: string) => Promise<void> | void;
|
||||
onRenameTab: (tab: WorkspaceTabDescriptor) => void;
|
||||
onCloseTabsToLeft: (tabId: string, paneTabs: WorkspaceTabDescriptor[]) => Promise<void> | void;
|
||||
@@ -175,7 +174,6 @@ export function SplitContainer({
|
||||
onCopyResumeCommand,
|
||||
onCopyAgentId,
|
||||
onCopyTerminalId,
|
||||
onCopyFilePath,
|
||||
onReloadAgent,
|
||||
onRenameTab,
|
||||
onCloseTabsToLeft,
|
||||
@@ -289,7 +287,6 @@ export function SplitContainer({
|
||||
onCopyResumeCommand={onCopyResumeCommand}
|
||||
onCopyAgentId={onCopyAgentId}
|
||||
onCopyTerminalId={onCopyTerminalId}
|
||||
onCopyFilePath={onCopyFilePath}
|
||||
onReloadAgent={onReloadAgent}
|
||||
onRenameTab={onRenameTab}
|
||||
onCloseTabsToLeft={onCloseTabsToLeft}
|
||||
@@ -427,7 +424,6 @@ function SplitNodeView({
|
||||
onCopyResumeCommand,
|
||||
onCopyAgentId,
|
||||
onCopyTerminalId,
|
||||
onCopyFilePath,
|
||||
onReloadAgent,
|
||||
onRenameTab,
|
||||
onCloseTabsToLeft,
|
||||
@@ -522,7 +518,6 @@ function SplitNodeView({
|
||||
onCopyResumeCommand={onCopyResumeCommand}
|
||||
onCopyAgentId={onCopyAgentId}
|
||||
onCopyTerminalId={onCopyTerminalId}
|
||||
onCopyFilePath={onCopyFilePath}
|
||||
onReloadAgent={onReloadAgent}
|
||||
onRenameTab={onRenameTab}
|
||||
onCloseTabsToLeft={onCloseTabsToLeft}
|
||||
@@ -577,7 +572,6 @@ function SplitNodeView({
|
||||
onCopyResumeCommand={onCopyResumeCommand}
|
||||
onCopyAgentId={onCopyAgentId}
|
||||
onCopyTerminalId={onCopyTerminalId}
|
||||
onCopyFilePath={onCopyFilePath}
|
||||
onReloadAgent={onReloadAgent}
|
||||
onRenameTab={onRenameTab}
|
||||
onCloseTabsToLeft={onCloseTabsToLeft}
|
||||
@@ -651,7 +645,6 @@ const SplitPaneView = memo(function SplitPaneView({
|
||||
onCopyResumeCommand,
|
||||
onCopyAgentId,
|
||||
onCopyTerminalId,
|
||||
onCopyFilePath,
|
||||
onReloadAgent,
|
||||
onRenameTab,
|
||||
onCloseTabsToLeft,
|
||||
@@ -849,7 +842,6 @@ const SplitPaneView = memo(function SplitPaneView({
|
||||
onCopyResumeCommand={onCopyResumeCommand}
|
||||
onCopyAgentId={onCopyAgentId}
|
||||
onCopyTerminalId={onCopyTerminalId}
|
||||
onCopyFilePath={onCopyFilePath}
|
||||
onReloadAgent={onReloadAgent}
|
||||
onRenameTab={onRenameTab}
|
||||
onCloseTabsToLeft={handleCloseTabsToLeft}
|
||||
|
||||
@@ -55,7 +55,7 @@ import { type NativeTerminalKeyEvent } from "../terminal/native-renderer/termina
|
||||
import {
|
||||
TerminalInput,
|
||||
type TerminalInputHandle,
|
||||
} from "../terminal/native-renderer/terminal-input.native";
|
||||
} from "../terminal/native-renderer/terminal-input";
|
||||
import {
|
||||
shouldClaimNativeTerminalSize,
|
||||
type NativeTerminalSizeClaimAction,
|
||||
|
||||
@@ -631,6 +631,7 @@ export default function TerminalEmulator({
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
data-pmono=""
|
||||
data-testid={testId}
|
||||
data-terminal-scrollbar-root="true"
|
||||
style={rootDivStyle}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
EMPTY_FOCUS_CLAIM_STATE,
|
||||
EMPTY_PALETTE_SYNC_STATE,
|
||||
canRequestFocusClaim,
|
||||
reconcileFocusClaim,
|
||||
resolveTerminalPaletteSync,
|
||||
resolveTerminalResizeClaim,
|
||||
settleFocusClaim,
|
||||
type FocusClaimState,
|
||||
@@ -250,3 +252,120 @@ describe("terminal pane focus claim", () => {
|
||||
expect(changed.shouldRequest).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("terminal pane palette sync", () => {
|
||||
const readyFocused = {
|
||||
isWorkspaceFocused: true,
|
||||
isPaneFocused: true,
|
||||
isAppActivelyVisible: true,
|
||||
isClientReady: true,
|
||||
isConnected: true,
|
||||
};
|
||||
|
||||
it("claims on focus, skips duplicate sends, and re-claims on theme change or explicit focus", () => {
|
||||
const first = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
expect(first).toMatchObject({ shouldSend: true, intent: "claim" });
|
||||
|
||||
const duplicate = resolveTerminalPaletteSync(first.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
expect(duplicate.shouldSend).toBe(false);
|
||||
|
||||
const themeFlipped = resolveTerminalPaletteSync(duplicate.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "dark",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
expect(themeFlipped).toMatchObject({ shouldSend: true, intent: "claim" });
|
||||
|
||||
const explicitReclaim = resolveTerminalPaletteSync(themeFlipped.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "dark",
|
||||
forceClaim: true,
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
expect(explicitReclaim).toMatchObject({ shouldSend: true, intent: "claim" });
|
||||
});
|
||||
|
||||
it("sends owner-only updates when theme changes while away and re-claims on return", () => {
|
||||
const claimed = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
const inSettings = resolveTerminalPaletteSync(claimed.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: { ...readyFocused, isWorkspaceFocused: false },
|
||||
});
|
||||
expect(inSettings.shouldSend).toBe(false);
|
||||
|
||||
const toggledInSettings = resolveTerminalPaletteSync(inSettings.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "dark",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: { ...readyFocused, isWorkspaceFocused: false },
|
||||
});
|
||||
expect(toggledInSettings).toMatchObject({ shouldSend: true, intent: "update" });
|
||||
|
||||
const returned = resolveTerminalPaletteSync(toggledInSettings.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "dark",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
expect(returned).toMatchObject({ shouldSend: true, intent: "claim" });
|
||||
});
|
||||
|
||||
it("never sends updates from an unfocused pane that has not claimed or against unsupported daemons", () => {
|
||||
const neverFocused = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "dark",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: { ...readyFocused, isPaneFocused: false },
|
||||
});
|
||||
expect(neverFocused.shouldSend).toBe(false);
|
||||
|
||||
const unsupported = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: false,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
expect(unsupported.shouldSend).toBe(false);
|
||||
});
|
||||
|
||||
it("resets on disconnect so reconnect re-claims ownership on the fresh connection", () => {
|
||||
const claimed = resolveTerminalPaletteSync(EMPTY_PALETTE_SYNC_STATE, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
const disconnected = resolveTerminalPaletteSync(claimed.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: { ...readyFocused, isConnected: false },
|
||||
});
|
||||
const reconnected = resolveTerminalPaletteSync(disconnected.state, {
|
||||
terminalKey: "ws:term-1",
|
||||
paletteKey: "light",
|
||||
supportsTerminalPaletteOwnership: true,
|
||||
readiness: readyFocused,
|
||||
});
|
||||
expect(reconnected).toMatchObject({ shouldSend: true, intent: "claim" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -127,3 +127,102 @@ export function settleFocusClaim(
|
||||
requestedKey: null,
|
||||
};
|
||||
}
|
||||
|
||||
export interface TerminalPaletteSyncState {
|
||||
terminalKey: string | null;
|
||||
claimed: boolean;
|
||||
sentPaletteKey: string | null;
|
||||
}
|
||||
|
||||
export const EMPTY_PALETTE_SYNC_STATE: TerminalPaletteSyncState = {
|
||||
terminalKey: null,
|
||||
claimed: false,
|
||||
sentPaletteKey: null,
|
||||
};
|
||||
|
||||
export interface TerminalPaletteSyncReadiness {
|
||||
isWorkspaceFocused: boolean;
|
||||
isPaneFocused: boolean;
|
||||
isAppActivelyVisible: boolean;
|
||||
isClientReady: boolean;
|
||||
isConnected: boolean;
|
||||
}
|
||||
|
||||
export function resolveTerminalPaletteSync(
|
||||
state: TerminalPaletteSyncState,
|
||||
input: {
|
||||
terminalKey: string | null;
|
||||
paletteKey: string;
|
||||
forceClaim?: boolean;
|
||||
supportsTerminalPaletteOwnership: boolean;
|
||||
readiness: TerminalPaletteSyncReadiness;
|
||||
},
|
||||
): {
|
||||
state: TerminalPaletteSyncState;
|
||||
shouldSend: boolean;
|
||||
intent: "claim" | "update";
|
||||
} {
|
||||
if (
|
||||
!input.supportsTerminalPaletteOwnership ||
|
||||
!input.terminalKey ||
|
||||
!input.readiness.isClientReady ||
|
||||
!input.readiness.isConnected
|
||||
) {
|
||||
return {
|
||||
state: EMPTY_PALETTE_SYNC_STATE,
|
||||
shouldSend: false,
|
||||
intent: "update",
|
||||
};
|
||||
}
|
||||
|
||||
const base = state.terminalKey === input.terminalKey ? state : EMPTY_PALETTE_SYNC_STATE;
|
||||
const canClaim =
|
||||
input.readiness.isWorkspaceFocused &&
|
||||
input.readiness.isPaneFocused &&
|
||||
input.readiness.isAppActivelyVisible;
|
||||
|
||||
if (canClaim) {
|
||||
if (input.forceClaim || !base.claimed || base.sentPaletteKey !== input.paletteKey) {
|
||||
return {
|
||||
state: {
|
||||
terminalKey: input.terminalKey,
|
||||
claimed: true,
|
||||
sentPaletteKey: input.paletteKey,
|
||||
},
|
||||
shouldSend: true,
|
||||
intent: "claim",
|
||||
};
|
||||
}
|
||||
return {
|
||||
state: base,
|
||||
shouldSend: false,
|
||||
intent: "claim",
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
input.readiness.isAppActivelyVisible &&
|
||||
base.sentPaletteKey !== null &&
|
||||
base.sentPaletteKey !== input.paletteKey
|
||||
) {
|
||||
return {
|
||||
state: {
|
||||
terminalKey: input.terminalKey,
|
||||
claimed: false,
|
||||
sentPaletteKey: input.paletteKey,
|
||||
},
|
||||
shouldSend: true,
|
||||
intent: "update",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
state: {
|
||||
terminalKey: input.terminalKey,
|
||||
claimed: false,
|
||||
sentPaletteKey: base.sentPaletteKey,
|
||||
},
|
||||
shouldSend: false,
|
||||
intent: "update",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -62,11 +62,17 @@ import { prepareDroppedPathsForTerminal } from "@/terminal/drop/terminal-path";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import {
|
||||
EMPTY_FOCUS_CLAIM_STATE,
|
||||
EMPTY_PALETTE_SYNC_STATE,
|
||||
canRequestFocusClaim,
|
||||
reconcileFocusClaim,
|
||||
resolveTerminalPaletteSync,
|
||||
resolveTerminalResizeClaim,
|
||||
settleFocusClaim,
|
||||
} from "./terminal-pane-focus-claim";
|
||||
import {
|
||||
terminalDefaultColorsFromTheme,
|
||||
terminalDefaultColorsKey,
|
||||
} from "@/utils/terminal-default-colors";
|
||||
import {
|
||||
TerminalStreamController,
|
||||
type TerminalStreamControllerStatus,
|
||||
@@ -276,6 +282,24 @@ export function TerminalPane({
|
||||
const { theme } = useUnistyles();
|
||||
const { settings } = useAppSettings();
|
||||
const xtermTheme = useMemo(() => toXtermTheme(theme.colors.terminal), [theme]);
|
||||
const {
|
||||
foreground: terminalForeground,
|
||||
background: terminalBackground,
|
||||
cursor: terminalCursor,
|
||||
} = theme.colors.terminal;
|
||||
const terminalDefaultColors = useMemo(
|
||||
() =>
|
||||
terminalDefaultColorsFromTheme({
|
||||
foreground: terminalForeground,
|
||||
background: terminalBackground,
|
||||
cursor: terminalCursor,
|
||||
}),
|
||||
[terminalBackground, terminalCursor, terminalForeground],
|
||||
);
|
||||
const terminalPaletteKey = useMemo(
|
||||
() => terminalDefaultColorsKey(terminalDefaultColors),
|
||||
[terminalDefaultColors],
|
||||
);
|
||||
const terminalFontFamily = useMemo(() => {
|
||||
const trimmed = settings.monoFontFamily.trim();
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
@@ -310,6 +334,10 @@ export function TerminalPane({
|
||||
const supportsTerminalSizeOwnership = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.features?.["terminal-size-ownership"] === true,
|
||||
);
|
||||
const supportsTerminalPaletteOwnership = useSessionStore(
|
||||
(state) =>
|
||||
state.sessions[serverId]?.serverInfo?.features?.["terminal-palette-ownership"] === true,
|
||||
);
|
||||
const characterWidths: TerminalCharacterWidths = useSessionStore((state) =>
|
||||
state.sessions[serverId]?.serverInfo?.features?.["terminal-grapheme-widths"] === true
|
||||
? "graphemes"
|
||||
@@ -387,6 +415,7 @@ export function TerminalPane({
|
||||
const keyboardRefitTimeoutsRef = useRef<Array<ReturnType<typeof setTimeout>>>([]);
|
||||
const lastAutoFocusKeyRef = useRef<string | null>(null);
|
||||
const paneFocusResizeClaimRef = useRef(EMPTY_FOCUS_CLAIM_STATE);
|
||||
const panePaletteSyncRef = useRef(EMPTY_PALETTE_SYNC_STATE);
|
||||
|
||||
useEffect(() => {
|
||||
terminalIdRef.current = terminalId;
|
||||
@@ -497,11 +526,51 @@ export function TerminalPane({
|
||||
terminalStreamKey,
|
||||
]);
|
||||
|
||||
const syncTerminalPalette = useStableEvent((options?: { forceClaim?: boolean }) => {
|
||||
const step = resolveTerminalPaletteSync(panePaletteSyncRef.current, {
|
||||
terminalKey: terminalId ? `${scopeKey}:${terminalId}` : null,
|
||||
paletteKey: terminalPaletteKey,
|
||||
forceClaim: options?.forceClaim,
|
||||
supportsTerminalPaletteOwnership,
|
||||
readiness: {
|
||||
isWorkspaceFocused: isTerminalPresented,
|
||||
isPaneFocused,
|
||||
isAppActivelyVisible,
|
||||
isClientReady: client !== null,
|
||||
isConnected,
|
||||
},
|
||||
});
|
||||
panePaletteSyncRef.current = step.state;
|
||||
if (step.shouldSend && client && terminalId) {
|
||||
client.sendTerminalInput(terminalId, {
|
||||
type: "palette",
|
||||
defaultColors: terminalDefaultColors,
|
||||
intent: step.intent,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
syncTerminalPalette();
|
||||
}, [
|
||||
client,
|
||||
isAppActivelyVisible,
|
||||
isConnected,
|
||||
isPaneFocused,
|
||||
isTerminalPresented,
|
||||
scopeKey,
|
||||
supportsTerminalPaletteOwnership,
|
||||
syncTerminalPalette,
|
||||
terminalId,
|
||||
terminalPaletteKey,
|
||||
]);
|
||||
|
||||
const handleTerminalFocus = useCallback(() => {
|
||||
if (isWorkspaceFocused && isPaneFocused) {
|
||||
setFocusedTerminalId(serverId, terminalId);
|
||||
}
|
||||
lastSentTerminalSizeRef.current = null;
|
||||
syncTerminalPalette({ forceClaim: true });
|
||||
requestTerminalReflow();
|
||||
emulatorRef.current?.claimSize();
|
||||
}, [
|
||||
@@ -510,6 +579,7 @@ export function TerminalPane({
|
||||
requestTerminalReflow,
|
||||
serverId,
|
||||
setFocusedTerminalId,
|
||||
syncTerminalPalette,
|
||||
terminalId,
|
||||
]);
|
||||
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
treeIndentGuideOffsets,
|
||||
treeRowPaddingLeft,
|
||||
TREE_INDENT_PER_LEVEL,
|
||||
WORKSPACE_TREE_ICON_SIZE,
|
||||
} from "@/components/tree-primitives";
|
||||
|
||||
describe("treeIndentGuideOffsets", () => {
|
||||
it("indents each level by 16px", () => {
|
||||
expect(TREE_INDENT_PER_LEVEL).toBe(16);
|
||||
expect(treeRowPaddingLeft(2) - treeRowPaddingLeft(1)).toBe(16);
|
||||
});
|
||||
|
||||
it("draws no guide for a root row", () => {
|
||||
expect(treeIndentGuideOffsets(0)).toEqual([]);
|
||||
});
|
||||
|
||||
it("centres one 1px guide under each ancestor's chevron", () => {
|
||||
const chevronCenter = (level: number) =>
|
||||
treeRowPaddingLeft(level) + WORKSPACE_TREE_ICON_SIZE / 2;
|
||||
|
||||
expect(treeIndentGuideOffsets(3).map((left) => left + 0.5)).toEqual([
|
||||
chevronCenter(0),
|
||||
chevronCenter(1),
|
||||
chevronCenter(2),
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -2,13 +2,14 @@ import { View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { ChevronRight } from "lucide-react-native";
|
||||
import { SPACING, type Theme } from "@/styles/theme";
|
||||
import { inlineUnistylesStyle } from "@/styles/unistyles-inline-style";
|
||||
|
||||
// Shared presentation primitives for the app's directory trees. Both the Files
|
||||
// explorer (server-loaded listings) and the Changes view (client-built from diff
|
||||
// paths) render different data, but their ROWS should look identical — same
|
||||
// indentation, density, name emphasis, and chevron. Keep those here so the two trees can't
|
||||
// indentation, guides, density, name emphasis, and chevron. Keep those here so the two trees can't
|
||||
// drift apart.
|
||||
export const TREE_INDENT_PER_LEVEL = 12;
|
||||
export const TREE_INDENT_PER_LEVEL = 16;
|
||||
export const WORKSPACE_FILE_ROW_VERTICAL_PADDING = SPACING[1.5];
|
||||
export const WORKSPACE_TREE_ICON_SIZE = 16;
|
||||
export const WORKSPACE_TREE_LOADING_ICON_SIZE = 14;
|
||||
@@ -26,6 +27,29 @@ export function treeRowPaddingLeft(depth: number): number {
|
||||
return SPACING[3] + depth * TREE_INDENT_PER_LEVEL;
|
||||
}
|
||||
|
||||
const INDENT_GUIDE_WIDTH = 1;
|
||||
|
||||
/** Left edge of each guide on a row at `depth`: one per ancestor, centred under its chevron. */
|
||||
export function treeIndentGuideOffsets(depth: number): number[] {
|
||||
const chevronCenter = (WORKSPACE_TREE_ICON_SIZE - INDENT_GUIDE_WIDTH) / 2;
|
||||
return Array.from({ length: depth }, (_, level) => treeRowPaddingLeft(level) + chevronCenter);
|
||||
}
|
||||
|
||||
/**
|
||||
* The ancestor lines of a tree row. Render it first inside the element that paints the row's
|
||||
* hover and selection fill, so the lines span the row and stay above the fill.
|
||||
*/
|
||||
export function TreeIndentGuides({ depth }: { depth: number }) {
|
||||
return treeIndentGuideOffsets(depth).map((left) => (
|
||||
<View
|
||||
key={left}
|
||||
pointerEvents="none"
|
||||
style={[styles.indentGuide, inlineUnistylesStyle({ left })]}
|
||||
testID="tree-indent-guide"
|
||||
/>
|
||||
));
|
||||
}
|
||||
|
||||
const foregroundExtraMutedIconColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
});
|
||||
@@ -59,7 +83,16 @@ export const workspaceTreeRowStyles = StyleSheet.create((theme: Theme) => ({
|
||||
nameHovered: { opacity: 1 },
|
||||
}));
|
||||
|
||||
const styles = StyleSheet.create((_theme: Theme) => ({
|
||||
const styles = StyleSheet.create((theme: Theme) => ({
|
||||
indentGuide: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
bottom: 0,
|
||||
width: INDENT_GUIDE_WIDTH,
|
||||
// Translucent ink, not `border`: a solid line that colour disappears into a hovered row's fill.
|
||||
backgroundColor: theme.colors.foregroundExtraMuted,
|
||||
opacity: theme.opacity[50],
|
||||
},
|
||||
chevron: {
|
||||
width: WORKSPACE_TREE_ICON_SIZE,
|
||||
height: WORKSPACE_TREE_ICON_SIZE,
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { useCallback, useRef, useState, type ReactElement } from "react";
|
||||
import { Pressable, View } from "react-native";
|
||||
import { useCallback, useEffect, useRef, useState, type ReactElement } from "react";
|
||||
import {
|
||||
Pressable,
|
||||
View,
|
||||
type NativeSyntheticEvent,
|
||||
type TextInputKeyPressEventData,
|
||||
} from "react-native";
|
||||
import { Search, X } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -7,6 +12,7 @@ import {
|
||||
EditingTextInput as TextInput,
|
||||
type EditingTextInputHandle,
|
||||
} from "@/components/ui/text-input";
|
||||
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
|
||||
|
||||
const ThemedSearch = withUnistyles(Search);
|
||||
const ThemedX = withUnistyles(X);
|
||||
@@ -27,6 +33,10 @@ export interface SearchFieldProps {
|
||||
clearAccessibilityLabel: string;
|
||||
/** Fill the container, for a search that heads one list. Defaults to the filter rail's width. */
|
||||
fullWidth?: boolean;
|
||||
/** `sm` heads a list in tight chrome such as a sidebar pane. */
|
||||
size?: "sm" | "md";
|
||||
/** Escape empties the field. Off where Escape already closes the surface around it. */
|
||||
clearOnEscape?: boolean;
|
||||
testID?: string;
|
||||
clearTestID?: string;
|
||||
}
|
||||
@@ -45,6 +55,8 @@ export function SearchField({
|
||||
accessibilityLabel,
|
||||
clearAccessibilityLabel,
|
||||
fullWidth = false,
|
||||
size = "md",
|
||||
clearOnEscape = false,
|
||||
testID,
|
||||
clearTestID,
|
||||
}: SearchFieldProps): ReactElement {
|
||||
@@ -56,10 +68,26 @@ export function SearchField({
|
||||
inputRef.current?.replaceText("");
|
||||
onChangeText("");
|
||||
}, [onChangeText]);
|
||||
const handleKeyPress = useCallback(
|
||||
(event: NativeSyntheticEvent<TextInputKeyPressEventData>) => {
|
||||
if (event.nativeEvent.key === "Escape") handleClear();
|
||||
},
|
||||
[handleClear],
|
||||
);
|
||||
// The input owns its text, so an owner emptying `value` has to empty it too.
|
||||
useEffect(() => {
|
||||
if (value === "" && inputRef.current?.getText()) inputRef.current.replaceText("");
|
||||
}, [value]);
|
||||
const small = size === "sm";
|
||||
|
||||
return (
|
||||
<View
|
||||
style={[styles.field, fullWidth && styles.fieldFullWidth, isFocused && styles.fieldFocused]}
|
||||
style={[
|
||||
styles.field,
|
||||
small && styles.fieldSmall,
|
||||
fullWidth && styles.fieldFullWidth,
|
||||
isFocused && styles.fieldFocused,
|
||||
]}
|
||||
>
|
||||
<ThemedSearch size={14} uniProps={mutedColorMapping} />
|
||||
<ThemedTextInput
|
||||
@@ -74,7 +102,8 @@ export function SearchField({
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
returnKeyType="search"
|
||||
style={styles.input}
|
||||
onKeyPress={clearOnEscape ? handleKeyPress : undefined}
|
||||
style={[styles.input, small && styles.inputSmall]}
|
||||
/>
|
||||
{value.length > 0 ? (
|
||||
<Pressable
|
||||
@@ -108,6 +137,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
borderWidth: theme.borderWidth[1],
|
||||
borderColor: theme.colors.border,
|
||||
},
|
||||
fieldSmall: {
|
||||
height: CONTROL_HEIGHTS.sm,
|
||||
paddingVertical: 0,
|
||||
paddingHorizontal: theme.spacing[1.5],
|
||||
},
|
||||
fieldFullWidth: {
|
||||
maxWidth: "100%",
|
||||
},
|
||||
@@ -127,4 +161,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
inputSmall: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -13,6 +13,7 @@ import PasteInput, {
|
||||
type PasteTextInputInstance,
|
||||
} from "@mattermost/react-native-paste-input";
|
||||
import { useIsInsideBottomSheet } from "@/components/ui/bottom-sheet-scope";
|
||||
import { reportNativeUserActivity } from "@/hooks/native-user-activity";
|
||||
import type { EditingTextInputHandle, EditingTextInputProps } from "./types";
|
||||
|
||||
type NativeInput = (TextInput | PasteTextInputInstance) & {
|
||||
@@ -130,6 +131,8 @@ export const EditingTextInput = forwardRef<EditingTextInputHandle, EditingTextIn
|
||||
const handleChangeText = useCallback(
|
||||
(nextText: string) => {
|
||||
textRef.current = nextText;
|
||||
// Soft and hardware keyboards type without touching the app's root view.
|
||||
reportNativeUserActivity();
|
||||
onChangeText?.(nextText);
|
||||
bumpTextRevision();
|
||||
},
|
||||
|
||||
@@ -24,7 +24,7 @@ import {
|
||||
import { useWorkspaceSetupStore } from "@/stores/workspace-setup-store";
|
||||
import { normalizeAgentSnapshot } from "@/utils/agent-snapshots";
|
||||
import { applyLegacyDaemonWorkspaceOwnership } from "@/workspace/legacy-daemon-workspaces";
|
||||
import { encodeImages } from "@/utils/encode-images";
|
||||
import { uploadImageAttachments } from "@/attachments/service";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import {
|
||||
resolveComposerAttachmentSubmitFormat,
|
||||
@@ -123,7 +123,6 @@ function buildCreateAgentOptions({
|
||||
composerState,
|
||||
text,
|
||||
attachments,
|
||||
encodedImages,
|
||||
workspaceDirectory,
|
||||
workspaceId,
|
||||
provider,
|
||||
@@ -136,7 +135,6 @@ function buildCreateAgentOptions({
|
||||
};
|
||||
text: string;
|
||||
attachments: NonNullable<CreateAgentRequestOptions["attachments"]>;
|
||||
encodedImages: NonNullable<CreateAgentRequestOptions["images"]> | null;
|
||||
workspaceDirectory: string;
|
||||
workspaceId: string;
|
||||
provider: CreateAgentRequestOptions["provider"];
|
||||
@@ -154,7 +152,6 @@ function buildCreateAgentOptions({
|
||||
? { systemPrompt: composerState.selectedSystemPrompt }
|
||||
: {}),
|
||||
...(text.trim() ? { initialPrompt: text.trim() } : {}),
|
||||
...(encodedImages && encodedImages.length > 0 ? { images: encodedImages } : {}),
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
};
|
||||
}
|
||||
@@ -330,14 +327,19 @@ export function WorkspaceSetupDialog() {
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
});
|
||||
const encodedImages = await encodeImages(wirePayload.images);
|
||||
const uploadedImageAttachments =
|
||||
wirePayload.images.length > 0
|
||||
? await uploadImageAttachments({
|
||||
client: withConnectedClient(),
|
||||
images: wirePayload.images,
|
||||
})
|
||||
: undefined;
|
||||
if (!pendingWorkspaceSetup) throw new Error(t("workspaceSetup.errors.pendingRequired"));
|
||||
let createdAgent: AgentSnapshotPayload | undefined;
|
||||
const { workspaceId: _workspaceId, ...agentInput } = buildCreateAgentOptions({
|
||||
composerState,
|
||||
text,
|
||||
attachments: wirePayload.attachments,
|
||||
encodedImages: encodedImages ?? null,
|
||||
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
|
||||
workspaceDirectory: cwd,
|
||||
workspaceId: "",
|
||||
provider: composerState.selectedProvider,
|
||||
@@ -387,6 +389,7 @@ export function WorkspaceSetupDialog() {
|
||||
navigateAfterCreation,
|
||||
serverId,
|
||||
ensureWorkspace,
|
||||
withConnectedClient,
|
||||
t,
|
||||
toast,
|
||||
supportsForgeSearch,
|
||||
|
||||
@@ -1,5 +1,9 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import type { AgentAttachment, ForgeSearchItem } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AgentAttachment,
|
||||
ForgeSearchItem,
|
||||
UploadedFileAttachment,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AttachmentMetadata,
|
||||
ComposerAttachment,
|
||||
@@ -181,17 +185,22 @@ interface FakeSendCall {
|
||||
options: {
|
||||
messageId: string;
|
||||
activeTurnBehavior?: "interrupt" | "steer";
|
||||
images: Array<{ data: string; mimeType: string }>;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments: AgentAttachment[];
|
||||
};
|
||||
}
|
||||
|
||||
function createFakeSendClient(
|
||||
options: { rejection?: Error; beforeRejection?: (call: FakeSendCall) => void } = {},
|
||||
): ComposerSendClient & { calls: FakeSendCall[] } {
|
||||
): ComposerSendClient & {
|
||||
calls: FakeSendCall[];
|
||||
uploadCalls: Array<{ fileName: string; mimeType: string; bytes: Uint8Array }>;
|
||||
} {
|
||||
const calls: FakeSendCall[] = [];
|
||||
const uploadCalls: Array<{ fileName: string; mimeType: string; bytes: Uint8Array }> = [];
|
||||
return {
|
||||
calls,
|
||||
uploadCalls,
|
||||
sendAgentMessage: async (agentId, text, opts) => {
|
||||
const call = { agentId, text, options: opts };
|
||||
calls.push(call);
|
||||
@@ -200,7 +209,21 @@ function createFakeSendClient(
|
||||
throw options.rejection;
|
||||
}
|
||||
},
|
||||
uploadFile: async () => ({ requestId: "test", file: null, error: null }),
|
||||
uploadFile: async (input) => {
|
||||
uploadCalls.push(input);
|
||||
return {
|
||||
requestId: `req-${uploadCalls.length}`,
|
||||
file: {
|
||||
type: "uploaded_file",
|
||||
id: `upload_${uploadCalls.length}`,
|
||||
fileName: input.fileName,
|
||||
mimeType: input.mimeType,
|
||||
size: input.bytes.byteLength,
|
||||
path: `/home/user/.paseo/uploads/upload_${uploadCalls.length}/${input.fileName}`,
|
||||
},
|
||||
error: null,
|
||||
};
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -289,8 +312,18 @@ function createFakeQueue(
|
||||
return fake;
|
||||
}
|
||||
|
||||
const passthroughEncodeImages = async (images: AttachmentMetadata[]) =>
|
||||
images.map((image) => ({ data: image.id, mimeType: image.mimeType }));
|
||||
const passthroughUploadImages = async (
|
||||
images: AttachmentMetadata[],
|
||||
): Promise<UploadedFileAttachment[]> =>
|
||||
images.map((image) => ({
|
||||
type: "uploaded_file",
|
||||
id: `upload_${image.id}`,
|
||||
fileName: image.fileName ?? `${image.id}.png`,
|
||||
mimeType: image.mimeType,
|
||||
size: image.byteSize ?? 0,
|
||||
path: `/home/user/.paseo/uploads/upload_${image.id}/${image.fileName ?? `${image.id}.png`}`,
|
||||
role: "image",
|
||||
}));
|
||||
|
||||
describe("cancelComposerAgent", () => {
|
||||
function baseInput(): {
|
||||
@@ -428,7 +461,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "steer this turn",
|
||||
attachments: [],
|
||||
encodeImages: async () => [],
|
||||
uploadImages: async () => [],
|
||||
submission: stream,
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
@@ -444,7 +477,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
encodeImages: async () => [],
|
||||
uploadImages: async () => [],
|
||||
submission: stream,
|
||||
activeTurnBehavior: "steer",
|
||||
activeTurnId: "turn-1",
|
||||
@@ -456,7 +489,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "legacy",
|
||||
text: "hello",
|
||||
attachments: [],
|
||||
encodeImages: async () => [],
|
||||
uploadImages: async () => [],
|
||||
submission: legacy,
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
@@ -474,7 +507,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "rejected prompt",
|
||||
attachments: [],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
}),
|
||||
).rejects.toBe(rejection);
|
||||
@@ -494,7 +527,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "force send",
|
||||
attachments: [],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
}),
|
||||
).rejects.toBe(transportError);
|
||||
@@ -517,7 +550,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "unknown state",
|
||||
attachments: [],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission,
|
||||
}),
|
||||
).rejects.toBe(transportError);
|
||||
@@ -538,14 +571,14 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "ambiguous steer",
|
||||
attachments: [],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission,
|
||||
activeTurnBehavior: "steer",
|
||||
}),
|
||||
).rejects.toBe(transportError);
|
||||
});
|
||||
|
||||
it("sends text + image data + structured attachments and appends user_message to the tail when head is empty", async () => {
|
||||
it("sends text + uploaded images + structured attachments without inlining base64 and appends user_message to the tail when head is empty", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const stream = createFakeStream();
|
||||
const image = imageWithId("img-2");
|
||||
@@ -558,7 +591,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
{ kind: "image", metadata: image },
|
||||
{ kind: "github_pr", item: prItem },
|
||||
],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
@@ -566,18 +599,28 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
const [call] = client.calls;
|
||||
expect(call.agentId).toBe("agent");
|
||||
expect(call.text).toBe("send attachments");
|
||||
expect(call.options.images).toEqual([{ data: image.id, mimeType: image.mimeType }]);
|
||||
expect(call.options.images).toBeUndefined();
|
||||
const expectedPrAttachment = {
|
||||
type: "forge_change_request",
|
||||
mimeType: "application/paseo-forge-change-request",
|
||||
forge: "github",
|
||||
number: 202,
|
||||
title: "Refactor composer attachments",
|
||||
url: "https://github.com/acme/paseo/pull/202",
|
||||
body: "PR body",
|
||||
baseRefName: "main",
|
||||
headRefName: "composer-attachments",
|
||||
};
|
||||
expect(call.options.attachments).toEqual([
|
||||
expectedPrAttachment,
|
||||
{
|
||||
type: "forge_change_request",
|
||||
mimeType: "application/paseo-forge-change-request",
|
||||
forge: "github",
|
||||
number: 202,
|
||||
title: "Refactor composer attachments",
|
||||
url: "https://github.com/acme/paseo/pull/202",
|
||||
body: "PR body",
|
||||
baseRefName: "main",
|
||||
headRefName: "composer-attachments",
|
||||
type: "uploaded_file",
|
||||
id: "upload_img-2",
|
||||
fileName: "img-2.png",
|
||||
mimeType: "image/png",
|
||||
size: 42,
|
||||
path: "/home/user/.paseo/uploads/upload_img-2/img-2.png",
|
||||
role: "image",
|
||||
},
|
||||
]);
|
||||
|
||||
@@ -588,7 +631,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
expect(userMessage.kind).toBe("user_message");
|
||||
expect(userMessage.text).toBe("send attachments");
|
||||
expect(userMessage.images).toEqual([image]);
|
||||
expect(userMessage.attachments).toEqual(call.options.attachments);
|
||||
expect(userMessage.attachments).toEqual([expectedPrAttachment]);
|
||||
expect(userMessage.id).toBe(call.options.messageId);
|
||||
expect(userMessage.clientMessageId).toBe(call.options.messageId);
|
||||
expect(userMessage.messageId).toBeUndefined();
|
||||
@@ -604,7 +647,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
text: "send old attachment",
|
||||
attachments: [{ kind: "forge_change_request", item: prItem }],
|
||||
attachmentSubmitFormat: "legacy-github",
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
@@ -637,7 +680,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "next message",
|
||||
attachments: [],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
@@ -645,7 +688,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
expect(stream.tail.get("agent")).toEqual([]);
|
||||
});
|
||||
|
||||
it("submits empty wire arrays when no attachments are provided", async () => {
|
||||
it("submits empty attachments and omits inline images when no attachments are provided", async () => {
|
||||
const client = createFakeSendClient();
|
||||
const stream = createFakeStream();
|
||||
|
||||
@@ -654,14 +697,12 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "plain message",
|
||||
attachments: [],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
expect(client.calls[0]?.options).toMatchObject({
|
||||
images: [],
|
||||
attachments: [],
|
||||
});
|
||||
expect(client.calls[0]?.options.images).toBeUndefined();
|
||||
expect(client.calls[0]?.options.attachments).toEqual([]);
|
||||
});
|
||||
|
||||
it("serializes workspace review attachments through the structured attachment path", async () => {
|
||||
@@ -674,12 +715,12 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "review this",
|
||||
attachments: [review],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
expect(client.calls[0]?.options.attachments).toEqual([review.attachment]);
|
||||
expect(client.calls[0]?.options.images).toEqual([]);
|
||||
expect(client.calls[0]?.options.images).toBeUndefined();
|
||||
});
|
||||
|
||||
it("serializes browser_element workspace attachments as text attachments at the wire boundary", async () => {
|
||||
@@ -692,7 +733,7 @@ describe("dispatchComposerAgentMessage", () => {
|
||||
agentId: "agent",
|
||||
text: "inspect element",
|
||||
attachments: [browserElement],
|
||||
encodeImages: passthroughEncodeImages,
|
||||
uploadImages: passthroughUploadImages,
|
||||
submission: stream,
|
||||
});
|
||||
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { uploadImageAttachments } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { ForgeSearchItem } from "@getpaseo/protocol/messages";
|
||||
import type { ActiveTurnBehavior } from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
ForgeSearchItem,
|
||||
UploadedFileAttachment,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type {
|
||||
AttachmentMetadata,
|
||||
ComposerAttachment,
|
||||
@@ -52,20 +56,13 @@ export interface ComposerSendClient {
|
||||
options: {
|
||||
messageId: string;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
images: Array<{ data: string; mimeType: string }>;
|
||||
images?: Array<{ data: string; mimeType: string }>;
|
||||
attachments: ReturnType<typeof splitComposerAttachmentsForSubmit>["attachments"];
|
||||
},
|
||||
) => Promise<unknown>;
|
||||
uploadFile: (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => Promise<{
|
||||
requestId: string;
|
||||
file: {
|
||||
type: "uploaded_file";
|
||||
id: string;
|
||||
fileName: string;
|
||||
mimeType: string;
|
||||
size: number;
|
||||
path: string;
|
||||
} | null;
|
||||
file: UploadedFileAttachment | null;
|
||||
error: string | null;
|
||||
}>;
|
||||
}
|
||||
@@ -191,9 +188,7 @@ export interface DispatchComposerAgentMessageInput {
|
||||
text: string;
|
||||
attachments: ComposerAttachment[];
|
||||
attachmentSubmitFormat?: ComposerAttachmentSubmitFormat;
|
||||
encodeImages: (
|
||||
images: AttachmentMetadata[],
|
||||
) => Promise<Array<{ data: string; mimeType: string }> | undefined>;
|
||||
uploadImages?: (images: AttachmentMetadata[]) => Promise<UploadedFileAttachment[] | undefined>;
|
||||
submission: MessageSubmissionWriter;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
activeTurnId?: string;
|
||||
@@ -218,12 +213,13 @@ export async function dispatchComposerAgentMessage(
|
||||
});
|
||||
input.submission.begin(input.agentId, userMessage);
|
||||
try {
|
||||
const imagesData = await input.encodeImages(wirePayload.images);
|
||||
const uploadedImageAttachments = input.uploadImages
|
||||
? await input.uploadImages(wirePayload.images)
|
||||
: await uploadImageAttachments({ client: input.client, images: wirePayload.images });
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
images: imagesData ?? [],
|
||||
attachments: wirePayload.attachments,
|
||||
attachments: [...wirePayload.attachments, ...(uploadedImageAttachments ?? [])],
|
||||
});
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AttachmentMetadata, AttachmentStore } from "@/attachments/types";
|
||||
import { __setAttachmentStoreForTests } from "@/attachments/store";
|
||||
import { requestWorkspaceDraftAgent } from "./create-agent-request";
|
||||
|
||||
function createFakeStore(bytesById: Record<string, Uint8Array>): AttachmentStore {
|
||||
return {
|
||||
storageType: "web-indexeddb",
|
||||
async save() {
|
||||
throw new Error("not used");
|
||||
},
|
||||
async encodeBase64() {
|
||||
throw new Error("encodeBase64 must not be called when uploading images");
|
||||
},
|
||||
async readBytes({ attachment }) {
|
||||
const bytes = bytesById[attachment.id];
|
||||
if (!bytes) throw new Error(`missing ${attachment.id}`);
|
||||
return bytes;
|
||||
},
|
||||
async resolvePreviewUrl() {
|
||||
return "blob:test";
|
||||
},
|
||||
async delete() {},
|
||||
async garbageCollect() {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("requestWorkspaceDraftAgent", () => {
|
||||
afterEach(() => {
|
||||
__setAttachmentStoreForTests(null);
|
||||
});
|
||||
|
||||
it("uploads draft images sequentially via uploadFile and sends them in attachments with role='image' instead of inline base64", async () => {
|
||||
const firstBytes = new Uint8Array([1, 2, 3, 4]);
|
||||
const secondBytes = new Uint8Array([5, 6, 7]);
|
||||
__setAttachmentStoreForTests(createFakeStore({ img1: firstBytes, img2: secondBytes }));
|
||||
|
||||
const uploadFile = vi.fn(
|
||||
async (input: { fileName: string; mimeType: string; bytes: Uint8Array }) => ({
|
||||
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 createAgent = vi.fn(async (input: Record<string, unknown>) => ({
|
||||
id: "agent-new",
|
||||
...input,
|
||||
}));
|
||||
const client = { uploadFile, createAgent } as unknown as DaemonClient;
|
||||
|
||||
const images: AttachmentMetadata[] = [
|
||||
{
|
||||
id: "img1",
|
||||
mimeType: "image/jpeg",
|
||||
storageType: "web-indexeddb",
|
||||
storageKey: "img1",
|
||||
fileName: "first.jpg",
|
||||
byteSize: firstBytes.byteLength,
|
||||
createdAt: 1,
|
||||
},
|
||||
{
|
||||
id: "img2",
|
||||
mimeType: "image/png",
|
||||
storageType: "web-indexeddb",
|
||||
storageKey: "img2",
|
||||
fileName: "second.png",
|
||||
byteSize: secondBytes.byteLength,
|
||||
createdAt: 2,
|
||||
},
|
||||
];
|
||||
|
||||
await requestWorkspaceDraftAgent(client, {
|
||||
workspaceId: "ws-1",
|
||||
config: { provider: "claude", cwd: "/repo" },
|
||||
text: "Look at these two photos",
|
||||
clientMessageId: "draft:initial-message",
|
||||
images,
|
||||
});
|
||||
|
||||
expect(uploadFile).toHaveBeenCalledTimes(2);
|
||||
expect(createAgent).toHaveBeenCalledTimes(1);
|
||||
const createCall = createAgent.mock.calls[0]?.[0] as Record<string, unknown>;
|
||||
expect(createCall.images).toBeUndefined();
|
||||
expect(createCall.attachments).toEqual([
|
||||
{
|
||||
type: "uploaded_file",
|
||||
id: "upload_first.jpg",
|
||||
fileName: "first.jpg",
|
||||
mimeType: "image/jpeg",
|
||||
size: 4,
|
||||
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: 3,
|
||||
path: "/home/user/.paseo/uploads/upload_second.png/second.png",
|
||||
role: "image",
|
||||
},
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,15 +1,15 @@
|
||||
import type { AgentSessionConfig } from "@getpaseo/protocol/agent-types";
|
||||
import type { AgentSnapshotPayload, CreateAgentRequestMessage } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { encodeImages } from "@/utils/encode-images";
|
||||
import type { UserMessageImageAttachment } from "@/types/stream";
|
||||
import { uploadImageAttachments } from "@/attachments/service";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
|
||||
export interface WorkspaceDraftAgentRequest {
|
||||
workspaceId: string;
|
||||
config: AgentSessionConfig;
|
||||
text: string;
|
||||
clientMessageId: string;
|
||||
images?: UserMessageImageAttachment[];
|
||||
images?: AttachmentMetadata[];
|
||||
attachments?: CreateAgentRequestMessage["attachments"];
|
||||
}
|
||||
|
||||
@@ -21,15 +21,13 @@ export async function requestWorkspaceDraftAgent(
|
||||
client: DaemonClient,
|
||||
request: WorkspaceDraftAgentRequest,
|
||||
): Promise<AgentSnapshotPayload> {
|
||||
const images = await encodeImages(request.images);
|
||||
const uploadedImageAttachments = await uploadImageAttachments({ client, images: request.images });
|
||||
const mergedAttachments = [...(request.attachments ?? []), ...(uploadedImageAttachments ?? [])];
|
||||
return await client.createAgent({
|
||||
config: request.config,
|
||||
workspaceId: request.workspaceId,
|
||||
clientMessageId: request.clientMessageId,
|
||||
...(request.text ? { initialPrompt: request.text } : {}),
|
||||
...(images && images.length > 0 ? { images } : {}),
|
||||
...(request.attachments && request.attachments.length > 0
|
||||
? { attachments: request.attachments }
|
||||
: {}),
|
||||
...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import type { UserMessageImageAttachment } from "@/types/stream";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import { useDraftAgentCreateFlow, type DraftCreateAttempt } from "./create-flow";
|
||||
|
||||
@@ -14,7 +14,7 @@ describe("useDraftAgentCreateFlow", () => {
|
||||
});
|
||||
|
||||
it("renders a prepared new-workspace submission before continuing it", async () => {
|
||||
const image: UserMessageImageAttachment = {
|
||||
const image: AttachmentMetadata = {
|
||||
id: "image-1",
|
||||
mimeType: "image/png",
|
||||
storageType: "web-indexeddb",
|
||||
@@ -37,7 +37,7 @@ describe("useDraftAgentCreateFlow", () => {
|
||||
async (ctx: {
|
||||
attempt: DraftCreateAttempt;
|
||||
text: string;
|
||||
images?: UserMessageImageAttachment[];
|
||||
images?: AttachmentMetadata[];
|
||||
attachments?: AgentAttachment[];
|
||||
cwd: string;
|
||||
}) => ({
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useCallback, useMemo, useReducer } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import type { AttachmentMetadata, ComposerAttachment } from "@/attachments/types";
|
||||
import {
|
||||
resolveComposerAttachmentSubmitFormat,
|
||||
splitComposerAttachmentsForSubmit,
|
||||
@@ -8,14 +8,14 @@ import {
|
||||
import { isActiveCreateFlowForDraft, useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import { handoffCreatedAgentMessageSubmission } from "@/composer/submission/writer";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { createUserMessage, type UserMessageImageAttachment } from "@/types/stream";
|
||||
import { createUserMessage } from "@/types/stream";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
|
||||
interface CreateAttempt {
|
||||
clientMessageId: string;
|
||||
text: string;
|
||||
timestamp: Date;
|
||||
images?: UserMessageImageAttachment[];
|
||||
images?: AttachmentMetadata[];
|
||||
attachments?: AgentAttachment[];
|
||||
}
|
||||
|
||||
@@ -82,7 +82,7 @@ interface SubmitContext {
|
||||
interface CreateRequestContext {
|
||||
attempt: CreateAttempt;
|
||||
text: string;
|
||||
images?: UserMessageImageAttachment[];
|
||||
images?: AttachmentMetadata[];
|
||||
attachments?: AgentAttachment[];
|
||||
cwd: string;
|
||||
}
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { AgentAttachment } from "@getpaseo/protocol/messages";
|
||||
import type { PendingCreateAttempt } from "@/stores/create-flow-store";
|
||||
import type { UserMessageImageAttachment } from "@/types/stream";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import { DRAFT_CAPABILITIES, resolveDraftTimeline } from "./timeline";
|
||||
|
||||
const image: UserMessageImageAttachment = {
|
||||
const image: AttachmentMetadata = {
|
||||
id: "image-1",
|
||||
mimeType: "image/png",
|
||||
storageType: "web-indexeddb",
|
||||
|
||||
@@ -22,7 +22,7 @@ import { useCreateFlowStore } from "@/stores/create-flow-store";
|
||||
import type { Agent } from "@/stores/session-store";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import { useWorkspaceDraftSubmissionStore } from "@/stores/workspace-draft-submission-store";
|
||||
import { encodeImages } from "@/utils/encode-images";
|
||||
import { uploadImageAttachments } from "@/attachments/service";
|
||||
import { shouldAutoFocusWorkspaceDraftComposer } from "@/screens/workspace/workspace-draft-pane-focus";
|
||||
import {
|
||||
resolveDraftWorkingDirectory,
|
||||
@@ -32,13 +32,12 @@ import {
|
||||
import { DRAFT_CAPABILITIES } from "@/composer/draft/timeline";
|
||||
import type { AgentSnapshotPayload } from "@getpaseo/protocol/messages";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { WorkspaceComposerAttachment } from "@/attachments/types";
|
||||
import type { AttachmentMetadata, WorkspaceComposerAttachment } from "@/attachments/types";
|
||||
import {
|
||||
useDraftWorkspaceAttachmentScopeKey,
|
||||
useWorkspaceAttachmentScopeKey,
|
||||
useWorkspaceAttachmentsStore,
|
||||
} from "@/attachments/workspace-attachments-store";
|
||||
import type { UserMessageImageAttachment } from "@/types/stream";
|
||||
import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import {
|
||||
@@ -141,7 +140,7 @@ async function submitDraftCreateRequest(input: {
|
||||
draftId: string;
|
||||
attempt: { clientMessageId: string };
|
||||
text: string;
|
||||
images?: UserMessageImageAttachment[];
|
||||
images?: AttachmentMetadata[];
|
||||
attachments?: unknown;
|
||||
cwd: string;
|
||||
client: DaemonClient | null;
|
||||
@@ -190,16 +189,16 @@ async function submitDraftCreateRequest(input: {
|
||||
composerState,
|
||||
});
|
||||
|
||||
const attachmentsArray = Array.isArray(attachments) ? attachments : undefined;
|
||||
const imagesData = await encodeImages(images);
|
||||
const attachmentsArray = Array.isArray(attachments) ? attachments : [];
|
||||
const uploadedImageAttachments = await uploadImageAttachments({ client, images });
|
||||
const mergedAttachments = [...attachmentsArray, ...(uploadedImageAttachments ?? [])];
|
||||
const request = {
|
||||
config,
|
||||
workspaceId,
|
||||
initialPrompt: text,
|
||||
clientMessageId: attempt.clientMessageId,
|
||||
...(Object.keys(composerState.metadata).length > 0 ? { metadata: composerState.metadata } : {}),
|
||||
...(imagesData && imagesData.length > 0 ? { images: imagesData } : {}),
|
||||
...(attachmentsArray && attachmentsArray.length > 0 ? { attachments: attachmentsArray } : {}),
|
||||
...(mergedAttachments.length > 0 ? { attachments: mergedAttachments } : {}),
|
||||
};
|
||||
const result = await client.createAgent({
|
||||
...request,
|
||||
|
||||
@@ -85,7 +85,7 @@ import {
|
||||
import type { ImageAttachment, MessagePayload, TextReplacement } from "./types";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import type { DraftCommandTarget } from "@/agent-commands";
|
||||
import { encodeImages } from "@/utils/encode-images";
|
||||
import { normalizePickedImageAssets } from "@/hooks/image-attachment-picker";
|
||||
import { focusWithRetries } from "@/utils/web-focus";
|
||||
import {
|
||||
cancelComposerAgent,
|
||||
@@ -1726,7 +1726,6 @@ function ComposerContentImpl({
|
||||
attachmentSubmitFormat: resolveComposerAttachmentSubmitFormat({
|
||||
supportsForgeAttachments: supportsForgeSearch,
|
||||
}),
|
||||
encodeImages,
|
||||
submission: createMessageSubmissionWriter(serverId),
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
@@ -1926,7 +1925,24 @@ function ComposerContentImpl({
|
||||
(files: readonly NativePastedFile[]) => {
|
||||
setPendingNativeImagePastes((pending) => pending + 1);
|
||||
void pickAndPersistImages({
|
||||
pickImages: async () => normalizeNativePastedImages(files),
|
||||
pickImages: async () => {
|
||||
const pasted = normalizeNativePastedImages(files);
|
||||
const result = [];
|
||||
for (const item of pasted) {
|
||||
if (
|
||||
item.source.kind === "file_uri" &&
|
||||
(item.mimeType === "image/heic" || item.mimeType === "image/heif")
|
||||
) {
|
||||
const converted = await normalizePickedImageAssets([
|
||||
{ uri: item.source.uri, mimeType: item.mimeType, fileName: item.fileName },
|
||||
]);
|
||||
result.push(...converted);
|
||||
} else {
|
||||
result.push(item);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
},
|
||||
persister: composerImageAttachmentPersister,
|
||||
})
|
||||
.then((newImages) => {
|
||||
|
||||
@@ -216,6 +216,17 @@ export function createDesktopAttachmentStore(bridge: DesktopAttachmentBridge): A
|
||||
return await bridge.readFileBase64(attachment.storageKey);
|
||||
},
|
||||
|
||||
async readBytes({ attachment }): Promise<Uint8Array> {
|
||||
assertDesktopAttachment(attachment);
|
||||
const base64 = await bridge.readFileBase64(attachment.storageKey);
|
||||
const binary = atob(base64);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes;
|
||||
},
|
||||
|
||||
async resolvePreviewUrl({ attachment }): Promise<string> {
|
||||
assertDesktopAttachment(attachment);
|
||||
return await bridge.resolvePreviewUrl(attachment);
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import {
|
||||
beginAgentInputFocusGuard,
|
||||
clearAgentInputFocusGuards,
|
||||
endAgentInputFocusGuard,
|
||||
isAgentInputMovingFocus,
|
||||
watchUserComposition,
|
||||
} from "./focus-guard";
|
||||
|
||||
function createFocusableWebview(browserId: string): HTMLElement {
|
||||
const webview = document.createElement("webview");
|
||||
webview.setAttribute("data-paseo-browser-id", browserId);
|
||||
webview.tabIndex = 0;
|
||||
document.body.appendChild(webview);
|
||||
return webview;
|
||||
}
|
||||
|
||||
describe("renderer agent input focus guard", () => {
|
||||
afterEach(() => {
|
||||
clearAgentInputFocusGuards();
|
||||
vi.useRealTimers();
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("restores the composer immediately and on the 50ms late-focus recheck", () => {
|
||||
vi.useFakeTimers();
|
||||
const composer = document.createElement("textarea");
|
||||
const webview = createFocusableWebview("browser-1");
|
||||
document.body.appendChild(composer);
|
||||
composer.focus();
|
||||
|
||||
expect(beginAgentInputFocusGuard("browser-1", "tok-1", () => webview)).toBe("ready");
|
||||
expect(isAgentInputMovingFocus("browser-1")).toBe(true);
|
||||
expect(isAgentInputMovingFocus()).toBe(true);
|
||||
|
||||
// Simulate CDP mousePressed moving focus into the webview.
|
||||
webview.focus();
|
||||
expect(document.activeElement).toBe(webview);
|
||||
|
||||
endAgentInputFocusGuard("tok-1");
|
||||
expect(document.activeElement).toBe(composer);
|
||||
expect(isAgentInputMovingFocus("browser-1")).toBe(true);
|
||||
|
||||
// Simulate a late Chromium focus event arriving within the 50ms recheck window.
|
||||
webview.focus();
|
||||
expect(document.activeElement).toBe(webview);
|
||||
|
||||
vi.advanceTimersByTime(50);
|
||||
expect(document.activeElement).toBe(composer);
|
||||
expect(isAgentInputMovingFocus("browser-1")).toBe(false);
|
||||
expect(isAgentInputMovingFocus()).toBe(false);
|
||||
});
|
||||
|
||||
it("restores the composer when a parked inert surface blurs focus to document.body", () => {
|
||||
vi.useFakeTimers();
|
||||
const composer = document.createElement("textarea");
|
||||
const surface = document.createElement("div");
|
||||
surface.setAttribute("inert", "");
|
||||
surface.setAttribute("tabindex", "-1");
|
||||
const webview = document.createElement("webview");
|
||||
surface.appendChild(webview);
|
||||
document.body.append(composer, surface);
|
||||
composer.focus();
|
||||
|
||||
expect(beginAgentInputFocusGuard("browser-parked", "tok-parked", () => webview)).toBe("ready");
|
||||
|
||||
// Simulate Chromium blurring composer to body while the parked webview is inert.
|
||||
composer.blur();
|
||||
expect(document.activeElement).toBe(document.body);
|
||||
|
||||
endAgentInputFocusGuard("tok-parked");
|
||||
expect(document.activeElement).toBe(composer);
|
||||
|
||||
vi.advanceTimersByTime(50);
|
||||
expect(isAgentInputMovingFocus("browser-parked")).toBe(false);
|
||||
});
|
||||
|
||||
it("keeps focus on the webview when the user was already focused in it", () => {
|
||||
const webview = createFocusableWebview("browser-active");
|
||||
webview.focus();
|
||||
|
||||
expect(beginAgentInputFocusGuard("browser-active", "tok-active", () => webview)).toBe("ready");
|
||||
expect(isAgentInputMovingFocus("browser-active")).toBe(false);
|
||||
|
||||
endAgentInputFocusGuard("tok-active");
|
||||
expect(document.activeElement).toBe(webview);
|
||||
});
|
||||
|
||||
it("does not yank focus back if the user focused another host input mid-press", () => {
|
||||
vi.useFakeTimers();
|
||||
const composer = document.createElement("textarea");
|
||||
const searchInput = document.createElement("input");
|
||||
const webview = createFocusableWebview("browser-other");
|
||||
document.body.append(composer, searchInput);
|
||||
composer.focus();
|
||||
|
||||
expect(beginAgentInputFocusGuard("browser-other", "tok-other", () => webview)).toBe("ready");
|
||||
searchInput.focus();
|
||||
|
||||
endAgentInputFocusGuard("tok-other");
|
||||
vi.advanceTimersByTime(50);
|
||||
expect(document.activeElement).toBe(searchInput);
|
||||
});
|
||||
|
||||
it("preserves the original composer across overlapping presses on two webviews", () => {
|
||||
vi.useFakeTimers();
|
||||
const composer = document.createElement("textarea");
|
||||
const webviewA = createFocusableWebview("browser-a");
|
||||
const webviewB = createFocusableWebview("browser-b");
|
||||
document.body.appendChild(composer);
|
||||
composer.focus();
|
||||
|
||||
expect(beginAgentInputFocusGuard("browser-a", "tok-a", () => webviewA)).toBe("ready");
|
||||
webviewA.focus();
|
||||
|
||||
// Second overlapping press starts while webviewA holds agent-taken focus.
|
||||
expect(beginAgentInputFocusGuard("browser-b", "tok-b", () => webviewB)).toBe("ready");
|
||||
webviewB.focus();
|
||||
|
||||
endAgentInputFocusGuard("tok-b");
|
||||
expect(document.activeElement).toBe(composer);
|
||||
|
||||
endAgentInputFocusGuard("tok-a");
|
||||
vi.advanceTimersByTime(50);
|
||||
expect(document.activeElement).toBe(composer);
|
||||
expect(isAgentInputMovingFocus()).toBe(false);
|
||||
});
|
||||
|
||||
it("blurs the webview when the saved host element was removed before release", () => {
|
||||
vi.useFakeTimers();
|
||||
const composer = document.createElement("textarea");
|
||||
const webview = createFocusableWebview("browser-removed");
|
||||
document.body.appendChild(composer);
|
||||
composer.focus();
|
||||
|
||||
expect(beginAgentInputFocusGuard("browser-removed", "tok-removed", () => webview)).toBe(
|
||||
"ready",
|
||||
);
|
||||
webview.focus();
|
||||
composer.remove();
|
||||
|
||||
endAgentInputFocusGuard("tok-removed");
|
||||
expect(document.activeElement).not.toBe(webview);
|
||||
vi.advanceTimersByTime(50);
|
||||
expect(isAgentInputMovingFocus()).toBe(false);
|
||||
});
|
||||
|
||||
it("refuses pointer input while the user has an active IME composition in the composer", () => {
|
||||
const unwatch = watchUserComposition();
|
||||
try {
|
||||
const composer = document.createElement("textarea");
|
||||
const webview = createFocusableWebview("browser-ime");
|
||||
document.body.appendChild(composer);
|
||||
composer.focus();
|
||||
|
||||
composer.dispatchEvent(new CompositionEvent("compositionstart", { bubbles: true }));
|
||||
expect(beginAgentInputFocusGuard("browser-ime", "tok-ime-1", () => webview)).toBe(
|
||||
"composing",
|
||||
);
|
||||
expect(isAgentInputMovingFocus("browser-ime")).toBe(false);
|
||||
|
||||
// Empty compositionupdate (Sogou/fcitx) must not end the composition guard.
|
||||
composer.dispatchEvent(
|
||||
new CompositionEvent("compositionupdate", { bubbles: true, data: "" }),
|
||||
);
|
||||
expect(beginAgentInputFocusGuard("browser-ime", "tok-ime-2", () => webview)).toBe(
|
||||
"composing",
|
||||
);
|
||||
|
||||
// Composition-owned input event must keep the guard active.
|
||||
composer.dispatchEvent(
|
||||
new InputEvent("input", { bubbles: true, isComposing: true, data: "あ" }),
|
||||
);
|
||||
expect(beginAgentInputFocusGuard("browser-ime", "tok-ime-3", () => webview)).toBe(
|
||||
"composing",
|
||||
);
|
||||
|
||||
// Composition end allows pointer input again.
|
||||
composer.dispatchEvent(new CompositionEvent("compositionend", { bubbles: true }));
|
||||
expect(beginAgentInputFocusGuard("browser-ime", "tok-ime-4", () => webview)).toBe("ready");
|
||||
endAgentInputFocusGuard("tok-ime-4");
|
||||
} finally {
|
||||
unwatch();
|
||||
}
|
||||
});
|
||||
|
||||
it("starts IME protection on nonempty compositionupdate and clears it on non-composing input", () => {
|
||||
const unwatch = watchUserComposition();
|
||||
try {
|
||||
const composer = document.createElement("textarea");
|
||||
const webview = createFocusableWebview("browser-ime-2");
|
||||
document.body.appendChild(composer);
|
||||
composer.focus();
|
||||
|
||||
composer.dispatchEvent(
|
||||
new CompositionEvent("compositionupdate", { bubbles: true, data: "漢" }),
|
||||
);
|
||||
expect(beginAgentInputFocusGuard("browser-ime-2", "tok-u1", () => webview)).toBe("composing");
|
||||
|
||||
// Missed compositionend is recovered by a normal non-composing input event.
|
||||
composer.dispatchEvent(
|
||||
new InputEvent("input", { bubbles: true, isComposing: false, data: "a" }),
|
||||
);
|
||||
expect(beginAgentInputFocusGuard("browser-ime-2", "tok-u2", () => webview)).toBe("ready");
|
||||
endAgentInputFocusGuard("tok-u2");
|
||||
} finally {
|
||||
unwatch();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,225 @@
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
import { getResidentBrowserWebview } from "@/desktop/browser/resident-webviews";
|
||||
|
||||
// Main brackets agent CDP pointer presses (browser_click, browser_drag) because
|
||||
// Chromium moves window focus into the guest on mousePressed even with focus
|
||||
// emulation enabled. Restore the user's host element afterward and refuse presses
|
||||
// while an IME composition is active so unfinished text is never committed.
|
||||
|
||||
const LATE_FOCUS_RECHECK_MS = 50;
|
||||
const ABANDONED_GUARD_MS = 30_000;
|
||||
|
||||
interface BrowserFocusGuardEvent {
|
||||
browserId: string;
|
||||
token: string;
|
||||
active: boolean;
|
||||
}
|
||||
|
||||
const releasesByToken = new Map<string, () => void>();
|
||||
const inFlightByBrowserId = new Map<string, number>();
|
||||
const pendingRecheckTimers = new Set<ReturnType<typeof setTimeout>>();
|
||||
|
||||
let composingElement: EventTarget | null = null;
|
||||
let inFlight = 0;
|
||||
let userElement: Element | null = null;
|
||||
let bridgeInstalled = false;
|
||||
|
||||
function decrementBrowserInFlight(browserId: string): void {
|
||||
const remaining = (inFlightByBrowserId.get(browserId) ?? 0) - 1;
|
||||
if (remaining <= 0) {
|
||||
inFlightByBrowserId.delete(browserId);
|
||||
} else {
|
||||
inFlightByBrowserId.set(browserId, remaining);
|
||||
}
|
||||
}
|
||||
|
||||
function settle(browserId: string): void {
|
||||
decrementBrowserInFlight(browserId);
|
||||
inFlight = Math.max(0, inFlight - 1);
|
||||
if (inFlight === 0) {
|
||||
userElement = null;
|
||||
}
|
||||
}
|
||||
|
||||
function isUserComposing(): boolean {
|
||||
return (
|
||||
typeof document !== "undefined" &&
|
||||
composingElement !== null &&
|
||||
composingElement === document.activeElement
|
||||
);
|
||||
}
|
||||
|
||||
export function isAgentInputMovingFocus(browserId?: string): boolean {
|
||||
if (browserId !== undefined) {
|
||||
return (inFlightByBrowserId.get(browserId) ?? 0) > 0;
|
||||
}
|
||||
return inFlight > 0;
|
||||
}
|
||||
|
||||
export function watchUserComposition(): () => void {
|
||||
if (typeof document === "undefined") {
|
||||
return () => {};
|
||||
}
|
||||
const onStart = (event: Event): void => {
|
||||
composingElement = event.target;
|
||||
};
|
||||
// Nonempty updates can start composition without compositionstart; empty updates
|
||||
// from IMEs such as Sogou/fcitx must not clear an open candidate session.
|
||||
const onUpdate = (event: Event): void => {
|
||||
const data = "data" in event ? (event as { data?: unknown }).data : undefined;
|
||||
if (typeof data === "string" && data !== "") {
|
||||
composingElement = event.target;
|
||||
}
|
||||
};
|
||||
const onEnd = (): void => {
|
||||
composingElement = null;
|
||||
};
|
||||
// Non-composing input clears missed compositionend events while preserving
|
||||
// composition-owned edits (e.g. Cangjie Backspace).
|
||||
const onInput = (event: Event): void => {
|
||||
const composing =
|
||||
"isComposing" in event ? (event as { isComposing?: unknown }).isComposing === true : false;
|
||||
if (!composing) {
|
||||
composingElement = null;
|
||||
}
|
||||
};
|
||||
const listeners: Array<[string, (event: Event) => void]> = [
|
||||
["compositionstart", onStart],
|
||||
["compositionupdate", onUpdate],
|
||||
["compositionend", onEnd],
|
||||
["input", onInput],
|
||||
];
|
||||
for (const [type, listener] of listeners) {
|
||||
document.addEventListener(type, listener, true);
|
||||
}
|
||||
return () => {
|
||||
for (const [type, listener] of listeners) {
|
||||
document.removeEventListener(type, listener, true);
|
||||
}
|
||||
composingElement = null;
|
||||
};
|
||||
}
|
||||
|
||||
export function beginAgentInputFocusGuard(
|
||||
browserId: string,
|
||||
token: string,
|
||||
lookupWebview: (id: string) => HTMLElement | null = getResidentBrowserWebview,
|
||||
): "ready" | "composing" {
|
||||
if (isUserComposing()) {
|
||||
return "composing";
|
||||
}
|
||||
if (typeof document === "undefined") {
|
||||
return "ready";
|
||||
}
|
||||
const webview = lookupWebview(browserId);
|
||||
if (!webview) {
|
||||
return "ready";
|
||||
}
|
||||
const active = document.activeElement;
|
||||
if (inFlight === 0) {
|
||||
// A user already focused in this browser page keeps focus there.
|
||||
if (active === webview) {
|
||||
return "ready";
|
||||
}
|
||||
userElement = active;
|
||||
} else if (
|
||||
active instanceof HTMLElement &&
|
||||
active !== document.body &&
|
||||
active.tagName !== "WEBVIEW"
|
||||
) {
|
||||
// Keep the earlier host element when activeElement belongs to an agent-focused
|
||||
// webview or document.body, but follow if the user moved to another host control.
|
||||
userElement = active;
|
||||
}
|
||||
|
||||
inFlight += 1;
|
||||
inFlightByBrowserId.set(browserId, (inFlightByBrowserId.get(browserId) ?? 0) + 1);
|
||||
|
||||
const restore = (): void => {
|
||||
const previous = userElement;
|
||||
const current = document.activeElement;
|
||||
const focusWasTaken =
|
||||
current === webview ||
|
||||
(current === document.body && previous !== null && previous !== document.body) ||
|
||||
(current === null && previous !== null);
|
||||
if (!focusWasTaken) {
|
||||
return;
|
||||
}
|
||||
if (previous instanceof HTMLElement && previous !== document.body && previous.isConnected) {
|
||||
previous.focus({ preventScroll: true });
|
||||
} else if (current === webview && typeof webview.blur === "function") {
|
||||
webview.blur();
|
||||
}
|
||||
};
|
||||
|
||||
const abandoned = setTimeout(() => endAgentInputFocusGuard(token), ABANDONED_GUARD_MS);
|
||||
releasesByToken.set(token, () => {
|
||||
clearTimeout(abandoned);
|
||||
restore();
|
||||
const recheck = setTimeout(() => {
|
||||
pendingRecheckTimers.delete(recheck);
|
||||
restore();
|
||||
settle(browserId);
|
||||
}, LATE_FOCUS_RECHECK_MS);
|
||||
pendingRecheckTimers.add(recheck);
|
||||
});
|
||||
return "ready";
|
||||
}
|
||||
|
||||
export function endAgentInputFocusGuard(token: string): void {
|
||||
const release = releasesByToken.get(token);
|
||||
releasesByToken.delete(token);
|
||||
release?.();
|
||||
}
|
||||
|
||||
export function clearAgentInputFocusGuards(): void {
|
||||
for (const release of releasesByToken.values()) {
|
||||
release();
|
||||
}
|
||||
releasesByToken.clear();
|
||||
for (const timer of pendingRecheckTimers) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
pendingRecheckTimers.clear();
|
||||
inFlightByBrowserId.clear();
|
||||
inFlight = 0;
|
||||
userElement = null;
|
||||
composingElement = null;
|
||||
}
|
||||
|
||||
function isBrowserFocusGuardEvent(value: unknown): value is BrowserFocusGuardEvent {
|
||||
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
||||
return false;
|
||||
}
|
||||
const record = value as Record<string, unknown>;
|
||||
return (
|
||||
typeof record.browserId === "string" &&
|
||||
typeof record.token === "string" &&
|
||||
typeof record.active === "boolean"
|
||||
);
|
||||
}
|
||||
|
||||
export function installBrowserFocusGuardBridge(): void {
|
||||
if (bridgeInstalled || !getIsElectron()) {
|
||||
return;
|
||||
}
|
||||
const desktop = getDesktopHost();
|
||||
const acknowledge = desktop?.browser?.acknowledgeFocusGuard;
|
||||
if (!desktop?.events?.on || typeof acknowledge !== "function") {
|
||||
return;
|
||||
}
|
||||
bridgeInstalled = true;
|
||||
watchUserComposition();
|
||||
void desktop.events.on("browser-focus-guard", (payload) => {
|
||||
if (!isBrowserFocusGuardEvent(payload)) {
|
||||
return;
|
||||
}
|
||||
if (payload.active) {
|
||||
const outcome = beginAgentInputFocusGuard(payload.browserId, payload.token);
|
||||
acknowledge({ token: payload.token, composing: outcome === "composing" });
|
||||
} else {
|
||||
endAgentInputFocusGuard(payload.token);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
prepareHostBrowserPartition as prepareHostBrowserPartitionDefault,
|
||||
readHostBrowserRouting as readHostBrowserRoutingDefault,
|
||||
} from "@/desktop/browser/proxy";
|
||||
import { installBrowserFocusGuardBridge } from "./focus-guard";
|
||||
import {
|
||||
createFixedBrowserViewport,
|
||||
createWorkspaceBrowser,
|
||||
@@ -57,6 +58,7 @@ export function mountBrowserAutomationHandler(
|
||||
options: BrowserAutomationHandlerOptions,
|
||||
): () => void {
|
||||
installBrowserProxyRendererBridge();
|
||||
installBrowserFocusGuardBridge();
|
||||
const getHost = options.getHost ?? getDesktopHost;
|
||||
const unsubscribe = options.client.on("browser.automation.execute.request", (request) => {
|
||||
void handleBrowserAutomationRequest({
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { createWorkspaceBrowser } from "@/desktop/browser/store";
|
||||
import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { buildWorkspaceTabPersistenceKey } from "@/workspace-tabs/model";
|
||||
|
||||
/** Opens a URL in a Paseo browser tab of one workspace. Only the desktop app has those tabs. */
|
||||
export function openUrlInWorkspaceBrowser({
|
||||
serverId,
|
||||
workspaceId,
|
||||
url,
|
||||
}: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
url: string;
|
||||
}): void {
|
||||
if (!getIsElectron()) return;
|
||||
const workspaceKey = buildWorkspaceTabPersistenceKey({ serverId, workspaceId });
|
||||
if (!workspaceKey) return;
|
||||
const { browserId } = createWorkspaceBrowser({ initialUrl: url });
|
||||
useWorkspaceLayoutStore.getState().openTab({
|
||||
workspaceKey,
|
||||
target: { kind: "browser", browserId },
|
||||
intent: "reveal",
|
||||
});
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user