mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-02 13:15:21 +00:00
Compare commits
70
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
282cbae1c1 | ||
|
|
5b2aa7e0ca | ||
|
|
f576407576 | ||
|
|
b2b05b599e | ||
|
|
8fc8cb51b4 | ||
|
|
18dc910689 | ||
|
|
711188aadc | ||
|
|
d207bc5a57 | ||
|
|
f3213a2259 | ||
|
|
370afb86c6 | ||
|
|
6caf7f6653 | ||
|
|
f4a6d7841c | ||
|
|
4db5d454cd | ||
|
|
b34d4f5c3f | ||
|
|
7bfdbbad2c | ||
|
|
98c98d1017 | ||
|
|
e9ea31ef3b | ||
|
|
5a6e6d1918 | ||
|
|
acd119743b | ||
|
|
a7bc7ac759 | ||
|
|
9b82a65f3d | ||
|
|
d131b54230 | ||
|
|
c75b718b2d | ||
|
|
3e2179cbc9 | ||
|
|
20755f5097 | ||
|
|
1fe9905fa3 | ||
|
|
211416b8eb | ||
|
|
ab5e1d6fcb | ||
|
|
5029998013 | ||
|
|
2719695236 | ||
|
|
dc66f296da | ||
|
|
f7ceb13bd7 | ||
|
|
fdec437e07 | ||
|
|
67b5da3544 | ||
|
|
197e84c337 | ||
|
|
4d9bc25a1d | ||
|
|
910e65d8b2 | ||
|
|
12e7f1fab1 | ||
|
|
bbdc3e326d | ||
|
|
bac45474de | ||
|
|
e928961472 | ||
|
|
83b80351f7 | ||
|
|
6eba86db2f | ||
|
|
f83c3bab70 | ||
|
|
535f3d36d0 | ||
|
|
32fe3074a0 | ||
|
|
5b1ccba548 | ||
|
|
6cffd3994d | ||
|
|
4101519112 | ||
|
|
da58a57998 | ||
|
|
f76fd024fb | ||
|
|
2f7e22e621 | ||
|
|
9592f88fdf | ||
|
|
0d244c192a | ||
|
|
6354565748 | ||
|
|
e06218e9f4 | ||
|
|
fec7454c31 | ||
|
|
5adfd4961c | ||
|
|
d1ee5dee63 | ||
|
|
1adabf70c8 | ||
|
|
87427c2aa1 | ||
|
|
cfa4536358 | ||
|
|
7f75b0e166 | ||
|
|
b0ca089d54 | ||
|
|
91e7713721 | ||
|
|
e20ea2aaf2 | ||
|
|
806214d285 | ||
|
|
e5edb6efd5 | ||
|
|
0a0544fa4f | ||
|
|
914143e8b0 |
+17
-11
@@ -236,17 +236,23 @@ wake-ups), or the child's own outstanding finish subscriptions as a caller. Hear
|
||||
crons, change-request watches, and other daemon background items never count: they are external
|
||||
triggers, not work the caller is waiting for.
|
||||
|
||||
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
|
||||
subscription follows the child: each later turn end reports `finished` again, and the child settling
|
||||
with nothing pending sends a final `finished` and removes the subscription, even when the work
|
||||
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
|
||||
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
|
||||
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
|
||||
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
|
||||
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
|
||||
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
|
||||
the child's last reply and the subscription ends. Remote children and providers without the probe
|
||||
report their first turn end as a settled `finished`.
|
||||
Every turn end reports `finished` at once, unless the child already sent an agent message to its
|
||||
caller during that turn and started no further tool work afterwards. In that case the child's
|
||||
message already delivered its reply, so the redundant `finished` notice is skipped: a settled watch
|
||||
ends silently, and a watch with pending work keeps following silently until a later turn starts or
|
||||
the work drains. Starting another non-reporting tool call or a new turn clears that mark (plain text output after the
|
||||
message does not), and errors, permission requests, cancellations, and closes are never suppressed. When work is still
|
||||
pending on an unreported turn end, the notice names it and the subscription follows the child: each
|
||||
later turn end reports `finished` again, and the child settling with nothing pending sends a final
|
||||
`finished` and removes the subscription, even when the work drains without another turn. Reporting
|
||||
at once keeps a long-lived task, such as a dev server, from leaving the caller without the child's
|
||||
reply. Following is what lets the caller hear the reply a background task wakes up later
|
||||
([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change that leaves work pending
|
||||
sends nothing. Errors, permission requests, and closes report as they happen. `followingSince` is
|
||||
stored when following starts, so a restart keeps following instead of waiting for another turn end.
|
||||
After 24 hours of following, the caller gets a final `finished` with the child's last reply and the
|
||||
subscription ends. Remote children and providers without the probe report their first turn end as a
|
||||
settled `finished`.
|
||||
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
|
||||
@@ -29,7 +29,7 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
- **The coalescer is leading + trailing.** The first delta after an idle window flushes synchronously; only the rest of the burst waits for the trailing timer. Reverting to trailing-only adds a full window to the first character of every turn. Same shape and the same reason as `TerminalOutputCoalescer`.
|
||||
- **The leading flush adds a canonical row, and that is fine.** A burst's first chunk lands as its own timeline row. `mergeAssistantChunks` / `mergeReasoningChunks` in `timeline-projection.ts` join contiguous same-turn rows, and clients read the projected timeline, so history is unaffected. Tests that assert on raw rows have to account for the extra row; tests that assert on what a client sees do not.
|
||||
- **The store holds the full text; only the rendered slice is paced.** Copy, selection, the chat outline, and scroll geometry all read the same string the user can see. Pacing the store instead would leave the bottom anchor chasing a content height that is ahead of the reveal.
|
||||
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. The native renderer keeps closed blocks in a stable head and sends the paced suffix to a separate tail view during streaming; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
|
||||
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. While streaming, the renderer keeps closed blocks in head parts and sends the paced suffix to a separate tail; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
|
||||
- **Message identity survives completion.** Assistant row ids are source message ids. Plugin rows can replace a source, so find, scroll-to-message and history reveal still use `getStreamItemMessageId`. Width-specific measurements describe whole rendered messages.
|
||||
- **First sight of a text is revealed whole.** Only growth is paced. This is what makes history hydration, timeline replay, a virtualized row remounting on scroll, and an already-finished message all render complete on first paint without a special case for each.
|
||||
- **Leaving `phase: "streaming"` snaps the reveal.** A completed turn must never be left holding characters. `layoutStream` sets the phase, so anything outside the live head with an active turn is already complete.
|
||||
@@ -49,11 +49,19 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
while text arrives, and release obsolete window caches as the reader reveals more history;
|
||||
window caches must stay bounded while their source timeline remains loaded.
|
||||
|
||||
## Native parsing cost
|
||||
## Markdown parsing cost
|
||||
|
||||
The native library reparses and measures its entire `markdown` prop on each update. During streaming, the renderer splits source at an mdast block boundary and memoizes the head, so per-frame updates parse only the tail. Boundary discovery runs when a source line completes, rather than on every reveal frame. The unfinished line and final parsed block stay in the tail, preserving list continuation, setext headings, tables and open fences. Reference-dependent source and HTML retain a larger tail because later source can change their meaning. A single long block therefore still carries its full parsing cost.
|
||||
Both engines reparse their entire `markdown` prop on each update: md4c in C++ on native, md4c in WASM plus a JSON tree on web. Source adaptation adds a full mdast parse for some text, such as any `&`, at about 1 µs per character. Rendering a growing reply whole on each reveal frame therefore makes the reply quadratic to stream.
|
||||
|
||||
Completion restores one native text view per Mermaid-delimited segment, so selection crosses prose paragraphs again. The head retains its trailing block margin while split. JS reveal remains the pacing source; native opacity animation stays disabled.
|
||||
While streaming, `createStreamingMarkdownSplitter` in `components/markdown/streaming.ts` splits the message into head parts and a tail, on every platform. The tail is the last block and the unfinished line, so list continuation, setext headings, tables and open fences render as they will when complete. Rules that keep the cost per frame flat as the reply grows:
|
||||
|
||||
- **Discovery is incremental.** The boundary moves only when a line completes, and each time the splitter parses only the source after the boundary. Blocks before it are closed and need no document context.
|
||||
- **Head parts are sealed at 2,000 characters.** Each completed block re-renders the head part it lands in. Only the last part grows, so that work stays bounded. A single head would re-render all closed blocks each time a block completes.
|
||||
- **The first part keeps its React key from the first frame to the completed message.** Completion re-renders it in place instead of remounting it, and the parts share one image occurrence key, so an image keeps its acquisition when its block moves into the head.
|
||||
|
||||
Two kinds of source fall back to a growing render, because later source can change how earlier source reads. A link definition can turn an earlier `[label]` into a link, so a message with one renders as one document until it completes. HTML needs its enclosing source, so HTML and every block after it stay in the tail. A single long block also carries its full cost.
|
||||
|
||||
Completion renders one view per Mermaid-delimited segment, so native selection crosses prose paragraphs again; while streaming it crosses only within a part. JS reveal remains the pacing source; native opacity animation stays disabled.
|
||||
|
||||
## Measuring
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
Use `MarkdownRenderer` for chat replies, file previews, plans, pull requests and changelog content. It uses `react-native-enriched-markdown` on iOS, Android and web. Keep source adaptation and renderer configuration in `components/markdown`; consumers supply Markdown and, when needed, its file location.
|
||||
|
||||
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Chat owns paced reveal, the web render cap, message identity and list measurement. Native renders completed messages together. While streaming, it keeps closed blocks in one head view and updates a separate tail, then reunites the text on completion. See [native parsing cost](agent-stream-performance.md#native-parsing-cost) for the boundary and pacing constraints.
|
||||
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Call `preloadMarkdownParser()` ahead of navigation or gate a loading skeleton on `useMarkdownParserReady()` (`packages/app/src/components/markdown/parser-ready.ts`) so cold web mounts do not paint an empty interim container. Chat owns paced reveal, the web render cap, message identity and list measurement. A completed message renders as one document. While streaming, the renderer keeps closed blocks in head parts and updates a separate tail, then reunites the text on completion. See [Markdown parsing cost](agent-stream-performance.md#markdown-parsing-cost) for the boundary and pacing constraints.
|
||||
|
||||
## Block spacing
|
||||
|
||||
Every block is separated by one gap, `density.blockGap`: 12 on compact layouts, 16 wider. Inside the library's text, every element style ends with that gap and the library drops it after the last block. Views stacked outside the library (Mermaid segments, streaming head and tail) use the same gap through `MarkdownBlockStack`. Do not give a block type its own margins; change the gap.
|
||||
Every block is separated by one gap, `density.blockGap`: 12 on compact layouts, 16 wider. Inside the library's text, every element style ends with that gap and the library drops it after the last block. Views stacked outside the library (Mermaid segments, streaming head parts and tail) use the same gap through `MarkdownBlockStack`. Do not give a block type its own margins; change the gap.
|
||||
|
||||
## Links and images
|
||||
|
||||
@@ -14,7 +14,11 @@ Workspace file links use the shared file-link resolver. The workspace supplies i
|
||||
|
||||
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.
|
||||
Compose the renderer's capabilities per surface instead of bundling them under one flag:
|
||||
|
||||
- `destinations="https"` restricts links and images to absolute `https://` destinations following the registry's overview contract in `packages/protocol/src/plugin-overview.ts` (which the website also uses). Any other destination renders as its label or alt text, no host files are read via `client.readFile`, and workspace path recognition is off so `Node.js` stays prose. The parser still autolinks bare `http://`, `www.` and email text, so a link press checks the URL again and opens only `https://`.
|
||||
- `forgeShorthand` (default `true`) controls whether `#12` / `owner/repo#12` references resolve against the workspace's `ForgeShorthandProvider`. Pull request comments keep `destinations="https"` with `forgeShorthand` enabled; plugin READMEs and the changelog disable `forgeShorthand` so they never link to whichever workspace happens to be open.
|
||||
- `softBreaks` (`"break"` default, `"join"` for READMEs and changelogs) controls whether single newlines inside a paragraph become hard breaks or join into one line as they do on a 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).
|
||||
|
||||
|
||||
@@ -146,9 +146,10 @@ definition, no longer eligible to begin.
|
||||
- Panels whose gesture wrapper already owns visibility use `RetainedPanelActivity` to provide the
|
||||
same active signal without adding another layout root. Persistent animations, timers, polling, and
|
||||
shared clocks must subscribe to that signal and stop when their final visible consumer leaves.
|
||||
- Synchronized step animations use one wall-clock-aligned source. Register a local shared value only
|
||||
while its retained panel is active so hidden animated styles remain mounted without receiving clock
|
||||
updates. Do not give every instance its own loop or leave hidden styles subscribed to the source.
|
||||
- Synchronized step animations use one source. Do not give every instance its own loop. A hidden
|
||||
instance stops running the source and keeps its place, because the active signal changes after the
|
||||
panel has slid into view; see
|
||||
[running-indicators.md](running-indicators.md#hidden-panels).
|
||||
- Retention order and render order are separate concerns. LRU metadata may change on every switch;
|
||||
keyed retained roots must keep a stable sibling order. Moving large retained roots triggered Fabric
|
||||
Differ failures (`addViewAt` / `removeViewAt` view reuse) on Android.
|
||||
|
||||
+53
-13
@@ -14,14 +14,37 @@ value.
|
||||
|
||||
`components/indicator-motion` owns the two pieces every indicator shares:
|
||||
|
||||
- `useIndicatorMotion()` decides whether an indicator may move: not under reduced motion, not in a
|
||||
retained panel that is not showing, not while the app is in the background. An indicator that may
|
||||
not move draws its resting frame and runs nothing. Ask this hook; do not read reduced motion or
|
||||
visibility yourself.
|
||||
- `useIndicatorMotion()` says what an indicator does now. Ask this hook; do not read reduced motion
|
||||
or visibility yourself.
|
||||
- `moving`: it runs.
|
||||
- `held`: nobody can see it, in a retained panel that is not showing or in an app in the
|
||||
background. It runs nothing and keeps its place.
|
||||
- `resting`: the system asks for reduced motion. It draws its resting frame and runs nothing.
|
||||
- The driver: `loop.web.ts` on web, `clock.ts` on native.
|
||||
|
||||
Animate only `transform` and `opacity`. Anything else is painted on the main thread every frame.
|
||||
|
||||
## Hidden panels
|
||||
|
||||
A phone's sidebar slides into view before its panel counts as showing: the panel's active signal
|
||||
changes when the slide settles, never during it (see [mobile-panels.md](mobile-panels.md)). An
|
||||
indicator that changes what it draws on that signal changes it in front of the user. A held ring
|
||||
that drew its resting position jumped to the running position at the end of every slide.
|
||||
|
||||
So on native a held indicator stays bound to its clock and stops running it:
|
||||
|
||||
- The clock and the loader's ticker count the time they have run, and hold it while nothing runs
|
||||
them. They are never set back to zero or to the wall clock.
|
||||
- While another panel runs the clock, a held view follows it. Measured on an Android emulator with
|
||||
six held rings behind a running chat, the app drew the same frames a second as with the rings
|
||||
unbound, and CPU on each thread differed by less than it does between two runs.
|
||||
- While nothing runs the clock, a held view costs nothing: behind an idle chat the app draws no
|
||||
frames.
|
||||
- One commit can stop the last moving indicator and start another, as when the sidebar replaces the
|
||||
chat. The clock stops after the commit, so it counts through that without a restart.
|
||||
|
||||
Web does not do this: a held indicator on web cancels its loop and draws its resting frame.
|
||||
|
||||
## Frames
|
||||
|
||||
Keeping the animation off the React thread does not make it free. Every time an indicator moves,
|
||||
@@ -88,11 +111,27 @@ For a transition that is fine. For an indicator that runs for an hour it was 22
|
||||
the UI thread of an Android emulator.
|
||||
|
||||
React Native's own `Animated` with `useNativeDriver: true` updates the view from the native driver
|
||||
and commits nothing. `clock.ts` builds a clock out of it: a decay that never slows, at one unit per
|
||||
millisecond, is the time since it started. Decay is the one native-driven animation that computes
|
||||
its value from the frame timestamp instead of replaying a 60 fps recording, so it is exact at any
|
||||
refresh rate and needs no loop restart. `Animated.modulo` and `interpolate` turn the clock into a
|
||||
rotation or a translation, all inside the native driver.
|
||||
and commits nothing. `clock.ts` builds a clock out of it: a linear timing at one unit per
|
||||
millisecond is the time since the clock started. `Animated.modulo` and `interpolate` turn the clock
|
||||
into a rotation or a translation, all inside the native driver.
|
||||
|
||||
The timing counts in spans of ten minutes. The end of a span is the one event that reaches the JS
|
||||
thread, which starts the next span where that one ended, so a cycle keeps its place from one span to
|
||||
the next.
|
||||
|
||||
The native driver owns the clock's value. The JS thread starts and stops the counting and never
|
||||
sets the value, so a stopped clock keeps the value its views show. When the clock stops, the driver
|
||||
reports the value it stopped at, and the next start counts on from it.
|
||||
|
||||
Do not drive the clock with a decay. A decay that never slows counts time without spans, but the
|
||||
driver ends a decay when its value moves less than 0.1 between two frames, whatever the
|
||||
deceleration. Two frames that carry the same millisecond are enough, and then every indicator on
|
||||
the clock freezes. Starting the decay again from the JS thread shows as a pause and a jump each
|
||||
time.
|
||||
|
||||
Android replays a timing as 60 positions a second at any refresh rate, and iOS interpolates between
|
||||
them. Every cycle on the clock is stepped at 30 positions a second, so this does not show. A cycle
|
||||
without steps would move 60 times a second on a 120 Hz Android display.
|
||||
|
||||
`cycle(periodMs, { steps })` holds the position at each step. The driver still ticks every frame,
|
||||
but a view whose transform did not change is not invalidated, so nothing is drawn between steps.
|
||||
@@ -100,14 +139,15 @@ but a view whose transform did not change is not invalidated, so nothing is draw
|
||||
The native clock starts on the frame where the driver picks it up, so two clocks started at
|
||||
different times turn their steps over on different frames. That is why the shimmer rides
|
||||
`sharedIndicatorClock`, the rings' clock, with `phase: "own"`: its pass starts at the clock's
|
||||
current step. The JS thread works out that step from the time it started the clock. The driver
|
||||
current step. The JS thread works out that step from the time it started the clock and the value
|
||||
the clock started from. The driver
|
||||
starts the clock a frame or two later, so a pass can start one step early or late. The band starts
|
||||
one band width outside the label, so this does not show.
|
||||
|
||||
The loader changes six times per cycle, so it does not ride the frame clock. `step-ticker.ts` wakes
|
||||
the JS thread once per step, aligned to wall-clock step boundaries, and publishes the step into a
|
||||
native `Animated.Value`. A wake-up that arrives late publishes the step that is current by then, so
|
||||
the loader never drifts and every loader shows the same step.
|
||||
the JS thread once per step and publishes the step into a native `Animated.Value`. A wake-up that
|
||||
arrives late publishes the step that is current by then, so the loader never drifts. Every loader
|
||||
reads the one value, so they all show the same step.
|
||||
|
||||
Do not apply Unistyles dynamic styles to these `Animated.View`s; see
|
||||
[unistyles.md](unistyles.md#reanimated-animatedview--dynamic-styles-crashes).
|
||||
|
||||
@@ -172,9 +172,10 @@ is offline and until a reconnected chat's check answers, so an unchanged chat ne
|
||||
toast. Returning from background on a socket that stayed connected shows nothing until the check
|
||||
answers: the chat stayed subscribed, so a slow answer is no reason to doubt it, and a socket that
|
||||
died without closing fails the foreground liveness probe and becomes a reconnect. Updating messages
|
||||
appears for a chat that is behind, until the fetch completes, and for an opened chat whose check is
|
||||
still unanswered `FRESHNESS_CHECK_QUIET_MS` after it was sent. That delay measures the daemon, so it
|
||||
starts at the request: on a cold start the cache read alone can take longer. Socket connectivity
|
||||
appears for a chat that is behind, until the fetch completes, and for an opened chat whose check or
|
||||
cursorless initial tail catch-up (such as a display-only cache) is still unanswered
|
||||
`FRESHNESS_CHECK_QUIET_MS` after the subscribe request was sent. That delay measures the daemon, so
|
||||
it starts at the request: on a cold start the cache read alone can take longer. Socket connectivity
|
||||
alone cannot certify that the displayed conversation is current. The timeline owner publishes freshness; the view renders it without a toast timer or a
|
||||
separate resume workflow.
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-04BfmBEaEZy3ohSi3Z8S3/a3xBsLKhls+8mcjJ0Y2/A=
|
||||
sha256-x6E6SY98/8pUNLomlPzSNedZ+ZKJPzsQeS9L455i+n0=
|
||||
|
||||
Generated
+7
@@ -12136,6 +12136,12 @@
|
||||
"dev": true,
|
||||
"license": "BSD-3-Clause"
|
||||
},
|
||||
"node_modules/@silvia-odwyer/photon-node": {
|
||||
"version": "0.3.4",
|
||||
"resolved": "https://registry.npmjs.org/@silvia-odwyer/photon-node/-/photon-node-0.3.4.tgz",
|
||||
"integrity": "sha512-bnly4BKB3KDTFxrUIcgCLbaeVVS8lrAkri1pEzskpmxu9MdfGQTy8b8EgcD83ywD3RPMsIulY8xJH5Awa+t9fA==",
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@sinclair/typebox": {
|
||||
"version": "0.27.10",
|
||||
"resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.10.tgz",
|
||||
@@ -40615,6 +40621,7 @@
|
||||
"@modelcontextprotocol/server": "2.4.0",
|
||||
"@opencode-ai/sdk": "1.14.46",
|
||||
"@opencode/client": "2.0.10",
|
||||
"@silvia-odwyer/photon-node": "^0.3.4",
|
||||
"@xterm/addon-serialize": "0.14.0",
|
||||
"@xterm/addon-unicode-graphemes": "0.5.0-beta.330",
|
||||
"@xterm/headless": "6.1.0-beta.334",
|
||||
|
||||
@@ -125,10 +125,17 @@ for (const theme of ["light", "dark"] as const) {
|
||||
await expect(
|
||||
page.getByRole("button", { name: "Hoplite provider details", exact: true }),
|
||||
).toHaveCount(0);
|
||||
expect((await client.getDaemonConfig()).config.providers?.hoplite).toBeUndefined();
|
||||
expect(
|
||||
(await client.getProvidersSnapshot()).entries.some((entry) => entry.provider === "hoplite"),
|
||||
).toBe(false);
|
||||
// The row leaves the list once Remove is confirmed, before the daemon answers.
|
||||
await expect
|
||||
.poll(async () => (await client.getDaemonConfig()).config.providers?.hoplite)
|
||||
.toBeUndefined();
|
||||
await expect
|
||||
.poll(async () =>
|
||||
(await client.getProvidersSnapshot()).entries.some(
|
||||
(entry) => entry.provider === "hoplite",
|
||||
),
|
||||
)
|
||||
.toBe(false);
|
||||
await writeFile(
|
||||
testInfo.outputPath(`hoplite-removed-${theme}.json`),
|
||||
JSON.stringify(await client.getProvidersSnapshot(), null, 2),
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
answerFreshnessCheck,
|
||||
commitTimelineTurnsWhileDisconnected,
|
||||
disconnectViewedTimeline,
|
||||
expectCleanLoadingSurfaces,
|
||||
expectEmptyChatSynced,
|
||||
expectPromptAndWholeReply,
|
||||
expectResumeAnsweredWithoutFetch,
|
||||
@@ -26,11 +27,14 @@ import {
|
||||
restoreViewedTimelineWithHeldResponse,
|
||||
restoreViewedTimelineWithLiveRowsFirst,
|
||||
reopenWithFreshnessCheckUnanswered,
|
||||
reopenWithTimelineTailUnanswered,
|
||||
seedStreamingReplyAgent,
|
||||
sendPromptWhileDisconnected,
|
||||
stopStreamingReply,
|
||||
waitForDisplayOnlyTimelineCache,
|
||||
waitForResumeAnswer,
|
||||
reopenAppWatchingForUpdatingToast,
|
||||
watchColdAndReloadLoadingSurfaces,
|
||||
watchForUpdatingToast,
|
||||
} from "../support/helpers/timeline-resume";
|
||||
|
||||
@@ -176,4 +180,36 @@ test.describe("Agent timeline resume", () => {
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("cold opens and display-only cache reloads keep loading steady and reserve Updating messages for slow replies", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const agent = await seedLongMockAgentTimeline({ turns: 30 });
|
||||
try {
|
||||
await watchColdAndReloadLoadingSurfaces(page);
|
||||
|
||||
await test.step("cold open fetches one tail without showing a premature toast", async () => {
|
||||
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
|
||||
await openAgentTimeline(page, agent);
|
||||
await expectTimelinePromptVisible(page, agent.newestPrompt);
|
||||
await expectCleanLoadingSurfaces(page, gate, requests);
|
||||
});
|
||||
|
||||
await test.step("display-only cached reload shows Updating messages until the overdue tail arrives", async () => {
|
||||
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.firstOlderPagePrompt);
|
||||
await waitForDisplayOnlyTimelineCache(page, agent);
|
||||
|
||||
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
|
||||
await reopenWithTimelineTailUnanswered({ page, gate, agentId: agent.agentId });
|
||||
await expectTimelinePromptVisible(page, agent.newestPrompt);
|
||||
gate.releaseHeldTimelineResponses();
|
||||
await expectCleanLoadingSurfaces(page, gate, requests);
|
||||
});
|
||||
} finally {
|
||||
gate.restore();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
expectAttachButtonDisabled,
|
||||
fillComposerDraft,
|
||||
dropFileOnComposer,
|
||||
pasteFilesIntoComposer,
|
||||
sendDraftToQueue,
|
||||
expectQueuedMessageButton,
|
||||
startRunningMockAgent,
|
||||
@@ -152,7 +153,7 @@ test.describe("Composer attachments", () => {
|
||||
// needed before this can be exercised end-to-end.
|
||||
});
|
||||
|
||||
test("attaches, previews, and removes an image before dropping a file", async ({
|
||||
test("attaches files from the menu, clipboard, and drag and drop", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
@@ -185,6 +186,19 @@ test.describe("Composer attachments", () => {
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("paste a Markdown file into the composer", async () => {
|
||||
const file = {
|
||||
name: "notes.md",
|
||||
mimeType: "text/markdown",
|
||||
buffer: Buffer.from("# Clipboard notes"),
|
||||
};
|
||||
const handled = await pasteFilesIntoComposer(page, [file]);
|
||||
await expect(page.getByText(file.name, { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
|
||||
expect(handled).toBe(true);
|
||||
await expectComposerDraft(page, "");
|
||||
});
|
||||
|
||||
await test.step("dropping an image focuses the composer", async () => {
|
||||
await blurComposerInput(page);
|
||||
await expectComposerNotFocused(page);
|
||||
@@ -192,6 +206,15 @@ test.describe("Composer attachments", () => {
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
await expectComposerFocused(page);
|
||||
});
|
||||
|
||||
await test.step("paste a file and an image together", async () => {
|
||||
await removeAttachmentPill(page, "composer-image-attachment-pill", "Remove image attachment");
|
||||
await expect(page.getByTestId("composer-image-attachment-pill")).toHaveCount(0);
|
||||
const file = { ...TEST_JSON, name: "clipboard.json" };
|
||||
await pasteFilesIntoComposer(page, [file, TEST_IMAGE]);
|
||||
await expect(page.getByRole("button", { name: file.name, exact: true })).toBeVisible();
|
||||
await expectAttachmentPill(page, "composer-image-attachment-pill");
|
||||
});
|
||||
});
|
||||
|
||||
test("dropped JSON file renders as a file attachment in New Workspace", async ({ page }) => {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { seedMockAgentWorkspace, openAgentRoute } from "../support/helpers/mock-agent";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { installDaemonWebSocketGate } from "../support/helpers/daemon-websocket-gate";
|
||||
import { openFileFromExplorer } from "../support/helpers/file-explorer";
|
||||
import { waitForWorkspaceInReplicaCache } from "../support/helpers/replica-cache-storage";
|
||||
import { openSettingsSection, clickSettingsBackToWorkspace } from "../support/helpers/settings";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import {
|
||||
@@ -547,3 +550,64 @@ test("keeps the comment shortcut in the editor beside an Explorer agent", async
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
async function restoreHostConnection(gate: Awaited<ReturnType<typeof installDaemonWebSocketGate>>) {
|
||||
gate.holdNextServerMessage("status");
|
||||
gate.restore();
|
||||
await gate.waitForHeldServerMessage("status");
|
||||
gate.releaseHeldServerMessage("status");
|
||||
}
|
||||
|
||||
test("loads Files and file filter automatically once the host connects after launch or disconnect", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const workspace = await withWorkspace();
|
||||
await writeFile(path.join(workspace.repoPath, "startup-repro.txt"), "hello\n", "utf8");
|
||||
|
||||
await test.step("open Files on the workspace before reloading", async () => {
|
||||
await workspace.navigateTo();
|
||||
const explorer = await ensureExplorerSidebar(page);
|
||||
await openFilesPanel(page);
|
||||
await expect(
|
||||
explorer
|
||||
.getByTestId("file-explorer-tree-scroll")
|
||||
.getByText("startup-repro.txt", { exact: true }),
|
||||
).toBeVisible();
|
||||
await waitForWorkspaceInReplicaCache(page, workspace.workspaceId);
|
||||
});
|
||||
|
||||
await test.step("reload while the host is unreachable and recover automatically on connect", async () => {
|
||||
await gate.drop();
|
||||
await page.reload();
|
||||
await gate.waitForBlockedConnection();
|
||||
|
||||
const explorer = explorerSidebar(page);
|
||||
await expect(explorer).toBeVisible();
|
||||
|
||||
await restoreHostConnection(gate);
|
||||
|
||||
await expect(
|
||||
explorer
|
||||
.getByTestId("file-explorer-tree-scroll")
|
||||
.getByText("startup-repro.txt", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(explorer.getByText("Host is not connected", { exact: true })).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("filter Files while disconnected and recover automatically on reconnect", async () => {
|
||||
const explorer = explorerSidebar(page);
|
||||
await gate.drop();
|
||||
await gate.waitForBlockedConnection();
|
||||
|
||||
await explorer.getByPlaceholder("Search files").fill("startup-repro");
|
||||
|
||||
await restoreHostConnection(gate);
|
||||
|
||||
await expect(
|
||||
explorer.getByTestId("file-filter-results").getByText("startup-repro.txt", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(explorer.getByText("Host is not connected", { exact: true })).toHaveCount(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -199,6 +199,39 @@ test("shows listing failure details beside healthy sessions and retries the fail
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps a request timeout visible while retrying the provider", async ({ page }) => {
|
||||
const gate = await installDaemonWebSocketGate(page);
|
||||
const flow = new ImportSessionFlow(page);
|
||||
await flow.openWorkspace(scenario.project.workspaceId, { width: 1280, height: 844 });
|
||||
await page.clock.install();
|
||||
|
||||
await test.step("the first listings time out before any response reaches the sheet", async () => {
|
||||
gate.setServerMessageSuppressed("fetch_recent_provider_sessions_response", true);
|
||||
await flow.openFromWorkspaceHeader();
|
||||
await expect
|
||||
.poll(() => gate.getClientRequestCount("fetch_recent_provider_sessions_request"))
|
||||
.toBeGreaterThanOrEqual(2);
|
||||
await page.clock.fastForward(101_000);
|
||||
await flow.expectProviderError("Claude");
|
||||
await flow.expectProviderRequestTimeout();
|
||||
gate.setServerMessageSuppressed("fetch_recent_provider_sessions_response", false);
|
||||
});
|
||||
|
||||
await test.step("Retry keeps the timeout visible until Claude replies", async () => {
|
||||
gate.holdNextClientRequest("fetch_recent_provider_sessions_request");
|
||||
await flow.startProviderRetry("claude");
|
||||
await gate.waitForHeldClientRequest();
|
||||
await flow.expectProviderRetryPending("claude");
|
||||
await flow.expectProviderError("Claude");
|
||||
await flow.expectProviderRequestTimeout();
|
||||
gate.releaseHeldClientRequest();
|
||||
|
||||
await flow.expectProviderRecovered("Claude");
|
||||
await flow.expectRows({ first: [scenario.importSessionId] });
|
||||
await flow.expectProviderError("Broken ACP");
|
||||
});
|
||||
});
|
||||
|
||||
test("Import Session keeps listings tied to their host during a switch and a pending import", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { expectComposerDraft, fillComposerDraft } from "../support/helpers/composer";
|
||||
import { gotoWorkspace } from "../support/helpers/launcher";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import { waitForDraftComposer } from "../support/helpers/command-center-agent-controls";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
|
||||
const openText = "Keep this open New Agent draft";
|
||||
const orphanText = "Unreachable draft from an earlier version";
|
||||
const existingAgentText = "Keep this archived conversation draft";
|
||||
|
||||
async function openDraftTab(page: Page): Promise<void> {
|
||||
await runWorkspaceActionFromCommandCenter(page, "New agent");
|
||||
await waitForDraftComposer(page);
|
||||
}
|
||||
|
||||
async function persistedDraftTexts(page: Page): Promise<string[]> {
|
||||
return page.evaluate(() => {
|
||||
const drafts = JSON.parse(localStorage.getItem("paseo-drafts") ?? "{}").state?.drafts ?? {};
|
||||
return Object.values(drafts).map(
|
||||
(record) => (record as { input: { text: string } }).input.text,
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
async function seedOrphanBeforeUpgrade(page: Page): Promise<void> {
|
||||
await page.evaluate(
|
||||
({ orphan, archived }) => {
|
||||
const makeDraft = (text: string) => ({
|
||||
input: { text, attachments: [] },
|
||||
lifecycle: "active",
|
||||
updatedAt: Date.now(),
|
||||
version: 1,
|
||||
});
|
||||
const envelope = JSON.parse(localStorage.getItem("paseo-drafts") ?? "{}");
|
||||
envelope.state.drafts["draft:old-server:previously-closed-tab"] = makeDraft(orphan);
|
||||
envelope.state.drafts["agent:old-server:archived-agent"] = makeDraft(archived);
|
||||
localStorage.setItem("paseo-drafts", JSON.stringify(envelope));
|
||||
localStorage.removeItem("paseo:orphaned-workspace-drafts-swept");
|
||||
const nonce = localStorage.getItem("@paseo:e2e-seed-nonce");
|
||||
if (nonce) localStorage.setItem("@paseo:e2e-disable-default-seed-once", nonce);
|
||||
},
|
||||
{ orphan: orphanText, archived: existingAgentText },
|
||||
);
|
||||
}
|
||||
|
||||
async function closeDraftWithShortcut(page: Page, answer: "cancel" | "discard"): Promise<void> {
|
||||
const prompt = page.waitForEvent("dialog");
|
||||
const shortcut = page.keyboard.press("Alt+Shift+w");
|
||||
const dialog = await prompt;
|
||||
expect(dialog.message()).toContain("Unsaved changes");
|
||||
if (answer === "cancel") await dialog.dismiss();
|
||||
else await dialog.accept();
|
||||
await shortcut;
|
||||
}
|
||||
|
||||
test("keeps open New Agent drafts through upgrade and confirms before discarding them", async ({
|
||||
page,
|
||||
}) => {
|
||||
const workspace = await seedWorkspace({ repoPrefix: "discard-new-agent-draft-" });
|
||||
try {
|
||||
await gotoWorkspace(page, workspace.workspaceId);
|
||||
await openDraftTab(page);
|
||||
await fillComposerDraft(page, openText);
|
||||
await expect.poll(() => persistedDraftTexts(page)).toContain(openText);
|
||||
await seedOrphanBeforeUpgrade(page);
|
||||
|
||||
await page.reload();
|
||||
await expectComposerDraft(page, openText);
|
||||
await expect.poll(() => persistedDraftTexts(page)).not.toContain(orphanText);
|
||||
await expect.poll(() => persistedDraftTexts(page)).toContain(existingAgentText);
|
||||
|
||||
await closeDraftWithShortcut(page, "cancel");
|
||||
await expectComposerDraft(page, openText);
|
||||
|
||||
await closeDraftWithShortcut(page, "discard");
|
||||
await expect.poll(() => persistedDraftTexts(page)).not.toContain(openText);
|
||||
await openDraftTab(page);
|
||||
await expectComposerDraft(page, "");
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
});
|
||||
@@ -11,6 +11,7 @@ import {
|
||||
installBrowserNotificationRecorder,
|
||||
openNotificationSettings,
|
||||
readRecordedBrowserNotifications,
|
||||
reloadAndWaitForDevicePresence,
|
||||
setNotificationSwitch,
|
||||
setPluginNotificationSwitch,
|
||||
} from "../support/helpers/notification-settings";
|
||||
@@ -107,7 +108,7 @@ test.describe("Settings → Notifications and OS notification filtering", () =>
|
||||
|
||||
await test.step("enabling Agent finished persists across page reload and allows finished notifications", async () => {
|
||||
await setNotificationSwitch(page, "Agent finished", true);
|
||||
await page.reload();
|
||||
await reloadAndWaitForDevicePresence(page);
|
||||
await expectNotificationSwitchState(page, "Agent finished", {
|
||||
checked: true,
|
||||
disabled: false,
|
||||
@@ -137,7 +138,7 @@ test.describe("Settings → Notifications and OS notification filtering", () =>
|
||||
).toBeVisible();
|
||||
await expectNotificationSubControlsDisabled(page, true);
|
||||
|
||||
await page.reload();
|
||||
await reloadAndWaitForDevicePresence(page);
|
||||
await expectNotificationSwitchState(page, "Enable notifications", {
|
||||
checked: false,
|
||||
disabled: false,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { createHostClient } from "@getpaseo/client/node";
|
||||
import { expect } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
addDirectHostFromSettings,
|
||||
@@ -24,11 +26,51 @@ import {
|
||||
slowConnectionToHost,
|
||||
expectTailscaleUpdateRequired,
|
||||
expectCompletePairingQr,
|
||||
expectConnectedClientRow,
|
||||
expectRelayConsent,
|
||||
expandConnectedClientRow,
|
||||
openDevicesPage,
|
||||
openPairDeviceModal,
|
||||
preparePairingHost,
|
||||
returnFromRelayToWaysToConnect,
|
||||
} from "../support/helpers/pair-device";
|
||||
|
||||
test("lists connected clients with scopes and navigates Pair a device → Relay → Back", async ({
|
||||
page,
|
||||
}) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-connected-clients", {
|
||||
mutableRelay: { enabled: true },
|
||||
});
|
||||
const viewer = createHostClient(`127.0.0.1:${daemon.port}`, {
|
||||
clientId: "cid_e2e_phone_viewer",
|
||||
clientType: "mobile",
|
||||
appVersion: "0.18.1",
|
||||
clientInfo: { name: "Test Phone", platform: "ios" },
|
||||
sessionPermissions: ["daemon.read", "workspace.read"],
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
try {
|
||||
await openDevicesPage(page, daemon);
|
||||
await expectConnectedClientRow(page, "This device", "Full access");
|
||||
await expandConnectedClientRow(page, "This device");
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("devices-connected-clients-card")
|
||||
.getByText("access.manage", { exact: true }),
|
||||
).toBeVisible();
|
||||
|
||||
await viewer.connect();
|
||||
await expectConnectedClientRow(page, "Test Phone", "Read-only");
|
||||
|
||||
await openPairDeviceModal(page);
|
||||
await expectPairingOffer(page);
|
||||
await returnFromRelayToWaysToConnect(page);
|
||||
} finally {
|
||||
await viewer.close();
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("opens relay consent in browser web", async ({ page }) => {
|
||||
const daemon = await startIsolatedHostDaemon("pair-device-browser-relay-off", {
|
||||
mutableRelay: { enabled: false },
|
||||
@@ -81,7 +123,7 @@ test("turns Tailscale on and off from Devices, asking first over Tailscale", asy
|
||||
}, testInfo) => {
|
||||
test.skip(process.platform !== "linux", "Uses a second IPv4 loopback address");
|
||||
// The journey opens Devices or the setup six times, two of them over a slowed connection.
|
||||
test.setTimeout(120_000);
|
||||
test.setTimeout(180_000);
|
||||
if (!baseURL) throw new Error("Expected the app base URL");
|
||||
const daemon = await startTailscaleTestDaemon(baseURL);
|
||||
try {
|
||||
|
||||
@@ -2,6 +2,10 @@ import path from "node:path";
|
||||
import { expect } from "../support/fixtures";
|
||||
import {
|
||||
test,
|
||||
expectInstantPrefetchedRelatedOpen,
|
||||
expectStableDesktopBackToListing,
|
||||
expectStableUncachedListingOpen,
|
||||
expectStackedFirstFrameOnNarrowDesktop,
|
||||
expectStillBrowsing,
|
||||
installFromPage,
|
||||
installListingFromRow,
|
||||
@@ -80,3 +84,89 @@ test("shows scorecard progressive disclosure, updates, custom links, and related
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-mobile-scorecard.png") });
|
||||
}
|
||||
});
|
||||
|
||||
test("renders branded sponsor buttons for single and stacked platforms in light and dark themes", async ({
|
||||
page,
|
||||
directoryHost,
|
||||
}) => {
|
||||
const captureDir = process.env.PASEO_CAPTURE_DIR;
|
||||
await page.setViewportSize({ width: 1280, height: 1000 });
|
||||
await page.emulateMedia({ colorScheme: "dark" });
|
||||
await openDirectory(page, directoryHost);
|
||||
await openListingPage(page);
|
||||
|
||||
const singleGithub = page.getByTestId("funding-button-github");
|
||||
await expect(singleGithub).toBeVisible();
|
||||
await expect(singleGithub).toContainText("Sponsor on GitHub");
|
||||
await expect(singleGithub).toHaveCSS("background-color", "rgba(219, 97, 162, 0.1)");
|
||||
await expect(singleGithub).toHaveCSS("border-top-color", "rgba(219, 97, 162, 0.32)");
|
||||
await expect(singleGithub.locator("svg")).toHaveAttribute("fill", "#ea7bb3");
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "app-gallery-single-dark.png") });
|
||||
}
|
||||
|
||||
await page.emulateMedia({ colorScheme: "light" });
|
||||
await expect(singleGithub).toBeVisible();
|
||||
await expect(singleGithub).toHaveCSS("background-color", "rgba(191, 57, 137, 0.08)");
|
||||
await expect(singleGithub).toHaveCSS("border-top-color", "rgba(191, 57, 137, 0.3)");
|
||||
await expect(singleGithub.locator("svg")).toHaveAttribute("fill", "#bf3989");
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "app-gallery-single-light.png") });
|
||||
}
|
||||
|
||||
await page.getByTestId("plugin-related-acme/pr-radar").click();
|
||||
const platforms = [
|
||||
["github", "Sponsor on GitHub"],
|
||||
["kofi", "Support on Ko-fi"],
|
||||
["buymeacoffee", "Buy Me a Coffee"],
|
||||
["opencollective", "Sponsor on Open Collective"],
|
||||
["patreon", "Support on Patreon"],
|
||||
["polar", "Sponsor on Polar"],
|
||||
["liberapay", "Donate on Liberapay"],
|
||||
["paypal", "Donate via PayPal"],
|
||||
["custom", "Sponsor"],
|
||||
] as const;
|
||||
|
||||
for (const [platform, label] of platforms) {
|
||||
const btn = page.getByTestId(`funding-button-${platform}`).filter({ visible: true });
|
||||
await expect(btn).toBeVisible();
|
||||
await expect(btn).toContainText(label);
|
||||
}
|
||||
const stackedKofi = page.getByTestId("funding-button-kofi").filter({ visible: true });
|
||||
await expect(stackedKofi).toHaveCSS("background-color", "rgba(217, 67, 64, 0.08)");
|
||||
await expect(stackedKofi.locator("svg")).toHaveAttribute("fill", "#d94340");
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "app-gallery-stacked-light.png") });
|
||||
}
|
||||
|
||||
await page.emulateMedia({ colorScheme: "dark" });
|
||||
for (const [platform] of platforms) {
|
||||
await expect(
|
||||
page.getByTestId(`funding-button-${platform}`).filter({ visible: true }),
|
||||
).toBeVisible();
|
||||
}
|
||||
await expect(stackedKofi).toHaveCSS("background-color", "rgba(255, 94, 91, 0.1)");
|
||||
await expect(stackedKofi.locator("svg")).toHaveAttribute("fill", "#ff7a78");
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "app-gallery-stacked-dark.png") });
|
||||
}
|
||||
});
|
||||
|
||||
test("opens plugin pages without empty markdown collapse, stacked back flash, or layout shift", async ({
|
||||
page,
|
||||
directoryHost,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 1280, height: 960 });
|
||||
directoryHost.setDetailDelayMs(250);
|
||||
await openDirectory(page, directoryHost);
|
||||
|
||||
await expectStableUncachedListingOpen(page);
|
||||
await expectInstantPrefetchedRelatedOpen(page, directoryHost);
|
||||
await expectStableDesktopBackToListing(page);
|
||||
await expectStackedFirstFrameOnNarrowDesktop(page);
|
||||
});
|
||||
|
||||
@@ -2,6 +2,8 @@ import path from "node:path";
|
||||
import type { Page, TestInfo } from "@playwright/test";
|
||||
import { test, expect } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { addConnectedHostsAndReload } from "../support/helpers/hosts";
|
||||
import { startIsolatedHostDaemon } from "../support/helpers/isolated-host-daemon";
|
||||
import {
|
||||
closeMobileAgentSidebar,
|
||||
expectMobileAgentSidebarHidden,
|
||||
@@ -141,6 +143,7 @@ async function withPaseoOwnedWorktree(
|
||||
async function readCachedRowIds(
|
||||
page: Page,
|
||||
rowKind: "workspace" | "checkpoint",
|
||||
hostServerId = getServerId(),
|
||||
): Promise<string[]> {
|
||||
return page.evaluate(
|
||||
async ({ serverId, kind }) => {
|
||||
@@ -169,7 +172,7 @@ async function readCachedRowIds(
|
||||
database.close();
|
||||
}
|
||||
},
|
||||
{ serverId: getServerId(), kind: rowKind },
|
||||
{ serverId: hostServerId, kind: rowKind },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -317,7 +320,60 @@ async function expectRecoveredWorkspacesAfterReload(
|
||||
});
|
||||
}
|
||||
|
||||
async function expectTimeSortingAvailable(page: Page): Promise<void> {
|
||||
await page.getByLabel("Display preferences", { exact: true }).click();
|
||||
await page.getByRole("menuitem", { name: /^Sort/ }).click();
|
||||
await expect(page.getByRole("menuitem", { name: "Created", exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("menuitem", { name: "Last prompt", exact: true })).toBeVisible();
|
||||
await page.getByRole("menuitem", { name: "Created", exact: true }).click();
|
||||
await page.getByLabel("Display preferences", { exact: true }).click();
|
||||
await expect(page.getByRole("menuitem", { name: /^Sort/ })).toContainText("Created");
|
||||
await page.keyboard.press("Escape");
|
||||
}
|
||||
|
||||
async function cacheSecondaryHostWorkspace(page: Page, serverId: string, workspaceId: string) {
|
||||
await expect(page.getByTestId(`sidebar-workspace-row-${serverId}:${workspaceId}`)).toBeVisible();
|
||||
await expect.poll(() => readCachedRowIds(page, "workspace", serverId)).toContain(workspaceId);
|
||||
}
|
||||
|
||||
test.describe("Sidebar workspace list", () => {
|
||||
test("keeps time sorting when a host's cached workspaces load offline", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const laptop = await startIsolatedHostDaemon("sidebar-sort-laptop");
|
||||
try {
|
||||
const other = await startIsolatedHostDaemon("sidebar-sort-other");
|
||||
try {
|
||||
const workspace = await seedWorkspace({
|
||||
repoPrefix: "sidebar-sort-laptop-",
|
||||
port: laptop.port,
|
||||
});
|
||||
try {
|
||||
await gotoAppShell(page);
|
||||
const hosts = [
|
||||
{ ...laptop, label: "Laptop" },
|
||||
{ ...other, label: "Other host" },
|
||||
];
|
||||
await test.step("cache the laptop workspace while its host is online", async () => {
|
||||
await addConnectedHostsAndReload(page, hosts);
|
||||
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
|
||||
await expectTimeSortingAvailable(page);
|
||||
});
|
||||
await test.step("reopen the sidebar with the laptop offline", async () => {
|
||||
await laptop.close();
|
||||
await addConnectedHostsAndReload(page, hosts);
|
||||
await cacheSecondaryHostWorkspace(page, laptop.serverId, workspace.workspaceId);
|
||||
await expectTimeSortingAvailable(page);
|
||||
});
|
||||
} finally {
|
||||
await workspace.cleanup();
|
||||
}
|
||||
} finally {
|
||||
await other.close();
|
||||
}
|
||||
} finally {
|
||||
await laptop.close();
|
||||
}
|
||||
});
|
||||
test("recovers missing workspaces from a damaged legacy cache after reload", async ({
|
||||
page,
|
||||
}, testInfo) => {
|
||||
|
||||
@@ -34,7 +34,9 @@ function report(input: {
|
||||
sourceLabel: input.sourceLabel,
|
||||
icon: ICON,
|
||||
report:
|
||||
input.report.status === "error" || input.report.status === "unavailable"
|
||||
input.report.status === "error" ||
|
||||
input.report.status === "unavailable" ||
|
||||
input.report.status === "not_fetched"
|
||||
? input.report
|
||||
: {
|
||||
status: "available",
|
||||
@@ -138,6 +140,45 @@ test.describe("usage settings", () => {
|
||||
await expect(card.getByText("64% used")).toBeVisible();
|
||||
});
|
||||
|
||||
test("a manual report asks for Refresh and changes only on the user's Refresh", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(120_000);
|
||||
const serverId = getServerId();
|
||||
const manual = (entry: UsageReportEntry): UsageReportEntry => ({ ...entry, refresh: "manual" });
|
||||
const usage = await installUsageReportsFixture(page, {
|
||||
lists: [
|
||||
(request) => [
|
||||
manual(
|
||||
report({
|
||||
sourceId: "quota",
|
||||
sourceLabel: "Quota",
|
||||
report: request.forceRefresh
|
||||
? { status: "available", windows: [{ id: "w", label: "Weekly", usedPct: 12 }] }
|
||||
: { status: "not_fetched" },
|
||||
}),
|
||||
),
|
||||
],
|
||||
],
|
||||
});
|
||||
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsHostSection(page, serverId, "usage");
|
||||
const card = page.getByTestId("usage-report-quota:account");
|
||||
await expect(
|
||||
card.getByText("Not checked yet. Quota usage updates only when you refresh it."),
|
||||
).toBeVisible({ timeout: 10_000 });
|
||||
await expect(card.getByText("Error", { exact: true })).toHaveCount(0);
|
||||
expect(forcedRefreshCount(usage)).toBe(0);
|
||||
|
||||
await card.getByTestId("usage-refresh").click();
|
||||
await expect(card.getByText("12% used")).toBeVisible();
|
||||
expect(usage.listRequests().filter((request) => request.forceRefresh)).toEqual([
|
||||
{ forceRefresh: true, reportIds: ["quota:account"] },
|
||||
]);
|
||||
});
|
||||
|
||||
test("asks to update a host without usage support and never calls it", async ({ page }) => {
|
||||
test.setTimeout(120_000);
|
||||
const serverId = getServerId();
|
||||
|
||||
@@ -3,12 +3,17 @@ import type { Locator, Page } from "@playwright/test";
|
||||
import { expect, test } from "../support/fixtures";
|
||||
import { createIdleAgent } from "../support/helpers/archive-tab";
|
||||
import { expectComposerVisible } from "../support/helpers/composer";
|
||||
import { clickNewTerminal, terminalSurfaceLocator } from "../support/helpers/launcher";
|
||||
import {
|
||||
clickNewChat,
|
||||
clickNewTerminal,
|
||||
terminalSurfaceLocator,
|
||||
} from "../support/helpers/launcher";
|
||||
import { renameModalInput } from "../support/helpers/rename";
|
||||
import { seedWorkspace } from "../support/helpers/seed-client";
|
||||
import { getServerId } from "../support/helpers/server-id";
|
||||
import { clickSettingsBackToWorkspace, openCompactSettings } from "../support/helpers/settings";
|
||||
import { openSettings } from "../support/helpers/app";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import { selectWorkspaceInSidebar } from "../support/helpers/sidebar";
|
||||
import { runWorkspaceActionFromCommandCenter } from "../support/helpers/command-center-workspace-actions";
|
||||
import {
|
||||
clickFirstTerminalTab,
|
||||
@@ -35,8 +40,12 @@ async function expectSameRenderedNode(
|
||||
);
|
||||
}
|
||||
|
||||
function isRenderedNodeConnected(node: Awaited<ReturnType<typeof captureRenderedNode>>) {
|
||||
return node.evaluate((candidate) => candidate.isConnected);
|
||||
}
|
||||
|
||||
async function expectNodeConnected(node: Awaited<ReturnType<typeof captureRenderedNode>>) {
|
||||
expect(await node.evaluate((candidate) => candidate.isConnected)).toBe(true);
|
||||
expect(await isRenderedNodeConnected(node)).toBe(true);
|
||||
}
|
||||
|
||||
async function getSettingsShortcut(page: Page) {
|
||||
@@ -50,6 +59,34 @@ async function waitForWorkspaceRoute(page: Page, route: string) {
|
||||
}
|
||||
|
||||
test.describe("Workspace pane mounting", () => {
|
||||
test("inactive composers expire while switching between other workspaces", async ({
|
||||
page,
|
||||
withWorkspace,
|
||||
}) => {
|
||||
const first = await withWorkspace({ prefix: "deck-expiry-first-" });
|
||||
const second = await withWorkspace({ prefix: "deck-expiry-second-" });
|
||||
const third = await withWorkspace({ prefix: "deck-expiry-third-" });
|
||||
const oneMinute = 60_000;
|
||||
|
||||
await page.clock.install();
|
||||
await gotoAppShell(page);
|
||||
await selectWorkspaceInSidebar(page, first.workspaceId);
|
||||
await clickNewChat(page);
|
||||
const composer = await captureRenderedNode(
|
||||
page.getByTestId("message-input-root").filter({ visible: true }),
|
||||
);
|
||||
|
||||
await selectWorkspaceInSidebar(page, second.workspaceId);
|
||||
await expect(page).toHaveURL(buildHostWorkspaceRoute(getServerId(), second.workspaceId));
|
||||
await page.clock.fastForward(9 * oneMinute);
|
||||
await expectNodeConnected(composer);
|
||||
|
||||
await selectWorkspaceInSidebar(page, third.workspaceId);
|
||||
await expect(page).toHaveURL(buildHostWorkspaceRoute(getServerId(), third.workspaceId));
|
||||
await page.clock.fastForward(2 * oneMinute);
|
||||
await expect.poll(() => isRenderedNodeConnected(composer)).toBe(false);
|
||||
});
|
||||
|
||||
test("workspace navigation keeps the existing agent composer mounted", async ({ page }) => {
|
||||
test.setTimeout(90_000);
|
||||
// Keep both split panes wide enough for the tab-rail interactions below.
|
||||
|
||||
@@ -13,6 +13,8 @@ function ad(...args) {
|
||||
});
|
||||
}
|
||||
|
||||
ad("press", 'label="Pair a device"', "--settle");
|
||||
ad("wait", "text", "Relay", "10000");
|
||||
ad("press", 'label="Relay"', "--settle");
|
||||
ad("wait", "text", "Pairing QR code", "10000");
|
||||
const { data } = JSON.parse(ad("snapshot", "-i", "--json"));
|
||||
|
||||
@@ -178,24 +178,50 @@ export async function attachFileFromMenu(
|
||||
await (await chooserPromise).setFiles(file);
|
||||
}
|
||||
|
||||
export async function dropFileOnComposer(
|
||||
page: Page,
|
||||
file: { name: string; mimeType: string; buffer: Buffer },
|
||||
): Promise<void> {
|
||||
const dataTransfer = await page.evaluateHandle(
|
||||
({ name, mimeType, base64 }) => {
|
||||
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
|
||||
const droppedFile = new File([bytes], name, { type: mimeType });
|
||||
interface TransferFile {
|
||||
name: string;
|
||||
mimeType: string;
|
||||
buffer: Buffer;
|
||||
}
|
||||
|
||||
function createFileTransfer(page: Page, files: TransferFile[]) {
|
||||
return page.evaluateHandle(
|
||||
(entries) => {
|
||||
const transfer = new DataTransfer();
|
||||
transfer.items.add(droppedFile);
|
||||
for (const { name, mimeType, base64 } of entries) {
|
||||
const bytes = Uint8Array.from(atob(base64), (char) => char.charCodeAt(0));
|
||||
transfer.items.add(new File([bytes], name, { type: mimeType }));
|
||||
}
|
||||
return transfer;
|
||||
},
|
||||
{
|
||||
name: file.name,
|
||||
mimeType: file.mimeType,
|
||||
base64: file.buffer.toString("base64"),
|
||||
},
|
||||
files.map(({ name, mimeType, buffer }) => ({
|
||||
name,
|
||||
mimeType,
|
||||
base64: buffer.toString("base64"),
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
export async function pasteFilesIntoComposer(page: Page, files: TransferFile[]): Promise<boolean> {
|
||||
const clipboardData = await createFileTransfer(page, files);
|
||||
try {
|
||||
const input = composerInput(page);
|
||||
await input.focus();
|
||||
return await input.evaluate((element, transfer) => {
|
||||
const event = new ClipboardEvent("paste", {
|
||||
clipboardData: transfer,
|
||||
bubbles: true,
|
||||
cancelable: true,
|
||||
});
|
||||
return !element.dispatchEvent(event);
|
||||
}, clipboardData);
|
||||
} finally {
|
||||
await clipboardData.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
export async function dropFileOnComposer(page: Page, file: TransferFile): Promise<void> {
|
||||
const dataTransfer = await createFileTransfer(page, [file]);
|
||||
|
||||
const composerRoot = page.getByTestId("message-input-root").filter({ visible: true }).first();
|
||||
await expect(composerRoot).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
@@ -132,11 +132,31 @@ export class ImportSessionFlow {
|
||||
}
|
||||
async retryProvider(provider: string, label: string) {
|
||||
await this.expectProviderError(label);
|
||||
await this.page.getByTestId(`import-session-retry-${provider}`).click();
|
||||
await this.startProviderRetry(provider);
|
||||
await expect(this.page.getByTestId(`import-session-retry-${provider}`)).toBeEnabled();
|
||||
await this.expectProviderError(label);
|
||||
await expect(this.page.getByRole("progressbar")).toHaveCount(0);
|
||||
}
|
||||
async startProviderRetry(provider: string) {
|
||||
await this.page.getByTestId(`import-session-retry-${provider}`).click();
|
||||
}
|
||||
async expectProviderRetryPending(provider: string) {
|
||||
await expect(this.page.getByTestId(`import-session-retry-${provider}`)).toBeDisabled();
|
||||
}
|
||||
async expectProviderRequestTimeout() {
|
||||
await expect(
|
||||
this.page
|
||||
.getByText("No response to fetch_recent_provider_sessions_request after 100000ms", {
|
||||
exact: true,
|
||||
})
|
||||
.first(),
|
||||
).toBeVisible();
|
||||
}
|
||||
async expectProviderRecovered(label: string) {
|
||||
await expect(
|
||||
this.page.getByText(`Could not load ${label} sessions`, { exact: true }),
|
||||
).toHaveCount(0);
|
||||
}
|
||||
async startImport(id: string) {
|
||||
await this.revealSession(id);
|
||||
await this.page.getByTestId(rowTestId(id)).click();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { expect, type Page, type WebSocket } from "@playwright/test";
|
||||
import { openSettingsSection } from "./settings";
|
||||
|
||||
export interface RecordedBrowserNotification {
|
||||
@@ -75,6 +75,32 @@ export async function installBrowserNotificationRecorder(page: Page): Promise<vo
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reloads the app and waits until it has told the daemon this device is present.
|
||||
*
|
||||
* The daemon shows an attention notification only on a client that has sent a
|
||||
* heartbeat. Settings render from local storage before the reloaded app connects,
|
||||
* so an agent that finishes right after the reload finds no present client and
|
||||
* no notification is shown.
|
||||
*/
|
||||
export async function reloadAndWaitForDevicePresence(page: Page): Promise<void> {
|
||||
let presenceReported = false;
|
||||
const watchHeartbeats = (socket: WebSocket) => {
|
||||
socket.on("framesent", (frame) => {
|
||||
if (typeof frame.payload === "string" && frame.payload.includes('"client_heartbeat"')) {
|
||||
presenceReported = true;
|
||||
}
|
||||
});
|
||||
};
|
||||
page.on("websocket", watchHeartbeats);
|
||||
try {
|
||||
await page.reload();
|
||||
await expect.poll(() => presenceReported).toBe(true);
|
||||
} finally {
|
||||
page.off("websocket", watchHeartbeats);
|
||||
}
|
||||
}
|
||||
|
||||
export async function readRecordedBrowserNotifications(
|
||||
page: Page,
|
||||
): Promise<RecordedBrowserNotification[]> {
|
||||
|
||||
@@ -66,6 +66,56 @@ type PairingHost =
|
||||
| Pick<IsolatedHostDaemon, "serverId" | "port">
|
||||
| Pick<OutdatedDaemon, "serverId" | "endpoint">;
|
||||
|
||||
export async function openDevicesPage(page: Page, daemon: PairingHost): Promise<void> {
|
||||
await openAppOnPairingHost(page, daemon);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expect(page.getByTestId("devices-connected-clients-card")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectConnectedClientRow(
|
||||
page: Page,
|
||||
title: string,
|
||||
scopeLabel: string,
|
||||
): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
const row = card.getByRole("button", { name: title, exact: true });
|
||||
await expect(row).toBeVisible();
|
||||
await expect(card.getByText(scopeLabel, { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expandConnectedClientRow(page: Page, title: string): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
await card.getByRole("button", { name: title, exact: true }).click();
|
||||
await expect(card.getByText("Permissions", { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function returnFromRelayToWaysToConnect(page: Page): Promise<void> {
|
||||
await page
|
||||
.getByTestId("devices-relay-pairing")
|
||||
.getByRole("button", { name: "Back", exact: true })
|
||||
.click();
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openPairDeviceWaysSheet(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("devices-pair-button")).toBeVisible();
|
||||
await page.getByTestId("devices-pair-button").click();
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
}
|
||||
|
||||
async function ensurePairDeviceWaysSheetOpen(page: Page): Promise<void> {
|
||||
const relayRow = page.getByTestId("devices-relay");
|
||||
const pairButton = page.getByTestId("devices-pair-button");
|
||||
await relayRow.or(pairButton).first().waitFor({ state: "visible" });
|
||||
if (!(await relayRow.isVisible())) {
|
||||
await pairButton.click();
|
||||
await expect(relayRow).toBeVisible();
|
||||
}
|
||||
}
|
||||
|
||||
export async function preparePairingHost(
|
||||
page: Page,
|
||||
daemon: PairingHost,
|
||||
@@ -74,9 +124,9 @@ export async function preparePairingHost(
|
||||
await openAppOnPairingHost(page, daemon, additionalHosts);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
|
||||
await expect(page.getByTestId("devices-pair-button")).toHaveCount(0);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await openPairDeviceWaysSheet(page);
|
||||
}
|
||||
|
||||
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
|
||||
@@ -185,10 +235,12 @@ export async function cancelTailscaleTurnOff(page: Page, address: string): Promi
|
||||
*/
|
||||
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||
const question = answerNextDialog(page, "accept");
|
||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
const scope = (await sheet.isVisible()) ? sheet : page;
|
||||
await scope.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expect(scope.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expectHostUnreachableAt(address);
|
||||
}
|
||||
|
||||
@@ -372,9 +424,12 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
|
||||
}
|
||||
|
||||
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
await expect(page.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||
await ensurePairDeviceWaysSheetOpen(page);
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
const scope = (await sheet.isVisible()) ? sheet : page;
|
||||
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toBeDisabled();
|
||||
await expect(scope.getByText("Update this host to use Tailscale", { exact: true })).toBeVisible();
|
||||
await expect(scope.getByRole("link", { name: "How to update", exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
|
||||
@@ -460,6 +515,7 @@ export function observeDaemonStatusPolling(page: Page, port: number) {
|
||||
}
|
||||
|
||||
export async function openPairDeviceModal(page: Page): Promise<void> {
|
||||
await ensurePairDeviceWaysSheetOpen(page);
|
||||
await page.getByRole("button", { name: "Relay", exact: true }).click();
|
||||
await expect(page.getByTestId("devices-relay-pairing")).toBeVisible();
|
||||
}
|
||||
@@ -579,9 +635,14 @@ export async function expectPairingDisconnected(page: Page): Promise<void> {
|
||||
}
|
||||
|
||||
export async function switchPairDeviceToHost(page: Page, serverId: string): Promise<void> {
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
if (await sheet.isVisible()) {
|
||||
await sheet.getByRole("button", { name: "Close", exact: true }).click();
|
||||
await expect(sheet).toHaveCount(0);
|
||||
}
|
||||
await selectSettingsHost(page, serverId);
|
||||
await expectAppRoute(page, buildSettingsHostSectionRoute(serverId, "devices"));
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
await openPairDeviceWaysSheet(page);
|
||||
}
|
||||
|
||||
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
||||
|
||||
@@ -31,7 +31,14 @@ export const LISTING = {
|
||||
overview: "Directory example keeps a checklist beside your agents.",
|
||||
};
|
||||
|
||||
export const test = base.extend<{ directoryHost: { serverId: string; port: number } }>({
|
||||
export const test = base.extend<{
|
||||
directoryHost: {
|
||||
serverId: string;
|
||||
port: number;
|
||||
setDetailDelayMs: (ms: number) => void;
|
||||
waitForDetailServed: (listingId: string) => Promise<void>;
|
||||
};
|
||||
}>({
|
||||
directoryHost: async ({ e2eWorker }, provide) => {
|
||||
void e2eWorker;
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-plugin-directory-"));
|
||||
@@ -42,7 +49,12 @@ export const test = base.extend<{ directoryHost: { serverId: string; port: numbe
|
||||
pluginRegistryUrl: registry.url,
|
||||
});
|
||||
try {
|
||||
await provide({ serverId: host.serverId, port: host.port });
|
||||
await provide({
|
||||
serverId: host.serverId,
|
||||
port: host.port,
|
||||
setDetailDelayMs: registry.setDetailDelayMs,
|
||||
waitForDetailServed: registry.waitForDetailServed,
|
||||
});
|
||||
} finally {
|
||||
await host.dispose();
|
||||
}
|
||||
@@ -161,26 +173,50 @@ function createRelatedFixtures(date: string) {
|
||||
650,
|
||||
],
|
||||
] as const;
|
||||
return specs.map(([id, name, description, installs]) => ({
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
license: "MIT",
|
||||
categories: ["tools"],
|
||||
author: { github: "acme", name: "Acme" },
|
||||
repository: { url: `https://github.com/${id}` },
|
||||
artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) },
|
||||
scorecardSummary: {
|
||||
health: { grade: "good" },
|
||||
review: { status: "passed", score: 4, noteCount: 0 },
|
||||
},
|
||||
media: [],
|
||||
submittedAt: date,
|
||||
reviewedAt: date,
|
||||
updatedAt: date,
|
||||
publishedAt: date,
|
||||
installs,
|
||||
}));
|
||||
return specs.map(([id, name, description, installs]) => {
|
||||
const entry: Record<string, unknown> = {
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
license: "MIT",
|
||||
categories: ["tools"],
|
||||
author:
|
||||
id === "acme/pr-radar"
|
||||
? {
|
||||
github: "acme",
|
||||
name: "Acme",
|
||||
bio: "Building developer workflow plugins for Paseo.",
|
||||
website: "https://acme.dev",
|
||||
}
|
||||
: { github: "acme", name: "Acme" },
|
||||
repository: { url: `https://github.com/${id}` },
|
||||
artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) },
|
||||
scorecardSummary: {
|
||||
health: { grade: "good" },
|
||||
review: { status: "passed", score: 4, noteCount: 0 },
|
||||
},
|
||||
media: [],
|
||||
submittedAt: date,
|
||||
reviewedAt: date,
|
||||
updatedAt: date,
|
||||
publishedAt: date,
|
||||
installs,
|
||||
};
|
||||
if (id === "acme/pr-radar") {
|
||||
entry.funding = [
|
||||
{ platform: "github", url: "https://github.com/sponsors/acme" },
|
||||
{ platform: "kofi", url: "https://ko-fi.com/acme" },
|
||||
{ platform: "buymeacoffee", url: "https://buymeacoffee.com/acme" },
|
||||
{ platform: "opencollective", url: "https://opencollective.com/acme" },
|
||||
{ platform: "patreon", url: "https://patreon.com/acme" },
|
||||
{ platform: "polar", url: "https://polar.sh/acme" },
|
||||
{ platform: "liberapay", url: "https://liberapay.com/acme" },
|
||||
{ platform: "paypal", url: "https://paypal.me/acme" },
|
||||
{ url: "https://ifdian.net/a/acme" },
|
||||
];
|
||||
}
|
||||
return entry;
|
||||
});
|
||||
}
|
||||
|
||||
async function startRegistry(listing: Record<string, unknown>) {
|
||||
@@ -285,20 +321,52 @@ async function startRegistry(listing: Record<string, unknown>) {
|
||||
readme: `# ${item.name}\n\n${item.description}`,
|
||||
};
|
||||
}
|
||||
let detailDelayMs = 0;
|
||||
const servedDetails = new Set<string>();
|
||||
const detailWaiters = new Map<string, Array<() => void>>();
|
||||
const markDetailServed = (requestUrl: string | undefined) => {
|
||||
const match = requestUrl ? /^\/plugins\/(.+)\.json$/.exec(requestUrl) : null;
|
||||
if (!match) return;
|
||||
const id = match[1]!;
|
||||
servedDetails.add(id);
|
||||
const waiters = detailWaiters.get(id);
|
||||
if (waiters) {
|
||||
detailWaiters.delete(id);
|
||||
for (const resolve of waiters) resolve();
|
||||
}
|
||||
};
|
||||
const server = createServer((request, response) => {
|
||||
const document = request.url ? documents[request.url] : undefined;
|
||||
if (!document) {
|
||||
response.writeHead(404).end();
|
||||
return;
|
||||
}
|
||||
response.setHeader("Content-Type", "application/json");
|
||||
response.end(JSON.stringify(document));
|
||||
const respond = () => {
|
||||
response.setHeader("Content-Type", "application/json");
|
||||
response.end(JSON.stringify(document), () => markDetailServed(request.url));
|
||||
};
|
||||
if (detailDelayMs > 0 && request.url?.startsWith("/plugins/")) {
|
||||
setTimeout(respond, detailDelayMs);
|
||||
} else {
|
||||
respond();
|
||||
}
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
const address = server.address();
|
||||
if (!address || typeof address === "string") throw new Error("Missing registry address");
|
||||
return {
|
||||
url: `http://127.0.0.1:${address.port}`,
|
||||
setDetailDelayMs: (ms: number) => {
|
||||
detailDelayMs = ms;
|
||||
},
|
||||
waitForDetailServed: (listingId: string) => {
|
||||
if (servedDetails.has(listingId)) return Promise.resolve();
|
||||
return new Promise<void>((resolve) => {
|
||||
const list = detailWaiters.get(listingId) ?? [];
|
||||
list.push(resolve);
|
||||
detailWaiters.set(listingId, list);
|
||||
});
|
||||
},
|
||||
close: () => new Promise<void>((resolve) => server.close(() => resolve())),
|
||||
};
|
||||
}
|
||||
@@ -372,3 +440,237 @@ export async function openFromInstalledTab(page: Page) {
|
||||
await selectInstalledTab(page);
|
||||
await openPluginPage(page, LISTING.name, "directory-example");
|
||||
}
|
||||
|
||||
interface PluginFrameSample {
|
||||
url: string;
|
||||
stacked: boolean;
|
||||
hasSkeleton: boolean;
|
||||
updatesLabel: string | null;
|
||||
overviewHeight: number | null;
|
||||
overviewTextLen: number;
|
||||
licenseY: number | null;
|
||||
relatedY: number | null;
|
||||
}
|
||||
|
||||
async function sampleFramesDuring(
|
||||
page: Page,
|
||||
{
|
||||
action,
|
||||
waitUntilSettled,
|
||||
}: { action: () => Promise<void>; waitUntilSettled: () => Promise<void> },
|
||||
): Promise<PluginFrameSample[]> {
|
||||
await page.evaluate(() => {
|
||||
const samples: PluginFrameSample[] = [];
|
||||
const host = window as unknown as {
|
||||
__pluginFrameSamples?: PluginFrameSample[];
|
||||
__stopPluginFrameSampling?: () => void;
|
||||
};
|
||||
host.__pluginFrameSamples = samples;
|
||||
let running = true;
|
||||
host.__stopPluginFrameSampling = () => {
|
||||
running = false;
|
||||
};
|
||||
|
||||
const isVisible = (el: Element): boolean => {
|
||||
const rect = el.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
const queryVisible = (selector: string): Element | null => {
|
||||
const nodes = Array.from(document.querySelectorAll(selector));
|
||||
for (let i = nodes.length - 1; i >= 0; i -= 1) {
|
||||
if (isVisible(nodes[i]!)) return nodes[i]!;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
const findVisibleText = (text: string): Element | null => {
|
||||
const walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
|
||||
let node: Node | null;
|
||||
let match: Element | null = null;
|
||||
while ((node = walker.nextNode())) {
|
||||
if (
|
||||
node.textContent?.trim() === text &&
|
||||
node.parentElement &&
|
||||
isVisible(node.parentElement)
|
||||
) {
|
||||
match = node.parentElement;
|
||||
}
|
||||
}
|
||||
return match;
|
||||
};
|
||||
const findOverviewCard = (tabsEl: Element | null, stacked: boolean): Element | null => {
|
||||
if (!tabsEl) return null;
|
||||
const container = stacked
|
||||
? (tabsEl.closest('[style*="overflow"]')?.parentElement ??
|
||||
tabsEl.parentElement?.parentElement?.parentElement)
|
||||
: tabsEl.parentElement?.parentElement;
|
||||
if (!container) return null;
|
||||
const visibleChildren = Array.from(container.children).filter(isVisible);
|
||||
return visibleChildren[visibleChildren.length - 1] ?? null;
|
||||
};
|
||||
const roundRect = (el: Element | null) => el?.getBoundingClientRect() ?? null;
|
||||
|
||||
const record = () => {
|
||||
const tabsEl = queryVisible('[data-testid="plugin-page-tabs"]');
|
||||
const stacked = Boolean(queryVisible('[data-testid="plugin-page-tab-details"]'));
|
||||
const updatesTabEl = queryVisible('[data-testid="plugin-page-tab-updates"]');
|
||||
const skeletonEl = queryVisible('[data-testid="plugin-overview-skeleton"]');
|
||||
const licenseRect = roundRect(findVisibleText("License"));
|
||||
const relatedRect = roundRect(findVisibleText("Related plugins"));
|
||||
const overviewCard = findOverviewCard(tabsEl, stacked);
|
||||
const overviewRect = roundRect(overviewCard);
|
||||
|
||||
samples.push({
|
||||
url: location.pathname,
|
||||
stacked,
|
||||
hasSkeleton: Boolean(skeletonEl),
|
||||
updatesLabel: updatesTabEl?.textContent?.trim() ?? null,
|
||||
overviewHeight: overviewRect ? Math.round(overviewRect.height) : null,
|
||||
overviewTextLen: overviewCard?.textContent?.trim().length ?? 0,
|
||||
licenseY: licenseRect ? Math.round(licenseRect.y) : null,
|
||||
relatedY: relatedRect ? Math.round(relatedRect.y) : null,
|
||||
});
|
||||
|
||||
if (running) requestAnimationFrame(record);
|
||||
};
|
||||
requestAnimationFrame(record);
|
||||
});
|
||||
|
||||
await action();
|
||||
await waitUntilSettled();
|
||||
await page.evaluate(
|
||||
() =>
|
||||
new Promise<void>((resolve) =>
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
|
||||
),
|
||||
);
|
||||
return page.evaluate(() => {
|
||||
const host = window as unknown as {
|
||||
__pluginFrameSamples?: PluginFrameSample[];
|
||||
__stopPluginFrameSampling?: () => void;
|
||||
};
|
||||
host.__stopPluginFrameSampling?.();
|
||||
return host.__pluginFrameSamples ?? [];
|
||||
});
|
||||
}
|
||||
|
||||
function assertOverviewNeverCollapsed(
|
||||
frames: PluginFrameSample[],
|
||||
{ minHeight }: { minHeight: number },
|
||||
) {
|
||||
const withOverview = frames.filter((frame) => frame.overviewHeight !== null);
|
||||
expect(withOverview.length).toBeGreaterThan(0);
|
||||
for (const frame of withOverview) {
|
||||
expect(frame.hasSkeleton || frame.overviewTextLen > 0).toBe(true);
|
||||
expect(frame.overviewHeight).toBeGreaterThanOrEqual(minHeight);
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the example listing without hovering first and verifies zero collapse or layout shift. */
|
||||
export async function expectStableUncachedListingOpen(page: Page) {
|
||||
const frames = await sampleFramesDuring(page, {
|
||||
action: async () => {
|
||||
await listingRow(page).getByText(LISTING.name, { exact: true }).click();
|
||||
},
|
||||
waitUntilSettled: async () => {
|
||||
await expect(page.getByText(LISTING.overview, { exact: true })).toBeVisible();
|
||||
},
|
||||
});
|
||||
const onPage = frames.filter((frame) => frame.url.endsWith(`/${LISTING.id}`));
|
||||
expect(onPage.length).toBeGreaterThan(0);
|
||||
for (const frame of onPage) {
|
||||
expect(frame.stacked).toBe(false);
|
||||
expect(frame.updatesLabel).not.toBe("Updates · 1");
|
||||
}
|
||||
assertOverviewNeverCollapsed(onPage, { minHeight: 200 });
|
||||
const licensePositions = new Set(
|
||||
onPage.map((frame) => frame.licenseY).filter((y): y is number => y !== null),
|
||||
);
|
||||
expect(licensePositions.size).toBe(1);
|
||||
const relatedPositions = new Set(
|
||||
onPage.map((frame) => frame.relatedY).filter((y): y is number => y !== null),
|
||||
);
|
||||
expect(relatedPositions.size).toBe(1);
|
||||
}
|
||||
|
||||
/** Hovers a related plugin to prefetch it, clicks it, and asserts Markdown lands on frame 1. */
|
||||
export async function expectInstantPrefetchedRelatedOpen(
|
||||
page: Page,
|
||||
{ waitForDetailServed }: { waitForDetailServed: (listingId: string) => Promise<void> },
|
||||
) {
|
||||
const relatedCard = page.getByTestId("plugin-related-acme/pr-radar").filter({ visible: true });
|
||||
await relatedCard.hover();
|
||||
await waitForDetailServed("acme/pr-radar");
|
||||
// Allow the local daemon WebSocket response to reach the browser query cache.
|
||||
await page.waitForTimeout(200);
|
||||
const frames = await sampleFramesDuring(page, {
|
||||
action: async () => {
|
||||
await relatedCard.click();
|
||||
},
|
||||
waitUntilSettled: async () => {
|
||||
await expect(pluginPageName(page)).toHaveText("PR Radar");
|
||||
await expect(
|
||||
page
|
||||
.getByText("Monitors pull requests and CI checks across connected hosts.")
|
||||
.filter({ visible: true })
|
||||
.nth(1),
|
||||
).toBeVisible();
|
||||
},
|
||||
});
|
||||
const onPage = frames.filter((frame) => frame.url.endsWith("/acme/pr-radar"));
|
||||
expect(onPage.length).toBeGreaterThan(0);
|
||||
for (const frame of onPage) {
|
||||
expect(frame.hasSkeleton).toBe(false);
|
||||
expect(frame.overviewTextLen).toBeGreaterThan(0);
|
||||
}
|
||||
}
|
||||
|
||||
/** Goes back to the previous plugin page and asserts it stays two-column on every frame. */
|
||||
export async function expectStableDesktopBackToListing(page: Page) {
|
||||
const frames = await sampleFramesDuring(page, {
|
||||
action: async () => {
|
||||
await page.goBack();
|
||||
},
|
||||
waitUntilSettled: async () => {
|
||||
await expect(pluginPageName(page)).toHaveText(LISTING.name);
|
||||
},
|
||||
});
|
||||
const onPage = frames.filter((frame) => frame.url.endsWith(`/${LISTING.id}`));
|
||||
expect(onPage.length).toBeGreaterThan(0);
|
||||
for (const frame of onPage) {
|
||||
expect(frame.stacked).toBe(false);
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens a listing in a narrow desktop split (< 700px detail width) and asserts stacked frame 1. */
|
||||
export async function expectStackedFirstFrameOnNarrowDesktop(page: Page) {
|
||||
await page
|
||||
.getByRole("button", { name: "Back to plugins", exact: true })
|
||||
.filter({ visible: true })
|
||||
.click();
|
||||
await expect(listingRow(page)).toBeVisible();
|
||||
await page.setViewportSize({ width: 920, height: 960 });
|
||||
const frames = await sampleFramesDuring(page, {
|
||||
action: async () => {
|
||||
await page
|
||||
.getByTestId("plugin-listing-acme/commit-diff")
|
||||
.filter({ visible: true })
|
||||
.getByText("Commit Diff", { exact: true })
|
||||
.click();
|
||||
},
|
||||
waitUntilSettled: async () => {
|
||||
await expect(pluginPageName(page)).toHaveText("Commit Diff");
|
||||
await expect(
|
||||
page
|
||||
.getByText("Compact commit history and inline file tree diff viewer.")
|
||||
.filter({ visible: true })
|
||||
.nth(1),
|
||||
).toBeVisible();
|
||||
},
|
||||
});
|
||||
const onPage = frames.filter((frame) => frame.url.endsWith("/acme/commit-diff"));
|
||||
expect(onPage.length).toBeGreaterThan(0);
|
||||
for (const frame of onPage) {
|
||||
expect(frame.stacked).toBe(true);
|
||||
}
|
||||
assertOverviewNeverCollapsed(onPage, { minHeight: 80 });
|
||||
}
|
||||
|
||||
@@ -175,6 +175,22 @@ export async function reopenWithFreshnessCheckUnanswered(
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toBeVisible();
|
||||
}
|
||||
|
||||
/** Reopens display-only history with the tail held until the app shows the outstanding update. */
|
||||
export async function reopenWithTimelineTailUnanswered({
|
||||
page,
|
||||
gate,
|
||||
agentId,
|
||||
}: {
|
||||
page: Page;
|
||||
gate: DaemonWebSocketGate;
|
||||
agentId: string;
|
||||
}): Promise<void> {
|
||||
gate.holdTimelineResponses(agentId);
|
||||
await page.reload();
|
||||
await gate.waitForHeldTimelineResponse();
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function answerFreshnessCheck(page: Page, gate: DaemonWebSocketGate): Promise<void> {
|
||||
gate.releaseHeldClientRequest();
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
@@ -324,6 +340,121 @@ export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<st
|
||||
return reply;
|
||||
}
|
||||
|
||||
interface LoadingSurfaceRecord {
|
||||
loaderText: string[];
|
||||
spinnerYsByTestId: Record<string, number[]>;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__loadingSurfaceRecord?: LoadingSurfaceRecord;
|
||||
}
|
||||
}
|
||||
|
||||
function recordLoadingSurfaces(): void {
|
||||
const record: LoadingSurfaceRecord = {
|
||||
loaderText: [],
|
||||
spinnerYsByTestId: {},
|
||||
};
|
||||
window.__loadingSurfaceRecord = record;
|
||||
|
||||
const isVisible = (el: Element | null): el is HTMLElement => {
|
||||
if (!(el instanceof HTMLElement)) return false;
|
||||
const style = window.getComputedStyle(el);
|
||||
if (style.display === "none" || style.visibility === "hidden" || style.opacity === "0") {
|
||||
return false;
|
||||
}
|
||||
const rect = el.getBoundingClientRect();
|
||||
return rect.width > 0 && rect.height > 0;
|
||||
};
|
||||
|
||||
const sample = () => {
|
||||
if (!document.body) return;
|
||||
for (const testId of [
|
||||
"workspace-loading",
|
||||
"agent-loading",
|
||||
"agent-history-overlay",
|
||||
"agent-initial-fill",
|
||||
]) {
|
||||
const el = document.querySelector(`[data-testid="${testId}"]`);
|
||||
if (!isVisible(el)) continue;
|
||||
const text = (el.textContent ?? "").trim();
|
||||
if (text.length > 0 && !record.loaderText.includes(text)) {
|
||||
record.loaderText.push(text);
|
||||
}
|
||||
const spinner = el.querySelector('[role="progressbar"]');
|
||||
if (spinner) {
|
||||
const y = Math.round(spinner.getBoundingClientRect().y);
|
||||
const list = record.spinnerYsByTestId[testId] ?? [];
|
||||
if (!list.includes(y)) list.push(y);
|
||||
record.spinnerYsByTestId[testId] = list;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
const observer = new MutationObserver(sample);
|
||||
observer.observe(document.documentElement ?? document, {
|
||||
childList: true,
|
||||
subtree: true,
|
||||
attributes: true,
|
||||
characterData: true,
|
||||
});
|
||||
sample();
|
||||
};
|
||||
|
||||
if (document.documentElement) start();
|
||||
else document.addEventListener("DOMContentLoaded", start, { once: true });
|
||||
}
|
||||
|
||||
/** Records loading text, spinner Y positions, and any Updating messages toast from first paint. */
|
||||
export async function watchColdAndReloadLoadingSurfaces(page: Page): Promise<void> {
|
||||
await page.addInitScript(recordLoadingSurfaces);
|
||||
await page.addInitScript(recordUpdatingToastTiming);
|
||||
}
|
||||
|
||||
/** Checks loading geometry and verifies the toast waits for a slow daemon reply. */
|
||||
export async function expectCleanLoadingSurfaces(
|
||||
page: Page,
|
||||
gate: DaemonWebSocketGate,
|
||||
before: TimelineRequestCounts,
|
||||
): Promise<void> {
|
||||
await gate.waitForServerMessage(TIMELINE_RESPONSE, before.fetches + 1);
|
||||
await expect(page.getByRole("alert").filter({ hasText: "Updating messages" })).toHaveCount(0);
|
||||
await expectToastWaitedForTheDaemon(page);
|
||||
const record = await page.evaluate(() => window.__loadingSurfaceRecord as LoadingSurfaceRecord);
|
||||
expect(record.loaderText, "loading states must not render visible text").toEqual([]);
|
||||
for (const [testId, ys] of Object.entries(record.spinnerYsByTestId)) {
|
||||
expect(
|
||||
ys.length,
|
||||
`${testId} spinner shifted vertically (${ys.join(", ")})`,
|
||||
).toBeLessThanOrEqual(1);
|
||||
}
|
||||
expect(
|
||||
gate.getTimelineRequestCount("after", before.agentId) - before.after,
|
||||
"initial tail load must not trigger a redundant after catch-up",
|
||||
).toBe(0);
|
||||
}
|
||||
|
||||
/** Waits until the persisted replica cache drops coverage to a display-only snapshot. */
|
||||
export async function waitForDisplayOnlyTimelineCache(
|
||||
page: Page,
|
||||
agent: LongTimelineAgent,
|
||||
): Promise<void> {
|
||||
await expect
|
||||
.poll(
|
||||
async () => {
|
||||
const cache = await readReplicaCache(page);
|
||||
const timeline = cache?.hosts
|
||||
?.flatMap((host) => host.timelines)
|
||||
.find((entry) => entry.agentId === agent.agentId);
|
||||
return timeline?.items ? { items: timeline.items.length, range: timeline.range } : null;
|
||||
},
|
||||
{ timeout: 15_000 },
|
||||
)
|
||||
.toMatchObject({ range: null });
|
||||
}
|
||||
|
||||
export async function expectPromptAndWholeReply(
|
||||
page: Page,
|
||||
agent: StreamingReplyAgent,
|
||||
|
||||
@@ -14,5 +14,8 @@ import { renderRootComponent } from "expo-router/build/renderRootComponent";
|
||||
import { startWatchdog } from "./src/watchdog";
|
||||
import { RootApp } from "./src/root-app";
|
||||
|
||||
import { sweepOrphanedWorkspaceDrafts } from "./src/workspace-tabs/sweep-orphaned-drafts";
|
||||
|
||||
startWatchdog();
|
||||
void sweepOrphanedWorkspaceDrafts();
|
||||
renderRootComponent(RootApp);
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useMemo } from "react";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { useHostRuntimeClient } from "@/runtime/host-runtime";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import type { GithubRepositoryChoice } from "./model";
|
||||
import { resolveSearch, type SearchResult } from "./search-result";
|
||||
|
||||
@@ -19,8 +19,9 @@ export function useDirectorySearch(input: {
|
||||
}): SearchResult<string> {
|
||||
const { hostId } = input;
|
||||
const client = useHostRuntimeClient(hostId ?? "");
|
||||
const isConnected = useHostRuntimeIsConnected(hostId ?? "");
|
||||
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
|
||||
const enabled = Boolean(client && input.enabled);
|
||||
const enabled = Boolean(client && isConnected && input.enabled);
|
||||
const search = useFetchQuery({
|
||||
queryKey: ["add-project-flow-directories", hostId, debouncedQuery],
|
||||
queryFn: async () => {
|
||||
@@ -64,8 +65,9 @@ export function useGithubRepositorySearch(input: {
|
||||
}): SearchResult<GithubRepositoryChoice> {
|
||||
const { hostId } = input;
|
||||
const client = useHostRuntimeClient(hostId ?? "");
|
||||
const isConnected = useHostRuntimeIsConnected(hostId ?? "");
|
||||
const debouncedQuery = useDebouncedValue(input.query, SEARCH_DEBOUNCE_MS);
|
||||
const enabled = Boolean(client && input.enabled);
|
||||
const enabled = Boolean(client && isConnected && input.enabled);
|
||||
const search = useFetchQuery({
|
||||
queryKey: ["add-project-flow-github", hostId, debouncedQuery],
|
||||
queryFn: async () => {
|
||||
|
||||
@@ -69,4 +69,27 @@ describe("host agent skills", () => {
|
||||
expect(result.current.supported).toBe(false);
|
||||
expect(client.getAgentSkillsStatus).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("waits until the host is connected before fetching and fetches once online", async () => {
|
||||
runtime.connected = false;
|
||||
const client = {
|
||||
getAgentSkillsStatus: vi.fn(async () => ({
|
||||
state: "not-installed",
|
||||
ops: [],
|
||||
available: ["paseo"],
|
||||
installed: [],
|
||||
selection: { mode: "all" },
|
||||
})),
|
||||
};
|
||||
runtime.clients.set("reconnecting-host", client);
|
||||
|
||||
const { result, rerender } = renderHook(() => useAgentSkills("reconnecting-host"), { wrapper });
|
||||
expect(client.getAgentSkillsStatus).not.toHaveBeenCalled();
|
||||
|
||||
runtime.connected = true;
|
||||
rerender();
|
||||
|
||||
await waitFor(() => expect(result.current.status?.available).toEqual(["paseo"]));
|
||||
expect(client.getAgentSkillsStatus).toHaveBeenCalledOnce();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -36,7 +36,7 @@ export function useAgentSkills(serverId: string) {
|
||||
if (!client) throw new Error(t("settings.host.skills.unavailable"));
|
||||
return client.getAgentSkillsStatus();
|
||||
},
|
||||
enabled: supported && client !== null,
|
||||
enabled: supported && client !== null && connected,
|
||||
retry: false,
|
||||
dataShape: "value",
|
||||
staleTimeMs: 0,
|
||||
|
||||
@@ -2,8 +2,9 @@
|
||||
* Pure state machine for the chat history's flick-to-dismiss gesture.
|
||||
*
|
||||
* Native keyboardDismissMode cannot express this interaction: "on-drag"
|
||||
* dismisses on the first pixel, while "interactive" is iOS-only. We therefore classify the list's existing scroll gesture at
|
||||
* release instead of introducing a competing pan recognizer.
|
||||
* dismisses on the first pixel, and iOS "interactive" only follows a finger
|
||||
* that reaches the keyboard. We therefore classify the list's existing scroll
|
||||
* gesture at release instead of introducing a competing pan recognizer.
|
||||
*/
|
||||
|
||||
const DISMISS_VELOCITY_POINTS_PER_MS = 1.5;
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import type { ScrollViewProps } from "react-native";
|
||||
|
||||
/**
|
||||
* iOS lets the keyboard follow a drag that reaches it, as in Messages. The
|
||||
* keyboard controller reports each frame of that drag, so the composer stays on
|
||||
* the keyboard edge.
|
||||
*/
|
||||
export const NATIVE_KEYBOARD_DISMISS_MODE: ScrollViewProps["keyboardDismissMode"] = "interactive";
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { ScrollViewProps } from "react-native";
|
||||
|
||||
/**
|
||||
* Android has no interactive keyboard dismissal. The flick classifier in
|
||||
* `model.ts` is the only drag that closes the keyboard there.
|
||||
*/
|
||||
export const NATIVE_KEYBOARD_DISMISS_MODE: ScrollViewProps["keyboardDismissMode"] = "none";
|
||||
+14
-4
@@ -13,13 +13,15 @@ import {
|
||||
recordScroll,
|
||||
releaseDrag,
|
||||
} from "./model";
|
||||
import { NATIVE_KEYBOARD_DISMISS_MODE } from "./native-dismiss-mode";
|
||||
|
||||
type ScrollEvent = NativeSyntheticEvent<NativeScrollEvent>;
|
||||
|
||||
/**
|
||||
* Owns the chat history's flick-to-dismiss behavior. The native stream only
|
||||
* forwards the LegendList scroll lifecycle; removing this hook and those three
|
||||
* calls removes the feature completely.
|
||||
* Owns how the chat history closes the keyboard: a flick toward older messages,
|
||||
* a drag into the keyboard on iOS, and a tap on content that no control claims.
|
||||
* The native stream spreads the two keyboard props and forwards the LegendList
|
||||
* scroll lifecycle; removing this hook and those calls removes the feature.
|
||||
*/
|
||||
export function useScrollKeyboardDismiss() {
|
||||
const { shift } = useKeyboardShift();
|
||||
@@ -53,5 +55,13 @@ export function useScrollKeyboardDismiss() {
|
||||
Keyboard.dismiss();
|
||||
});
|
||||
|
||||
return { onScroll, onScrollBeginDrag, onScrollEndDrag };
|
||||
return {
|
||||
keyboardDismissMode: NATIVE_KEYBOARD_DISMISS_MODE,
|
||||
// "handled" lets links, tool calls, and copy buttons act on the first tap
|
||||
// while the keyboard is open. A tap that no child claims still closes it.
|
||||
keyboardShouldPersistTaps: "handled" as const,
|
||||
onScroll,
|
||||
onScrollBeginDrag,
|
||||
onScrollEndDrag,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -26,7 +26,6 @@ import {
|
||||
} from "@legendapp/list/react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { useNativeSplashHold } from "@/native-splash";
|
||||
@@ -123,15 +122,6 @@ function distanceFromEnd(input: {
|
||||
return Math.max(0, input.contentHeight - input.viewportHeight - input.offsetY);
|
||||
}
|
||||
const viewportStyle: ViewStyle = { flex: 1 };
|
||||
const initialFillStyle: ViewStyle = {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
left: 0,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
};
|
||||
|
||||
function keyExtractor(item: { id: string }): string {
|
||||
return item.id;
|
||||
@@ -159,6 +149,7 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange,
|
||||
onNearHistoryStart,
|
||||
isLoadingOlderHistory,
|
||||
@@ -265,6 +256,12 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
() => historyStartPagination.state.status === "settling",
|
||||
);
|
||||
const finishInitialFill = useStableEvent(() => historyStartPagination.reveal());
|
||||
const reportInitialHistoryVisibility = useStableEvent((visible: boolean) => {
|
||||
onInitialHistoryVisibilityChange?.(visible);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
reportInitialHistoryVisibility(historyStartPaginationState.visible);
|
||||
}, [historyStartPaginationState.visible, reportInitialHistoryVisibility]);
|
||||
const retryHistoryStart = useStableEvent(() => historyStartPagination.rearm());
|
||||
const scheduleHistoryStartSettle = useStableEvent(() => {
|
||||
let scheduler = historyStartSettleSchedulerRef.current;
|
||||
@@ -795,6 +792,8 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
onMomentumScrollBegin={handleMomentumScrollBegin}
|
||||
onMomentumScrollEnd={handleMomentumScrollEnd}
|
||||
scrollEventThrottle={16}
|
||||
keyboardDismissMode={scrollKeyboardDismiss.keyboardDismissMode}
|
||||
keyboardShouldPersistTaps={scrollKeyboardDismiss.keyboardShouldPersistTaps}
|
||||
onContentSizeChange={handleContentSizeChange}
|
||||
onItemSizeChanged={handleItemSizeChanged}
|
||||
onReady={handleListPlaced}
|
||||
@@ -811,11 +810,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
{canExpandDrawDistance ? (
|
||||
<InitialDrawDistanceExpansion schedule={drawDistanceExpansion.schedule} />
|
||||
) : null}
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<View pointerEvents="none" style={initialFillStyle}>
|
||||
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import { flushSync } from "react-dom";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getStreamItemMessageId, type StreamItem } from "@/types/stream";
|
||||
@@ -77,14 +76,6 @@ const historyStartSlotStyle: CSSProperties = {
|
||||
};
|
||||
|
||||
const streamRowsHostStyle: CSSProperties = { position: "relative", width: "100%" };
|
||||
const initialFillStyle: CSSProperties = {
|
||||
position: "absolute",
|
||||
inset: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
pointerEvents: "none",
|
||||
};
|
||||
|
||||
// Rows and the live auxiliary (turn footer, pending permissions) center their content with
|
||||
// `alignSelf`, which only applies inside a flex container.
|
||||
@@ -439,6 +430,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange,
|
||||
onReadingPositionChange,
|
||||
onNearHistoryStart,
|
||||
@@ -707,6 +699,12 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
() => historyStartPagination.state.status === "settling",
|
||||
);
|
||||
const finishInitialFill = useStableEvent(() => historyStartPagination.reveal());
|
||||
const reportInitialHistoryVisibility = useStableEvent((visible: boolean) => {
|
||||
onInitialHistoryVisibilityChange?.(visible);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
reportInitialHistoryVisibility(historyStartPaginationState.visible);
|
||||
}, [historyStartPaginationState.visible, reportInitialHistoryVisibility]);
|
||||
const rearmHistoryStartFromUserIntent = useStableEvent(() => historyStartPagination.rearm());
|
||||
const scheduleHistoryStartPrependSettle = useStableEvent(() => {
|
||||
let scheduler = historyStartSettleSchedulerRef.current;
|
||||
@@ -1750,11 +1748,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
{shouldRenderEmpty ? listEmptyComponent : null}
|
||||
</div>
|
||||
</div>
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<div style={initialFillStyle}>
|
||||
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
|
||||
</div>
|
||||
) : null}
|
||||
{scrollEnabled && !isMobileBreakpoint ? (
|
||||
<DomOverlayScrollbar
|
||||
scrollContainerRef={scrollContainerRef}
|
||||
|
||||
@@ -94,6 +94,8 @@ export interface StreamRenderInput {
|
||||
isAuthoritativeHistoryReady: boolean;
|
||||
isInitialHistoryLoading?: boolean;
|
||||
revealInitialHistory?: boolean;
|
||||
/** When supplied, the host pane owns the full-pane initial-fill loading overlay. */
|
||||
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
|
||||
onNearBottomChange: (value: boolean) => void;
|
||||
// The history row under the top of the viewport, for surfaces that mark where the reader
|
||||
// is in the transcript. Only the web viewport measures it today.
|
||||
|
||||
@@ -258,6 +258,8 @@ export interface AgentStreamViewProps {
|
||||
isAuthoritativeHistoryReady?: boolean;
|
||||
isInitialHistoryLoading?: boolean;
|
||||
revealInitialHistory?: boolean;
|
||||
/** When supplied, the host pane owns the full-pane initial-fill loading overlay. */
|
||||
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
|
||||
/** Tail space required by a transparent overlay rendered at the bottom edge. */
|
||||
bottomOverlayTailClearance?: number;
|
||||
/** Bottom offset required for controls floating above that overlay. */
|
||||
@@ -357,6 +359,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady = true,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
bottomOverlayTailClearance = 0,
|
||||
bottomOverlayControlClearance,
|
||||
toast,
|
||||
@@ -1231,6 +1234,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange: nearBottom.set,
|
||||
onReadingPositionChange: handleReadingPositionChange,
|
||||
onNearHistoryStart: loadOlder,
|
||||
@@ -1384,6 +1388,9 @@ function agentStreamViewPropsEqual(
|
||||
if (left.revealInitialHistory !== right.revealInitialHistory) {
|
||||
reasons.push("revealInitialHistory");
|
||||
}
|
||||
if (left.onInitialHistoryVisibilityChange !== right.onInitialHistoryVisibilityChange) {
|
||||
reasons.push("onInitialHistoryVisibilityChange");
|
||||
}
|
||||
if (left.bottomOverlayTailClearance !== right.bottomOverlayTailClearance) {
|
||||
reasons.push("bottomOverlayTailClearance");
|
||||
}
|
||||
|
||||
@@ -147,6 +147,9 @@ function HostWorkspaceRouteContent() {
|
||||
}
|
||||
|
||||
function WorkspaceDeck() {
|
||||
// The compiler caches render-time Date.now() without this directive.
|
||||
"use no memo";
|
||||
|
||||
const activeSelection = useActiveWorkspaceSelection();
|
||||
const [retainedSelections, setRetainedSelections] = useState<RetainedWorkspaceSelection[]>(() =>
|
||||
activeSelection ? [{ selection: activeSelection, inactiveSince: null }] : [],
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { getFileExtension } from "@/attachments/file-types";
|
||||
import { getFileExtension, getMimeTypeFromPath } from "@/attachments/file-types";
|
||||
import { copyDesktopAttachmentFile } from "@/desktop/attachments/desktop-file-commands";
|
||||
import { readDesktopFileBase64 } from "@/desktop/attachments/desktop-preview-url";
|
||||
|
||||
@@ -8,6 +8,14 @@ export interface SelectedFile {
|
||||
readBytes(): Promise<Uint8Array>;
|
||||
}
|
||||
|
||||
export function selectedFileFromWebFile(file: File): SelectedFile {
|
||||
return {
|
||||
fileName: file.name,
|
||||
mimeType: file.type || getMimeTypeFromPath(file.name),
|
||||
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
|
||||
};
|
||||
}
|
||||
|
||||
function base64ToUint8Array(base64: string): Uint8Array {
|
||||
const binaryString = atob(base64);
|
||||
const bytes = new Uint8Array(binaryString.length);
|
||||
|
||||
@@ -0,0 +1,137 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import type { DaemonClient, FileReadResult } from "@getpaseo/client/internal/daemon-client";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { AssistantFileLinkResolverProvider } from "@/assistant-file-links";
|
||||
import { ForgeShorthandProvider } from "@/git/forge-shorthand";
|
||||
import { ChangelogBody } from "./changelog-sheet";
|
||||
import type { ChangelogState } from "./changelog-source";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
beforeEach(() => vi.stubGlobal("React", React));
|
||||
|
||||
let root: Root | null = null;
|
||||
let container: HTMLDivElement | null = null;
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root?.unmount());
|
||||
container?.remove();
|
||||
root = null;
|
||||
container = null;
|
||||
});
|
||||
|
||||
function noop() {}
|
||||
|
||||
const CHANGELOG_FIXTURE_STATE: ChangelogState = {
|
||||
status: "ready",
|
||||
releases: [
|
||||
{
|
||||
version: "0.19.0",
|
||||
date: "2026-12-01",
|
||||
highlights:
|
||||
"Highlights see #123, [Release](https://paseo.sh/changelog), [Local](/etc/passwd), ",
|
||||
sections: [
|
||||
{
|
||||
title: "Fixed",
|
||||
body: "Section   see #456",
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
version: "0.18.0",
|
||||
date: "2026-11-20",
|
||||
highlights: "",
|
||||
sections: [
|
||||
{
|
||||
title: "Added",
|
||||
body: "Only sections  [Docs](https://paseo.sh/docs) see #789",
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
function createFakeFileReader() {
|
||||
const reads: { cwd: string; path: string }[] = [];
|
||||
const client = {
|
||||
async readFile(cwd: string, path: string): Promise<FileReadResult> {
|
||||
reads.push({ cwd, path });
|
||||
return {
|
||||
kind: "image",
|
||||
path,
|
||||
mime: "image/png",
|
||||
size: 4,
|
||||
modifiedAt: "2026-12-01T00:00:00.000Z",
|
||||
bytes: new Uint8Array([1, 2, 3, 4]),
|
||||
};
|
||||
},
|
||||
} as unknown as DaemonClient;
|
||||
return { reads, client };
|
||||
}
|
||||
|
||||
async function settleLayout() {
|
||||
for (let frame = 0; frame < 2; frame++) {
|
||||
await act(() => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())));
|
||||
}
|
||||
}
|
||||
|
||||
describe("changelog Markdown safety", () => {
|
||||
it("never calls client.readFile and does not link workspace forge shorthand in highlights or sections", async () => {
|
||||
const { reads, client: fakeClient } = createFakeFileReader();
|
||||
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
|
||||
act(() =>
|
||||
root?.render(
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AssistantFileLinkResolverProvider
|
||||
serverId="server-1"
|
||||
workspaceRoot="/repo"
|
||||
client={fakeClient}
|
||||
>
|
||||
<ForgeShorthandProvider
|
||||
forge="github"
|
||||
remoteUrl="https://github.com/acme/widgets.git"
|
||||
forgeWeb={null}
|
||||
>
|
||||
<ChangelogBody
|
||||
state={CHANGELOG_FIXTURE_STATE}
|
||||
shownReleases={2}
|
||||
onShowMore={noop}
|
||||
onRetry={noop}
|
||||
/>
|
||||
</ForgeShorthandProvider>
|
||||
</AssistantFileLinkResolverProvider>
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
|
||||
await expect.poll(() => container?.textContent).toContain("HighlightLocal");
|
||||
await expect.poll(() => container?.textContent).toContain("DirectSectionLocal");
|
||||
await settleLayout();
|
||||
|
||||
expect(reads).toEqual([]);
|
||||
|
||||
const links = Array.from(container.querySelectorAll("a")).map((a) => ({
|
||||
text: a.textContent,
|
||||
href: a.getAttribute("href"),
|
||||
}));
|
||||
expect(links).toContainEqual(
|
||||
expect.objectContaining({ text: "Release", href: "https://paseo.sh/changelog" }),
|
||||
);
|
||||
expect(links).toContainEqual(
|
||||
expect.objectContaining({ text: "Docs", href: "https://paseo.sh/docs" }),
|
||||
);
|
||||
expect(links.some((l) => l.text === "#123" || l.text === "#789" || l.text === "Local")).toBe(
|
||||
false,
|
||||
);
|
||||
|
||||
const imgs = Array.from(container.querySelectorAll("img"));
|
||||
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("HighlightLocal");
|
||||
expect(imgs.map((img) => img.getAttribute("alt"))).not.toContain("DirectSectionLocal");
|
||||
});
|
||||
});
|
||||
@@ -86,7 +86,7 @@ interface ChangelogBodyProps {
|
||||
onRetry: () => void;
|
||||
}
|
||||
|
||||
function ChangelogBody({ state, shownReleases, onShowMore, onRetry }: ChangelogBodyProps) {
|
||||
export function ChangelogBody({ state, shownReleases, onShowMore, onRetry }: ChangelogBodyProps) {
|
||||
const { t } = useTranslation();
|
||||
const appVersion = useMemo(() => resolveAppVersion()?.replace(/^v/i, "") ?? null, []);
|
||||
|
||||
@@ -168,7 +168,15 @@ const ReleaseView = memo(function ReleaseView({ release, isCurrent }: ReleaseVie
|
||||
<View style={styles.headingSpacer} />
|
||||
{date ? <Text style={styles.date}>{date}</Text> : null}
|
||||
</View>
|
||||
{hasHighlights ? <MarkdownRenderer text={release.highlights} compact /> : null}
|
||||
{hasHighlights ? (
|
||||
<MarkdownRenderer
|
||||
text={release.highlights}
|
||||
compact
|
||||
destinations="https"
|
||||
forgeShorthand={false}
|
||||
softBreaks="join"
|
||||
/>
|
||||
) : null}
|
||||
{hasHighlights && release.sections.length > 0 ? (
|
||||
<Button
|
||||
variant="ghost"
|
||||
@@ -188,7 +196,15 @@ function ReleaseSections({ sections }: { sections: readonly ChangelogSection[] }
|
||||
return keyChangelogSections(sections).map(({ key, section }) => (
|
||||
<View key={key} style={styles.section}>
|
||||
{section.title ? <Text style={styles.sectionTitle}>{section.title}</Text> : null}
|
||||
{section.body ? <MarkdownRenderer text={section.body} compact /> : null}
|
||||
{section.body ? (
|
||||
<MarkdownRenderer
|
||||
text={section.body}
|
||||
compact
|
||||
destinations="https"
|
||||
forgeShorthand={false}
|
||||
softBreaks="join"
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
));
|
||||
}
|
||||
|
||||
@@ -66,6 +66,7 @@ import type {
|
||||
ExplorerEntry,
|
||||
} from "@/stores/session-store";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useHostRuntimeClient, useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import { FileActionsContextMenuContent } from "@/components/file-actions-menu";
|
||||
import { ContextMenu, ContextMenuTrigger, useContextMenu } from "@/components/ui/context-menu";
|
||||
import { useFileExplorerActions } from "@/hooks/use-file-explorer-actions";
|
||||
@@ -570,13 +571,33 @@ export function FileExplorerPane({
|
||||
const treeListRef = useRef<FlatList<ExplorerListRow>>(null);
|
||||
const scrollbar = useOverlayFlatListScrollbar(treeListRef, { enabled: !isCompact });
|
||||
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const connectionStatus = useHostRuntimeConnectionStatus(serverId);
|
||||
const canFetch = Boolean(client && connectionStatus === "online");
|
||||
const isHostConnecting = connectionStatus === "connecting" || connectionStatus === "idle";
|
||||
const isHostUnavailable = connectionStatus === "offline" || connectionStatus === "error";
|
||||
|
||||
const hasInitializedRef = useRef(false);
|
||||
const wasCanFetchRef = useRef(canFetch);
|
||||
|
||||
useEffect(() => {
|
||||
hasInitializedRef.current = false;
|
||||
wasCanFetchRef.current = false;
|
||||
}, [workspaceStateKey]);
|
||||
|
||||
useEffect(() => {
|
||||
const reconnected = !wasCanFetchRef.current && canFetch;
|
||||
wasCanFetchRef.current = canFetch;
|
||||
if (!canFetch) {
|
||||
return;
|
||||
}
|
||||
if (
|
||||
reconnected &&
|
||||
workspaceStateKey &&
|
||||
useSessionStore.getState().sessions[serverId]?.fileExplorer.get(workspaceStateKey)?.lastError
|
||||
) {
|
||||
hasInitializedRef.current = false;
|
||||
}
|
||||
void initializeExplorer({
|
||||
hasWorkspaceScope,
|
||||
hasInitializedRef,
|
||||
@@ -587,9 +608,12 @@ export function FileExplorerPane({
|
||||
setExpandedPathsForWorkspace,
|
||||
});
|
||||
}, [
|
||||
canFetch,
|
||||
client,
|
||||
expandedPaths,
|
||||
hasWorkspaceScope,
|
||||
requestDirectoryListing,
|
||||
serverId,
|
||||
setExpandedPathsForWorkspace,
|
||||
showHiddenFiles,
|
||||
workspaceStateKey,
|
||||
@@ -1007,12 +1031,16 @@ export function FileExplorerPane({
|
||||
onLayout: scrollbar.onLayout,
|
||||
});
|
||||
|
||||
const displayedError =
|
||||
error ??
|
||||
(!directories.has(".") && isHostUnavailable ? t("workspace.terminal.hostDisconnected") : null);
|
||||
const showInitialLoading = resolveShowInitialLoading({
|
||||
directories,
|
||||
isExplorerLoading,
|
||||
pendingRequest,
|
||||
isHostConnecting,
|
||||
});
|
||||
const showBackFromError = Boolean(error && selectedEntryPath);
|
||||
const showBackFromError = Boolean(displayedError && selectedEntryPath);
|
||||
const errorRecoveryPath = useMemo(() => getErrorRecoveryPath(explorerState), [explorerState]);
|
||||
|
||||
const rowActions = useMemo<EntryRowActions>(
|
||||
@@ -1184,7 +1212,7 @@ export function FileExplorerPane({
|
||||
style={styles.container}
|
||||
>
|
||||
<FileExplorerPaneContent
|
||||
error={error}
|
||||
error={displayedError}
|
||||
isCompact={isCompact}
|
||||
serverId={serverId}
|
||||
workspaceRoot={normalizedWorkspaceRoot}
|
||||
@@ -1551,14 +1579,19 @@ function resolveShowInitialLoading({
|
||||
directories,
|
||||
isExplorerLoading,
|
||||
pendingRequest,
|
||||
isHostConnecting,
|
||||
}: {
|
||||
directories: Map<string, unknown>;
|
||||
isExplorerLoading: boolean;
|
||||
pendingRequest: AgentFileExplorerState["pendingRequest"] | null;
|
||||
isHostConnecting: boolean;
|
||||
}): boolean {
|
||||
if (directories.has(".")) {
|
||||
return false;
|
||||
}
|
||||
if (isHostConnecting) {
|
||||
return true;
|
||||
}
|
||||
return Boolean(
|
||||
isExplorerLoading && pendingRequest?.mode === "list" && pendingRequest?.path === ".",
|
||||
);
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
resolveProvidersToFetch,
|
||||
requiresImportSessionsHostUpgrade,
|
||||
type SessionsQueryResult,
|
||||
type SessionsListing,
|
||||
sumFilteredAlreadyImportedCount,
|
||||
} from "@/components/import-session-sheet-view-model";
|
||||
|
||||
@@ -37,15 +38,13 @@ function entry(
|
||||
}
|
||||
|
||||
function settled(
|
||||
data: SessionsQueryResult["data"],
|
||||
flags?: Partial<Omit<SessionsQueryResult, "data">>,
|
||||
response: SessionsListing["response"],
|
||||
requestError: string | null = null,
|
||||
): SessionsQueryResult {
|
||||
return {
|
||||
data,
|
||||
isError: false,
|
||||
data: response || requestError !== null ? { response, requestError } : undefined,
|
||||
isLoading: false,
|
||||
isPending: false,
|
||||
...flags,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -181,7 +180,7 @@ describe("collectProviderErrorRows", () => {
|
||||
it("returns a row for each provider whose request failed", () => {
|
||||
const rows = collectProviderErrorRows(
|
||||
["claude", "codex"],
|
||||
[settled(undefined, { isError: true }), settled({ entries: [] })],
|
||||
[settled(undefined, ""), settled({ entries: [] })],
|
||||
new Map([["claude", "Claude Code"]]),
|
||||
);
|
||||
expect(rows).toEqual([
|
||||
@@ -206,22 +205,15 @@ describe("collectProviderErrorRows", () => {
|
||||
});
|
||||
|
||||
it("uses provider id when the label map has no entry", () => {
|
||||
const rows = collectProviderErrorRows(
|
||||
["codex"],
|
||||
[settled(undefined, { isError: true })],
|
||||
new Map(),
|
||||
);
|
||||
const rows = collectProviderErrorRows(["codex"], [settled(undefined, "")], new Map());
|
||||
expect(rows).toEqual([{ provider: "codex", label: "codex", message: null, retrying: false }]);
|
||||
});
|
||||
|
||||
it("shows the current request failure instead of an older provider error", () => {
|
||||
const query = {
|
||||
...settled(
|
||||
{ entries: [], providerErrors: [{ provider: "codex", message: "old provider failure" }] },
|
||||
{ isError: true },
|
||||
),
|
||||
error: new Error(" Connection closed. Reconnect the host and retry. "),
|
||||
};
|
||||
const query = settled(
|
||||
{ entries: [], providerErrors: [{ provider: "codex", message: "old provider failure" }] },
|
||||
" Connection closed. Reconnect the host and retry. ",
|
||||
);
|
||||
expect(collectProviderErrorRows(["codex"], [query], new Map())).toEqual([
|
||||
{
|
||||
provider: "codex",
|
||||
@@ -278,7 +270,7 @@ describe("hasMoreSessions", () => {
|
||||
|
||||
it("keeps reporting more while the next page replaces placeholder rows", () => {
|
||||
expect(
|
||||
hasMoreSessions([settled({ entries: [entry()] }, { isPlaceholderData: true })], 45),
|
||||
hasMoreSessions([{ ...settled({ entries: [entry()] }), isPlaceholderData: true }], 45),
|
||||
).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -30,16 +30,19 @@ export function requiresImportSessionsHostUpgrade(input: {
|
||||
return !input.supportsSnapshot || (Boolean(input.workspaceId) && !input.supportsWorkspaceTarget);
|
||||
}
|
||||
|
||||
interface SessionsResponse {
|
||||
entries: FetchRecentProviderSessionEntry[];
|
||||
filteredAlreadyImportedCount?: number;
|
||||
providerErrors?: Array<{ provider: string; message: string }>;
|
||||
}
|
||||
|
||||
export interface SessionsListing {
|
||||
response: SessionsResponse | undefined;
|
||||
requestError: string | null;
|
||||
}
|
||||
|
||||
export interface SessionsQueryResult {
|
||||
data:
|
||||
| {
|
||||
entries: FetchRecentProviderSessionEntry[];
|
||||
filteredAlreadyImportedCount?: number;
|
||||
providerErrors?: Array<{ provider: string; message: string }>;
|
||||
}
|
||||
| undefined;
|
||||
isError: boolean;
|
||||
error?: Error | null;
|
||||
data: SessionsListing | undefined;
|
||||
isFetching?: boolean;
|
||||
isLoading: boolean;
|
||||
isPending: boolean;
|
||||
@@ -78,8 +81,8 @@ export function aggregateSessionEntries(
|
||||
const seen = new Set<string>();
|
||||
const collected: FetchRecentProviderSessionEntry[] = [];
|
||||
for (const query of queries) {
|
||||
if (!query.data) continue;
|
||||
for (const entry of query.data.entries) {
|
||||
if (!query.data?.response) continue;
|
||||
for (const entry of query.data.response.entries) {
|
||||
const key = `${entry.providerId}:${entry.providerHandleId}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
@@ -97,7 +100,7 @@ export function sumFilteredAlreadyImportedCount(
|
||||
): number {
|
||||
let total = 0;
|
||||
for (const query of queries) {
|
||||
total += query.data?.filteredAlreadyImportedCount ?? 0;
|
||||
total += query.data?.response?.filteredAlreadyImportedCount ?? 0;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
@@ -114,7 +117,7 @@ export function hasMoreSessions(
|
||||
): boolean {
|
||||
if (nextPageLimit(limit) === limit) return false;
|
||||
return queries.some((entryQuery) => {
|
||||
const count = entryQuery.data?.entries.length ?? 0;
|
||||
const count = entryQuery.data?.response?.entries.length ?? 0;
|
||||
return entryQuery.isPlaceholderData ? count > 0 : count >= limit;
|
||||
});
|
||||
}
|
||||
@@ -142,11 +145,12 @@ export function collectProviderErrorRows(
|
||||
const query = queries[index];
|
||||
const provider = providersToFetch[index];
|
||||
if (!query || provider === undefined) continue;
|
||||
const failed = query.isError || (query.data?.providerErrors?.length ?? 0) > 0;
|
||||
if (!failed) continue;
|
||||
const failure = query.data?.providerErrors?.find((error) => error.provider === provider);
|
||||
const failureMessage = query.isError ? query.error?.message : failure?.message;
|
||||
const message = failureMessage?.trim() || null;
|
||||
const failure = query.data?.response?.providerErrors?.find(
|
||||
(error) => error.provider === provider,
|
||||
);
|
||||
const failureMessage = query.data?.requestError ?? failure?.message;
|
||||
if (failureMessage === undefined) continue;
|
||||
const message = failureMessage.trim() || null;
|
||||
rows.push({
|
||||
provider,
|
||||
label: providerLabelById.get(provider) ?? provider,
|
||||
|
||||
@@ -455,24 +455,43 @@ describe("ImportSessionSheet", () => {
|
||||
expect(screen.queryByText("No recent sessions to import.")).toBeNull();
|
||||
});
|
||||
|
||||
it("shows a fetch error state when recent provider sessions cannot be loaded", async () => {
|
||||
const fetchRecentProviderSessions = vi.fn(async () => {
|
||||
throw new Error("recent sessions unavailable");
|
||||
});
|
||||
const importAgent = vi.fn();
|
||||
|
||||
renderSheet(
|
||||
{ fetchRecentProviderSessions, importAgent } as Pick<
|
||||
DaemonClient,
|
||||
"fetchRecentProviderSessions" | "importAgent"
|
||||
>,
|
||||
{
|
||||
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
|
||||
it("keeps a request error visible while Retry is pending and clears it after success", async () => {
|
||||
const retry =
|
||||
Promise.withResolvers<Awaited<ReturnType<DaemonClient["fetchRecentProviderSessions"]>>>();
|
||||
let firstRequest = true;
|
||||
const client = createRecentSessionsClient(
|
||||
async () => {
|
||||
if (firstRequest) {
|
||||
firstRequest = false;
|
||||
throw new Error("recent sessions unavailable");
|
||||
}
|
||||
return retry.promise;
|
||||
},
|
||||
async () => {
|
||||
throw new Error("Unexpected import");
|
||||
},
|
||||
);
|
||||
|
||||
await screen.findByText("Could not load Claude Code sessions");
|
||||
screen.getByTestId("import-session-retry-claude");
|
||||
renderSheet(client, {
|
||||
snapshot: { supportsSnapshot: true, entries: [createSnapshotEntry("claude")] },
|
||||
});
|
||||
|
||||
await screen.findByText("recent sessions unavailable");
|
||||
fireEvent.click(screen.getByTestId("import-session-retry-claude"));
|
||||
|
||||
try {
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText("recent sessions unavailable")).toBeTruthy();
|
||||
expect(screen.getByRole("button", { name: "Retry" }).getAttribute("aria-disabled")).toBe(
|
||||
"true",
|
||||
);
|
||||
});
|
||||
} finally {
|
||||
retry.resolve({ requestId: "retry", entries: [] });
|
||||
}
|
||||
|
||||
await screen.findByText("No recent sessions to import.");
|
||||
expect(screen.queryByText("recent sessions unavailable")).toBeNull();
|
||||
});
|
||||
|
||||
it("loads recent provider sessions for the workspace and renders descriptor-owned labels", async () => {
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import React, { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { Pressable, type PressableStateCallbackType, Text, View } from "react-native";
|
||||
import { useMutation, useQueries, useQueryClient, type QueryClient } from "@tanstack/react-query";
|
||||
import {
|
||||
queryOptions,
|
||||
useMutation,
|
||||
useQueries,
|
||||
useQueryClient,
|
||||
type QueryClient,
|
||||
} from "@tanstack/react-query";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type {
|
||||
DaemonClient,
|
||||
@@ -42,6 +48,7 @@ import {
|
||||
PER_PROVIDER_LIMIT,
|
||||
previousPageLimit,
|
||||
type ProviderErrorRow,
|
||||
type SessionsListing,
|
||||
resolveImportTarget,
|
||||
resolveProvidersToFetch,
|
||||
requiresImportSessionsHostUpgrade,
|
||||
@@ -73,10 +80,6 @@ interface ImportSessionSheetProps {
|
||||
onImported?: (agent: ImportedAgent) => void;
|
||||
}
|
||||
|
||||
type RecentSessionsResponse = Awaited<
|
||||
ReturnType<RecentProviderSessionsClient["fetchRecentProviderSessions"]>
|
||||
>;
|
||||
|
||||
type SessionsQueryKey = ReadonlyArray<string | number | null>;
|
||||
|
||||
function buildSessionsQueryRoot(serverId: string | null, cwd: string | null) {
|
||||
@@ -98,18 +101,6 @@ function buildSessionsQueryKey(input: {
|
||||
];
|
||||
}
|
||||
|
||||
interface SessionsQueryConfig {
|
||||
queryKey: SessionsQueryKey;
|
||||
enabled: boolean;
|
||||
// A provider that cannot answer stays broken until the user asks again. React
|
||||
// Query's default retry would keep the header spinner turning and pile up
|
||||
// in-flight daemon requests behind a dead provider (#2512).
|
||||
retry: false;
|
||||
refetchOnMount: true;
|
||||
placeholderData: () => RecentSessionsResponse | undefined;
|
||||
queryFn: () => Promise<RecentSessionsResponse>;
|
||||
}
|
||||
|
||||
function buildSessionsQueriesConfig(args: {
|
||||
queryClient: QueryClient;
|
||||
providersToFetch: AgentProvider[] | null;
|
||||
@@ -120,39 +111,63 @@ function buildSessionsQueriesConfig(args: {
|
||||
query: string;
|
||||
limit: number;
|
||||
hostDisconnectedMessage?: string;
|
||||
}): SessionsQueryConfig[] {
|
||||
}) {
|
||||
const { queryClient, providersToFetch, visible, client, serverId, cwd, query, limit } = args;
|
||||
const { hostDisconnectedMessage } = args;
|
||||
if (providersToFetch === null) return [];
|
||||
const enabled = visible && Boolean(client);
|
||||
const previousLimit = previousPageLimit(limit);
|
||||
return providersToFetch.map((provider) => ({
|
||||
queryKey: buildSessionsQueryKey({ serverId, cwd, query, limit, provider }),
|
||||
enabled,
|
||||
retry: false as const,
|
||||
// An import can invalidate an inactive host. Refresh its listing when observed again.
|
||||
refetchOnMount: true as const,
|
||||
// While Load more fetches the next page, keep showing the page it grew from. React Query's
|
||||
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
|
||||
// has no previous data, so the rows would vanish and the list would remount at the top.
|
||||
placeholderData: () =>
|
||||
previousLimit === null
|
||||
? undefined
|
||||
: queryClient.getQueryData<RecentSessionsResponse>(
|
||||
buildSessionsQueryKey({ serverId, cwd, query, limit: previousLimit, provider }),
|
||||
),
|
||||
queryFn: async () => {
|
||||
if (!client) {
|
||||
throw new Error(hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"));
|
||||
}
|
||||
return await client.fetchRecentProviderSessions({
|
||||
...(cwd ? { cwd } : {}),
|
||||
providers: [provider],
|
||||
limit,
|
||||
...(query ? { query } : {}),
|
||||
});
|
||||
},
|
||||
}));
|
||||
const defaultStaleTime = queryClient.getDefaultOptions().queries?.staleTime;
|
||||
return providersToFetch.map((provider) => {
|
||||
const queryKey = buildSessionsQueryKey({ serverId, cwd, query, limit, provider });
|
||||
return queryOptions({
|
||||
queryKey,
|
||||
enabled,
|
||||
// Let the user retry a failed listing without an automatic retry loop.
|
||||
retry: false,
|
||||
// An import can invalidate an inactive host. Refresh its listing when observed again.
|
||||
refetchOnMount: true,
|
||||
// While Load more fetches the next page, keep showing the page it grew from. React Query's
|
||||
// keepPreviousData cannot do this here: useQueries gives a changed key a new observer, which
|
||||
// has no previous data, so the rows would vanish and the list would remount at the top.
|
||||
placeholderData: () => {
|
||||
if (previousLimit === null) return undefined;
|
||||
const previous = queryClient.getQueryData<SessionsListing>(
|
||||
buildSessionsQueryKey({ serverId, cwd, query, limit: previousLimit, provider }),
|
||||
);
|
||||
return previous?.response ? { response: previous.response, requestError: null } : undefined;
|
||||
},
|
||||
// Refetch failed listings when the sheet reopens.
|
||||
staleTime: (listingQuery) => {
|
||||
if (listingQuery.state.data?.requestError != null) return 0;
|
||||
if (typeof defaultStaleTime !== "function") return defaultStaleTime ?? 0;
|
||||
const cachedQuery = queryClient.getQueryCache().get(listingQuery.queryHash);
|
||||
return cachedQuery ? defaultStaleTime(cachedQuery) : 0;
|
||||
},
|
||||
queryFn: async (): Promise<SessionsListing> => {
|
||||
try {
|
||||
if (!client) {
|
||||
throw new Error(
|
||||
hostDisconnectedMessage ?? i18n.t("workspace.terminal.hostDisconnected"),
|
||||
);
|
||||
}
|
||||
const response = await client.fetchRecentProviderSessions({
|
||||
...(cwd ? { cwd } : {}),
|
||||
providers: [provider],
|
||||
limit,
|
||||
...(query ? { query } : {}),
|
||||
});
|
||||
return { response, requestError: null };
|
||||
} catch (error) {
|
||||
// Cache the last outcome so a new fetch cannot clear the error row.
|
||||
return {
|
||||
response: queryClient.getQueryData<SessionsListing>(queryKey)?.response,
|
||||
requestError: error instanceof Error ? error.message : String(error),
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
interface SheetStatusMessagesProps {
|
||||
@@ -808,7 +823,8 @@ export function ImportSessionSheet({
|
||||
(isQueryingProviders &&
|
||||
queries.some((providerQuery) => providerQuery.isLoading || providerQuery.isPending));
|
||||
const allQueriesErrored =
|
||||
isQueryingProviders && queries.every((providerQuery) => providerQuery.isError);
|
||||
isQueryingProviders &&
|
||||
queries.every((providerQuery) => providerQuery.data?.requestError != null);
|
||||
const allQueriesSettled =
|
||||
isQueryingProviders &&
|
||||
queries.every((providerQuery) => !providerQuery.isLoading && !providerQuery.isPending);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Animated } from "react-native";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { createIndicatorClock } from "./clock";
|
||||
import { type ClockDriver, createIndicatorClock } from "./clock";
|
||||
|
||||
const PERIOD_MS = 900;
|
||||
const STEPS = 27;
|
||||
@@ -35,6 +35,44 @@ function frames(hz: number, count: number): number[] {
|
||||
return Array.from({ length: count }, (_, frame) => (frame * 1000) / hz);
|
||||
}
|
||||
|
||||
// A driver that advances nothing by itself, so the test decides when each span ends and when the
|
||||
// native driver says where a stopped clock is.
|
||||
function heldDriver() {
|
||||
const spansFromMs: number[] = [];
|
||||
const reports: ((heldMs: number) => void)[] = [];
|
||||
let onEnd: ((result: { finished: boolean }) => void) | null = null;
|
||||
function end(finished: boolean) {
|
||||
const ended = onEnd;
|
||||
onEnd = null;
|
||||
ended?.({ finished });
|
||||
}
|
||||
return {
|
||||
drive(_elapsedMs: Animated.Value, fromMs: number): ClockDriver {
|
||||
spansFromMs.push(fromMs);
|
||||
return {
|
||||
start(ended) {
|
||||
onEnd = ended;
|
||||
},
|
||||
stop(onHeld) {
|
||||
reports.push(onHeld);
|
||||
end(false);
|
||||
},
|
||||
};
|
||||
},
|
||||
/** What the native driver reports when it has counted a whole span. */
|
||||
finish: () => end(true),
|
||||
/** The native driver's answer to the oldest stop it has not answered. */
|
||||
reportHeld: (heldMs: number) => reports.shift()?.(heldMs),
|
||||
running: () => onEnd !== null,
|
||||
spansFromMs,
|
||||
};
|
||||
}
|
||||
|
||||
// The clock stops after the commit that took its last indicator away.
|
||||
async function commit(): Promise<void> {
|
||||
await Promise.resolve();
|
||||
}
|
||||
|
||||
describe("indicator clock", () => {
|
||||
test("a cycle without steps advances with every frame", () => {
|
||||
expect(positionsAt([0, 16, 450, 899, 900, 916])).toEqual([0, 16, 450, 899, 0, 16]);
|
||||
@@ -87,7 +125,7 @@ describe("indicator clock", () => {
|
||||
const shimmerPeriodMs = shimmerSteps * STEP_MS;
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs);
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, heldDriver().drive);
|
||||
const stop = clock.run();
|
||||
|
||||
// The shared clock has been running for a while when the shimmer appears.
|
||||
@@ -120,4 +158,113 @@ describe("indicator clock", () => {
|
||||
|
||||
expect(read(shimmer)).toBe(0);
|
||||
});
|
||||
|
||||
test("a span that ends under a running indicator is followed by one from where it ended", async () => {
|
||||
let nowMs = 0;
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
// The JS thread hears about the end a few milliseconds after it.
|
||||
nowMs = 600_012;
|
||||
driver.finish();
|
||||
|
||||
expect(driver.running()).toBe(true);
|
||||
expect(driver.spansFromMs).toEqual([0, 600_000]);
|
||||
|
||||
stop();
|
||||
await commit();
|
||||
expect(driver.running()).toBe(false);
|
||||
});
|
||||
|
||||
test("a stopped clock holds its time and counts on from it", async () => {
|
||||
let nowMs = 0;
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
|
||||
|
||||
const stop = clock.run();
|
||||
nowMs = 5000;
|
||||
stop();
|
||||
await commit();
|
||||
expect(driver.running()).toBe(false);
|
||||
// The native driver started counting a frame after the JS thread asked.
|
||||
driver.reportHeld(4983);
|
||||
|
||||
nowMs = 90_000;
|
||||
clock.run();
|
||||
|
||||
expect(driver.spansFromMs).toEqual([0, 4983]);
|
||||
});
|
||||
|
||||
test("a clock restarted before the driver reports counts on from its own reading", async () => {
|
||||
let nowMs = 0;
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => nowMs, driver.drive);
|
||||
|
||||
const stopFirst = clock.run();
|
||||
nowMs = 5000;
|
||||
stopFirst();
|
||||
await commit();
|
||||
const stopSecond = clock.run();
|
||||
nowMs = 7000;
|
||||
stopSecond();
|
||||
await commit();
|
||||
// The answer to the first stop arrives after the second.
|
||||
driver.reportHeld(4983);
|
||||
clock.run();
|
||||
|
||||
expect(driver.spansFromMs).toEqual([0, 5000, 7000]);
|
||||
});
|
||||
|
||||
test("the clock keeps counting when one indicator takes over from another in a commit", async () => {
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(new Animated.Value(0), () => 0, driver.drive);
|
||||
|
||||
const stopChat = clock.run();
|
||||
stopChat();
|
||||
const stopSidebar = clock.run();
|
||||
await commit();
|
||||
|
||||
expect(driver.running()).toBe(true);
|
||||
expect(driver.spansFromMs).toEqual([0]);
|
||||
|
||||
stopSidebar();
|
||||
await commit();
|
||||
expect(driver.running()).toBe(false);
|
||||
});
|
||||
|
||||
test("a cycle with its own phase on a stopped clock starts where the clock will count on", async () => {
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
nowMs = 5000;
|
||||
stop();
|
||||
await commit();
|
||||
driver.reportHeld(4983);
|
||||
|
||||
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
|
||||
elapsedMs.setValue(4983);
|
||||
|
||||
expect(read(shimmer)).toBeLessThan(STEP_MS);
|
||||
});
|
||||
|
||||
test("a cycle with its own phase starts at its first step in a later span too", () => {
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
nowMs = 600_012;
|
||||
driver.finish();
|
||||
// The second span started at 600 000 on the clock, 12 ms late on the JS thread.
|
||||
nowMs = 640_012;
|
||||
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
|
||||
elapsedMs.setValue(640_000);
|
||||
stop();
|
||||
|
||||
expect(read(shimmer)).toBeLessThan(STEP_MS);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,11 +1,17 @@
|
||||
import { useEffect } from "react";
|
||||
import { Animated } from "react-native";
|
||||
import { Animated, Easing } from "react-native";
|
||||
|
||||
// A decay that never slows is a clock: with a velocity of one unit per millisecond the value is the
|
||||
// time since it started. Decay is the one native-driven animation that computes its value from the
|
||||
// frame's timestamp instead of replaying a 60 fps recording, so the motion is exact at any refresh
|
||||
// rate and never ends or loops.
|
||||
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
|
||||
// The clock counts time in spans this long: a linear timing of one unit per millisecond, which the
|
||||
// native driver reads off the frame's timestamp. Only the end of a span comes back to the JS
|
||||
// thread, which starts the next one where that one ended.
|
||||
//
|
||||
// A decay that never slows would count without spans, but the driver ends a decay whose value did
|
||||
// not move between two frames, and two frames that carry the same millisecond are enough. A timing
|
||||
// has no such check.
|
||||
//
|
||||
// The timing is sent to the driver as one value for every 60th of a second, so a longer span costs
|
||||
// more each time the clock starts.
|
||||
const SPAN_MS = 10 * 60 * 1000;
|
||||
|
||||
// The clock starts on a frame and advances a whole frame at a time, so at 60, 90 and 120 Hz a step
|
||||
// that is a whole number of frames long would turn over exactly on a frame, and rounding would
|
||||
@@ -14,7 +20,8 @@ const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: tr
|
||||
const STEP_LEAD = 1 / 8;
|
||||
|
||||
/**
|
||||
* Milliseconds, counted on the UI thread by React Native's native animation driver.
|
||||
* Milliseconds for which the clock has run, counted on the UI thread by React Native's native
|
||||
* animation driver.
|
||||
*
|
||||
* Views bound to it are updated by the native driver directly. Nothing reaches the JS thread, React
|
||||
* does not render, and no shadow tree is committed — which is what a Reanimated shared value costs
|
||||
@@ -37,28 +44,76 @@ export interface CycleOptions {
|
||||
export interface IndicatorClock {
|
||||
/** Where a cycle of `periodMs` currently is, as milliseconds into the cycle. */
|
||||
cycle(periodMs: number, options?: CycleOptions): Animated.AnimatedInterpolation<number>;
|
||||
/** Runs the clock until the returned function is called. It restarts from zero when idle. */
|
||||
/**
|
||||
* Runs the clock until the returned function is called. A clock nobody runs holds its time, and
|
||||
* counts on from it when it runs again, so a view bound to it stays where it stopped.
|
||||
*/
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
/** What advances the clock's value through one span, or until it is stopped. */
|
||||
export interface ClockDriver {
|
||||
start(onEnd: (result: { finished: boolean }) => void): void;
|
||||
/** Stops counting, then reports the time the clock stopped at. */
|
||||
stop(onHeld: (heldMs: number) => void): void;
|
||||
}
|
||||
|
||||
function countSpan(elapsedMs: Animated.Value, fromMs: number): ClockDriver {
|
||||
const span = Animated.timing(elapsedMs, {
|
||||
toValue: fromMs + SPAN_MS,
|
||||
duration: SPAN_MS,
|
||||
easing: Easing.linear,
|
||||
useNativeDriver: true,
|
||||
});
|
||||
return {
|
||||
start: (onEnd) => span.start(onEnd),
|
||||
stop: (onHeld) => elapsedMs.stopAnimation(onHeld),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `now` is the JS thread's view of the time the clock reads. The native driver starts the clock a
|
||||
* frame or two after `run()` is called, so a cycle with its own phase can start a step into its
|
||||
* pass, or a step before it; the run-in before the first position hides either.
|
||||
* The native driver owns the clock's time: the JS thread never sets it, only starts and stops the
|
||||
* counting. `now` lets the JS thread follow along. The native driver starts counting a frame or two
|
||||
* after it is asked, so a cycle with its own phase can start a step into its pass, or a step
|
||||
* before it; the run-in before the first position hides either.
|
||||
*/
|
||||
export function createIndicatorClock(
|
||||
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
|
||||
now: () => number = () => performance.now(),
|
||||
drive: (elapsedMs: Animated.Value, fromMs: number) => ClockDriver = countSpan,
|
||||
): IndicatorClock {
|
||||
let runners = 0;
|
||||
let ticking: Animated.CompositeAnimation | null = null;
|
||||
let startedAtMs = 0;
|
||||
let ticking: ClockDriver | null = null;
|
||||
// While the clock counts: when, on the JS thread, it read zero.
|
||||
let zeroAtMs = 0;
|
||||
// While it does not: the time it holds.
|
||||
let heldMs = 0;
|
||||
let lastStopped: ClockDriver | null = null;
|
||||
|
||||
function currentStepStartMs(stepMs: number): number {
|
||||
if (!ticking) {
|
||||
return 0;
|
||||
}
|
||||
return Math.floor((now() - startedAtMs) / stepMs) * stepMs;
|
||||
const elapsed = ticking ? now() - zeroAtMs : heldMs;
|
||||
return Math.floor(elapsed / stepMs) * stepMs;
|
||||
}
|
||||
|
||||
function count(fromMs: number) {
|
||||
zeroAtMs = now() - fromMs;
|
||||
const driver = drive(elapsedMs, fromMs);
|
||||
ticking = driver;
|
||||
driver.start(({ finished }) => {
|
||||
if (finished && ticking === driver) count(fromMs + SPAN_MS);
|
||||
});
|
||||
}
|
||||
|
||||
function hold() {
|
||||
if (runners > 0 || !ticking) return;
|
||||
const stopped = ticking;
|
||||
ticking = null;
|
||||
lastStopped = stopped;
|
||||
// The JS thread's reading stands until the native driver reports its own.
|
||||
heldMs = now() - zeroAtMs;
|
||||
stopped.stop((reportedMs) => {
|
||||
if (!ticking && lastStopped === stopped) heldMs = reportedMs;
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -76,17 +131,13 @@ export function createIndicatorClock(
|
||||
run() {
|
||||
runners += 1;
|
||||
if (!ticking) {
|
||||
elapsedMs.setValue(0);
|
||||
startedAtMs = now();
|
||||
ticking = Animated.decay(elapsedMs, CLOCK_CONFIG);
|
||||
ticking.start();
|
||||
count(heldMs);
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0) {
|
||||
ticking?.stop();
|
||||
ticking = null;
|
||||
}
|
||||
// One commit can take the last indicator away and bring another, as when a panel replaces
|
||||
// another. Stopping after the commit keeps the clock counting through that.
|
||||
if (runners === 0) queueMicrotask(hold);
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
@@ -35,15 +35,21 @@ function useReducedMotion(): boolean {
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a running indicator may move right now. It holds still when the system asks for reduced
|
||||
* motion, and while nobody can see it: in a retained panel that is not showing, or in an app that
|
||||
* is in the background.
|
||||
* What a running indicator does right now.
|
||||
*
|
||||
* An indicator that is not moving draws its resting frame and runs nothing.
|
||||
* - `moving`: it runs.
|
||||
* - `held`: nobody can see it, in a retained panel that is not showing or in an app that is in the
|
||||
* background. It runs nothing and keeps its place, so it continues from there when it is seen
|
||||
* again. A panel slides into view before it counts as showing, and an indicator that dropped to
|
||||
* its resting frame would jump when the slide ends.
|
||||
* - `resting`: the system asks for reduced motion. It draws its resting frame and runs nothing.
|
||||
*/
|
||||
export function useIndicatorMotion(): boolean {
|
||||
export type IndicatorMotion = "moving" | "held" | "resting";
|
||||
|
||||
export function useIndicatorMotion(): IndicatorMotion {
|
||||
const panelActive = useRetainedPanelActive();
|
||||
const appVisible = useAppVisible();
|
||||
const reducedMotion = useReducedMotion();
|
||||
return panelActive && appVisible && !reducedMotion;
|
||||
if (reducedMotion) return "resting";
|
||||
return panelActive && appVisible ? "moving" : "held";
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ const styles = StyleSheet.create({
|
||||
* Native label shimmer: a gradient band slides behind a mask cut in the shape of the label. The
|
||||
* native animation driver moves the band; see `indicator-motion/clock.ts`. The band rides the
|
||||
* shared clock, so its steps turn over on the same frames as the status rings', and starts its own
|
||||
* pass so the highlight enters from the left when it starts moving.
|
||||
* pass so the highlight enters from the left when it appears.
|
||||
*/
|
||||
export const LabelShimmer = memo(function LabelShimmer({
|
||||
label,
|
||||
@@ -61,21 +61,23 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
const moving = useIndicatorMotion() && measured;
|
||||
const motion = useIndicatorMotion();
|
||||
// A held band stays on the clock, so it keeps its place and its pass.
|
||||
const sweeping = motion !== "resting" && measured;
|
||||
const [gradientId] = useState(
|
||||
() => `shimmer-gradient-${Math.random().toString(36).substring(2, 9)}`,
|
||||
);
|
||||
useRunningClock(sharedIndicatorClock, moving);
|
||||
useRunningClock(sharedIndicatorClock, motion === "moving" && measured);
|
||||
|
||||
const { durationMs, steps } = getShimmerCycle(label, secondaryLabel);
|
||||
const { peakWidth, fromX, toX } = getRowSweep(rowSize.width);
|
||||
const { width, height } = rowSize;
|
||||
|
||||
const trackStyle = useMemo(() => [styles.track, { width, height }], [height, width]);
|
||||
// Built again each time the band starts moving, so each start begins a new pass.
|
||||
// Built again each time the band appears, so each appearance begins a new pass.
|
||||
const bandStyle = useMemo(
|
||||
() =>
|
||||
moving
|
||||
sweeping
|
||||
? [
|
||||
styles.band,
|
||||
{ width: peakWidth, height },
|
||||
@@ -90,7 +92,7 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
},
|
||||
]
|
||||
: null,
|
||||
[durationMs, fromX, height, moving, peakWidth, steps, toX],
|
||||
[durationMs, fromX, height, sweeping, peakWidth, steps, toX],
|
||||
);
|
||||
const maskElement = useMemo(
|
||||
() => (
|
||||
@@ -110,7 +112,7 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
[height, label, labelStyle, secondaryLabel, secondaryLabelStyle, width],
|
||||
);
|
||||
|
||||
if (!moving) {
|
||||
if (!sweeping) {
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,7 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { labelSpan, secondarySpan } = measurements;
|
||||
const moving = useIndicatorMotion();
|
||||
const moving = useIndicatorMotion() === "moving";
|
||||
const { durationMs, steps } = getShimmerCycle(label, secondaryLabel);
|
||||
const sweep = getTextSweep({ labelSpan, secondarySpan: secondaryLabel ? secondarySpan : null });
|
||||
|
||||
|
||||
@@ -167,6 +167,79 @@ describe("resolveMarkdownPreviewImageSource", () => {
|
||||
}),
|
||||
).toBe("C:/Users/test/repo/images/hero.png");
|
||||
});
|
||||
|
||||
it("keeps extended-length local Windows drive paths and local drive file URIs", () => {
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source: "\\\\?\\C:\\foo\\bar.png",
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: "C:\\repo",
|
||||
}),
|
||||
).toBe("C:/foo/bar.png");
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source: "file:///C:/foo/bar.png",
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: "C:\\repo",
|
||||
}),
|
||||
).toBe("C:/foo/bar.png");
|
||||
});
|
||||
|
||||
it.each([
|
||||
"\\\\host\\share\\x.png",
|
||||
"//host/share/x.png",
|
||||
"\\\\?\\UNC\\host\\share\\x.png",
|
||||
"file://host/share/x.png",
|
||||
"\\\\.\\pipe\\foo",
|
||||
"\\\\?\\Volume{01234567-89ab-cdef-0123-456789abcdef}",
|
||||
])("rejects UNC, remote file URI, and Windows device source %s", (source) => {
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source,
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: "C:\\repo",
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("allows UNC and relative images inside a UNC workspace while rejecting paths outside it", () => {
|
||||
const uncRoot = "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj";
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source: "\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png",
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: uncRoot,
|
||||
}),
|
||||
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png");
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source: "file://wsl.localhost/Ubuntu/home/me/proj/shot.png?v=1#top",
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: uncRoot,
|
||||
}),
|
||||
).toBe("\\\\wsl.localhost\\Ubuntu\\home\\me\\proj\\shot.png");
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source: "./images/hero.png",
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: uncRoot,
|
||||
}),
|
||||
).toBe("//wsl.localhost/Ubuntu/home/me/proj/docs/images/hero.png");
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source: "../../../../outside.png",
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: uncRoot,
|
||||
}),
|
||||
).toBeNull();
|
||||
expect(
|
||||
resolveMarkdownPreviewImageSource({
|
||||
source: "\\\\other\\share\\leak.png",
|
||||
markdownPath: "docs/guide.md",
|
||||
workspaceRoot: uncRoot,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("local assistant Markdown images", () => {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { localFileSourceToPath } from "@/attachments/utils";
|
||||
import {
|
||||
isUncPathWithinRoot,
|
||||
parseUncPath,
|
||||
stripLocalImageQueryAndFragment,
|
||||
} from "@getpaseo/protocol/path-utils";
|
||||
import { normalizeLocalImagePath } from "@/utils/assistant-image-source";
|
||||
import { isAbsolutePath } from "@/utils/path";
|
||||
|
||||
function trimTrailingSeparators(value: string): string {
|
||||
@@ -126,9 +131,10 @@ export function resolveMarkdownPreviewImageSource(input: {
|
||||
return source;
|
||||
}
|
||||
|
||||
const pathSource = source.replace(/[?#].*$/, "");
|
||||
const path = localFileSourceToPath(
|
||||
pathSource.startsWith("file://") ? pathSource : decodeRelativeSource(pathSource),
|
||||
const pathSource = stripLocalImageQueryAndFragment(source);
|
||||
const path = normalizeLocalImagePath(
|
||||
/^file:/i.test(pathSource) ? pathSource : decodeRelativeSource(pathSource),
|
||||
{ workspaceRoot: input.workspaceRoot },
|
||||
);
|
||||
if (!path) {
|
||||
return null;
|
||||
@@ -146,5 +152,13 @@ export function resolveMarkdownPreviewImageSource(input: {
|
||||
return path;
|
||||
}
|
||||
|
||||
return joinAbsolute(directory, path);
|
||||
const joined = joinAbsolute(directory, path);
|
||||
if (!joined) {
|
||||
return null;
|
||||
}
|
||||
const joinedUnc = parseUncPath(joined);
|
||||
if (joinedUnc && !isUncPathWithinRoot(joinedUnc, input.workspaceRoot)) {
|
||||
return null;
|
||||
}
|
||||
return joined;
|
||||
}
|
||||
|
||||
@@ -62,17 +62,24 @@ afterEach(() => {
|
||||
__setAttachmentStoreForTests(null);
|
||||
});
|
||||
|
||||
function renderMarkdownSource(text: string, initialProps: MarkdownImageContext) {
|
||||
function renderMarkdownSource(
|
||||
text: string,
|
||||
initialProps: MarkdownImageContext,
|
||||
options?: Parameters<typeof useMarkdownSource>[2],
|
||||
) {
|
||||
// No retries: a failed read settles at once. For a host's Markdown this is the state once the
|
||||
// retries have run out on a host that is slow to connect.
|
||||
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
const rendered = renderHook((props: MarkdownImageContext) => useMarkdownSource(text, props), {
|
||||
wrapper,
|
||||
initialProps,
|
||||
});
|
||||
const rendered = renderHook(
|
||||
(props: MarkdownImageContext) => useMarkdownSource(text, props, options),
|
||||
{
|
||||
wrapper,
|
||||
initialProps,
|
||||
},
|
||||
);
|
||||
return { ...rendered, queryClient };
|
||||
}
|
||||
|
||||
@@ -104,3 +111,32 @@ it("shows the alt text of a file image in Markdown that belongs to no host", asy
|
||||
expect(result.current.markdown.replace(PENDING_MARKDOWN_IMAGE, "pending")).toBe("Chart"),
|
||||
);
|
||||
});
|
||||
|
||||
it("never calls client.readFile when destinations are restricted to https", async () => {
|
||||
const files = createHostFiles();
|
||||
const { result, queryClient } = renderMarkdownSource(
|
||||
"   ",
|
||||
{ serverId: "srv_test", workspaceRoot: "/repo", client: files },
|
||||
{ destinations: "https" },
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.isFetching()).toBe(0);
|
||||
expect(result.current.markdown).toBe("Local Relative Unc RemoteFile");
|
||||
});
|
||||
expect(files.reads).toEqual([]);
|
||||
});
|
||||
|
||||
it("never calls client.readFile for UNC, remote file URI, or Windows device paths in host Markdown", async () => {
|
||||
const files = createHostFiles();
|
||||
const { result, queryClient } = renderMarkdownSource(
|
||||
"   ",
|
||||
{ serverId: "srv_test", workspaceRoot: "C:/repo", client: files },
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(queryClient.isFetching()).toBe(0);
|
||||
expect(result.current.markdown).toBe("Unc SlashUnc Remote Pipe");
|
||||
});
|
||||
expect(files.reads).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -14,7 +14,7 @@ import { resolveAssistantImageSource } from "@/utils/assistant-image-source";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { AttachmentMetadata } from "@/attachments/types";
|
||||
import { resolveMarkdownPreviewImageSource } from "./image-source";
|
||||
import { prepareMarkdownSource } from "./source";
|
||||
import { prepareMarkdownSource, type MarkdownDestinations } from "./source";
|
||||
import { decodeMarkdownImage, getMarkdownImageStatus } from "./image-decoding";
|
||||
|
||||
const urls = createAssistantImageAcquisitionCache<{ uri: string; attachment: AttachmentMetadata }>({
|
||||
@@ -41,23 +41,29 @@ export function useMarkdownSource(
|
||||
links: {
|
||||
commandNames?: ReadonlySet<string>;
|
||||
forgeReferencePattern?: string;
|
||||
external?: boolean;
|
||||
destinations?: MarkdownDestinations;
|
||||
} = {},
|
||||
/** Identity of this occurrence's image acquisitions. Defaults to one per call site. */
|
||||
occurrence?: string,
|
||||
) {
|
||||
const occurrenceKey = useId();
|
||||
const { commandNames, forgeReferencePattern, external } = links;
|
||||
const ownOccurrence = useId();
|
||||
const occurrenceKey = occurrence ?? ownOccurrence;
|
||||
const { commandNames, forgeReferencePattern, destinations = "host" } = links;
|
||||
const httpsOnly = destinations === "https";
|
||||
const workspaceRoot = httpsOnly ? undefined : context.workspaceRoot;
|
||||
const prepared = useMemo(
|
||||
() =>
|
||||
prepareMarkdownSource(text, context.workspaceRoot, {
|
||||
prepareMarkdownSource(text, workspaceRoot, {
|
||||
supportsSvg: isWeb,
|
||||
commandNames,
|
||||
forgeReferencePattern,
|
||||
external,
|
||||
destinations,
|
||||
}),
|
||||
[text, context.workspaceRoot, commandNames, forgeReferencePattern, external],
|
||||
[text, workspaceRoot, commandNames, forgeReferencePattern, destinations],
|
||||
);
|
||||
const sources = [...new Set(prepared.images.map((image) => image.source))];
|
||||
const acquisitions = sources.map((source) => {
|
||||
if (httpsOnly) return null;
|
||||
const resolved = resolveMarkdownPreviewImageSource({
|
||||
source,
|
||||
markdownPath: context.filePath ?? "",
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import {
|
||||
isMarkdownParserReady,
|
||||
preloadMarkdownParser as preloadEngineParser,
|
||||
} from "react-native-enriched-markdown";
|
||||
|
||||
/**
|
||||
* Starts initializing the web Markdown WASM parser ahead of the first render.
|
||||
* Safe to call repeatedly and a no-op on native.
|
||||
*/
|
||||
export function preloadMarkdownParser(): void {
|
||||
void preloadEngineParser().catch(() => {
|
||||
// EnrichedMarkdownText renders a plain-text fallback if parser initialization fails.
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* True once synchronous Markdown parsing is available, so surfaces with a loading
|
||||
* skeleton can keep it visible instead of collapsing to an empty container while
|
||||
* WASM compiles on cold start.
|
||||
*/
|
||||
export function useMarkdownParserReady({ enabled = true }: { enabled?: boolean } = {}): boolean {
|
||||
const [ready, setReady] = useState(isMarkdownParserReady);
|
||||
useEffect(() => {
|
||||
if (!enabled || ready) return;
|
||||
if (isMarkdownParserReady()) {
|
||||
setReady(true);
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
void preloadEngineParser()
|
||||
.catch(() => {
|
||||
// Still resolve readiness so EnrichedMarkdownText can render its fallback.
|
||||
})
|
||||
.finally(() => {
|
||||
if (!cancelled) setReady(true);
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [enabled, ready]);
|
||||
return ready;
|
||||
}
|
||||
@@ -1,6 +1,11 @@
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { toNativeLinkRecognition } from "react-native-enriched-markdown/src/utils/regexParser";
|
||||
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import {
|
||||
isMarkdownParserReady,
|
||||
parseMarkdown,
|
||||
parseMarkdownSync,
|
||||
preloadMarkdownParser,
|
||||
} from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import { recognizeTextLinks } from "react-native-enriched-markdown/src/web/recognizeTextLinks";
|
||||
import { matchCommandLink } from "@/agent-commands";
|
||||
import { createForgeShorthand } from "@/git/forge-shorthand";
|
||||
@@ -1340,11 +1345,15 @@ it.each([false, true])(
|
||||
},
|
||||
);
|
||||
|
||||
describe("external Markdown", () => {
|
||||
const external = (source: string) => prepareMarkdownSource(source, undefined, { external: true });
|
||||
describe("https-only destinations Markdown", () => {
|
||||
const httpsOnly = (source: string, forgeReferencePattern?: string) =>
|
||||
prepareMarkdownSource(source, "/repo", {
|
||||
destinations: "https",
|
||||
forgeReferencePattern,
|
||||
});
|
||||
|
||||
it("recognizes no files, forge references or commands, only https URLs", () => {
|
||||
const { linkRecognition } = external("Needs Node.js 22 and `~/.dsh/.env`, see #12");
|
||||
it("recognizes no files, forge references or commands when forge shorthand is omitted", () => {
|
||||
const { linkRecognition } = httpsOnly("Needs Node.js 22 and `~/.dsh/.env`, see #12");
|
||||
expect("Needs Node.js 22, see #12".match(linkRecognition.text)).toBeNull();
|
||||
expect(linkRecognition.inlineCode.test("~/.dsh/.env")).toBe(false);
|
||||
expect("Docs at https://example.com/a.".match(linkRecognition.text)).toEqual([
|
||||
@@ -1352,17 +1361,48 @@ describe("external Markdown", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps https links and leaves any other destination as its label", () => {
|
||||
it("keeps forge references alongside https URLs without recognizing local file paths", () => {
|
||||
const shorthand = createForgeShorthand({
|
||||
forge: "github",
|
||||
remoteUrl: "https://github.com/acme/widgets.git",
|
||||
});
|
||||
expect(shorthand).not.toBeNull();
|
||||
const { linkRecognition } = httpsOnly(
|
||||
"Fixes #123 and other/repo#456, touches src/index.ts and `package.json`, see https://example.com/docs",
|
||||
shorthand!.pattern,
|
||||
);
|
||||
expect(
|
||||
external(
|
||||
"[Guide](docs/guide.md), [site](https://example.com), [mail](mailto:a@b.c), [ref][r]\n\n[r]: ./x",
|
||||
).render(),
|
||||
).toBe("Guide, [site](https://example.com), mail, ref\n\n[r]: ./x");
|
||||
"Fixes #123 and other/repo#456, touches src/index.ts, see https://example.com/docs".match(
|
||||
linkRecognition.text,
|
||||
),
|
||||
).toEqual(["#123", "other/repo#456", "https://example.com/docs"]);
|
||||
expect(linkRecognition.inlineCode.test("package.json")).toBe(false);
|
||||
expect(linkRecognition.inlineCode.test("https://example.com/docs")).toBe(true);
|
||||
});
|
||||
|
||||
it("shows a relative image as its alt text", () => {
|
||||
expect(external(" ").render()).toBe(
|
||||
"Demo ",
|
||||
it("keeps https links and leaves any other destination as its label", () => {
|
||||
expect(
|
||||
httpsOnly(
|
||||
"[Guide](docs/guide.md), [Local](/etc/passwd), [site](https://example.com), [mail](mailto:a@b.c), [ref][r]\n\n[r]: ./x",
|
||||
).render(),
|
||||
).toBe("Guide, Local, [site](https://example.com), mail, ref\n\n[r]: ./x");
|
||||
});
|
||||
|
||||
it("keeps only https images and leaves relative, local, and UNC images as alt text", () => {
|
||||
const prepared = httpsOnly(
|
||||
"   ",
|
||||
);
|
||||
expect(prepared.images.map((image) => image.source)).toEqual(["https://x/a.png"]);
|
||||
expect(prepared.render()).toBe("Demo Local Unc ");
|
||||
});
|
||||
});
|
||||
|
||||
describe("web Markdown parser preload", () => {
|
||||
it("marks the WASM parser ready and enables synchronous parsing after preload", async () => {
|
||||
await preloadMarkdownParser();
|
||||
expect(isMarkdownParserReady()).toBe(true);
|
||||
const ast = parseMarkdownSync("# Heading\n\nBody");
|
||||
expect(ast).not.toBeNull();
|
||||
expect(ast?.children?.map((node) => node.type)).toEqual(["Heading", "Paragraph"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { memo, useMemo, useRef, useState, type ComponentProps } from "react";
|
||||
import { memo, useId, useMemo, useRef, useState, type ComponentProps } from "react";
|
||||
import { EnrichedMarkdownText, type LinkPressEvent } from "react-native-enriched-markdown";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
@@ -20,21 +20,23 @@ 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";
|
||||
import { PENDING_MARKDOWN_IMAGE, type MarkdownDestinations } from "./source";
|
||||
import {
|
||||
createStreamingMarkdownSplitter,
|
||||
createStreamingMarkdownStabilizer,
|
||||
PENDING_MARKDOWN_LINK,
|
||||
splitStreamingMarkdown,
|
||||
} from "./streaming";
|
||||
import { MarkdownStreamingContext } from "./streaming-context";
|
||||
import { useMarkdownSource, type MarkdownImageContext } from "./images";
|
||||
|
||||
import { MermaidFence, splitMermaidFences } from "./fence/mermaid";
|
||||
|
||||
export type { MarkdownDestinations };
|
||||
export type MarkdownSoftBreaks = "break" | "join";
|
||||
|
||||
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
|
||||
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
// A README is written for its forge, where the lines of a paragraph join into one.
|
||||
const EXTERNAL_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
|
||||
const JOINED_SOFT_BREAKS_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
|
||||
|
||||
// Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it.
|
||||
const markdownStyle =
|
||||
@@ -61,46 +63,75 @@ export interface MarkdownRendererProps extends MarkdownImageContext {
|
||||
muted?: boolean;
|
||||
selectable?: boolean;
|
||||
streaming?: boolean;
|
||||
onLinkPress?: (url: string) => unknown;
|
||||
agentCommands?: boolean;
|
||||
/**
|
||||
* Author-controlled Markdown from outside this host, such as a plugin README: only its https
|
||||
* links and images work, nothing is read as a file, forge reference or command, and the lines of
|
||||
* a paragraph join as they do on its forge.
|
||||
* Which link and image destinations are allowed.
|
||||
* - `"host"` (default): host/workspace file links, host images, and web URLs.
|
||||
* - `"https"`: absolute `https://` links and images only; never reads host files or recognizes local paths.
|
||||
*/
|
||||
external?: boolean;
|
||||
destinations?: MarkdownDestinations;
|
||||
/** Recognize workspace forge references such as `#123` when a forge context is present. Defaults to `true`. */
|
||||
forgeShorthand?: boolean;
|
||||
/** Whether single newlines inside a paragraph break the line (`"break"`, default) or join into one line (`"join"`). */
|
||||
softBreaks?: MarkdownSoftBreaks;
|
||||
}
|
||||
|
||||
/** All Markdown surfaces share the same engine and source adaptation. */
|
||||
export const MarkdownRenderer = memo(function MarkdownRenderer(props: MarkdownRendererProps) {
|
||||
const nativeStreaming = !isWeb && !!props.streaming;
|
||||
// Only completed lines affect block closure. Do not run mdast on every reveal frame.
|
||||
const completeLines = nativeStreaming
|
||||
? props.text.slice(0, props.text.lastIndexOf("\n") + 1)
|
||||
: "";
|
||||
const boundary = useMemo(
|
||||
() => splitStreamingMarkdown(completeLines, true).head.length,
|
||||
[completeLines],
|
||||
);
|
||||
const tailStabilizerRef = useRef<ReturnType<typeof createStreamingMarkdownStabilizer> | null>(
|
||||
null,
|
||||
);
|
||||
const [split] = useState(createStreamingMarkdownSplitter);
|
||||
const [stabilizeTail] = useState(() => createStreamingMarkdownStabilizer().stabilize);
|
||||
// Head and tail are one message: an image keeps its acquisition when its block moves into the head.
|
||||
const imageOccurrence = useId();
|
||||
const Part = props.agentCommands ? CommandMarkdownPart : MarkdownPart;
|
||||
if (!nativeStreaming || boundary === 0) return <Part {...props} />;
|
||||
const tail = (tailStabilizerRef.current ??= createStreamingMarkdownStabilizer()).stabilize(
|
||||
props.text.slice(boundary),
|
||||
);
|
||||
const { head, tail } = props.streaming ? split(props.text) : { head: [], tail: "" };
|
||||
// Without a head, the whole message is the first part.
|
||||
const parts =
|
||||
head.length === 0
|
||||
? [{ text: props.text, streaming: props.streaming }]
|
||||
: head.map((text) => ({ text, streaming: false }));
|
||||
const stableTail = head.length === 0 ? "" : stabilizeTail(tail);
|
||||
// The first part stays mounted from the first streamed frame to the completed message, so
|
||||
// completion and every boundary move re-render it instead of replacing it. That needs the same
|
||||
// children shape in every render: the parts, then the tail slot. Sealed head parts keep their
|
||||
// text, so they do not render again. A part is keyed by where it starts in the message, which
|
||||
// never changes while it streams.
|
||||
let partStart = 0;
|
||||
return (
|
||||
<MarkdownBlockStack>
|
||||
<Part {...props} text={props.text.slice(0, boundary)} streaming={false} />
|
||||
{tail.trim().length > 0 ? <Part {...props} text={tail} streaming preStabilized /> : null}
|
||||
{parts.map((part) => {
|
||||
const start = partStart;
|
||||
partStart += part.text.length;
|
||||
return (
|
||||
<Part
|
||||
key={start}
|
||||
{...props}
|
||||
text={part.text}
|
||||
streaming={part.streaming}
|
||||
imageOccurrence={imageOccurrence}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
{stableTail.trim().length > 0 ? (
|
||||
<Part
|
||||
key="tail"
|
||||
{...props}
|
||||
text={stableTail}
|
||||
streaming
|
||||
preStabilized
|
||||
imageOccurrence={imageOccurrence}
|
||||
/>
|
||||
) : null}
|
||||
</MarkdownBlockStack>
|
||||
);
|
||||
});
|
||||
|
||||
const CommandMarkdownPart = memo(function CommandMarkdownPart(
|
||||
props: MarkdownRendererProps & { preStabilized?: boolean },
|
||||
) {
|
||||
interface MarkdownPartProps extends MarkdownRendererProps {
|
||||
preStabilized?: boolean;
|
||||
/** Identity of the message's image acquisitions, shared by its parts. */
|
||||
imageOccurrence: string;
|
||||
}
|
||||
|
||||
const CommandMarkdownPart = memo(function CommandMarkdownPart(props: MarkdownPartProps) {
|
||||
const commandHints = useAgentCommandHints();
|
||||
return <MarkdownPart {...props} commandHints={commandHints} />;
|
||||
});
|
||||
@@ -117,23 +148,12 @@ function MarkdownText(props: ComponentProps<typeof ThemedMarkdown> & { markdown:
|
||||
return <ThemedMarkdown {...props} {...longPress} />;
|
||||
}
|
||||
|
||||
const MarkdownPart = memo(function MarkdownPart({
|
||||
text,
|
||||
compact = false,
|
||||
muted = false,
|
||||
selectable = true,
|
||||
streaming = false,
|
||||
preStabilized = false,
|
||||
onLinkPress,
|
||||
agentCommands: _agentCommands,
|
||||
external = false,
|
||||
commandHints = null,
|
||||
...imageContext
|
||||
}: MarkdownRendererProps & { commandHints?: CommandHints | null; preStabilized?: boolean }) {
|
||||
const environment = useAssistantFileLinkEnvironment();
|
||||
const actions = useAssistantFileLinkActions();
|
||||
const workspaceForgeShorthand = useForgeShorthand();
|
||||
const forgeShorthand = external ? null : workspaceForgeShorthand;
|
||||
function resolveHostImageContext(
|
||||
destinations: MarkdownDestinations,
|
||||
imageContext: MarkdownImageContext,
|
||||
environment: ReturnType<typeof useAssistantFileLinkEnvironment>,
|
||||
): MarkdownImageContext {
|
||||
if (destinations === "https") return {};
|
||||
const environmentMatchesHost =
|
||||
!imageContext.serverId || imageContext.serverId === environment.serverId;
|
||||
const client =
|
||||
@@ -141,6 +161,34 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
(environmentMatchesHost && environment.client?.readFile
|
||||
? { readFile: environment.client.readFile.bind(environment.client) }
|
||||
: undefined);
|
||||
return {
|
||||
workspaceRoot: environmentMatchesHost ? environment.workspaceRoot : undefined,
|
||||
serverId: environment.serverId,
|
||||
...imageContext,
|
||||
client,
|
||||
};
|
||||
}
|
||||
|
||||
const MarkdownPart = memo(function MarkdownPart({
|
||||
text,
|
||||
compact = false,
|
||||
muted = false,
|
||||
selectable = true,
|
||||
streaming = false,
|
||||
preStabilized = false,
|
||||
agentCommands: _agentCommands,
|
||||
destinations = "host",
|
||||
forgeShorthand = true,
|
||||
softBreaks = "break",
|
||||
commandHints = null,
|
||||
imageOccurrence,
|
||||
...imageContext
|
||||
}: MarkdownPartProps & { commandHints?: CommandHints | null }) {
|
||||
const httpsOnly = destinations === "https";
|
||||
const environment = useAssistantFileLinkEnvironment();
|
||||
const actions = useAssistantFileLinkActions();
|
||||
const workspaceForgeShorthand = useForgeShorthand();
|
||||
const activeForgeShorthand = forgeShorthand ? workspaceForgeShorthand : null;
|
||||
const stabilizerRef = useRef<ReturnType<typeof createStreamingMarkdownStabilizer> | null>(null);
|
||||
const stabilizedText = useMemo(() => {
|
||||
if (!streaming || preStabilized) return text;
|
||||
@@ -148,31 +196,27 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
}, [streaming, preStabilized, text]);
|
||||
const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(
|
||||
stabilizedText,
|
||||
{
|
||||
workspaceRoot: environmentMatchesHost ? environment.workspaceRoot : undefined,
|
||||
serverId: environment.serverId,
|
||||
...imageContext,
|
||||
client,
|
||||
},
|
||||
resolveHostImageContext(destinations, imageContext, environment),
|
||||
{
|
||||
commandNames: commandHints?.names,
|
||||
forgeReferencePattern: forgeShorthand?.pattern,
|
||||
external,
|
||||
forgeReferencePattern: activeForgeShorthand?.pattern,
|
||||
destinations,
|
||||
},
|
||||
imageOccurrence,
|
||||
);
|
||||
const [image, setImage] = useState<ImageLightboxSource | null>(null);
|
||||
// What a link is, for pressing it and for its menu alike.
|
||||
const readLink = useStableEvent(({ url, sourceType }: LinkPressEvent): ReadMarkdownLink => {
|
||||
if (streaming && url === PENDING_MARKDOWN_LINK) return { kind: "inert" };
|
||||
if (external) {
|
||||
const command = commandHints && matchCommandLink(url, sourceType, commandHints.names);
|
||||
if (command) return { kind: "command", command };
|
||||
const forgeUrl = sourceType === "text" ? activeForgeShorthand?.resolve(url) : null;
|
||||
if (forgeUrl) return { kind: "web", url: forgeUrl };
|
||||
if (httpsOnly) {
|
||||
// The parser still autolinks bare http, www and email text; only https links open.
|
||||
const safe = pluginOverviewUrl(url);
|
||||
return safe ? { kind: "web", url: safe } : { kind: "inert" };
|
||||
}
|
||||
const command = commandHints && matchCommandLink(url, sourceType, commandHints.names);
|
||||
if (command) return { kind: "command", command };
|
||||
const forgeUrl = sourceType === "text" ? forgeShorthand?.resolve(url) : null;
|
||||
if (forgeUrl) return { kind: "web", url: forgeUrl };
|
||||
return { kind: "source", source: linkSource(url, sourceType) };
|
||||
});
|
||||
const pressLink = useStableEvent((event: LinkPressEvent) => {
|
||||
@@ -182,15 +226,14 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
} 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");
|
||||
actions.open(link.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;
|
||||
!httpsOnly && 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);
|
||||
@@ -223,7 +266,7 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
uniProps={pickMarkdownStyle(compact, muted)}
|
||||
flavor="github"
|
||||
selectable={selectable}
|
||||
md4cFlags={external ? EXTERNAL_MD4C_FLAGS : MD4C_FLAGS}
|
||||
md4cFlags={softBreaks === "join" ? JOINED_SOFT_BREAKS_MD4C_FLAGS : MD4C_FLAGS}
|
||||
linkRecognition={linkRecognition}
|
||||
enableTaskListItemToggle={false}
|
||||
enableLinkPreview={false}
|
||||
|
||||
@@ -57,11 +57,24 @@ function textPattern(forgeReferencePattern?: string): RegExp {
|
||||
return pattern;
|
||||
}
|
||||
|
||||
// External Markdown links only what its author wrote as an https URL.
|
||||
const EXTERNAL_LINKS = {
|
||||
text: new RegExp(BARE_URL.replace("https?", "https"), "g"),
|
||||
inlineCode: /^https:\/\/[^\s<>]+$/,
|
||||
};
|
||||
// External/https-only Markdown links only what its author wrote as an https URL,
|
||||
// plus optional forge shorthand when the caller enables it.
|
||||
const HTTPS_BARE_URL = BARE_URL.replace("https?", "https");
|
||||
const HTTPS_TEXT_PATTERN = new RegExp(HTTPS_BARE_URL, "g");
|
||||
const HTTPS_INLINE_CODE_PATTERN = /^https:\/\/[^\s<>]+$/;
|
||||
const httpsTextPatternsByForgeReference = new Map<string, RegExp>();
|
||||
|
||||
function httpsTextPattern(forgeReferencePattern?: string): RegExp {
|
||||
if (!forgeReferencePattern) return HTTPS_TEXT_PATTERN;
|
||||
let pattern = httpsTextPatternsByForgeReference.get(forgeReferencePattern);
|
||||
if (!pattern) {
|
||||
pattern = new RegExp(String.raw`(?:${HTTPS_BARE_URL}|${forgeReferencePattern})`, "g");
|
||||
httpsTextPatternsByForgeReference.set(forgeReferencePattern, pattern);
|
||||
}
|
||||
return pattern;
|
||||
}
|
||||
|
||||
export type MarkdownDestinations = "host" | "https";
|
||||
|
||||
function linkMetadata(inlineCodePaths: ReadonlySet<string>, forgeReferencePattern?: string) {
|
||||
// The engine accepts regexes on both platforms. Classify complete code spans
|
||||
@@ -167,11 +180,12 @@ export function prepareMarkdownSource(
|
||||
/** Regex source for forge references such as `#12`; see `@/git/forge-shorthand`. */
|
||||
forgeReferencePattern?: string;
|
||||
/**
|
||||
* Author-controlled Markdown from outside this host, such as a plugin README. It follows the
|
||||
* registry's overview contract: only absolute https links and images, and nothing is
|
||||
* recognized as a file, forge reference or command.
|
||||
* Allowed link and image destinations:
|
||||
* - `"host"` (default): host/workspace file links, host images, and web URLs.
|
||||
* - `"https"`: absolute `https://` links and images only (the registry overview contract);
|
||||
* nothing is recognized as a local file path.
|
||||
*/
|
||||
external?: boolean;
|
||||
destinations?: MarkdownDestinations;
|
||||
} = {},
|
||||
) {
|
||||
source = normalizeMarkdownHtml(source);
|
||||
@@ -182,9 +196,15 @@ export function prepareMarkdownSource(
|
||||
extensions: [gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
}));
|
||||
const external = options.external === true;
|
||||
const metadata = external
|
||||
? { linkRecognition: EXTERNAL_LINKS, linkSource: markdownLinkSource }
|
||||
const httpsOnly = options.destinations === "https";
|
||||
const metadata = httpsOnly
|
||||
? {
|
||||
linkRecognition: {
|
||||
text: httpsTextPattern(options.forgeReferencePattern),
|
||||
inlineCode: HTTPS_INLINE_CODE_PATTERN,
|
||||
},
|
||||
linkSource: markdownLinkSource,
|
||||
}
|
||||
: linkMetadata(
|
||||
collectInlineCodePaths(source, workspaceRoot, options.commandNames),
|
||||
options.forgeReferencePattern,
|
||||
@@ -198,8 +218,8 @@ export function prepareMarkdownSource(
|
||||
!/^[\t >]*[^\t >\r\n][^\r\n]*(?:\r\n|\r|\n)[^\r\n]+(?:\r\n|\r|\n)(?=[\t >:|-]*\|)[\t >|]*:?-[-\t :|]*$/m.test(
|
||||
source,
|
||||
) &&
|
||||
!mayLinkIntoWorkspace(source, workspaceRoot) &&
|
||||
!(external && /\]|<[a-z]+:/i.test(source))
|
||||
!(!httpsOnly && mayLinkIntoWorkspace(source, workspaceRoot)) &&
|
||||
!(httpsOnly && /\]|<[a-z]+:/i.test(source))
|
||||
) {
|
||||
return { images, ...metadata, render: () => source };
|
||||
}
|
||||
@@ -218,7 +238,7 @@ export function prepareMarkdownSource(
|
||||
) {
|
||||
const target = node.type === "image" ? node : definitions.get(node.identifier);
|
||||
if (
|
||||
(external && !pluginOverviewUrl(target?.url)) ||
|
||||
(httpsOnly && !pluginOverviewUrl(target?.url)) ||
|
||||
(target &&
|
||||
options.supportsSvg === false &&
|
||||
/(?:\.svg(?:[?#]|$)|^data:image\/svg\+xml)/i.test(target.url))
|
||||
@@ -308,8 +328,9 @@ export function prepareMarkdownSource(
|
||||
const boundary = lineStart - newline.length;
|
||||
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
|
||||
}
|
||||
if (external) dropUnsafeDestination(node, start, end);
|
||||
if (node.type === "link") {
|
||||
if (httpsOnly) {
|
||||
dropUnsafeDestination(node, start, end);
|
||||
} else if (node.type === "link") {
|
||||
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
|
||||
if (title !== null)
|
||||
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
|
||||
|
||||
@@ -4,21 +4,73 @@ import { recognizeTextLinks } from "react-native-enriched-markdown/src/web/recog
|
||||
import type { ASTNode } from "react-native-enriched-markdown/src/web/types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { prepareMarkdownSource } from "./source";
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import {
|
||||
createStreamingMarkdownSplitter,
|
||||
createStreamingMarkdownStabilizer,
|
||||
PENDING_MARKDOWN_LINK,
|
||||
splitStreamingMarkdown,
|
||||
stabilizeStreamingMarkdown,
|
||||
} from "./streaming";
|
||||
|
||||
describe("native streaming Markdown", () => {
|
||||
it("keeps completed messages together for selection", () => {
|
||||
const text = "First.\n\nSecond.\n\nThird.";
|
||||
expect(splitStreamingMarkdown(text, false)).toEqual({ head: text, tail: "" });
|
||||
});
|
||||
/** Feeds each prefix of `source` to one splitter, the way a streaming message grows. */
|
||||
function streamSplits(source: string, step = 1) {
|
||||
const split = createStreamingMarkdownSplitter();
|
||||
const splits: { text: string; parts: string[]; head: string; tail: string }[] = [];
|
||||
for (let end = 0; end <= source.length; end += step) {
|
||||
const text = source.slice(0, end);
|
||||
const { head, tail } = split(text);
|
||||
splits.push({ text, parts: head, head: head.join(""), tail });
|
||||
}
|
||||
return splits;
|
||||
}
|
||||
|
||||
function splitOnce(text: string) {
|
||||
const { head, tail } = createStreamingMarkdownSplitter()(text);
|
||||
return { head: head.join(""), tail };
|
||||
}
|
||||
|
||||
// The shape of a long agent reply: sections of headings, nested lists, task lists, quotes,
|
||||
// links, literal brackets, entities, inline code, images and tables.
|
||||
function longReply(sections: number): string {
|
||||
return Array.from(
|
||||
{ length: sections },
|
||||
(_, index) => `## ${index + 1}. Area ${index}
|
||||
|
||||
The list batches the pending text node only when the [text](https://example.com/${index}) changed. Q&A, \`a && b\` and [x] stay literal.
|
||||
|
||||
- Keep **first paint** under \`${index}ms\`
|
||||
- Measured with \`performance.mark("${index}")\`
|
||||
- Avoid layout thrash during \`scroll\`
|
||||
|
||||
1. Snapshot the state
|
||||
1. Freeze everything before the last blank line
|
||||
2. Commit once per frame
|
||||
|
||||
> **Note:** the anchor invalidates a frozen prefix.
|
||||
>
|
||||
> > Nested: the parser measures the tool output.
|
||||
|
||||
#### Checklist
|
||||
|
||||
- [x] Baseline captured on desktop
|
||||
- [ ] Baseline captured on Android
|
||||
|
||||
| Step | Result |
|
||||
| --- | --- |
|
||||
| ${index} | Ready |
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
`,
|
||||
).join("");
|
||||
}
|
||||
|
||||
describe("streaming Markdown split", () => {
|
||||
it("commits earlier blocks only after the following source line is complete", () => {
|
||||
expect(splitStreamingMarkdown("First.\n\nSecond", true).head).toBe("");
|
||||
expect(splitStreamingMarkdown("First.\n\nSecond\n", true)).toEqual({
|
||||
expect(splitOnce("First.\n\nSecond").head).toBe("");
|
||||
expect(splitOnce("First.\n\nSecond\n")).toEqual({
|
||||
head: "First.\n\n",
|
||||
tail: "Second\n",
|
||||
});
|
||||
@@ -33,50 +85,116 @@ describe("native streaming Markdown", () => {
|
||||
"| A | B |\n| --- | --- |\n| x | y |\n",
|
||||
"```ts\nconst value = 1;\n```\n",
|
||||
"<div>\nbody\n\nmore\n</div>\n",
|
||||
"[label]\n\n[label]: /target\n",
|
||||
"[label]: /target\n\n[label]\n",
|
||||
"- [x] done\n- [ ] open\n",
|
||||
])("keeps an unfinished construct together: %s", (block) => {
|
||||
const prefix = "Introduction.\n\n";
|
||||
const source = prefix + block;
|
||||
const split = splitStreamingMarkdown(source, true);
|
||||
const split = splitOnce(source);
|
||||
expect(split.head.length).toBeLessThanOrEqual(prefix.length);
|
||||
expect(split.head + split.tail).toBe(source);
|
||||
let previous = 0;
|
||||
for (let end = 0; end <= source.length; end++) {
|
||||
const prefixSplit = splitStreamingMarkdown(source.slice(0, end), true);
|
||||
expect(prefixSplit.head.length, `prefix ${end} of ${source}`).toBeGreaterThanOrEqual(
|
||||
previous,
|
||||
);
|
||||
previous = prefixSplit.head.length;
|
||||
for (const { text, head } of streamSplits(source)) {
|
||||
expect(head.length, `prefix ${text.length} of ${source}`).toBeGreaterThanOrEqual(previous);
|
||||
previous = head.length;
|
||||
}
|
||||
});
|
||||
it("preserves the indentation that controls fence content and list continuation", () => {
|
||||
for (const tail of [" ```ts\n const n = 1;\n", " - first\n continued\n"]) {
|
||||
expect(splitStreamingMarkdown(`Intro.\n\n${tail}`, true)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail,
|
||||
});
|
||||
expect(splitOnce(`Intro.\n\n${tail}`)).toEqual({ head: "Intro.\n\n", tail });
|
||||
}
|
||||
});
|
||||
it("keeps unresolved references and HTML in the tail even after later blocks", () => {
|
||||
for (const block of ["[label]", "[label]: /target", "<div>body</div>"]) {
|
||||
expect(splitStreamingMarkdown(`Intro.\n\n${block}\n\nNext.\n\nEnd.\n`, true).head).toBe(
|
||||
"Intro.\n\n",
|
||||
it("commits task lists and literal brackets once a later block starts", () => {
|
||||
for (const block of ["- [x] done\n- [ ] open", "Read [the notes] first.", "Q&A: `a && b`"]) {
|
||||
expect(splitOnce(`Intro.\n\n${block}\n\nNext.\n\nEnd.\n`).head).toBe(
|
||||
`Intro.\n\n${block}\n\nNext.\n\n`,
|
||||
);
|
||||
}
|
||||
});
|
||||
it("never retreats or loses source across every prefix of mixed Markdown", () => {
|
||||
it("keeps HTML and everything after it in the tail", () => {
|
||||
expect(splitOnce("Intro.\n\n<div>body</div>\n\nNext.\n\nEnd.\n").head).toBe("Intro.\n\n");
|
||||
});
|
||||
it("renders a message with a link definition as one document", () => {
|
||||
const source = "See [label].\n\nNext.\n\n[label]: /target\n\nEnd.\n";
|
||||
const definitionEnd = source.indexOf("/target\n") + "/target\n".length;
|
||||
for (const { text, head } of streamSplits(source)) {
|
||||
if (text.length >= definitionEnd) expect(head, `prefix ${text.length}`).toBe("");
|
||||
}
|
||||
// Before the definition arrives, the reference is plain text and its block commits.
|
||||
expect(splitOnce(source.slice(0, source.indexOf("[label]:"))).head).toBe("See [label].\n\n");
|
||||
expect(splitOnce("[label]: /target\n\nSee [label].\n\nEnd.\n").head).toBe("");
|
||||
});
|
||||
it("never loses source and only retreats for a definition across every prefix", () => {
|
||||
const fixture = readFileSync(new URL("./streaming.fixture.md", import.meta.url), "utf8");
|
||||
let previous = 0;
|
||||
for (let end = 0; end <= fixture.length; end++) {
|
||||
const text = fixture.slice(0, end);
|
||||
const { head, tail } = splitStreamingMarkdown(text, true);
|
||||
expect(head.length, `prefix ${end}`).toBeGreaterThanOrEqual(previous);
|
||||
for (const { text, head, tail } of streamSplits(fixture)) {
|
||||
expect(head.length, `prefix ${text.length}`).toBeGreaterThanOrEqual(previous);
|
||||
expect(head + tail).toBe(text);
|
||||
previous = head.length;
|
||||
}
|
||||
expect(previous).toBeGreaterThan(1000);
|
||||
}, 15000);
|
||||
it("keeps the tail to the last block across a long reply", () => {
|
||||
const reply = longReply(40);
|
||||
const split = createStreamingMarkdownSplitter();
|
||||
let longestTail = 0;
|
||||
for (let end = reply.indexOf("\n") + 1; end > 0; end = reply.indexOf("\n", end) + 1) {
|
||||
longestTail = Math.max(longestTail, split(reply.slice(0, end)).tail.length);
|
||||
}
|
||||
// The longest block is one section's task list or table, not the reply.
|
||||
expect(reply.length).toBeGreaterThan(20_000);
|
||||
expect(longestTail).toBeLessThan(400);
|
||||
}, 15000);
|
||||
it("re-renders a bounded amount of the head per frame however long the reply grows", () => {
|
||||
const reply = longReply(40);
|
||||
let previous: string[] = [];
|
||||
let mostInOneFrame = 0;
|
||||
for (const { parts, head } of streamSplits(reply, 7)) {
|
||||
const rerendered = parts
|
||||
.filter((part, index) => part !== previous[index])
|
||||
.reduce((sum, part) => sum + part.length, 0);
|
||||
mostInOneFrame = Math.max(mostInOneFrame, rerendered);
|
||||
expect(head).toBe(reply.slice(0, head.length));
|
||||
previous = parts;
|
||||
}
|
||||
expect(previous.length).toBeGreaterThan(5);
|
||||
// One sealed part's worth plus a block, not the reply.
|
||||
expect(mostInOneFrame).toBeLessThan(2500);
|
||||
}, 15000);
|
||||
it("finds the same split incrementally as from scratch at every prefix", () => {
|
||||
const fixture = readFileSync(new URL("./streaming.fixture.md", import.meta.url), "utf8");
|
||||
for (const source of [
|
||||
fixture,
|
||||
longReply(3),
|
||||
"Intro.\n\n[label]\n\nNext.\n\n[label]: /target\n\nEnd.\n",
|
||||
"Intro.\n\n- one\n\n continued\n\nAfter.\n\n<div>\nbody\n</div>\n\nTail.\n",
|
||||
]) {
|
||||
for (const { text, head } of streamSplits(source)) {
|
||||
expect(head, `prefix ${text.length}`).toBe(splitOnce(text).head);
|
||||
}
|
||||
}
|
||||
}, 30000);
|
||||
it("parses only the source after the settled head", () => {
|
||||
const parsed: string[] = [];
|
||||
const split = createStreamingMarkdownSplitter((completeLines) => {
|
||||
parsed.push(completeLines);
|
||||
return fromMarkdown(completeLines);
|
||||
});
|
||||
const blocks = Array.from({ length: 200 }, (_, index) => `Paragraph ${index}.\n\n`).join("");
|
||||
split(blocks);
|
||||
parsed.length = 0;
|
||||
expect(split(`${blocks}Next.\n`).head.join("")).toBe(blocks);
|
||||
expect(parsed).toEqual(["Paragraph 199.\n\nNext.\n"]);
|
||||
parsed.length = 0;
|
||||
split(`${blocks}Next.\nmore`);
|
||||
expect(parsed).toEqual([]);
|
||||
});
|
||||
it("starts over when the source no longer extends what it split", () => {
|
||||
const split = createStreamingMarkdownSplitter();
|
||||
expect(split("First.\n\nSecond.\n").head).toEqual(["First.\n\n"]);
|
||||
expect(split("Other.\n\nText.\n").head).toEqual(["Other.\n\n"]);
|
||||
expect(split("[a]: /b\n\nOther.\n").head).toEqual([]);
|
||||
expect(split("Fresh.\n\nText.\n").head).toEqual(["Fresh.\n\n"]);
|
||||
});
|
||||
});
|
||||
|
||||
const STREAM_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { Nodes } from "mdast";
|
||||
import type { Nodes, Root } from "mdast";
|
||||
|
||||
export {
|
||||
createStreamingMarkdownStabilizer,
|
||||
@@ -9,30 +9,96 @@ export {
|
||||
stabilizeStreamingMarkdown,
|
||||
} from "./streaming-stabilize";
|
||||
|
||||
// A later definition can resolve even a currently plain-text shortcut reference.
|
||||
// Keep its entire containing block, and all definitions, in the shared tail.
|
||||
// HTML normalization likewise needs the complete enclosing source.
|
||||
function needsDocumentContext(node: Nodes): boolean {
|
||||
if (node.type === "html" || node.type === "definition") return true;
|
||||
if (node.type === "linkReference" || node.type === "imageReference") return true;
|
||||
if (node.type === "text" && node.value.includes("[")) return true;
|
||||
return "children" in node && node.children.some(needsDocumentContext);
|
||||
export interface StreamingMarkdownSplit {
|
||||
/**
|
||||
* Closed blocks, which render the same whatever arrives later. Only the last part grows; a part
|
||||
* that reached `HEAD_PART_LENGTH` never changes again.
|
||||
*/
|
||||
head: string[];
|
||||
/** The last block and the unfinished line. */
|
||||
tail: string;
|
||||
}
|
||||
|
||||
/** The last parsed block and unfinished line are mutable; earlier blocks are closed. */
|
||||
export function splitStreamingMarkdown(text: string, streaming: boolean) {
|
||||
if (!streaming) return { head: text, tail: "" };
|
||||
const completeLines = text.slice(0, text.lastIndexOf("\n") + 1);
|
||||
const tree = fromMarkdown(completeLines, {
|
||||
// Each completed block re-renders the head part it lands in. Sealing parts at this length keeps
|
||||
// that work bounded as the reply grows, with a few views for a long reply.
|
||||
const HEAD_PART_LENGTH = 2000;
|
||||
|
||||
export type StreamingMarkdownParser = (completeLines: string) => Root;
|
||||
|
||||
const parseBlocks: StreamingMarkdownParser = (completeLines) =>
|
||||
fromMarkdown(completeLines, {
|
||||
extensions: [gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
});
|
||||
|
||||
// HTML normalization needs the complete enclosing source, so HTML and every block after it
|
||||
// stay in the tail.
|
||||
function needsDocumentContext(node: Nodes): boolean {
|
||||
if (node.type === "html") return true;
|
||||
return "children" in node && node.children.some(needsDocumentContext);
|
||||
}
|
||||
|
||||
// A definition can turn `[label]` anywhere in the message into a link, including in blocks that
|
||||
// already closed. mdast only creates a reference for a label that is defined.
|
||||
function hasDefinition(node: Nodes): boolean {
|
||||
if (node.type === "definition") return true;
|
||||
return "children" in node && node.children.some(hasDefinition);
|
||||
}
|
||||
|
||||
/**
|
||||
* Splits one growing message into head parts that stay fixed and a tail that changes with each
|
||||
* reveal frame. Create one per streaming message.
|
||||
*
|
||||
* Only completed lines can close a block, so the boundary moves when a line completes. Blocks
|
||||
* before the boundary are closed and need no document context, so each line parses only the
|
||||
* source after the boundary, and the work per line stays bounded by the last block. A message with
|
||||
* a link definition renders as one document, the way it will when it completes.
|
||||
*/
|
||||
export function createStreamingMarkdownSplitter(
|
||||
parse: StreamingMarkdownParser = parseBlocks,
|
||||
): (text: string) => StreamingMarkdownSplit {
|
||||
let completeLines = "";
|
||||
let boundary = 0;
|
||||
for (let index = 0; index < tree.children.length - 1; index++) {
|
||||
if (needsDocumentContext(tree.children[index])) break;
|
||||
// mdast starts some nodes after their indentation; the next parser needs it too.
|
||||
const nextStart = tree.children[index + 1].position!.start.offset!;
|
||||
boundary = text.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
let partStarts = [0];
|
||||
let hasDefinitions = false;
|
||||
|
||||
function advance(lines: string) {
|
||||
if (lines === completeLines) return;
|
||||
if (!lines.startsWith(completeLines)) {
|
||||
// Not an append: nothing settled so far is known to hold.
|
||||
boundary = 0;
|
||||
partStarts = [0];
|
||||
hasDefinitions = false;
|
||||
}
|
||||
completeLines = lines;
|
||||
if (hasDefinitions) return;
|
||||
const open = lines.slice(boundary);
|
||||
const tree = parse(open);
|
||||
if (tree.children.some(hasDefinition)) {
|
||||
hasDefinitions = true;
|
||||
boundary = 0;
|
||||
partStarts = [0];
|
||||
return;
|
||||
}
|
||||
let settled = 0;
|
||||
for (let index = 0; index < tree.children.length - 1; index++) {
|
||||
if (needsDocumentContext(tree.children[index])) break;
|
||||
// mdast starts some nodes after their indentation; the next parser needs it too.
|
||||
const nextStart = tree.children[index + 1].position!.start.offset!;
|
||||
settled = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
}
|
||||
if (settled === 0) return;
|
||||
if (boundary - partStarts[partStarts.length - 1] >= HEAD_PART_LENGTH) partStarts.push(boundary);
|
||||
boundary += settled;
|
||||
}
|
||||
return { head: text.slice(0, boundary), tail: text.slice(boundary) };
|
||||
|
||||
return (text) => {
|
||||
advance(text.slice(0, text.lastIndexOf("\n") + 1));
|
||||
if (boundary === 0) return { head: [], tail: text };
|
||||
const ends = [...partStarts.slice(1), boundary];
|
||||
return {
|
||||
head: partStarts.map((start, index) => text.slice(start, ends[index])),
|
||||
tail: text.slice(boundary),
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
@@ -12,6 +12,8 @@ import { withContentDrag } from "@/components/ui/content-drag";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { ICON_SIZE, SPACING, type Theme } from "@/styles/theme";
|
||||
|
||||
export const PAGE_LAYOUT_WIDE_MAX_WIDTH = 1080;
|
||||
|
||||
// Rows on a page drag to reorder, so the page stops scrolling while a drag holds the touch.
|
||||
const PageScrollView =
|
||||
Platform.OS === "android"
|
||||
@@ -137,9 +139,9 @@ export function PageTitle({
|
||||
descriptionTestID,
|
||||
}: PageTitleProps) {
|
||||
return (
|
||||
<View style={styles.titleBlock} testID={testID}>
|
||||
<View style={styles.titleBlock}>
|
||||
<View style={styles.titleRow}>
|
||||
<View style={styles.titleParts}>
|
||||
<View style={styles.titleParts} testID={testID}>
|
||||
{parent ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
@@ -198,7 +200,7 @@ const styles = StyleSheet.create((theme) => ({
|
||||
padding: theme.spacing[4],
|
||||
paddingTop: theme.spacing[6],
|
||||
width: "100%",
|
||||
maxWidth: 1080,
|
||||
maxWidth: PAGE_LAYOUT_WIDE_MAX_WIDTH,
|
||||
alignSelf: "center",
|
||||
},
|
||||
titleBlock: {
|
||||
|
||||
@@ -6,6 +6,8 @@ import { SettingsRowHeader, type SettingsRowHintStatus } from "./row-header";
|
||||
|
||||
interface SettingsCollapsibleRowProps {
|
||||
label: string;
|
||||
/** An icon or status indicator shown before the label. */
|
||||
leading?: ReactNode;
|
||||
/** A line under the label explaining the group. */
|
||||
hint?: string;
|
||||
hintStatus?: SettingsRowHintStatus;
|
||||
@@ -13,6 +15,8 @@ interface SettingsCollapsibleRowProps {
|
||||
summary?: string;
|
||||
/** A control acting on the row's subject in place, such as a switch, before the chevron. */
|
||||
control?: ReactNode;
|
||||
/** Passive trailing element (such as a pill) shown before the chevron. */
|
||||
trailing?: ReactNode;
|
||||
/** Names the expand/collapse button for assistive tech when the label alone is not enough. */
|
||||
accessibilityLabel?: string;
|
||||
defaultExpanded?: boolean;
|
||||
@@ -28,10 +32,12 @@ interface SettingsCollapsibleRowProps {
|
||||
*/
|
||||
export function SettingsCollapsibleRow({
|
||||
label,
|
||||
leading,
|
||||
hint,
|
||||
hintStatus,
|
||||
summary,
|
||||
control,
|
||||
trailing,
|
||||
accessibilityLabel,
|
||||
defaultExpanded = false,
|
||||
testID,
|
||||
@@ -50,10 +56,12 @@ export function SettingsCollapsibleRow({
|
||||
<View testID={testID}>
|
||||
<SettingsRowHeader
|
||||
label={label}
|
||||
leading={leading}
|
||||
hint={hint}
|
||||
hintStatus={hintStatus}
|
||||
summary={summary}
|
||||
control={control}
|
||||
trailing={trailing}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
onPress={toggle}
|
||||
expanded={expanded}
|
||||
|
||||
@@ -36,6 +36,8 @@ export interface SettingsRowHeaderProps {
|
||||
summary?: string;
|
||||
/** An icon drawn directly before the summary text, such as a provider glyph beside a model name. */
|
||||
summaryLeading?: ReactNode;
|
||||
/** Passive trailing element (such as a status pill) shown before the chevron; lets presses pass through to the row. */
|
||||
trailing?: ReactNode;
|
||||
onPress: () => void;
|
||||
disabled?: boolean;
|
||||
/** Turns the chevron down, for a row whose children are revealed in place. */
|
||||
@@ -75,6 +77,7 @@ export function SettingsRowHeader({
|
||||
hintStatus,
|
||||
summary,
|
||||
summaryLeading,
|
||||
trailing,
|
||||
onPress,
|
||||
disabled,
|
||||
expanded = false,
|
||||
@@ -135,6 +138,14 @@ export function SettingsRowHeader({
|
||||
<ControlSizeProvider size={layout.controlSize}>{control}</ControlSizeProvider>
|
||||
</View>
|
||||
) : null}
|
||||
{trailing ? (
|
||||
<View
|
||||
style={[styles.trailingAccessory, styles.passThrough]}
|
||||
{...HIDDEN_FROM_ASSISTIVE_TECH}
|
||||
>
|
||||
{trailing}
|
||||
</View>
|
||||
) : null}
|
||||
<RowTrailing
|
||||
hinted={hinted}
|
||||
external={external}
|
||||
@@ -250,6 +261,10 @@ const styles = StyleSheet.create((theme) => ({
|
||||
control: {
|
||||
marginRight: theme.spacing[3],
|
||||
},
|
||||
trailingAccessory: {
|
||||
marginRight: theme.spacing[2],
|
||||
flexShrink: 0,
|
||||
},
|
||||
// The button under the row's content; it fills the row, padding included.
|
||||
pressTarget: {
|
||||
...StyleSheet.absoluteFill,
|
||||
|
||||
@@ -22,12 +22,12 @@ const turning = { transform: [{ rotate: rotation }] };
|
||||
|
||||
/** Native running indicator. The native animation driver turns the quarter; see `clock.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const moving = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, moving);
|
||||
const motion = useIndicatorMotion();
|
||||
useRunningClock(sharedIndicatorClock, motion === "moving");
|
||||
|
||||
return (
|
||||
<StatusRingFrame backdrop={backdrop}>
|
||||
<Animated.View style={[rotatorStyles.rotator, moving && turning]}>
|
||||
<Animated.View style={[rotatorStyles.rotator, motion !== "resting" && turning]}>
|
||||
<View style={styles.arc} />
|
||||
</Animated.View>
|
||||
</StatusRingFrame>
|
||||
|
||||
@@ -23,7 +23,7 @@ const TURNING: IndicatorLoop = {
|
||||
|
||||
/** Web running indicator. The browser's compositor turns the quarter; see `loop.web.ts`. */
|
||||
export const StatusRing = memo(function StatusRing({ backdrop }: StatusRingProps) {
|
||||
const moving = useIndicatorMotion();
|
||||
const moving = useIndicatorMotion() === "moving";
|
||||
const rotatorRef = useIndicatorLoop(moving ? TURNING : null);
|
||||
|
||||
return (
|
||||
|
||||
@@ -34,8 +34,9 @@ const resting = DOTS.map((dot) => ({
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
const motion = moving ? blinking : resting;
|
||||
const motion = useIndicatorMotion();
|
||||
const dots = motion === "resting" ? resting : blinking;
|
||||
const moving = motion === "moving";
|
||||
|
||||
useEffect(() => {
|
||||
if (!moving) return;
|
||||
@@ -48,7 +49,7 @@ export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
{DOTS.map((dot) => (
|
||||
<Animated.View
|
||||
key={dot}
|
||||
style={[layout.dots[dot], motion[dot]]}
|
||||
style={[layout.dots[dot], dots[dot]]}
|
||||
testID="synced-loader-dot"
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -36,7 +36,7 @@ const RESTING = DOTS.map(
|
||||
*/
|
||||
export function SyncedLoader(props: SyncedLoaderProps) {
|
||||
const layout = useSyncedLoaderLayout(props);
|
||||
const moving = useIndicatorMotion();
|
||||
const moving = useIndicatorMotion() === "moving";
|
||||
|
||||
return (
|
||||
<View style={layout.container} testID="synced-loader">
|
||||
|
||||
@@ -41,21 +41,28 @@ describe("synced loader step ticker", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
test("starts mid-cycle on the step the wall clock is on", () => {
|
||||
vi.setSystemTime(950 * 4 + 500);
|
||||
test("holds its step while no loader runs and continues from it", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
vi.advanceTimersByTime(140);
|
||||
vi.advanceTimersByTime(400);
|
||||
stop();
|
||||
vi.advanceTimersByTime(10_000);
|
||||
const stopAgain = ticker.run();
|
||||
vi.advanceTimersByTime(80);
|
||||
stopAgain();
|
||||
|
||||
// Stopped 83 ms into step 2, so step 3 comes 75 ms after the loader runs again.
|
||||
expect(published).toEqual([
|
||||
{ step: 3, atMs: 950 * 4 + 500 },
|
||||
{ step: 4, atMs: 950 * 4 + 634 },
|
||||
{ step: 0, atMs: 0 },
|
||||
{ step: 1, atMs: 159 },
|
||||
{ step: 2, atMs: 317 },
|
||||
{ step: 2, atMs: 10_400 },
|
||||
{ step: 3, atMs: 10_475 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("catches up to the wall clock after a late wake-up instead of drifting", () => {
|
||||
test("catches up after a late wake-up instead of drifting", () => {
|
||||
const { ticker, published } = startRecordingTicker();
|
||||
|
||||
const stop = ticker.run();
|
||||
|
||||
@@ -3,12 +3,15 @@ import { getSyncedLoaderStep, getSyncedLoaderStepRemainingMs } from "./state";
|
||||
/**
|
||||
* Publishes the loader's step each time it changes, and at no other time.
|
||||
*
|
||||
* The loader has six frames a cycle, so it needs six wake-ups a cycle. Each wake-up reads the wall
|
||||
* clock and sleeps until the next step is due, which keeps a late timer from pushing every later
|
||||
* step back and keeps every loader in the app on the same step.
|
||||
* The loader has six frames a cycle, so it needs six wake-ups a cycle. Each wake-up reads the time
|
||||
* and sleeps until the next step is due, which keeps a late timer from pushing every later step
|
||||
* back. Every loader in the app reads this one ticker, so they all show the same step.
|
||||
*/
|
||||
export interface SyncedLoaderStepTicker {
|
||||
/** Ticks until the returned function is called. Publishes the current step at once. */
|
||||
/**
|
||||
* Ticks until the returned function is called. A ticker nobody runs holds its step, and continues
|
||||
* from it when it runs again. Publishes the current step at once.
|
||||
*/
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
@@ -17,17 +20,21 @@ export function createSyncedLoaderStepTicker(
|
||||
): SyncedLoaderStepTicker {
|
||||
let runners = 0;
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
// How long the ticker has run: up to its latest start, and since.
|
||||
let ranMs = 0;
|
||||
let startedAtMs = 0;
|
||||
|
||||
function tick(): void {
|
||||
const nowMs = Date.now();
|
||||
publish(getSyncedLoaderStep(nowMs));
|
||||
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(nowMs));
|
||||
const runMs = ranMs + Date.now() - startedAtMs;
|
||||
publish(getSyncedLoaderStep(runMs));
|
||||
timer = setTimeout(tick, getSyncedLoaderStepRemainingMs(runMs));
|
||||
}
|
||||
|
||||
return {
|
||||
run() {
|
||||
runners += 1;
|
||||
if (timer === null) {
|
||||
startedAtMs = Date.now();
|
||||
tick();
|
||||
}
|
||||
return () => {
|
||||
@@ -35,6 +42,7 @@ export function createSyncedLoaderStepTicker(
|
||||
if (runners === 0 && timer !== null) {
|
||||
clearTimeout(timer);
|
||||
timer = null;
|
||||
ranMs += Date.now() - startedAtMs;
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
@@ -100,6 +100,21 @@ describe("bottom sheet visibility tracker", () => {
|
||||
expect(sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }, { type: "dismiss" }]);
|
||||
});
|
||||
|
||||
it("dismisses a sheet hidden after its interrupted open reported -1, once it lands open", () => {
|
||||
const { sheet, tracker, closeCount } = setup();
|
||||
tracker.attachController(sheet);
|
||||
tracker.syncDesired({ visible: true });
|
||||
|
||||
// The open animation is interrupted and reports the closed detent, the owner hides the
|
||||
// sheet, and the sheet then finishes opening anyway.
|
||||
tracker.handleSheetIndexChange(-1);
|
||||
tracker.syncDesired({ visible: false });
|
||||
tracker.handleSheetIndexChange(0);
|
||||
|
||||
expect(sheet.events).toEqual([{ type: "present" }, { type: "dismiss" }]);
|
||||
expect(closeCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("waits to present until the sheet controller becomes available", () => {
|
||||
const { sheet, tracker } = setup();
|
||||
tracker.syncDesired({ visible: true });
|
||||
|
||||
@@ -117,9 +117,10 @@ export function createBottomSheetVisibilityTracker(opts: {
|
||||
},
|
||||
handleSheetIndexChange(index) {
|
||||
if (index !== -1) {
|
||||
if (phase === "presenting" || phase === "dismissing") {
|
||||
setPhase("presented");
|
||||
}
|
||||
// An open detent means the sheet is on screen, whatever the tracker last heard. An
|
||||
// interrupted open can report -1 first, and an owner that hid the sheet in that window
|
||||
// already moved the tracker to closed.
|
||||
setPhase("presented");
|
||||
// A dismiss sent before the sheet measured its layout is dropped, and the sheet still
|
||||
// finishes opening. The owner wants it hidden, so it goes again.
|
||||
if (!visible && isEnabled !== false) {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Text, View } from "react-native";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -9,17 +9,15 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
});
|
||||
|
||||
/**
|
||||
* A screen or pane waiting for its content. Every wait shows the same spinner in the same place,
|
||||
* so a wait that changes what it is waiting for changes only the words under it.
|
||||
* A screen or pane waiting for its content. Shows one centered spinner with no visible text so
|
||||
* switching between cache, host, and fill waits never shifts its position.
|
||||
*/
|
||||
export function LoadingState({
|
||||
title,
|
||||
description,
|
||||
accessibilityLabel,
|
||||
testID,
|
||||
}: {
|
||||
/** What the wait is for. Leave it out while the wait is too short to read. */
|
||||
title?: string;
|
||||
description?: string;
|
||||
/** What the wait is for, announced by screen readers only. */
|
||||
accessibilityLabel?: string;
|
||||
testID?: string;
|
||||
}) {
|
||||
return (
|
||||
@@ -27,14 +25,8 @@ export function LoadingState({
|
||||
<ThemedLoadingSpinner
|
||||
size="small"
|
||||
uniProps={foregroundMutedColorMapping}
|
||||
accessibilityLabel={title}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
/>
|
||||
{title ? (
|
||||
<View style={styles.textStack}>
|
||||
<Text style={styles.title}>{title}</Text>
|
||||
{description ? <Text style={styles.description}>{description}</Text> : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -44,23 +36,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[6],
|
||||
},
|
||||
textStack: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
maxWidth: 520,
|
||||
},
|
||||
title: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
textAlign: "center",
|
||||
},
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
textAlign: "center",
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useRouter } from "expo-router";
|
||||
import { useEffect, useMemo } from "react";
|
||||
import { useSidebarCallouts } from "@/contexts/sidebar-callout-context";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useHostRuntimeClient } from "@/runtime/host-runtime";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useWorkspaceFields } from "@/stores/session-store-hooks";
|
||||
import {
|
||||
@@ -21,6 +21,7 @@ export function WorktreeSetupCalloutSource() {
|
||||
);
|
||||
const activeProject = selectedWorkspaceProject;
|
||||
const client = useHostRuntimeClient(activeProject?.serverId ?? "");
|
||||
const isConnected = useHostRuntimeIsConnected(activeProject?.serverId ?? "");
|
||||
const callouts = useSidebarCallouts();
|
||||
const router = useRouter();
|
||||
const openProjectSettings = useStableEvent(() => {
|
||||
@@ -38,7 +39,7 @@ export function WorktreeSetupCalloutSource() {
|
||||
}
|
||||
return client.readProjectConfig(activeProject.repoRoot);
|
||||
},
|
||||
enabled: Boolean(client && activeProject),
|
||||
enabled: Boolean(client && isConnected && activeProject),
|
||||
retry: false,
|
||||
});
|
||||
|
||||
|
||||
@@ -995,6 +995,65 @@ describe("attachments restored from a queued message", () => {
|
||||
expect(client.calls[0]?.options.attachments).toEqual([uploadedImage]);
|
||||
});
|
||||
|
||||
it("clears the optimistic timeline bubble when a direct send is queued behind a boundary", async () => {
|
||||
const client = createFakeSendClient();
|
||||
client.sendAgentMessage = async (agentId, text, options) => {
|
||||
client.calls.push({ agentId, text, options });
|
||||
return { deliveryStatus: "queued", messageId: options.messageId };
|
||||
};
|
||||
const stream = createFakeStream();
|
||||
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: "agent",
|
||||
text: "follow up",
|
||||
attachments: [],
|
||||
submission: stream,
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
|
||||
expect(stream.tail.get("agent") ?? []).toEqual([]);
|
||||
expect(stream.head.get("agent") ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
it("clears the optimistic timeline bubble and settles staged switch via queued callback when a direct provider switch is queued", async () => {
|
||||
const client = createFakeSendClient();
|
||||
client.switchAgentProvider = async () => ({
|
||||
deliveryStatus: "queued",
|
||||
agent: undefined,
|
||||
});
|
||||
const stream = createFakeStream();
|
||||
let committed = 0;
|
||||
let queued = 0;
|
||||
|
||||
await dispatchComposerAgentMessage({
|
||||
client,
|
||||
agentId: "agent",
|
||||
text: "switch later",
|
||||
attachments: [],
|
||||
submission: stream,
|
||||
currentProvider: "claude",
|
||||
stagedProviderSwitch: {
|
||||
provider: "codex",
|
||||
model: null,
|
||||
thinkingOptionId: null,
|
||||
modeId: null,
|
||||
providerOptions: {},
|
||||
},
|
||||
onProviderSwitchCommitted: () => {
|
||||
committed += 1;
|
||||
},
|
||||
onProviderSwitchQueued: () => {
|
||||
queued += 1;
|
||||
},
|
||||
});
|
||||
|
||||
expect(committed).toBe(0);
|
||||
expect(queued).toBe(1);
|
||||
expect(stream.tail.get("agent") ?? []).toEqual([]);
|
||||
expect(stream.head.get("agent") ?? []).toEqual([]);
|
||||
});
|
||||
|
||||
it("counts a restored forge item as selected and toggles it off", () => {
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], issueItem)).toBe(true);
|
||||
expect(isAttachmentSelectedForForgeItem([restoredIssue], prItem)).toBe(false);
|
||||
|
||||
@@ -217,6 +217,7 @@ export interface DispatchComposerAgentMessageInput {
|
||||
currentModel?: string | null;
|
||||
stagedProviderSwitch?: StagedProviderSwitch | null;
|
||||
onProviderSwitchCommitted?: (agent: AgentSnapshotPayload | undefined) => void | Promise<void>;
|
||||
onProviderSwitchQueued?: () => void;
|
||||
}
|
||||
|
||||
function buildPendingProviderSwitch(
|
||||
@@ -242,6 +243,15 @@ function buildPendingProviderSwitch(
|
||||
});
|
||||
}
|
||||
|
||||
function isQueuedDeliveryResult(result: unknown): boolean {
|
||||
return (
|
||||
typeof result === "object" &&
|
||||
result !== null &&
|
||||
"deliveryStatus" in result &&
|
||||
result.deliveryStatus === "queued"
|
||||
);
|
||||
}
|
||||
|
||||
export async function dispatchComposerAgentMessage(
|
||||
input: DispatchComposerAgentMessageInput,
|
||||
): Promise<void> {
|
||||
@@ -281,16 +291,25 @@ export async function dispatchComposerAgentMessage(
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
if (isQueuedDeliveryResult(result)) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
input.onProviderSwitchQueued?.();
|
||||
return;
|
||||
}
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
await input.onProviderSwitchCommitted?.(result.agent);
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
const result = await input.client.sendAgentMessage(input.agentId, input.text, {
|
||||
messageId: clientMessageId,
|
||||
...(input.activeTurnBehavior ? { activeTurnBehavior: input.activeTurnBehavior } : {}),
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
});
|
||||
if (isQueuedDeliveryResult(result)) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
return;
|
||||
}
|
||||
input.submission.accept(input.agentId, clientMessageId);
|
||||
} catch (error) {
|
||||
input.submission.reject(input.agentId, clientMessageId);
|
||||
|
||||
@@ -3,7 +3,11 @@ import {
|
||||
isRasterImageFile,
|
||||
isRasterImagePath,
|
||||
} from "@/attachments/file-types";
|
||||
import { readDesktopFileBytes, type SelectedFile } from "@/attachments/selected-file";
|
||||
import {
|
||||
readDesktopFileBytes,
|
||||
selectedFileFromWebFile,
|
||||
type SelectedFile,
|
||||
} from "@/attachments/selected-file";
|
||||
import type { DroppedItem } from "@/components/file-drop/types";
|
||||
|
||||
interface DroppedAttachmentsRuntime {
|
||||
@@ -36,12 +40,7 @@ export function droppedItemsToSelectedFiles(
|
||||
if (isRasterImageFile(item.file)) {
|
||||
continue;
|
||||
}
|
||||
const file = item.file;
|
||||
files.push({
|
||||
fileName: file.name,
|
||||
mimeType: file.type || getMimeTypeFromPath(file.name),
|
||||
readBytes: async () => new Uint8Array(await file.arrayBuffer()),
|
||||
});
|
||||
files.push(selectedFileFromWebFile(item.file));
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -24,7 +24,6 @@ import {
|
||||
} from "@/provider-selection/provider-selection";
|
||||
import { findThinkingOptionReplacement } from "@/provider-selection/resolve-agent-form";
|
||||
import { useDraftStore, type DraftInput } from "@/stores/draft-store";
|
||||
import { AfterPaintPublication } from "@/composer/after-paint-publication";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import type { ComposerTextSource } from "@/composer/text-source";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
@@ -147,14 +146,6 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
const textPublication = useMemo(
|
||||
() =>
|
||||
new AfterPaintPublication<string>((nextText) => {
|
||||
useDraftStore.getState().editDraftText({ draftKey, text: nextText });
|
||||
}),
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
// Text another module put in the draft (a plugin writing to a composer that is not on screen)
|
||||
// reaches the input the way a rewind restore does.
|
||||
const replacementRequest = useDraftStore(
|
||||
@@ -165,28 +156,26 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
const shown = shownReplacementRequestRef.current;
|
||||
if (shown.draftKey === draftKey && shown.request === replacementRequest) return;
|
||||
shownReplacementRequestRef.current = { draftKey, request: replacementRequest };
|
||||
textPublication.cancel();
|
||||
publishTextReplacement("replace", textSource.getSnapshot());
|
||||
}, [draftKey, publishTextReplacement, replacementRequest, textPublication, textSource]);
|
||||
}, [draftKey, publishTextReplacement, replacementRequest, textSource]);
|
||||
|
||||
const editText = useCallback(
|
||||
(nextText: string) => {
|
||||
if (isWeb) {
|
||||
textPublication.stage(nextText);
|
||||
useDraftStore.getState().stageDraftText({ draftKey, text: nextText });
|
||||
} else {
|
||||
useDraftStore.getState().editDraftText({ draftKey, text: nextText });
|
||||
}
|
||||
},
|
||||
[draftKey, textPublication],
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
const replaceText = useCallback(
|
||||
(nextText: string) => {
|
||||
textPublication.cancel();
|
||||
useDraftStore.getState().editDraftText({ draftKey, text: nextText });
|
||||
publishTextReplacement("replace", nextText);
|
||||
},
|
||||
[draftKey, publishTextReplacement, textPublication],
|
||||
[draftKey, publishTextReplacement],
|
||||
);
|
||||
|
||||
const setAttachments = useCallback(
|
||||
@@ -208,18 +197,17 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
|
||||
const clear = useCallback(
|
||||
(lifecycle: "sent" | "abandoned") => {
|
||||
textPublication.cancel();
|
||||
useDraftStore.getState().clearDraftInput({ draftKey, lifecycle });
|
||||
if (lifecycle === "sent") useDraftStore.getState().clearDraftMetadata({ draftKey });
|
||||
},
|
||||
[draftKey, textPublication],
|
||||
[draftKey],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
const flush = () => useDraftStore.getState().flushDraftText(draftKey);
|
||||
const flushWhenHidden = () => {
|
||||
if (document.visibilityState === "hidden") textPublication.flush();
|
||||
if (document.visibilityState === "hidden") flush();
|
||||
};
|
||||
const flush = () => textPublication.flush();
|
||||
const canListenForPageHide =
|
||||
isWeb && typeof window !== "undefined" && typeof window.addEventListener === "function";
|
||||
if (isWeb && typeof document !== "undefined") {
|
||||
@@ -235,9 +223,9 @@ export function useAgentInputDraft(input: UseAgentInputDraftInput): AgentInputDr
|
||||
if (canListenForPageHide) {
|
||||
window.removeEventListener("pagehide", flush);
|
||||
}
|
||||
textPublication.flush();
|
||||
flush();
|
||||
};
|
||||
}, [textPublication]);
|
||||
}, [draftKey]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
@@ -166,7 +166,7 @@ import type {
|
||||
WorkspaceFileComposerAttachment,
|
||||
WorkspaceComposerAttachment,
|
||||
} from "@/attachments/types";
|
||||
import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { selectedFileFromWebFile, type SelectedFile } from "@/attachments/selected-file";
|
||||
import { resolveComposerAttachmentSubmitFormat } from "@/composer/attachments/submit";
|
||||
import { ComposerInputProvider, type ComposerInput } from "@/composer/session";
|
||||
import type { ComposerFocusOptions } from "@/composer/model";
|
||||
@@ -1775,6 +1775,11 @@ function ComposerContentImpl({
|
||||
}
|
||||
}
|
||||
},
|
||||
onProviderSwitchQueued: () => {
|
||||
if (stagedProviderSwitch) {
|
||||
settleStagedProviderSwitch(serverId, targetAgentId, stagedProviderSwitch);
|
||||
}
|
||||
},
|
||||
activeTurnBehavior,
|
||||
activeTurnId:
|
||||
activeTurnBehavior === "steer"
|
||||
@@ -2041,6 +2046,13 @@ function ComposerContentImpl({
|
||||
[addFiles, client, t],
|
||||
);
|
||||
|
||||
const handlePasteFiles = useCallback(
|
||||
(files: File[]) => {
|
||||
void uploadSelectedFiles(files.map(selectedFileFromWebFile));
|
||||
},
|
||||
[uploadSelectedFiles],
|
||||
);
|
||||
|
||||
const handlePickFile = useCallback(async () => {
|
||||
if (!client) {
|
||||
toastErrorRef.current(t("composer.errors.daemonClientDisconnected"));
|
||||
@@ -2698,6 +2710,7 @@ function ComposerContentImpl({
|
||||
attachmentMenuItems={attachmentMenuItems}
|
||||
onAttachButtonRef={handleAttachButtonRef}
|
||||
onAddImages={addImages}
|
||||
onPasteFiles={handlePasteFiles}
|
||||
onPasteImages={handleNativePasteImages}
|
||||
client={client}
|
||||
isReadyForDictation={isDictationReady}
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
useRef,
|
||||
useCallback,
|
||||
useEffect,
|
||||
useEffectEvent,
|
||||
useLayoutEffect,
|
||||
useImperativeHandle,
|
||||
useMemo,
|
||||
@@ -64,6 +65,7 @@ import {
|
||||
collectImageFilesFromClipboardData,
|
||||
filesToImageAttachments,
|
||||
} from "@/utils/image-attachments-from-files";
|
||||
import { isRasterImageFile } from "@/attachments/file-types";
|
||||
import type { ComposerAttachment } from "@/attachments/types";
|
||||
import type { ImageAttachment, MessagePayload, TextReplacement } from "@/composer/types";
|
||||
import { focusWithRetries } from "@/utils/web-focus";
|
||||
@@ -81,7 +83,7 @@ import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
@@ -173,6 +175,7 @@ export interface MessageInputProps {
|
||||
attachmentMenuItems: AttachmentMenuItem[];
|
||||
onAttachButtonRef?: (node: View | null) => void;
|
||||
onAddImages?: (images: ImageAttachment[]) => void;
|
||||
onPasteFiles?: (files: File[]) => void;
|
||||
onPasteImages?: (files: readonly NativePastedFile[]) => void;
|
||||
client: DaemonClient | null;
|
||||
/** Dictation start gate from host runtime (socket connected + directory ready). */
|
||||
@@ -520,22 +523,36 @@ function getTextInputNativeElement(current: ComposerTextInputHandle | null): HTM
|
||||
interface PasteEffectArgs {
|
||||
textarea: HTMLElement | null;
|
||||
isConnected: boolean;
|
||||
isSubmitLoading: boolean;
|
||||
disabled: boolean;
|
||||
isDictating: boolean;
|
||||
isRealtimeVoiceForCurrentAgent: boolean;
|
||||
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
|
||||
onPasteFiles: ((files: File[]) => void) | undefined;
|
||||
}
|
||||
|
||||
function usePasteEffect(args: PasteEffectArgs): void {
|
||||
const {
|
||||
textarea,
|
||||
isConnected,
|
||||
isSubmitLoading,
|
||||
disabled,
|
||||
isDictating,
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
onAddImages,
|
||||
onPasteFiles,
|
||||
} = args;
|
||||
|
||||
const pasteFiles = useEffectEvent((clipboardData: DataTransfer | null) => {
|
||||
if (!isConnected || isSubmitLoading || !onPasteFiles || getIsElectron()) return false;
|
||||
|
||||
const files = Array.from(clipboardData?.files ?? []).filter((file) => !isRasterImageFile(file));
|
||||
if (files.length === 0) return false;
|
||||
|
||||
onPasteFiles(files);
|
||||
return true;
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!isWeb) return;
|
||||
|
||||
@@ -546,8 +563,13 @@ function usePasteEffect(args: PasteEffectArgs): void {
|
||||
if (disabled || isDictating || isRealtimeVoiceForCurrentAgent) return;
|
||||
|
||||
const imageFiles = collectImageFilesFromClipboardData(event.clipboardData);
|
||||
const didPasteFiles = pasteFiles(event.clipboardData);
|
||||
if (didPasteFiles) event.preventDefault();
|
||||
|
||||
if (imageFiles.length === 0) {
|
||||
if (pasteLinkedClipboardText(textarea, event.clipboardData)) event.preventDefault();
|
||||
if (!didPasteFiles && pasteLinkedClipboardText(textarea, event.clipboardData)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!isConnected || !onAddImages) return;
|
||||
@@ -1191,6 +1213,7 @@ interface ResolvedMessageInputProps {
|
||||
attachmentMenuItems: AttachmentMenuItem[];
|
||||
onAttachButtonRef: ((node: View | null) => void) | undefined;
|
||||
onAddImages: ((images: ImageAttachment[]) => void) | undefined;
|
||||
onPasteFiles: ((files: File[]) => void) | undefined;
|
||||
onPasteImages: ((files: readonly NativePastedFile[]) => void) | undefined;
|
||||
client: DaemonClient | null;
|
||||
isReadyForDictation: boolean | undefined;
|
||||
@@ -1239,6 +1262,7 @@ function resolveMessageInputProps(props: MessageInputProps): ResolvedMessageInpu
|
||||
attachmentMenuItems: props.attachmentMenuItems,
|
||||
onAttachButtonRef: props.onAttachButtonRef,
|
||||
onAddImages: props.onAddImages,
|
||||
onPasteFiles: props.onPasteFiles,
|
||||
onPasteImages: props.onPasteImages,
|
||||
client: props.client,
|
||||
isReadyForDictation: props.isReadyForDictation,
|
||||
@@ -1321,6 +1345,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
attachmentMenuItems,
|
||||
onAttachButtonRef,
|
||||
onAddImages,
|
||||
onPasteFiles,
|
||||
onPasteImages,
|
||||
client,
|
||||
isReadyForDictation,
|
||||
@@ -1874,6 +1899,8 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isDictating,
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
onAddImages,
|
||||
onPasteFiles,
|
||||
isSubmitLoading,
|
||||
});
|
||||
|
||||
const handleSelectionChange = useCallback(
|
||||
|
||||
@@ -659,7 +659,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
}),
|
||||
prepareHostBrowserPartition: async (serverId) => {
|
||||
preparedServers.push(serverId);
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
toBrowserRoutingHost,
|
||||
type BrowserRoutingHost,
|
||||
type ClassifyHostBrowserRoutingInput,
|
||||
type HostBrowserRouting,
|
||||
} from "./classify";
|
||||
|
||||
@@ -23,6 +24,7 @@ const statusListenersByServerId = new Map<string, Set<() => void>>();
|
||||
const trackedHostIds = new Set<string>();
|
||||
const lastTunnelPathStatus = new Map<string, string>();
|
||||
const lastSentTargetKey = new Map<string, string>();
|
||||
const routingSnapshots = new Map<string, { key: string; routing: HostBrowserRouting }>();
|
||||
let bridgeInstalled = false;
|
||||
|
||||
function notifyStatusListeners(serverId: string): void {
|
||||
@@ -117,6 +119,7 @@ export function installBrowserProxyRendererBridge(): void {
|
||||
trackedHostIds.delete(serverId);
|
||||
lastTunnelPathStatus.delete(serverId);
|
||||
lastSentTargetKey.delete(serverId);
|
||||
routingSnapshots.delete(serverId);
|
||||
statusByServerId.delete(serverId);
|
||||
notifyStatusListeners(serverId);
|
||||
void desktop.browser?.releaseHostProxy?.(serverId).catch(() => {});
|
||||
@@ -147,22 +150,41 @@ export function installBrowserProxyRendererBridge(): void {
|
||||
.catch(() => {});
|
||||
}
|
||||
};
|
||||
// Runtime changes cover status and active connection of every host, including origins.
|
||||
store.subscribeAll(reconcileTrackedHosts);
|
||||
// Session changes carry server_info features that gate the tunnel.
|
||||
useSessionStore.subscribe((state, previous) => {
|
||||
for (const serverId of trackedHostIds) {
|
||||
const originServerId = routedOriginServerId(
|
||||
store.getSnapshot(serverId)?.activeConnection ?? null,
|
||||
);
|
||||
for (const id of originServerId ? [serverId, originServerId] : [serverId]) {
|
||||
if (state.sessions[id]?.serverInfo !== previous.sessions[id]?.serverInfo) {
|
||||
reconcileTrackedHosts();
|
||||
return;
|
||||
subscribeRoutingInputs(() => trackedHostIds, reconcileTrackedHosts);
|
||||
}
|
||||
|
||||
/** Calls `listener` when the routing input of any host in `serverIds()` may have changed. */
|
||||
function subscribeRoutingInputs(
|
||||
serverIds: () => Iterable<string>,
|
||||
listener: () => void,
|
||||
): () => void {
|
||||
const store = getHostRuntimeStore();
|
||||
const routingHostIds = (serverId: string) => {
|
||||
const originServerId = routedOriginServerId(
|
||||
store.getSnapshot(serverId)?.activeConnection ?? null,
|
||||
);
|
||||
return originServerId ? [serverId, originServerId] : [serverId];
|
||||
};
|
||||
const unsubscribes = [
|
||||
// Status and active connection of every host, including origins.
|
||||
store.subscribeAll(listener),
|
||||
// Saved connections and passwords.
|
||||
store.subscribeHostList(listener),
|
||||
// server_info features gate the tunnel.
|
||||
useSessionStore.subscribe((state, previous) => {
|
||||
for (const serverId of serverIds()) {
|
||||
for (const id of routingHostIds(serverId)) {
|
||||
if (state.sessions[id]?.serverInfo !== previous.sessions[id]?.serverInfo) {
|
||||
listener();
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
for (const unsubscribe of unsubscribes) unsubscribe();
|
||||
};
|
||||
}
|
||||
|
||||
function readBrowserRoutingHost(serverId: string): BrowserRoutingHost {
|
||||
@@ -175,24 +197,35 @@ function readBrowserRoutingHost(serverId: string): BrowserRoutingHost {
|
||||
});
|
||||
}
|
||||
|
||||
export function readHostBrowserRouting(serverId: string): HostBrowserRouting {
|
||||
/** A host and, when it is routed, the origin host its tunnel runs through. */
|
||||
function readBrowserRoutingInput(serverId: string): ClassifyHostBrowserRoutingInput {
|
||||
const host = readBrowserRoutingHost(serverId);
|
||||
const originServerId = routedOriginServerId(host.activeConnection);
|
||||
return classifyHostBrowserRouting({
|
||||
...host,
|
||||
origin: originServerId ? readBrowserRoutingHost(originServerId) : null,
|
||||
});
|
||||
return { ...host, origin: originServerId ? readBrowserRoutingHost(originServerId) : null };
|
||||
}
|
||||
|
||||
export function readHostBrowserRouting(serverId: string): HostBrowserRouting {
|
||||
return classifyHostBrowserRouting(readBrowserRoutingInput(serverId));
|
||||
}
|
||||
|
||||
/** {@link readHostBrowserRouting}, keeping its identity while the routing is unchanged. */
|
||||
export function getHostBrowserRoutingSnapshot(serverId: string): HostBrowserRouting {
|
||||
const routing = readHostBrowserRouting(serverId);
|
||||
const key = JSON.stringify(routing);
|
||||
const cached = routingSnapshots.get(serverId);
|
||||
if (cached?.key === key) return cached.routing;
|
||||
routingSnapshots.set(serverId, { key, routing });
|
||||
return routing;
|
||||
}
|
||||
|
||||
export function subscribeHostBrowserRouting(serverId: string, listener: () => void): () => void {
|
||||
return subscribeRoutingInputs(() => [serverId], listener);
|
||||
}
|
||||
|
||||
/** "online" when the host, and its origin when routed, are both online. */
|
||||
function readTunnelPathStatus(serverId: string): string {
|
||||
const store = getHostRuntimeStore();
|
||||
const snapshot = store.getSnapshot(serverId);
|
||||
const status = snapshot?.connectionStatus ?? "offline";
|
||||
const originServerId = routedOriginServerId(snapshot?.activeConnection ?? null);
|
||||
const originStatus = originServerId
|
||||
? (store.getSnapshot(originServerId)?.connectionStatus ?? "offline")
|
||||
: "online";
|
||||
const { connectionStatus: status, origin } = readBrowserRoutingInput(serverId);
|
||||
const originStatus = origin?.connectionStatus ?? "online";
|
||||
return status === "online" && originStatus === "online" ? "online" : `${status}/${originStatus}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -68,7 +68,7 @@ describe("classifyHostBrowserRouting", () => {
|
||||
const relayConn: HostConnection = {
|
||||
id: "relay:relay.paseo.sh",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
@@ -121,24 +121,14 @@ describe("classifyHostBrowserRouting", () => {
|
||||
).toEqual({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
});
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-ssh", remoteSsh)).toEqual({
|
||||
type: "remoteSsh",
|
||||
host: "devbox",
|
||||
sshPort: 2222,
|
||||
daemonPort: 6767,
|
||||
});
|
||||
expect(extractBrowserProxyTarget("remote-ssh", remoteSsh)).toBe("ssh://devbox:2222");
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-relay", relayConn)).toEqual({
|
||||
type: "relay",
|
||||
serverId: "remote-relay",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
});
|
||||
expect(extractBrowserProxyTarget("remote-relay", relayConn)).toBe(
|
||||
"relay://relay.paseo.sh:443/remote-relay?key=AAAA&ssl=true&security=protected",
|
||||
);
|
||||
});
|
||||
|
||||
it("fails closed for old daemons, connecting hosts, and offline remote hosts", () => {
|
||||
@@ -187,7 +177,7 @@ describe("classifyHostBrowserRouting", () => {
|
||||
const supportedRemote = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
};
|
||||
const oldRemote = { kind: "remote" as const, support: "daemon_update_required" as const };
|
||||
const local = { kind: "local" as const };
|
||||
@@ -256,12 +246,7 @@ describe("classifyHostBrowserRouting for routed hosts", () => {
|
||||
expect(classify({}, localSocketOrigin)).toEqual({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: {
|
||||
type: "routed",
|
||||
serverId: "srv-b",
|
||||
originServerId: "srv-a",
|
||||
origin: { type: "directSocket", path: "/tmp/paseo.sock" },
|
||||
},
|
||||
target: { via: "unix:///tmp/paseo.sock", serverId: "srv-b" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -278,7 +263,7 @@ describe("classifyHostBrowserRouting for routed hosts", () => {
|
||||
};
|
||||
expect(classify({}, origin)).toMatchObject({
|
||||
support: "supported",
|
||||
target: { type: "routed", origin: { type: "directTcp", endpoint: "127.0.0.1:6767" } },
|
||||
target: { via: "tcp://127.0.0.1:6767", serverId: "srv-b" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -298,21 +283,12 @@ describe("classifyHostBrowserRouting for routed hosts", () => {
|
||||
remote({ id: "tcp", type: "directTcp", endpoint: "a.example:6767", useTls: true }),
|
||||
),
|
||||
).toMatchObject({
|
||||
target: {
|
||||
origin: {
|
||||
type: "directTcp",
|
||||
endpoint: "a.example:6767",
|
||||
useTls: true,
|
||||
password: "origin-secret",
|
||||
},
|
||||
},
|
||||
target: { via: "tcp://a.example:6767?ssl=true", originPassword: "origin-secret" },
|
||||
});
|
||||
expect(
|
||||
classify({}, remote({ id: "ssh", type: "remoteSsh", host: "me@a", sshPort: 2222 })),
|
||||
).toMatchObject({
|
||||
target: {
|
||||
origin: { type: "remoteSsh", host: "me@a", sshPort: 2222, password: "origin-secret" },
|
||||
},
|
||||
target: { via: "ssh://me@a:2222", originPassword: "origin-secret" },
|
||||
});
|
||||
expect(
|
||||
classify(
|
||||
@@ -326,13 +302,8 @@ describe("classifyHostBrowserRouting for routed hosts", () => {
|
||||
),
|
||||
).toMatchObject({
|
||||
target: {
|
||||
origin: {
|
||||
type: "relay",
|
||||
serverId: "srv-a",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
password: "origin-secret",
|
||||
},
|
||||
via: "relay://relay.paseo.sh:443/srv-a?key=AAAA&ssl=true",
|
||||
originPassword: "origin-secret",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,16 +1,12 @@
|
||||
import { parseHostPort } from "@getpaseo/protocol/daemon-endpoints";
|
||||
import type {
|
||||
DesktopBrowserProxyDaemonTarget,
|
||||
DesktopBrowserProxyOriginTarget,
|
||||
DesktopBrowserProxyTarget,
|
||||
} from "@/desktop/host";
|
||||
import type { HostTransportSpec } from "@getpaseo/protocol/host-target";
|
||||
import type {
|
||||
ActiveConnection,
|
||||
HostRuntimeConnectionStatus,
|
||||
HostRuntimeSnapshot,
|
||||
} from "@/runtime/host-runtime";
|
||||
import type { DaemonServerInfo } from "@/stores/session-store";
|
||||
import type { HostConnection, HostProfile } from "@/types/host-connection";
|
||||
import { hostConnectionUri, type HostConnection, type HostProfile } from "@/types/host-connection";
|
||||
|
||||
const IPV4_LOOPBACK_PATTERN = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||
|
||||
@@ -59,53 +55,18 @@ export function isLocalHostConnection(connection: HostConnection | ActiveConnect
|
||||
return false;
|
||||
}
|
||||
|
||||
function daemonTargetOf(
|
||||
serverId: string,
|
||||
connection: HostConnection,
|
||||
): DesktopBrowserProxyDaemonTarget | null {
|
||||
if (connection.type === "directTcp") {
|
||||
return {
|
||||
type: "directTcp",
|
||||
endpoint: connection.endpoint,
|
||||
...(connection.useTls !== undefined ? { useTls: connection.useTls } : {}),
|
||||
};
|
||||
}
|
||||
if (connection.type === "remoteSsh") {
|
||||
return {
|
||||
type: "remoteSsh",
|
||||
host: connection.host,
|
||||
...(connection.sshPort !== undefined ? { sshPort: connection.sshPort } : {}),
|
||||
...(connection.daemonPort !== undefined ? { daemonPort: connection.daemonPort } : {}),
|
||||
};
|
||||
}
|
||||
if (connection.type === "relay") {
|
||||
return {
|
||||
type: "relay",
|
||||
serverId,
|
||||
relayEndpoint: connection.relayEndpoint,
|
||||
...(connection.useTls !== undefined ? { useTls: connection.useTls } : {}),
|
||||
daemonPublicKeyB64: connection.daemonPublicKeyB64,
|
||||
...(connection.minimumSecurityMode === "protected"
|
||||
? { minimumSecurityMode: "protected" }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The connection Electron main dials to tunnel to this host, or null when it is local. */
|
||||
export function extractBrowserProxyTarget(
|
||||
serverId: string,
|
||||
connection: HostConnection,
|
||||
): DesktopBrowserProxyDaemonTarget | null {
|
||||
if (connection.type === "directTcp" && isLoopbackDirectTcpEndpoint(connection.endpoint)) {
|
||||
return null;
|
||||
}
|
||||
return daemonTargetOf(serverId, connection);
|
||||
): string | null {
|
||||
if (isLocalHostConnection(connection)) return null;
|
||||
return hostConnectionUri(connection, serverId);
|
||||
}
|
||||
|
||||
export type HostBrowserRouting =
|
||||
| { kind: "local" }
|
||||
| { kind: "remote"; support: "supported"; target: DesktopBrowserProxyTarget }
|
||||
| { kind: "remote"; support: "supported"; target: HostTransportSpec }
|
||||
| { kind: "remote"; support: "daemon_update_required" }
|
||||
| { kind: "remote"; support: "host_connecting" }
|
||||
| { kind: "remote"; support: "host_offline" };
|
||||
@@ -193,20 +154,14 @@ function unavailableWhileDisconnected(host: BrowserRoutingHost): UnsupportedRout
|
||||
return null;
|
||||
}
|
||||
|
||||
/** How Electron main reaches the origin daemon: the origin's active connection and password. */
|
||||
function originTargetOf(origin: BrowserRoutingHost): DesktopBrowserProxyOriginTarget | null {
|
||||
/** The origin daemon's active connection, which Electron main dials to reach a routed host. */
|
||||
function originConnectionOf(origin: BrowserRoutingHost): string | null {
|
||||
const connection = findMatchingHostConnection(
|
||||
origin.connections,
|
||||
origin.activeConnectionId,
|
||||
origin.activeConnection,
|
||||
);
|
||||
if (!connection) return null;
|
||||
const credentials = origin.password ? { password: origin.password } : {};
|
||||
if (connection.type === "directSocket" || connection.type === "directPipe") {
|
||||
return { type: connection.type, path: connection.path, ...credentials };
|
||||
}
|
||||
const daemon = daemonTargetOf(origin.serverId, connection);
|
||||
return daemon ? { ...daemon, ...credentials } : null;
|
||||
return connection ? hostConnectionUri(connection, origin.serverId) : null;
|
||||
}
|
||||
|
||||
function classifyRoutedHost(
|
||||
@@ -232,18 +187,17 @@ function classifyRoutedHost(
|
||||
return { kind: "remote", support: "daemon_update_required" };
|
||||
}
|
||||
|
||||
const originTarget = originTargetOf(origin);
|
||||
if (!originTarget) {
|
||||
const via = originConnectionOf(origin);
|
||||
if (!via) {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
return {
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: {
|
||||
type: "routed",
|
||||
via,
|
||||
serverId: host.serverId,
|
||||
originServerId,
|
||||
origin: originTarget,
|
||||
...(origin.password ? { originPassword: origin.password } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -99,7 +99,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
const supportedRouting = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -182,12 +182,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
});
|
||||
|
||||
describe("routed hosts", () => {
|
||||
const routedTarget = {
|
||||
type: "routed" as const,
|
||||
serverId: "srv-dev",
|
||||
originServerId: "srv-mac",
|
||||
origin: { type: "directSocket" as const, path: "/tmp/paseo.sock" },
|
||||
};
|
||||
const routedTarget = { via: "unix:///tmp/paseo.sock", serverId: "srv-dev" };
|
||||
const input = {
|
||||
effectiveRoutingMode: "host" as const,
|
||||
localPartition: "persist:paseo-browser",
|
||||
|
||||
@@ -2,16 +2,17 @@ import { useCallback, useEffect, useMemo, useState, useSyncExternalStore } from
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost, type DesktopBrowserProxyStatus } from "@/desktop/host";
|
||||
import { resolveBrowserRoutingMode, type BrowserRoutingMode } from "@/desktop/browser/store";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useHosts } from "@/runtime/host-runtime";
|
||||
import { normalizeHostLabel } from "@/types/host-connection";
|
||||
import {
|
||||
ensureHostBrowserProxy,
|
||||
getCachedBrowserProxyStatus,
|
||||
getHostBrowserRoutingSnapshot,
|
||||
installBrowserProxyRendererBridge,
|
||||
subscribeBrowserProxyStatus,
|
||||
subscribeHostBrowserRouting,
|
||||
} from "./bridge";
|
||||
import { classifyHostBrowserRouting, routedOriginServerId, toBrowserRoutingHost } from "./classify";
|
||||
import type { HostBrowserRouting } from "./classify";
|
||||
|
||||
export type BrowserProxyPaneState =
|
||||
| {
|
||||
@@ -60,10 +61,7 @@ function hasPreparedHostPartition(
|
||||
}
|
||||
|
||||
function resolveRemoteUnavailablePaneState(
|
||||
support: Exclude<
|
||||
Extract<ReturnType<typeof classifyHostBrowserRouting>, { kind: "remote" }>["support"],
|
||||
"supported"
|
||||
>,
|
||||
support: Exclude<Extract<HostBrowserRouting, { kind: "remote" }>["support"], "supported">,
|
||||
hostLabel: string,
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
): BrowserProxyPaneState {
|
||||
@@ -109,7 +107,7 @@ function resolvePreparedHostPaneStatus(
|
||||
}
|
||||
|
||||
export function resolveBrowserProxyPaneState(input: {
|
||||
routing: ReturnType<typeof classifyHostBrowserRouting>;
|
||||
routing: HostBrowserRouting;
|
||||
effectiveRoutingMode: BrowserRoutingMode;
|
||||
localPartition: string;
|
||||
hostLabel: string;
|
||||
@@ -189,19 +187,10 @@ export function useHostBrowserProxy(input: {
|
||||
[hosts, serverId],
|
||||
);
|
||||
const hostLabel = normalizeHostLabel(host?.label, serverId);
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
// A routed host's tunnel runs through its origin host, so the origin's connection
|
||||
// and features gate it too.
|
||||
const originServerId = routedOriginServerId(runtimeSnapshot?.activeConnection ?? null);
|
||||
const originProfile = useMemo(
|
||||
() =>
|
||||
originServerId ? (hosts.find((entry) => entry.serverId === originServerId) ?? null) : null,
|
||||
[hosts, originServerId],
|
||||
);
|
||||
const originSnapshot = useHostRuntimeSnapshot(originServerId ?? "");
|
||||
const originServerInfo = useSessionStore((state) =>
|
||||
originServerId ? (state.sessions[originServerId]?.serverInfo ?? null) : null,
|
||||
const routing = useSyncExternalStore(
|
||||
useCallback((onChange) => subscribeHostBrowserRouting(serverId, onChange), [serverId]),
|
||||
() => getHostBrowserRoutingSnapshot(serverId),
|
||||
() => getHostBrowserRoutingSnapshot(serverId),
|
||||
);
|
||||
|
||||
const proxyStatusSnapshot = useSyncExternalStore(
|
||||
@@ -213,31 +202,6 @@ export function useHostBrowserProxy(input: {
|
||||
const [retryCounter, setRetryCounter] = useState(0);
|
||||
const [ensureError, setEnsureError] = useState<string | null>(null);
|
||||
|
||||
const routing = useMemo(
|
||||
() =>
|
||||
classifyHostBrowserRouting({
|
||||
...toBrowserRoutingHost({ serverId, profile: host, snapshot: runtimeSnapshot, serverInfo }),
|
||||
origin: originServerId
|
||||
? toBrowserRoutingHost({
|
||||
serverId: originServerId,
|
||||
profile: originProfile,
|
||||
snapshot: originSnapshot,
|
||||
serverInfo: originServerInfo,
|
||||
})
|
||||
: null,
|
||||
}),
|
||||
[
|
||||
host,
|
||||
originProfile,
|
||||
originServerId,
|
||||
originServerInfo,
|
||||
originSnapshot,
|
||||
runtimeSnapshot,
|
||||
serverId,
|
||||
serverInfo,
|
||||
],
|
||||
);
|
||||
|
||||
const effectiveRoutingMode = resolveBrowserRoutingMode(
|
||||
{ routingMode },
|
||||
routing.kind === "remote",
|
||||
|
||||
@@ -1,29 +1,16 @@
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
import { localListenOfHostTarget, parseHostTarget } from "@getpaseo/protocol/host-target";
|
||||
import { hostConnectionUri, type HostConnection } from "@/types/host-connection";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
|
||||
function connectionListen(connection: HostConnection): string | null {
|
||||
switch (connection.type) {
|
||||
case "directTcp":
|
||||
return connection.endpoint;
|
||||
case "directSocket":
|
||||
return `unix://${connection.path}`;
|
||||
case "directPipe":
|
||||
return `pipe://${connection.path}`;
|
||||
case "remoteSsh":
|
||||
case "routed":
|
||||
case "relay":
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Desktop main checks that this target matches the live desktop-managed daemon.
|
||||
// A plain browser has no bridge and falls back to its saved host password.
|
||||
export async function readDesktopManagedLocalCredential(
|
||||
connection: HostConnection,
|
||||
host: { serverId: string; connection: HostConnection },
|
||||
invoke: (listen: string) => Promise<unknown> = async (listen) =>
|
||||
getDesktopHost()?.invoke?.("desktop_local_credential", { listen }),
|
||||
): Promise<string | undefined> {
|
||||
const listen = connectionListen(connection);
|
||||
const uri = hostConnectionUri(host.connection, host.serverId);
|
||||
const listen = uri ? localListenOfHostTarget(parseHostTarget(uri)) : null;
|
||||
if (!listen) return undefined;
|
||||
const credential = await invoke(listen);
|
||||
return typeof credential === "string" ? credential : undefined;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Platform } from "react-native";
|
||||
import { getElectronHost } from "@/desktop/electron/host";
|
||||
import type { BrowserKeyboardPolicy } from "@/keyboard";
|
||||
import type { IdentityColorName } from "@/styles/identity-colors";
|
||||
import type { HostTransportSpec } from "@getpaseo/protocol/host-target";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
|
||||
type BrowserAutomationExecuteRequest = Extract<
|
||||
@@ -172,44 +173,6 @@ export type BrowserProfileRemoveResult =
|
||||
| { ok: true }
|
||||
| { ok: false; code: "reserved" | "invalid" | "not_found" | "io" };
|
||||
|
||||
/** A daemon Electron main dials directly to open a network tunnel. */
|
||||
export type DesktopBrowserProxyDaemonTarget =
|
||||
| {
|
||||
type: "directTcp";
|
||||
endpoint: string;
|
||||
useTls?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "remoteSsh";
|
||||
host: string;
|
||||
sshPort?: number;
|
||||
daemonPort?: number;
|
||||
}
|
||||
| {
|
||||
type: "relay";
|
||||
serverId: string;
|
||||
relayEndpoint: string;
|
||||
useTls?: boolean;
|
||||
daemonPublicKeyB64: string;
|
||||
minimumSecurityMode?: "protected";
|
||||
};
|
||||
|
||||
/** The daemon a routed host is reached through, with that daemon's own credentials. */
|
||||
export type DesktopBrowserProxyOriginTarget = (
|
||||
| DesktopBrowserProxyDaemonTarget
|
||||
| { type: "directSocket"; path: string }
|
||||
| { type: "directPipe"; path: string }
|
||||
) & { password?: string };
|
||||
|
||||
export type DesktopBrowserProxyTarget =
|
||||
| DesktopBrowserProxyDaemonTarget
|
||||
| {
|
||||
type: "routed";
|
||||
serverId: string;
|
||||
originServerId: string;
|
||||
origin: DesktopBrowserProxyOriginTarget;
|
||||
};
|
||||
|
||||
export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting" | "error";
|
||||
|
||||
export interface DesktopBrowserProxyStatusSnapshot {
|
||||
@@ -254,13 +217,10 @@ export interface DesktopBrowserBridge {
|
||||
}) => Promise<void>;
|
||||
ensureHostProxy?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
target: HostTransportSpec;
|
||||
forceReconnect?: boolean;
|
||||
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
|
||||
updateHostProxyTarget?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
}) => Promise<void>;
|
||||
updateHostProxyTarget?: (input: { serverId: string; target: HostTransportSpec }) => Promise<void>;
|
||||
getHostProxyStatus?: (serverId: string) => Promise<DesktopBrowserProxyStatusSnapshot | null>;
|
||||
releaseHostProxy?: (serverId: string) => Promise<void>;
|
||||
deliverProxyTicket?: (input: {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import Constants from "expo-constants";
|
||||
import { Platform } from "react-native";
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
|
||||
function mapNativePlatform(os: string): HelloClientPlatform {
|
||||
if (os === "ios") return "ios";
|
||||
if (os === "android") return "android";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function resolveAppClientIdentity(): {
|
||||
clientType: "mobile" | "browser";
|
||||
clientInfo: HelloClientInfo;
|
||||
} {
|
||||
const deviceName = Constants.deviceName?.trim();
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
platform: mapNativePlatform(Platform.OS),
|
||||
...(deviceName ? { name: deviceName.slice(0, 128) } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
|
||||
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
|
||||
const normalized = raw?.toLowerCase();
|
||||
if (normalized === "darwin" || normalized === "macos") return "macos";
|
||||
if (normalized === "linux") return "linux";
|
||||
if (normalized === "win32" || normalized === "windows") return "windows";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function parseBrowserName(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) return undefined;
|
||||
if (/Edg\//.test(userAgent)) return "Edge";
|
||||
if (/Firefox\//.test(userAgent)) return "Firefox";
|
||||
if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) return "Chrome";
|
||||
if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) return "Safari";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolveAppClientIdentity(): {
|
||||
clientType: "mobile" | "browser";
|
||||
clientInfo: HelloClientInfo;
|
||||
} {
|
||||
if (getIsElectron()) {
|
||||
const desktop = getDesktopHost();
|
||||
const label = desktop?.browserHostLabel?.trim();
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
platform: mapDesktopPlatform(desktop?.platform),
|
||||
...(label ? { name: label.slice(0, 128) } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const browserName =
|
||||
typeof navigator !== "undefined" ? parseBrowserName(navigator.userAgent) : undefined;
|
||||
return {
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
platform: "web",
|
||||
...(browserName ? { name: browserName } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { TFunction } from "i18next";
|
||||
import type {
|
||||
DaemonClientsSnapshot,
|
||||
DaemonSessionSummary,
|
||||
DaemonSessionTransport,
|
||||
WSClientType,
|
||||
} from "@getpaseo/protocol/daemon-clients";
|
||||
import type { DaemonPermission } from "@getpaseo/protocol/messages";
|
||||
import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsCollapsibleRow,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
} from "@/components/settings";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
|
||||
type StatusDotTone = "online" | "warning" | "error" | "offline";
|
||||
|
||||
function StatusDot({ tone }: { tone: StatusDotTone }) {
|
||||
return (
|
||||
<View style={styles.dotSlot}>
|
||||
<View
|
||||
style={[
|
||||
styles.dot,
|
||||
tone === "online" && styles.dotOnline,
|
||||
tone === "warning" && styles.dotWarning,
|
||||
tone === "error" && styles.dotError,
|
||||
tone === "offline" && styles.dotOffline,
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS_DOTS: Record<StatusDotTone, React.ReactNode> = {
|
||||
online: <StatusDot tone="online" />,
|
||||
warning: <StatusDot tone="warning" />,
|
||||
error: <StatusDot tone="error" />,
|
||||
offline: <StatusDot tone="offline" />,
|
||||
};
|
||||
|
||||
function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[]; t: TFunction }) {
|
||||
const summary = summarizePermissions(permissions);
|
||||
let label: string;
|
||||
if (summary.kind === "full") {
|
||||
label = t("devices.scopes.fullAccess");
|
||||
} else if (summary.kind === "read_only") {
|
||||
label = t("devices.scopes.readOnly");
|
||||
} else if (summary.count === 1) {
|
||||
label = t("devices.scopes.countOne");
|
||||
} else {
|
||||
label = t("devices.scopes.countOther", { count: summary.count });
|
||||
}
|
||||
return <StatusBadge label={label} variant="muted" size="xs" />;
|
||||
}
|
||||
|
||||
function PermissionPillsRow({
|
||||
permissions,
|
||||
t,
|
||||
}: {
|
||||
permissions: readonly DaemonPermission[];
|
||||
t: TFunction;
|
||||
}) {
|
||||
return (
|
||||
<SettingsRow label={t("devices.details.permissions")}>
|
||||
<View style={styles.scopePills}>
|
||||
{permissions.length > 0 ? (
|
||||
permissions.map((permission) => (
|
||||
<StatusBadge key={permission} label={permission} variant="muted" size="xs" />
|
||||
))
|
||||
) : (
|
||||
<Text style={styles.nestedValue}>{t("devices.scopes.none")}</Text>
|
||||
)}
|
||||
</View>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFunction): string | null {
|
||||
if (!isoTimestamp) return null;
|
||||
const duration = formatConnectedDuration(isoTimestamp);
|
||||
if (!duration) return null;
|
||||
if (duration.kind === "just_now") return t("devices.time.justNow");
|
||||
if (duration.kind === "minutes") return t("devices.time.minutesAgo", { count: duration.count });
|
||||
if (duration.kind === "hours") return t("devices.time.hoursAgo", { count: duration.count });
|
||||
return t("devices.time.daysAgo", { count: duration.count });
|
||||
}
|
||||
|
||||
function formatTransportLabel(
|
||||
transport: DaemonSessionTransport,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
switch (transport) {
|
||||
case "local_ipc":
|
||||
case "local":
|
||||
return t("devices.transport.local");
|
||||
case "tailscale":
|
||||
return t("devices.transport.tailscale");
|
||||
case "relay":
|
||||
return t("devices.transport.relay");
|
||||
case "hub":
|
||||
return t("devices.transport.hub");
|
||||
case "via":
|
||||
return viaHostName
|
||||
? t("devices.transport.via", { host: viaHostName })
|
||||
: t("devices.transport.viaHost");
|
||||
case "direct":
|
||||
return t("devices.transport.direct");
|
||||
}
|
||||
}
|
||||
|
||||
function formatClientPlatformLabel(
|
||||
clientType: WSClientType,
|
||||
platform: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (platform === "ios") return "iOS";
|
||||
if (platform === "android") return "Android";
|
||||
if (platform === "macos" || platform === "linux" || platform === "windows") {
|
||||
return t("devices.kind.desktop");
|
||||
}
|
||||
if (clientType === "browser" || platform === "web") return t("devices.kind.web");
|
||||
if (clientType === "mobile") return t("devices.kind.mobile");
|
||||
if (clientType === "hub") return t("devices.kind.hub");
|
||||
if (clientType === "cli") return "CLI";
|
||||
return "MCP";
|
||||
}
|
||||
|
||||
function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
|
||||
if (session.isCurrentSession) return t("devices.connected.thisDevice");
|
||||
if (session.name) return session.name;
|
||||
return formatClientPlatformLabel(session.clientType, session.platform, t);
|
||||
}
|
||||
|
||||
function formatSessionHint(
|
||||
session: DaemonSessionSummary,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
const transport = formatTransportLabel(session.transport, viaHostName, t);
|
||||
const platform = formatClientPlatformLabel(session.clientType, session.platform, t);
|
||||
const detail = session.appVersion ? `${platform} ${session.appVersion}` : platform;
|
||||
return detail === transport ? transport : `${transport} · ${detail}`;
|
||||
}
|
||||
|
||||
function ConnectedClientRow({
|
||||
session,
|
||||
viaHostName,
|
||||
}: {
|
||||
session: DaemonSessionSummary;
|
||||
viaHostName: string | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tone: StatusDotTone = session.socketCount > 0 ? "online" : "warning";
|
||||
const connectedLabel = formatDurationLabel(session.connectedAt, t);
|
||||
const trailing = useMemo(
|
||||
() => <ScopePill permissions={session.permissions} t={t} />,
|
||||
[session.permissions, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={formatSessionTitle(session, t)}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={formatSessionHint(session, viaHostName, t)}
|
||||
trailing={trailing}
|
||||
testID={`devices-client-${session.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={session.permissions} t={t} />
|
||||
{connectedLabel ? (
|
||||
<SettingsRow label={t("devices.details.connected")}>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{session.socketCount === 0 ? (
|
||||
<SettingsRow label={t("devices.details.status")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
function InboundDaemonRow({
|
||||
daemon,
|
||||
routedSessions,
|
||||
}: {
|
||||
daemon: DaemonSessionSummary;
|
||||
routedSessions: readonly DaemonSessionSummary[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tone: StatusDotTone = daemon.socketCount > 0 ? "online" : "warning";
|
||||
const label = daemon.name ?? t("devices.hosts.unnamed");
|
||||
const transport = formatTransportLabel(daemon.transport, null, t);
|
||||
const hintParts = [t("devices.hosts.inbound"), transport];
|
||||
if (routedSessions.length > 0) {
|
||||
hintParts.push(t("devices.hosts.routedCount", { count: routedSessions.length }));
|
||||
}
|
||||
const connectedLabel = formatDurationLabel(daemon.connectedAt, t);
|
||||
const trailing = useMemo(
|
||||
() => <ScopePill permissions={daemon.permissions} t={t} />,
|
||||
[daemon.permissions, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={label}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={hintParts.join(" · ")}
|
||||
trailing={trailing}
|
||||
testID={`devices-inbound-host-${daemon.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={daemon.permissions} t={t} />
|
||||
{routedSessions.map((routed) => (
|
||||
<SettingsRow
|
||||
key={routed.sessionId}
|
||||
label={formatSessionTitle(routed, t)}
|
||||
hint={t("devices.hosts.routedSession")}
|
||||
>
|
||||
<ScopePill permissions={routed.permissions} t={t} />
|
||||
</SettingsRow>
|
||||
))}
|
||||
{daemon.appVersion ? (
|
||||
<SettingsRow label={t("devices.details.version")}>
|
||||
<Text style={styles.nestedValue}>{daemon.appVersion}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{connectedLabel ? (
|
||||
<SettingsRow label={t("devices.details.connected")}>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{daemon.socketCount === 0 ? (
|
||||
<SettingsRow label={t("devices.details.status")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
function outboundHostTone(status: HostSummary["status"]): StatusDotTone {
|
||||
switch (status) {
|
||||
case "online":
|
||||
return "online";
|
||||
case "connecting":
|
||||
return "warning";
|
||||
case "error":
|
||||
return "error";
|
||||
case "offline":
|
||||
case "disabled":
|
||||
return "offline";
|
||||
}
|
||||
}
|
||||
|
||||
function outboundHostStatusLabel(status: HostSummary["status"], t: TFunction): string | undefined {
|
||||
switch (status) {
|
||||
case "connecting":
|
||||
return t("devices.status.connecting");
|
||||
case "error":
|
||||
return t("devices.status.error");
|
||||
case "disabled":
|
||||
return t("devices.status.disabled");
|
||||
case "offline":
|
||||
return t("devices.status.offline");
|
||||
case "online":
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function OutboundHostRow({ host }: { host: HostSummary }) {
|
||||
const { t } = useTranslation();
|
||||
const tone = outboundHostTone(host.status);
|
||||
const label = host.label ?? host.serverId ?? host.targetDescription;
|
||||
const hintParts = [t("devices.hosts.outbound"), host.targetDescription];
|
||||
const statusSummary = outboundHostStatusLabel(host.status, t);
|
||||
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, t);
|
||||
const trailing = useMemo(
|
||||
() =>
|
||||
host.status === "online" && host.permissions ? (
|
||||
<ScopePill permissions={host.permissions} t={t} />
|
||||
) : undefined,
|
||||
[host.permissions, host.status, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={label}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={hintParts.join(" · ")}
|
||||
hintStatus={host.status === "error" ? "error" : undefined}
|
||||
summary={statusSummary}
|
||||
trailing={trailing}
|
||||
testID={`devices-outbound-host-${host.registrationId}`}
|
||||
>
|
||||
{host.permissions ? <PermissionPillsRow permissions={host.permissions} t={t} /> : null}
|
||||
{host.error ? (
|
||||
<SettingsRow label={t("devices.details.error")}>
|
||||
<Text style={styles.nestedError}>{host.error.message}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{host.version ? (
|
||||
<SettingsRow label={t("devices.details.version")}>
|
||||
<Text style={styles.nestedValue}>{host.version}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{connectedLabel ? (
|
||||
<SettingsRow
|
||||
label={
|
||||
host.status === "online"
|
||||
? t("devices.details.connected")
|
||||
: t("devices.details.lastSeen")
|
||||
}
|
||||
>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
type ConnectedClientsLoadState =
|
||||
| { status: "loading" }
|
||||
| { status: "ready"; snapshot: DaemonClientsSnapshot }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
function useConnectedClients(serverId: string, enabled: boolean): ConnectedClientsLoadState {
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const [state, setState] = useState<ConnectedClientsLoadState>({ status: "loading" });
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !client) {
|
||||
setState({ status: "loading" });
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
const observation = client.observeConnectedClients();
|
||||
const apply = (snapshot: DaemonClientsSnapshot) => {
|
||||
if (active) setState({ status: "ready", snapshot });
|
||||
};
|
||||
const unsubscribe = observation.subscribe({
|
||||
snapshot: apply,
|
||||
update: (message) => {
|
||||
if (message.type === "daemon.clients.changed") {
|
||||
apply({
|
||||
sessions: message.payload.sessions,
|
||||
});
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
if (!active) return;
|
||||
setState({
|
||||
status: "error",
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
},
|
||||
});
|
||||
void observation.ready.then(apply).catch((err: unknown) => {
|
||||
if (!active) return;
|
||||
setState({
|
||||
status: "error",
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribe();
|
||||
void observation.release();
|
||||
};
|
||||
}, [client, enabled]);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
function useOutboundHosts(serverId: string, enabled: boolean): HostDirectory | null {
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const [directory, setDirectory] = useState<HostDirectory | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !client) {
|
||||
setDirectory(null);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
const observation = client.observeHosts();
|
||||
const apply = (next: HostDirectory) => {
|
||||
if (active) setDirectory(next);
|
||||
};
|
||||
const unsubscribe = observation.subscribe({
|
||||
snapshot: apply,
|
||||
update: (message) => {
|
||||
if (message.type === "hosts.changed") apply(message.payload.directory);
|
||||
},
|
||||
});
|
||||
void observation.ready.then(apply).catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribe();
|
||||
void observation.release();
|
||||
};
|
||||
}, [client, enabled]);
|
||||
|
||||
return directory;
|
||||
}
|
||||
|
||||
const EMPTY_SESSIONS: readonly DaemonSessionSummary[] = [];
|
||||
|
||||
function ConnectedClientsCardBody({
|
||||
isOnline,
|
||||
hasServerInfo,
|
||||
supportsConnectedClients,
|
||||
canViewClients,
|
||||
clientsState,
|
||||
connectedClients,
|
||||
hostNameBySessionId,
|
||||
}: {
|
||||
isOnline: boolean;
|
||||
hasServerInfo: boolean;
|
||||
supportsConnectedClients: boolean;
|
||||
canViewClients: boolean;
|
||||
clientsState: ConnectedClientsLoadState;
|
||||
connectedClients: readonly DaemonSessionSummary[];
|
||||
hostNameBySessionId: ReadonlyMap<string, string | null>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const updateLink = useMemo(
|
||||
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
|
||||
[t],
|
||||
);
|
||||
|
||||
if (!isOnline) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.unavailable")}
|
||||
hint={t("workspace.terminal.hostDisconnected")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (hasServerInfo && !supportsConnectedClients) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.updateTitle")}
|
||||
hint={t("devices.connected.updateHint")}
|
||||
link={updateLink}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!canViewClients) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.permissionTitle")}
|
||||
hint={t("devices.connected.permissionHint")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (clientsState.status === "loading") {
|
||||
return <SettingsRow label={t("devices.connected.loading")} />;
|
||||
}
|
||||
if (clientsState.status === "error") {
|
||||
return <SettingsRow label={t("devices.connected.errorTitle")} error={clientsState.message} />;
|
||||
}
|
||||
if (connectedClients.length === 0) {
|
||||
return <SettingsRow label={t("devices.connected.empty")} />;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{connectedClients.map((entry) => (
|
||||
<ConnectedClientRow
|
||||
key={entry.sessionId}
|
||||
session={entry}
|
||||
viaHostName={
|
||||
entry.viaSessionId ? (hostNameBySessionId.get(entry.viaSessionId) ?? null) : null
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
|
||||
const isOnline = connectionStatus === "online";
|
||||
// COMPAT(connectedClients): added in v0.19.0, remove gate after 2027-06-01.
|
||||
const supportsConnectedClients = serverInfo?.features?.connectedClients === true;
|
||||
const supportsConnectedHosts = serverInfo?.features?.connectedHosts === true;
|
||||
const canViewClients =
|
||||
!serverInfo?.permissions || serverInfo.permissions.includes("access.manage");
|
||||
|
||||
const clientsState = useConnectedClients(
|
||||
serverId,
|
||||
isOnline && supportsConnectedClients && canViewClients,
|
||||
);
|
||||
const outboundDirectory = useOutboundHosts(serverId, isOnline && supportsConnectedHosts);
|
||||
|
||||
const sessions =
|
||||
clientsState.status === "ready" ? clientsState.snapshot.sessions : EMPTY_SESSIONS;
|
||||
const inboundDaemons = useMemo(
|
||||
() => sessions.filter((entry) => entry.servesHostLink === true),
|
||||
[sessions],
|
||||
);
|
||||
const connectedClients = useMemo(
|
||||
() => sessions.filter((entry) => !entry.servesHostLink),
|
||||
[sessions],
|
||||
);
|
||||
const hostNameBySessionId = useMemo(
|
||||
() => new Map(inboundDaemons.map((daemon) => [daemon.sessionId, daemon.name])),
|
||||
[inboundDaemons],
|
||||
);
|
||||
const routedByHostSessionId = useMemo(() => {
|
||||
const grouped = new Map<string, DaemonSessionSummary[]>();
|
||||
for (const entry of sessions) {
|
||||
if (!entry.viaSessionId) continue;
|
||||
const list = grouped.get(entry.viaSessionId);
|
||||
if (list) list.push(entry);
|
||||
else grouped.set(entry.viaSessionId, [entry]);
|
||||
}
|
||||
return grouped;
|
||||
}, [sessions]);
|
||||
|
||||
const outboundHosts = outboundDirectory?.hosts ?? [];
|
||||
const hasConnectedHosts = inboundDaemons.length > 0 || outboundHosts.length > 0;
|
||||
|
||||
return (
|
||||
<View>
|
||||
<SettingsSection title={t("devices.connected.title")}>
|
||||
<SettingsCard testID="devices-connected-clients-card">
|
||||
<ConnectedClientsCardBody
|
||||
isOnline={isOnline}
|
||||
hasServerInfo={Boolean(serverInfo)}
|
||||
supportsConnectedClients={supportsConnectedClients}
|
||||
canViewClients={canViewClients}
|
||||
clientsState={clientsState}
|
||||
connectedClients={connectedClients}
|
||||
hostNameBySessionId={hostNameBySessionId}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
{isOnline && hasConnectedHosts ? (
|
||||
<SettingsSection title={t("devices.hosts.title")}>
|
||||
<SettingsCard testID="devices-connected-hosts-card">
|
||||
{inboundDaemons.map((daemon) => (
|
||||
<InboundDaemonRow
|
||||
key={daemon.sessionId}
|
||||
daemon={daemon}
|
||||
routedSessions={routedByHostSessionId.get(daemon.sessionId) ?? EMPTY_SESSIONS}
|
||||
/>
|
||||
))}
|
||||
{outboundHosts.map((host) => (
|
||||
<OutboundHostRow key={host.registrationId} host={host} />
|
||||
))}
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
dotSlot: {
|
||||
width: 10,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
dot: {
|
||||
width: 7,
|
||||
height: 7,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
dotOnline: {
|
||||
backgroundColor: theme.colors.statusDotSuccess,
|
||||
},
|
||||
dotWarning: {
|
||||
backgroundColor: theme.colors.statusDotWarning,
|
||||
},
|
||||
dotError: {
|
||||
backgroundColor: theme.colors.statusDotDanger,
|
||||
},
|
||||
dotOffline: {
|
||||
backgroundColor: theme.colors.foregroundExtraMuted,
|
||||
},
|
||||
scopePills: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
justifyContent: "flex-end",
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
nestedValue: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
nestedError: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.statusDanger,
|
||||
},
|
||||
}));
|
||||
@@ -1,2 +1,4 @@
|
||||
export { ConnectedDevicesView } from "./connected-devices-view";
|
||||
export { PairDeviceHeaderAction } from "./pair-device-header-action";
|
||||
export { PairDeviceModal } from "./pair-device-modal";
|
||||
export { WaysToConnect } from "./ways-to-connect";
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Plus } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { PairDeviceSection } from "./pair-device-section";
|
||||
import { WaysToConnect } from "./ways-to-connect";
|
||||
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
const ThemedPlus = withUnistyles(Plus);
|
||||
const iconProps = (theme: Theme) => ({
|
||||
size: theme.iconSize.sm,
|
||||
color: theme.colors.foreground,
|
||||
});
|
||||
const plusIcon = <ThemedPlus uniProps={iconProps} />;
|
||||
|
||||
type PairStep = "ways" | "relay";
|
||||
|
||||
export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [step, setStep] = useState<PairStep>("ways");
|
||||
|
||||
const handleOpen = useCallback(() => {
|
||||
setStep("ways");
|
||||
setVisible(true);
|
||||
}, []);
|
||||
const handleClose = useCallback(() => {
|
||||
setVisible(false);
|
||||
}, []);
|
||||
const handleDismiss = useCallback(() => {
|
||||
setStep("ways");
|
||||
}, []);
|
||||
const handleOpenRelay = useCallback(() => setStep("relay"), []);
|
||||
const handleBackToWays = useCallback(() => setStep("ways"), []);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() =>
|
||||
step === "relay"
|
||||
? {
|
||||
title: t("devices.relay.title"),
|
||||
back: {
|
||||
onPress: handleBackToWays,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
}
|
||||
: {
|
||||
title: t("settings.host.pairDevices.rowTitle"),
|
||||
},
|
||||
[handleBackToWays, step, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
leftIcon={plusIcon}
|
||||
onPress={handleOpen}
|
||||
testID="devices-pair-button"
|
||||
>
|
||||
{t("settings.host.pairDevices.rowTitle")}
|
||||
</Button>
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={handleClose}
|
||||
onDismiss={handleDismiss}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={480}
|
||||
desktopHeight={520}
|
||||
testID={step === "relay" ? "devices-relay-pairing" : "devices-pair-sheet"}
|
||||
>
|
||||
{step === "relay" ? (
|
||||
<PairDeviceSection serverId={serverId} onClose={handleClose} />
|
||||
) : (
|
||||
<WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />
|
||||
)}
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DAEMON_PERMISSIONS } from "@getpaseo/protocol/messages";
|
||||
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
|
||||
|
||||
describe("summarizePermissions", () => {
|
||||
it("detects full access, read-only, and custom scope counts", () => {
|
||||
expect(summarizePermissions(DAEMON_PERMISSIONS)).toEqual({ kind: "full" });
|
||||
expect(summarizePermissions(["daemon.read", "workspace.read"])).toEqual({
|
||||
kind: "read_only",
|
||||
});
|
||||
expect(summarizePermissions(["workspace.read"])).toEqual({ kind: "read_only" });
|
||||
expect(summarizePermissions(["hub.execute", "workspace.read"])).toEqual({
|
||||
kind: "count",
|
||||
count: 2,
|
||||
});
|
||||
expect(summarizePermissions([])).toEqual({ kind: "count", count: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatConnectedDuration", () => {
|
||||
const now = Date.parse("2026-11-28T15:00:00.000Z");
|
||||
|
||||
it("formats relative durations cleanly", () => {
|
||||
expect(formatConnectedDuration("2026-11-28T14:59:30.000Z", now)).toEqual({
|
||||
kind: "just_now",
|
||||
});
|
||||
expect(formatConnectedDuration("2026-11-28T14:46:00.000Z", now)).toEqual({
|
||||
kind: "minutes",
|
||||
count: 14,
|
||||
});
|
||||
expect(formatConnectedDuration("2026-11-28T13:00:00.000Z", now)).toEqual({
|
||||
kind: "hours",
|
||||
count: 2,
|
||||
});
|
||||
expect(formatConnectedDuration("2026-11-25T15:00:00.000Z", now)).toEqual({
|
||||
kind: "days",
|
||||
count: 3,
|
||||
});
|
||||
expect(formatConnectedDuration("not-a-date", now)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { DAEMON_PERMISSIONS, type DaemonPermission } from "@getpaseo/protocol/messages";
|
||||
|
||||
const READ_ONLY_PERMISSIONS: ReadonlySet<DaemonPermission> = new Set([
|
||||
"daemon.read",
|
||||
"workspace.read",
|
||||
]);
|
||||
|
||||
export type PermissionSummary =
|
||||
| { kind: "full" }
|
||||
| { kind: "read_only" }
|
||||
| { kind: "count"; count: number };
|
||||
|
||||
export function summarizePermissions(permissions: readonly DaemonPermission[]): PermissionSummary {
|
||||
const unique = new Set(permissions);
|
||||
if (unique.size >= DAEMON_PERMISSIONS.length) {
|
||||
return { kind: "full" };
|
||||
}
|
||||
if (unique.size > 0 && [...unique].every((permission) => READ_ONLY_PERMISSIONS.has(permission))) {
|
||||
return { kind: "read_only" };
|
||||
}
|
||||
return { kind: "count", count: unique.size };
|
||||
}
|
||||
|
||||
export function formatConnectedDuration(
|
||||
isoTimestamp: string,
|
||||
nowMs = Date.now(),
|
||||
): { kind: "just_now" } | { kind: "minutes" | "hours" | "days"; count: number } | null {
|
||||
const parsedMs = Date.parse(isoTimestamp);
|
||||
if (!Number.isFinite(parsedMs)) return null;
|
||||
const elapsedSeconds = Math.max(0, Math.floor((nowMs - parsedMs) / 1000));
|
||||
if (elapsedSeconds < 60) return { kind: "just_now" };
|
||||
const minutes = Math.floor(elapsedSeconds / 60);
|
||||
if (minutes < 60) return { kind: "minutes", count: minutes };
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return { kind: "hours", count: hours };
|
||||
return { kind: "days", count: Math.floor(hours / 24) };
|
||||
}
|
||||
@@ -5,14 +5,26 @@ import { PairDeviceModal } from "./pair-device-modal";
|
||||
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
|
||||
import { TailscaleRow } from "./tailscale-row";
|
||||
|
||||
export interface WaysToConnectProps {
|
||||
serverId: string;
|
||||
/** When provided, tapping Relay delegates to the caller (e.g., to advance inside an existing sheet) instead of opening a stacked modal. */
|
||||
onOpenRelay?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet,
|
||||
* and Tailscale, a switch and an address. Settings and the setup's phone step show this same block.
|
||||
*/
|
||||
export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
export function WaysToConnect({ serverId, onOpenRelay }: WaysToConnectProps) {
|
||||
const { t } = useTranslation();
|
||||
const [pairing, setPairing] = useState(false);
|
||||
const openPairing = useCallback(() => setPairing(true), []);
|
||||
const openPairing = useCallback(() => {
|
||||
if (onOpenRelay) {
|
||||
onOpenRelay();
|
||||
return;
|
||||
}
|
||||
setPairing(true);
|
||||
}, [onOpenRelay]);
|
||||
const closePairing = useCallback(() => setPairing(false), []);
|
||||
const docsLink = useMemo(
|
||||
() => ({
|
||||
@@ -34,12 +46,14 @@ export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
/>
|
||||
<TailscaleRow serverId={serverId} />
|
||||
</SettingsCard>
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
{onOpenRelay ? null : (
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
)}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { useOverlayFlatListScrollbar } from "@/components/ui/overlay-scrollbar/use-overlay-flat-list-scrollbar";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { useDebouncedValue } from "@/hooks/use-debounced-value";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useHostRuntimeClient, useHostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { toErrorMessage } from "@/utils/error-messages";
|
||||
import { resolveFileFilterView, type FileFilterMatch, type FileFilterResponse } from "./model";
|
||||
@@ -40,7 +40,10 @@ export function FileFilterResults({
|
||||
renderMatch: (match: FileFilterMatch, index: number) => ReactElement;
|
||||
}): ReactElement {
|
||||
const { t } = useTranslation();
|
||||
const client = useSessionStore((state) => state.sessions[serverId]?.client ?? null);
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const connectionStatus = useHostRuntimeConnectionStatus(serverId);
|
||||
const canFetch = Boolean(client && connectionStatus === "online");
|
||||
const isHostUnavailable = connectionStatus === "offline" || connectionStatus === "error";
|
||||
const debouncedQuery = useDebouncedValue(query, SEARCH_DEBOUNCE_MS);
|
||||
const search = useFetchQuery({
|
||||
queryKey: [FILE_FILTER_QUERY_KEY, serverId, workspaceRoot, debouncedQuery],
|
||||
@@ -56,14 +59,18 @@ export function FileFilterResults({
|
||||
if (payload.error) throw new Error(payload.error);
|
||||
return { query: debouncedQuery, entries: payload.entries };
|
||||
},
|
||||
enabled: canFetch,
|
||||
dataShape: "list",
|
||||
staleTimeMs: 0,
|
||||
retry: false,
|
||||
});
|
||||
const queryError = search.error && debouncedQuery === query ? toErrorMessage(search.error) : null;
|
||||
const view = resolveFileFilterView({
|
||||
query,
|
||||
response: search.data,
|
||||
error: search.error && debouncedQuery === query ? toErrorMessage(search.error) : null,
|
||||
error:
|
||||
queryError ??
|
||||
(!canFetch && isHostUnavailable ? t("workspace.terminal.hostDisconnected") : null),
|
||||
isFetching: search.isFetching,
|
||||
showHiddenFiles,
|
||||
});
|
||||
@@ -75,7 +82,9 @@ export function FileFilterResults({
|
||||
[renderMatch],
|
||||
);
|
||||
const { refetch } = search;
|
||||
const handleRetry = useCallback(() => void refetch(), [refetch]);
|
||||
const handleRetry = useCallback(() => {
|
||||
if (canFetch) void refetch();
|
||||
}, [canFetch, refetch]);
|
||||
|
||||
if (view.status === "results") {
|
||||
return (
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user