Compare commits

...
Author SHA1 Message Date
Mohamed Boudra 67d512ca27 fix(app): hold running indicators in place while their panel is hidden
A ring, loader or shimmer in a panel that was not showing drew its resting
frame. On a phone the sidebar slides into view before its panel counts as
showing, so every ring sat at the resting position during the slide and
jumped to the running position when the slide settled.

A hidden indicator now stays bound to its clock and stops running it. The
clock and the loader's ticker hold the time they have run and count on from
it, so an indicator continues from where it stopped.
2026-12-01 13:25:22 +01:00
Mohamed Boudra bdad80d9bf fix(app): count the indicator clock with a timing the driver cannot end early
The native clock was a decay that never slows. React Native's driver ends
a decay when its value moves less than 0.1 between two frames, and two
frames that carry the same millisecond are enough. #11586 started the
decay again from the JS thread, but every end still showed as a pause and
a jump until the JS thread got to it.

The clock is now a linear timing, which the driver reads off the time
since it started and has no such check. It counts in ten-minute spans.
The end of a span is the one event that reaches the JS thread, which
starts the next span at the current time.
2026-12-01 13:25:22 +01:00
paseo-bot[bot]andDesmond Leong 1adabf70c8 fix(claude): settle stopped subagents after a daemon restart (#11594)
Claude can send a stop before it announces tasks in the new session. Match the terminal notice to the restored child so the open chat updates its original row.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Desmond Leong <desmond@returning.ai>
2026-12-01 12:12:45 +00:00
87427c2aa1 Release the microphone when voice mode stops without a daemon connection (#11587)
If the daemon is unreachable when voice mode stops, setVoiceMode(false)
rejects and stopVoice never stopped microphone capture or released the
screen wake lock. The runtime then reported voice as disabled while the
microphone stayed open.

Release capture and the wake lock in a finally block. The rejection still
propagates to the caller.

Closes #7558

Co-authored-by: luke <luopeihuan@gmail.com>
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-12-01 18:10:26 +07:00
Mohamed Boudra cfa4536358 Show Antigravity usage again, refreshed only when you ask (#11585)
* Show Antigravity usage again, refreshed only when you ask

Google's December 2026 terms allow running the unmodified agy harness,
including `agy -p`, through supported interfaces. Each `agy -p "/usage"`
still refreshes the quota on Google's backend, so Paseo must not run it
in the background.

Add `refresh: "manual"` to usage source registrations. The daemon never
fetches a manual source on lists, polls, or agent observations. A
targeted or host-wide forceRefresh fetches it once and caches the result
until the next forceRefresh. Before the first refresh, the report entry
has status `not_fetched`, and the card asks the user to refresh. A failed
manual refresh is not retried.

Restore the Antigravity usage source as a manual source. API key sign-in
reports a no-quota message instead of an error.

Update the Antigravity docs for the new terms and the plugin reference
for the new field.

Refs #10952

* Keep a manual usage result when agents join or leave the account

A manual result was keyed by the account's login set. Each Antigravity
agent adds a login, so a second agent or a closed agent reset the card to
"Not checked yet". Key a manual result by its report id instead.
2026-12-01 18:08:31 +07:00
Mohamed Boudra 7f75b0e166 Keep status rings turning when the native driver ends their clock (#11586)
Every status ring and tool-call shimmer on native rides one decay animation. React Native's driver ends a decay when its value moves less than 0.1 between two frames, and on Android two frames that carry the same millisecond are enough. The clock kept its handle, so every indicator froze until all of them left the screen and one came back.

The clock now listens for the driver ending the decay and starts it again at the current time.
2026-12-01 18:00:04 +07:00
Mohamed Boudra b0ca089d54 Skip redundant finished notification after a child agent reports via send_agent_prompt (#11583)
* fix(server): skip redundant finished notice after a child reports to its caller

When a watched child calls send_agent_prompt to report back to its caller, its final wrap-up response usually takes longer than the 2s message-delivery quiet window, so the caller wakes up on the report and then receives a second redundant 'Agent ... finished' notification once the child's turn ends.

Track per-watch report state on the daemon instead of relying on debounce timing or extra agent parameters: admitting an agent-message from a watched child to its caller marks active (non-pending) watches for that pair as reported, while subsequent non-reporting tool calls or a new turn_started clear the mark. Clean turn completions with the mark set end silently (or keep following silently if pending work remains); errors, permission requests, cancellations, and closes are never suppressed.

* docs(agent-lifecycle): note text-only output after explicit report keeps mark

* fix(server): ignore turn 1 turn_started after report and update cross-host batch e2e test

On remote children, turn 1's own turn_started frame can arrive over the observation stream after a fast send_agent_message already marked the watch as reported. Track turn completion so only a turn_started after a completed turn resets per-turn report state.

Update hosts.e2e.test.ts so turn 1 verifies suppression of the redundant finished notice after REMOTE_REPORT, and a follow-up unreported turn exercises automatic remote completion delivery.
2026-12-01 17:44:03 +07:00
Mohamed Boudra 91e7713721 refactor(client,desktop,app): share HostTransportSpec and protocol URIs for browser proxy (#11577)
Follows up on #11561 so adding a new transport (such as hub://) requires no parallel union or dial branch in the desktop browser proxy.

- Move HostTransportSpec, localListenOfHostTarget, and serializeSshTransportUri into @getpaseo/protocol so app, client, and desktop share one URI and local-listen contract.
- Move routed (via) dialing into @getpaseo/client/node createHostTransportFactory (lazy-loading the full client entry so @getpaseo/client/node/lean stays lean) and export DaemonTransport and HostTransportSpec publicly.
- Collapse BrowserProxyTarget / DesktopBrowserProxyTarget onto HostTransportSpec, remove per-transport branches from openTunnelWireConnection, and deduplicate browser routing input assembly between the hook and bridge.
- Rename linkCeiling to admittedCeiling in server handleTunnelHello to match both routed channels and Hub sockets.
2026-12-01 17:43:46 +07:00
SunicemanandShane Su e20ea2aaf2 fix(acp): preserve plain-text setting errors (#11431)
Co-authored-by: Shane Su <shane.su@maiscrm.com>
2026-12-01 10:42:48 +00:00
Mohamed Boudraandluoph 806214d285 Keep long Markdown replies cheap to stream on web and mobile (#11582)
Streaming one long reply made each reveal frame more expensive as the reply grew. The renderer now splits a streaming message into sealed head parts and a tail on every platform, and finds the boundary by parsing only the source after it.

Refs #7584

Co-authored-by: luoph <1686898+luoph@users.noreply.github.com>
2026-12-01 17:36:12 +07:00
KiritoXDone e5edb6efd5 fix(server): keep the full last reply across notifications (#11578) 2026-12-01 10:12:40 +00:00
Mohamed Boudra 0a0544fa4f fix(app): keep chat loading minimal and stop post-load Updating messages flash (#11575)
* fix(app): simplify chat loading state and eliminate post-load updating toast

Loading a workspace or chat previously shifted the spinner vertically as status text swapped in and out, jumped again when underfilled history handed off to the stream viewport overlay, and flashed an "Updating messages" toast right after content painted.

- Render LoadingState as a centered minimal spinner with accessibilityLabel only (no visible text).
- Hoist the agent-initial-fill overlay onto ChatAgentReadyContent so initial history fill shares the same full-pane geometry as agent-loading and reveals the chat and composer together.
- Emit a follow-up catch_up after a bootstrap tail replace only when live head rows actually extend past endCursor.seq, avoiding a redundant after fetch that kept visibility catch-up pending after the chat rendered.
- Keep the FRESHNESS_CHECK_QUIET_MS quiet window across initial subscribe and tail catch-up for opened cursorless chats (such as display-only caches with range: null).

* refactor(app): remove dead viewport initial-fill fallback and unused hostName prop

* fix(app): keep initial history fill overlay non-interactive

The previous viewport-level agent-initial-fill overlay used pointerEvents: none so pointer interactions were never blocked while underfilled history fetched older pages. Hoisting it onto ChatHistoryLoadingOverlay omitted pointerEvents: none, which intercepted scroll.hover() until the held page timed out.
2026-12-01 17:09:59 +07:00
Mohamed Boudra 914143e8b0 Show connected clients and hosts with scopes in Devices settings (#11209)
* feat(devices): show connected clients and hosts with scopes in host settings

Expose live daemon sessions and inbound/outbound peer daemon links in
Settings → Host → Devices, and move Ways to connect (Relay + Tailscale)
into a Pair a device header button sheet so the Devices view stays focused
on active connections.

Protocol changes stay backward compatible with older daemons and clients:
- Optional hello.clientInfo carries device name, platform, kind, and peer
  daemon identity without widening the existing clientType enum.
- daemon.clients.list.request/.response/.changed (gated on
  server_info.features.connectedClients and access.manage) streams live
  connected clients and inbound daemon links with their routed sessions.
- HostSummary gains optional version, permissions, and connectedAt fields
  populated from the remote daemon's server_info while online.

* fix(devices): trim unused client wire fields, stabilize pair modal, and add browser E2E

* fix(devices): reset pair modal step on dismiss and close sheet before host switch

* fix(page-layout): attach titleTestID to title parts instead of outer header with actions

* refactor(devices): flatten daemon session summary primitive and align with auth plan

* fix(devices): keep idle and reconnecting host-link sessions visible via hello.hostLink
2026-12-01 16:59:16 +07:00
149 changed files with 6193 additions and 1282 deletions
+17 -11
View File
@@ -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.
+12 -4
View File
@@ -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 -2
View File
@@ -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. 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
+4 -3
View File
@@ -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
View File
@@ -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).
+4 -3
View File
@@ -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.
@@ -14,6 +14,7 @@ import {
answerFreshnessCheck,
commitTimelineTurnsWhileDisconnected,
disconnectViewedTimeline,
expectCleanLoadingSurfaces,
expectEmptyChatSynced,
expectPromptAndWholeReply,
expectResumeAnsweredWithoutFetch,
@@ -29,8 +30,10 @@ import {
seedStreamingReplyAgent,
sendPromptWhileDisconnected,
stopStreamingReply,
waitForDisplayOnlyTimelineCache,
waitForResumeAnswer,
reopenAppWatchingForUpdatingToast,
watchColdAndReloadLoadingSurfaces,
watchForUpdatingToast,
} from "../support/helpers/timeline-resume";
@@ -176,4 +179,36 @@ test.describe("Agent timeline resume", () => {
await agent.cleanup();
}
});
test("cold opens and display-only cache reloads stay textless, steady, and free of Updating messages", 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 flashing Updating messages", 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 settles quietly without Updating messages", async () => {
await scrollTimelineUntilOlderHistoryIsReachable(page, agent.firstOlderPagePrompt);
await waitForDisplayOnlyTimelineCache(page, agent);
const requests = rememberTimelineRequestCounts(gate, agent.agentId);
await page.reload();
await expectTimelinePromptVisible(page, agent.newestPrompt);
await waitForResumeAnswer(gate, requests);
await expectCleanLoadingSurfaces(page, gate, requests);
});
} finally {
gate.restore();
await agent.cleanup();
}
});
});
@@ -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 {
@@ -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();
@@ -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"));
@@ -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> {
@@ -324,6 +324,124 @@ export async function stopStreamingReply(agent: StreamingReplyAgent): Promise<st
return reply;
}
interface LoadingSurfaceRecord {
loaderText: string[];
spinnerYsByTestId: Record<string, number[]>;
sawUpdatingToast: boolean;
}
declare global {
interface Window {
__loadingSurfaceRecord?: LoadingSurfaceRecord;
}
}
function recordLoadingSurfaces(): void {
const record: LoadingSurfaceRecord = {
loaderText: [],
spinnerYsByTestId: {},
sawUpdatingToast: false,
};
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;
}
}
if (document.querySelector('[data-testid="agent-updating-toast"]') !== null) {
record.sawUpdatingToast = true;
}
};
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);
}
/** Asserts every loading surface stayed textless, unshifted, and free of Updating messages. */
export async function expectCleanLoadingSurfaces(
page: Page,
gate: DaemonWebSocketGate,
before: TimelineRequestCounts,
): Promise<void> {
await waitForNextPaint(page);
const record = await page.evaluate(() => window.__loadingSurfaceRecord as LoadingSurfaceRecord);
expect(record.loaderText, "loading states must not render visible text").toEqual([]);
expect(record.sawUpdatingToast, "Updating messages must not flash after chat loads").toBe(false);
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,
@@ -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;
@@ -811,11 +808,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>
);
}
+7 -14
View File
@@ -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.
+7
View File
@@ -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");
}
@@ -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 });
@@ -43,8 +43,11 @@ export function useMarkdownSource(
forgeReferencePattern?: string;
external?: boolean;
} = {},
/** Identity of this occurrence's image acquisitions. Defaults to one per call site. */
occurrence?: string,
) {
const occurrenceKey = useId();
const ownOccurrence = useId();
const occurrenceKey = occurrence ?? ownOccurrence;
const { commandNames, forgeReferencePattern, external } = links;
const prepared = useMemo(
() =>
@@ -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 {
@@ -22,9 +22,9 @@ import { WEB_RENDERERS } from "./renderers";
import { createMarkdownStyles } from "./styles";
import { PENDING_MARKDOWN_IMAGE } from "./source";
import {
createStreamingMarkdownSplitter,
createStreamingMarkdownStabilizer,
PENDING_MARKDOWN_LINK,
splitStreamingMarkdown,
} from "./streaming";
import { MarkdownStreamingContext } from "./streaming-context";
import { useMarkdownSource, type MarkdownImageContext } from "./images";
@@ -73,34 +73,60 @@ export interface MarkdownRendererProps extends MarkdownImageContext {
/** 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} />;
});
@@ -128,8 +154,9 @@ const MarkdownPart = memo(function MarkdownPart({
agentCommands: _agentCommands,
external = false,
commandHints = null,
imageOccurrence,
...imageContext
}: MarkdownRendererProps & { commandHints?: CommandHints | null; preStabilized?: boolean }) {
}: MarkdownPartProps & { commandHints?: CommandHints | null }) {
const environment = useAssistantFileLinkEnvironment();
const actions = useAssistantFileLinkActions();
const workspaceForgeShorthand = useForgeShorthand();
@@ -159,6 +186,7 @@ const MarkdownPart = memo(function MarkdownPart({
forgeReferencePattern: forgeShorthand?.pattern,
external,
},
imageOccurrence,
);
const [image, setImage] = useState<ImageLightboxSource | null>(null);
// What a link is, for pressing it and for its menu alike.
@@ -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 |
![Diagram ${index}](https://example.com/${index}.png)
---
`,
).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),
};
};
}
@@ -137,9 +137,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"
@@ -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;
}
};
},
@@ -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",
},
}));
@@ -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;
+3 -43
View File
@@ -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) } : {}),
},
};
}
+47
View File
@@ -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,
},
}));
+2
View File
@@ -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();
});
});
+37
View File
@@ -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) };
}
+22 -8
View File
@@ -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>
);
}
+66
View File
@@ -2019,6 +2019,71 @@ export const ar: TranslationResources = {
confirmMessage: "هذا الجهاز متصل عبر Tailscale وسيفقد اتصاله بالمضيف.",
confirmAction: "إيقاف",
},
connected: {
title: "العملاء المتصلون",
thisDevice: "هذا الجهاز",
loading: "جارٍ تحميل العملاء المتصلين...",
empty: "لا يوجد عملاء متصلون",
unavailable: "تعذّر تحميل العملاء المتصلين",
updateTitle: "حدّث هذا المضيف لعرض العملاء المتصلين",
updateHint: "هذا المضيف لا يبلّغ عن العملاء المتصلين بعد",
permissionTitle: "مطلوب إذن إدارة الوصول",
permissionHint: "جلستك لا تملك إذن عرض العملاء المتصلين",
errorTitle: "تعذّر تحميل العملاء المتصلين",
},
hosts: {
title: "المضيفون المتصلون",
inbound: "وارد",
outbound: "صادر",
unnamed: "مضيف متصل",
routedCount: "{{count}} موجّهة",
routedSession: "جلسة موجّهة",
},
scopes: {
fullAccess: "وصول كامل",
readOnly: "للقراءة فقط",
countOne: "نطاق واحد",
countOther: "{{count}} نطاقات",
none: "لا شيء",
},
transport: {
local: "محلي",
tailscale: "Tailscale",
relay: "التتابع",
hub: "Hub",
via: "عبر {{host}}",
viaHost: "عبر مضيف",
direct: "مباشر",
},
kind: {
desktop: "سطح المكتب",
web: "الويب",
mobile: "الجوّال",
hub: "Hub",
plugin: "إضافة",
client: "عميل",
},
details: {
permissions: "الأذونات",
connected: "متصل",
lastSeen: "آخر اتصال",
status: "الحالة",
version: "الإصدار",
error: "خطأ",
},
status: {
connecting: "جارٍ الاتصال",
reconnecting: "إعادة الاتصال",
offline: "غير متصل",
disabled: "معطّل",
error: "خطأ",
},
time: {
justNow: "الآن",
minutesAgo: "منذ {{count}} د",
hoursAgo: "منذ {{count}} س",
daysAgo: "منذ {{count}} ي",
},
},
pairing: {
hostPassword: {
@@ -2421,6 +2486,7 @@ export const ar: TranslationResources = {
options: "الإعدادات",
host: "المضيف",
refreshFailed: "تعذّر تحديث الاستخدام",
notFetched: "لم يتم التحقق بعد. لا يتم تحديث استخدام {{source}} إلا عند تحديثه.",
noHosts: "لا توجد مضيفات متصلة",
agentError: "تعذّر تحميل الاستخدام: {{reason}}",
pin: "تثبيت",
+66
View File
@@ -2049,6 +2049,71 @@ export const en = {
"This device is connected through Tailscale and will lose its connection to the host.",
confirmAction: "Turn off",
},
connected: {
title: "Connected clients",
thisDevice: "This device",
loading: "Loading connected clients...",
empty: "No connected clients",
unavailable: "Unable to load connected clients",
updateTitle: "Update this host to view connected clients",
updateHint: "This host does not report connected clients yet",
permissionTitle: "Access management required",
permissionHint: "Your session does not have permission to view connected clients",
errorTitle: "Could not load connected clients",
},
hosts: {
title: "Connected hosts",
inbound: "Inbound",
outbound: "Outbound",
unnamed: "Connected host",
routedCount: "{{count}} routed",
routedSession: "Routed session",
},
scopes: {
fullAccess: "Full access",
readOnly: "Read-only",
countOne: "1 scope",
countOther: "{{count}} scopes",
none: "None",
},
transport: {
local: "Local",
tailscale: "Tailscale",
relay: "Relay",
hub: "Hub",
via: "Via {{host}}",
viaHost: "Via host",
direct: "Direct",
},
kind: {
desktop: "Desktop",
web: "Web",
mobile: "Mobile",
hub: "Hub",
plugin: "Plugin",
client: "Client",
},
details: {
permissions: "Permissions",
connected: "Connected",
lastSeen: "Last online",
status: "Status",
version: "Version",
error: "Error",
},
status: {
connecting: "Connecting",
reconnecting: "Reconnecting",
offline: "Offline",
disabled: "Disabled",
error: "Error",
},
time: {
justNow: "Just now",
minutesAgo: "{{count}}m ago",
hoursAgo: "{{count}}h ago",
daysAgo: "{{count}}d ago",
},
},
pairing: {
hostPassword: {
@@ -2451,6 +2516,7 @@ export const en = {
options: "Settings",
host: "Host",
refreshFailed: "Unable to refresh usage",
notFetched: "Not checked yet. {{source}} usage updates only when you refresh it.",
noHosts: "No connected hosts",
agentError: "Unable to load usage: {{reason}}",
pin: "Pin",
+66
View File
@@ -2073,6 +2073,71 @@ export const es: TranslationResources = {
"Este dispositivo está conectado mediante Tailscale y perderá la conexión con el host.",
confirmAction: "Desactivar",
},
connected: {
title: "Clientes conectados",
thisDevice: "Este dispositivo",
loading: "Cargando clientes conectados...",
empty: "No hay clientes conectados",
unavailable: "No se pudieron cargar los clientes conectados",
updateTitle: "Actualiza este host para ver los clientes conectados",
updateHint: "Este host todavía no informa de los clientes conectados",
permissionTitle: "Se requiere gestión de acceso",
permissionHint: "Tu sesión no tiene permiso para ver los clientes conectados",
errorTitle: "No se pudieron cargar los clientes conectados",
},
hosts: {
title: "Hosts conectados",
inbound: "Entrante",
outbound: "Saliente",
unnamed: "Host conectado",
routedCount: "{{count}} enrutadas",
routedSession: "Sesión enrutada",
},
scopes: {
fullAccess: "Acceso completo",
readOnly: "Solo lectura",
countOne: "1 ámbito",
countOther: "{{count}} ámbitos",
none: "Ninguno",
},
transport: {
local: "Local",
tailscale: "Tailscale",
relay: "Relé",
hub: "Hub",
via: "Vía {{host}}",
viaHost: "Vía host",
direct: "Directo",
},
kind: {
desktop: "Escritorio",
web: "Web",
mobile: "Móvil",
hub: "Hub",
plugin: "Plugin",
client: "Cliente",
},
details: {
permissions: "Permisos",
connected: "Conectado",
lastSeen: "Última conexión",
status: "Estado",
version: "Versión",
error: "Error",
},
status: {
connecting: "Conectando",
reconnecting: "Reconectando",
offline: "Sin conexión",
disabled: "Desactivado",
error: "Error",
},
time: {
justNow: "Ahora mismo",
minutesAgo: "hace {{count}} min",
hoursAgo: "hace {{count}} h",
daysAgo: "hace {{count}} d",
},
},
pairing: {
hostPassword: {
@@ -2477,6 +2542,7 @@ export const es: TranslationResources = {
options: "Configuración",
host: "Host",
refreshFailed: "No se pudo actualizar el uso",
notFetched: "Aún sin comprobar. El uso de {{source}} solo se actualiza cuando lo actualizas.",
noHosts: "No hay hosts conectados",
agentError: "No se pudo cargar el uso: {{reason}}",
pin: "Fijar",
+67
View File
@@ -2070,6 +2070,71 @@ export const fr: TranslationResources = {
confirmMessage: "Cet appareil est connecté via Tailscale et perdra sa connexion à l’hôte.",
confirmAction: "Désactiver",
},
connected: {
title: "Clients connectés",
thisDevice: "Cet appareil",
loading: "Chargement des clients connectés...",
empty: "Aucun client connecté",
unavailable: "Impossible de charger les clients connectés",
updateTitle: "Mettez cet hôte à jour pour voir les clients connectés",
updateHint: "Cet hôte ne signale pas encore les clients connectés",
permissionTitle: "Gestion des accès requise",
permissionHint: "Votre session n’est pas autorisée à voir les clients connectés",
errorTitle: "Impossible de charger les clients connectés",
},
hosts: {
title: "Hôtes connectés",
inbound: "Entrant",
outbound: "Sortant",
unnamed: "Hôte connecté",
routedCount: "{{count}} routées",
routedSession: "Session routée",
},
scopes: {
fullAccess: "Accès complet",
readOnly: "Lecture seule",
countOne: "1 portée",
countOther: "{{count}} portées",
none: "Aucune",
},
transport: {
local: "Local",
tailscale: "Tailscale",
relay: "Relais",
hub: "Hub",
via: "Via {{host}}",
viaHost: "Via un hôte",
direct: "Direct",
},
kind: {
desktop: "Bureau",
web: "Web",
mobile: "Mobile",
hub: "Hub",
plugin: "Plugin",
client: "Client",
},
details: {
permissions: "Autorisations",
connected: "Connecté",
lastSeen: "Dernière connexion",
status: "Statut",
version: "Version",
error: "Erreur",
},
status: {
connecting: "Connexion",
reconnecting: "Reconnexion",
offline: "Hors ligne",
disabled: "Désactivé",
error: "Erreur",
},
time: {
justNow: "À l’instant",
minutesAgo: "il y a {{count}} min",
hoursAgo: "il y a {{count}} h",
daysAgo: "il y a {{count}} j",
},
},
pairing: {
hostPassword: {
@@ -2476,6 +2541,8 @@ export const fr: TranslationResources = {
options: "Paramètres",
host: "Hôte",
refreshFailed: "Impossible d’actualiser l’utilisation",
notFetched:
"Pas encore vérifié. L’utilisation de {{source}} n’est mise à jour que lorsque vous l’actualisez.",
noHosts: "Aucun hôte connecté",
agentError: "Impossible de charger l’utilisation : {{reason}}",
pin: "Épingler",
+66
View File
@@ -2040,6 +2040,71 @@ export const ja: TranslationResources = {
confirmMessage: "このデバイスは Tailscale 経由で接続しているため、ホストとの接続が切れます。",
confirmAction: "オフにする",
},
connected: {
title: "接続中のクライアント",
thisDevice: "このデバイス",
loading: "接続中のクライアントを読み込み中...",
empty: "接続中のクライアントはありません",
unavailable: "接続中のクライアントを読み込めません",
updateTitle: "接続中のクライアントを表示するにはこのホストを更新してください",
updateHint: "このホストはまだ接続中のクライアントの報告に対応していません",
permissionTitle: "アクセス管理権限が必要です",
permissionHint: "このセッションには接続中のクライアントを表示する権限がありません",
errorTitle: "接続中のクライアントを読み込めませんでした",
},
hosts: {
title: "接続されたホスト",
inbound: "インバウンド",
outbound: "アウトバウンド",
unnamed: "接続されたホスト",
routedCount: "{{count}} 件のルート",
routedSession: "ルーティング済みセッション",
},
scopes: {
fullAccess: "フルアクセス",
readOnly: "読み取り専用",
countOne: "1 スコープ",
countOther: "{{count}} スコープ",
none: "なし",
},
transport: {
local: "ローカル",
tailscale: "Tailscale",
relay: "リレー",
hub: "Hub",
via: "{{host}} 経由",
viaHost: "ホスト経由",
direct: "ダイレクト",
},
kind: {
desktop: "デスクトップ",
web: "Web",
mobile: "モバイル",
hub: "Hub",
plugin: "プラグイン",
client: "クライアント",
},
details: {
permissions: "権限",
connected: "接続時間",
lastSeen: "最終オンライン",
status: "ステータス",
version: "バージョン",
error: "エラー",
},
status: {
connecting: "接続中",
reconnecting: "再接続中",
offline: "オフライン",
disabled: "無効",
error: "エラー",
},
time: {
justNow: "たった今",
minutesAgo: "{{count}}分前",
hoursAgo: "{{count}}時間前",
daysAgo: "{{count}}日前",
},
},
pairing: {
hostPassword: {
@@ -2446,6 +2511,7 @@ export const ja: TranslationResources = {
options: "設定",
host: "ホスト",
refreshFailed: "使用状況を更新できません",
notFetched: "まだ確認していません。{{source}} の使用状況は、更新したときだけ更新されます。",
noHosts: "接続中のホストがありません",
agentError: "使用状況を読み込めません: {{reason}}",
pin: "ピン留め",
+66
View File
@@ -2031,6 +2031,71 @@ export const ko: TranslationResources = {
confirmMessage: "이 기기는 Tailscale로 연결되어 있어 호스트와의 연결이 끊깁니다.",
confirmAction: "끄기",
},
connected: {
title: "연결된 클라이언트",
thisDevice: "이 기기",
loading: "연결된 클라이언트를 불러오는 중...",
empty: "연결된 클라이언트가 없습니다",
unavailable: "연결된 클라이언트를 불러올 수 없습니다",
updateTitle: "연결된 클라이언트를 보려면 이 호스트를 업데이트하세요",
updateHint: "이 호스트는 아직 연결된 클라이언트 보고를 지원하지 않습니다",
permissionTitle: "접근 관리 권한이 필요합니다",
permissionHint: "현재 세션에는 연결된 클라이언트를 볼 권한이 없습니다",
errorTitle: "연결된 클라이언트를 불러오지 못했습니다",
},
hosts: {
title: "연결된 호스트",
inbound: "인바운드",
outbound: "아웃바운드",
unnamed: "연결된 호스트",
routedCount: "라우팅 {{count}}개",
routedSession: "라우팅된 세션",
},
scopes: {
fullAccess: "전체 권한",
readOnly: "읽기 전용",
countOne: "범위 1개",
countOther: "범위 {{count}}개",
none: "없음",
},
transport: {
local: "로컬",
tailscale: "Tailscale",
relay: "릴레이",
hub: "Hub",
via: "{{host}} 경유",
viaHost: "호스트 경유",
direct: "직접 연결",
},
kind: {
desktop: "데스크톱",
web: "웹",
mobile: "모바일",
hub: "Hub",
plugin: "플러그인",
client: "클라이언트",
},
details: {
permissions: "권한",
connected: "연결됨",
lastSeen: "마지막 온라인",
status: "상태",
version: "버전",
error: "오류",
},
status: {
connecting: "연결 중",
reconnecting: "다시 연결 중",
offline: "오프라인",
disabled: "비활성화됨",
error: "오류",
},
time: {
justNow: "방금 전",
minutesAgo: "{{count}}분 전",
hoursAgo: "{{count}}시간 전",
daysAgo: "{{count}}일 전",
},
},
pairing: {
hostPassword: {
@@ -2433,6 +2498,7 @@ export const ko: TranslationResources = {
options: "설정",
host: "호스트",
refreshFailed: "사용량을 새로 고칠 수 없습니다",
notFetched: "아직 확인하지 않았습니다. {{source}} 사용량은 새로 고칠 때만 업데이트됩니다.",
noHosts: "연결된 호스트가 없습니다",
agentError: "사용량을 불러올 수 없습니다: {{reason}}",
pin: "고정",
+66
View File
@@ -2057,6 +2057,71 @@ export const ptBR: TranslationResources = {
"Este dispositivo está conectado pelo Tailscale e perderá a conexão com o host.",
confirmAction: "Desativar",
},
connected: {
title: "Clientes conectados",
thisDevice: "Este dispositivo",
loading: "Carregando clientes conectados...",
empty: "Nenhum cliente conectado",
unavailable: "Não foi possível carregar os clientes conectados",
updateTitle: "Atualize este host para ver clientes conectados",
updateHint: "Este host ainda não informa clientes conectados",
permissionTitle: "Gerenciamento de acesso necessário",
permissionHint: "Sua sessão não tem permissão para ver clientes conectados",
errorTitle: "Não foi possível carregar os clientes conectados",
},
hosts: {
title: "Hosts conectados",
inbound: "Entrada",
outbound: "Saída",
unnamed: "Host conectado",
routedCount: "{{count}} roteadas",
routedSession: "Sessão roteada",
},
scopes: {
fullAccess: "Acesso total",
readOnly: "Somente leitura",
countOne: "1 escopo",
countOther: "{{count}} escopos",
none: "Nenhum",
},
transport: {
local: "Local",
tailscale: "Tailscale",
relay: "Relay",
hub: "Hub",
via: "Via {{host}}",
viaHost: "Via host",
direct: "Direto",
},
kind: {
desktop: "Desktop",
web: "Web",
mobile: "Celular",
hub: "Hub",
plugin: "Plugin",
client: "Cliente",
},
details: {
permissions: "Permissões",
connected: "Conectado",
lastSeen: "Última vez online",
status: "Status",
version: "Versão",
error: "Erro",
},
status: {
connecting: "Conectando",
reconnecting: "Reconectando",
offline: "Offline",
disabled: "Desativado",
error: "Erro",
},
time: {
justNow: "Agora mesmo",
minutesAgo: "há {{count}}m",
hoursAgo: "há {{count}}h",
daysAgo: "há {{count}}d",
},
},
pairing: {
hostPassword: {
@@ -2461,6 +2526,7 @@ export const ptBR: TranslationResources = {
options: "Configurações",
host: "Host",
refreshFailed: "Não foi possível atualizar o uso",
notFetched: "Ainda não verificado. O uso de {{source}} só é atualizado quando você o atualiza.",
noHosts: "Nenhum host conectado",
agentError: "Não foi possível carregar o uso: {{reason}}",
pin: "Fixar",
+67
View File
@@ -2056,6 +2056,71 @@ export const ru: TranslationResources = {
confirmMessage: "Это устройство подключено через Tailscale и потеряет соединение с хостом.",
confirmAction: "Выключить",
},
connected: {
title: "Подключённые клиенты",
thisDevice: "Это устройство",
loading: "Загрузка подключённых клиентов...",
empty: "Нет подключённых клиентов",
unavailable: "Не удалось загрузить подключённых клиентов",
updateTitle: "Обновите этот хост, чтобы видеть подключённых клиентов",
updateHint: "Этот хост ещё не передаёт список подключённых клиентов",
permissionTitle: "Требуются права управления доступом",
permissionHint: "У текущей сессии нет прав для просмотра подключённых клиентов",
errorTitle: "Не удалось загрузить подключённых клиентов",
},
hosts: {
title: "Подключённые хосты",
inbound: "Входящее",
outbound: "Исходящее",
unnamed: "Подключённый хост",
routedCount: "{{count}} маршр.",
routedSession: "Маршрутизируемая сессия",
},
scopes: {
fullAccess: "Полный доступ",
readOnly: "Только чтение",
countOne: "1 право",
countOther: "{{count}} прав",
none: "Нет",
},
transport: {
local: "Локально",
tailscale: "Tailscale",
relay: "Ретранслятор",
hub: "Hub",
via: "Через {{host}}",
viaHost: "Через хост",
direct: "Напрямую",
},
kind: {
desktop: "Десктоп",
web: "Веб",
mobile: "Мобильный",
hub: "Hub",
plugin: "Плагин",
client: "Клиент",
},
details: {
permissions: "Разрешения",
connected: "Подключено",
lastSeen: "Последний раз в сети",
status: "Статус",
version: "Версия",
error: "Ошибка",
},
status: {
connecting: "Подключение",
reconnecting: "Переподключение",
offline: "Не в сети",
disabled: "Отключено",
error: "Ошибка",
},
time: {
justNow: "Только что",
minutesAgo: "{{count}} мин назад",
hoursAgo: "{{count}} ч назад",
daysAgo: "{{count}} дн назад",
},
},
pairing: {
hostPassword: {
@@ -2462,6 +2527,8 @@ export const ru: TranslationResources = {
options: "Настройки",
host: "Хост",
refreshFailed: "Не удалось обновить использование",
notFetched:
"Ещё не проверено. Использование {{source}} обновляется, только когда вы его обновляете.",
noHosts: "Нет подключённых хостов",
agentError: "Не удалось загрузить использование: {{reason}}",
pin: "Закрепить",
+66
View File
@@ -2001,6 +2001,71 @@ export const zhCN: TranslationResources = {
confirmMessage: "此设备通过 Tailscale 连接,关闭后将与主机断开连接。",
confirmAction: "关闭",
},
connected: {
title: "已连接的客户端",
thisDevice: "此设备",
loading: "正在加载已连接的客户端...",
empty: "没有已连接的客户端",
unavailable: "无法加载已连接的客户端",
updateTitle: "更新此主机以查看已连接的客户端",
updateHint: "此主机暂不支持报告已连接的客户端",
permissionTitle: "需要访问管理权限",
permissionHint: "当前会话无权查看已连接的客户端",
errorTitle: "无法加载已连接的客户端",
},
hosts: {
title: "已连接的主机",
inbound: "入站",
outbound: "出站",
unnamed: "已连接的主机",
routedCount: "{{count}} 个路由",
routedSession: "路由会话",
},
scopes: {
fullAccess: "完全访问",
readOnly: "只读",
countOne: "1 项权限",
countOther: "{{count}} 项权限",
none: "无",
},
transport: {
local: "本地",
tailscale: "Tailscale",
relay: "中继",
hub: "Hub",
via: "经由 {{host}}",
viaHost: "经由主机",
direct: "直连",
},
kind: {
desktop: "桌面端",
web: "网页端",
mobile: "移动端",
hub: "Hub",
plugin: "插件",
client: "客户端",
},
details: {
permissions: "权限",
connected: "连接时间",
lastSeen: "上次在线",
status: "状态",
version: "版本",
error: "错误",
},
status: {
connecting: "连接中",
reconnecting: "重新连接中",
offline: "离线",
disabled: "已禁用",
error: "错误",
},
time: {
justNow: "刚刚",
minutesAgo: "{{count}} 分钟前",
hoursAgo: "{{count}} 小时前",
daysAgo: "{{count}} 天前",
},
},
pairing: {
hostPassword: {
@@ -2397,6 +2462,7 @@ export const zhCN: TranslationResources = {
options: "设置",
host: "主机",
refreshFailed: "无法刷新用量",
notFetched: "尚未检查。{{source}} 用量仅在你刷新时更新。",
noHosts: "没有已连接的主机",
agentError: "无法加载用量:{{reason}}",
pin: "固定",
+73 -12
View File
@@ -665,7 +665,7 @@ function AgentPanelBody({
/**
* The pane's loading state, for its agent or the agent's history. A visible pane keeps the launch
* splash up while the cache can still answer; after that it says what the host has yet to send.
* splash up while the cache can still answer; after that the minimal spinner stays in place.
*/
function AgentLoadingState({
serverId,
@@ -686,7 +686,7 @@ function AgentLoadingState({
return (
<LoadingState
testID={testID}
title={
accessibilityLabel={
wait.waitingFor === "agent"
? t("agentPanel.states.loadingAgent")
: t("agentPanel.states.loadingHistory")
@@ -1258,6 +1258,14 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
) : (
agentComposerSection
);
const isInitialHistoryLoading =
routeBottomAnchorRequest?.reason === "initial-entry" &&
!hasCachedHistory &&
!showHistorySyncError;
const {
isHidden: isInitialHistoryHidden,
onVisibilityChange: handleInitialHistoryVisibilityChange,
} = useInitialHistoryOverlay(agentId, isInitialHistoryLoading);
const handleAttentionInteraction = useCallback(() => {
onAttentionInputFocus();
return false;
@@ -1277,12 +1285,9 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
draft={draft}
routeBottomAnchorRequest={routeBottomAnchorRequest}
hasAppliedAuthoritativeHistory={hasAppliedAuthoritativeHistory}
isInitialHistoryLoading={
routeBottomAnchorRequest?.reason === "initial-entry" &&
!hasCachedHistory &&
!showHistorySyncError
}
isInitialHistoryLoading={isInitialHistoryLoading}
revealInitialHistory={hasCachedHistory || showHistorySyncError}
onInitialHistoryVisibilityChange={handleInitialHistoryVisibilityChange}
hasActiveComposer={hasActiveComposer}
toast={toastApi}
onOpenWorkspaceFile={onOpenWorkspaceFile}
@@ -1311,11 +1316,12 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
const dockOverlay = (
<>
{showHistorySyncOverlay ? (
<View style={styles.historySyncOverlay}>
<AgentLoadingState serverId={serverId} agentId={agentId} testID="agent-history-overlay" />
</View>
) : null}
<ChatHistoryLoadingOverlay
serverId={serverId}
agentId={agentId}
showHistorySyncOverlay={showHistorySyncOverlay}
showInitialHistoryOverlay={isInitialHistoryHidden}
/>
<TimelineSyncStatus sync={timelineSync} toast={toast} onDismiss={dismiss} />
</>
@@ -1370,6 +1376,55 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
});
});
function useInitialHistoryOverlay(agentId: string, isInitialHistoryLoading: boolean) {
const [revealedAgentId, setRevealedAgentId] = useState<string | null>(null);
const onVisibilityChange = useCallback(
(visible: boolean) => {
setRevealedAgentId((current) => {
if (visible) return agentId;
return current === agentId ? null : current;
});
},
[agentId],
);
return {
isHidden: isInitialHistoryLoading && revealedAgentId !== agentId,
onVisibilityChange,
};
}
function ChatHistoryLoadingOverlay({
serverId,
agentId,
showHistorySyncOverlay,
showInitialHistoryOverlay,
}: {
serverId: string;
agentId: string;
showHistorySyncOverlay: boolean;
showInitialHistoryOverlay: boolean;
}) {
const { t } = useTranslation();
if (showHistorySyncOverlay) {
return (
<View style={styles.historySyncOverlay}>
<AgentLoadingState serverId={serverId} agentId={agentId} testID="agent-history-overlay" />
</View>
);
}
if (showInitialHistoryOverlay) {
return (
<View style={[styles.historySyncOverlay, styles.initialHistoryOverlay]}>
<LoadingState
testID="agent-initial-fill"
accessibilityLabel={t("agentPanel.states.loadingHistory")}
/>
</View>
);
}
return null;
}
function wrapAgentCommandProvider({
enabled,
serverId,
@@ -1467,6 +1522,7 @@ const AgentStreamSection = memo(function AgentStreamSection({
hasAppliedAuthoritativeHistory,
isInitialHistoryLoading,
revealInitialHistory,
onInitialHistoryVisibilityChange,
hasActiveComposer,
toast,
onOpenWorkspaceFile,
@@ -1480,6 +1536,7 @@ const AgentStreamSection = memo(function AgentStreamSection({
hasAppliedAuthoritativeHistory: boolean;
isInitialHistoryLoading: boolean;
revealInitialHistory: boolean;
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
hasActiveComposer: boolean;
toast: ReturnType<typeof useToastHost>["api"];
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
@@ -1572,6 +1629,7 @@ const AgentStreamSection = memo(function AgentStreamSection({
isAuthoritativeHistoryReady={hasAppliedAuthoritativeHistory}
isInitialHistoryLoading={isInitialHistoryLoading}
revealInitialHistory={revealInitialHistory}
onInitialHistoryVisibilityChange={onInitialHistoryVisibilityChange}
bottomOverlayTailClearance={bottomOverlayTailClearance}
bottomOverlayControlClearance={bottomOverlayControlClearance}
toast={toast}
@@ -1948,6 +2006,9 @@ const styles = StyleSheet.create((theme) => ({
justifyContent: "center",
zIndex: 40,
},
initialHistoryOverlay: {
pointerEvents: "none",
},
archivingOverlay: {
position: "absolute",
top: 0,
+13 -6
View File
@@ -48,9 +48,13 @@ it("requests the managed connection credential through desktop main without a we
requests.push(listen);
return token;
};
expect(await readDesktopManagedLocalCredential(connection, invoke)).toBe("local-token");
expect(
await readDesktopManagedLocalCredential({ serverId: "srv-local", connection }, invoke),
).toBe("local-token");
token = "rotated-token";
expect(await readDesktopManagedLocalCredential(connection, invoke)).toBe("rotated-token");
expect(
await readDesktopManagedLocalCredential({ serverId: "srv-local", connection }, invoke),
).toBe("rotated-token");
expect(requests).toEqual(["localhost:6767", "localhost:6767"]);
});
@@ -5541,10 +5545,13 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
connectToDaemon: async ({ host: probeHost, connection }) => {
expect(probeHost.password).toBeUndefined();
const credential = await readDesktopManagedLocalCredential(connection, async (listen) => {
credentialRequests.push(listen);
return listen === "localhost:6799" ? "local-token" : null;
});
const credential = await readDesktopManagedLocalCredential(
{ serverId: probeHost.serverId, connection },
async (listen) => {
credentialRequests.push(listen);
return listen === "localhost:6799" ? "local-token" : null;
},
);
expect(credential).toBe("local-token");
return {
client: makeConnectedProbeClient(5) as unknown as DaemonClient,
+8 -3
View File
@@ -43,6 +43,7 @@ import {
shouldUseTlsForDefaultHostedRelay,
} from "@/utils/daemon-endpoints";
import { resolveAppVersion } from "@/utils/app-version";
import { resolveAppClientIdentity } from "@/devices/client-info";
import { ConnectionOfferSchema, type ConnectionOffer } from "@getpaseo/protocol/connection-offer";
import { HostConfirmations, type HostConfirmationRequest } from "./host-confirmation";
import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon";
@@ -586,10 +587,12 @@ function createDefaultDeps(
createClient: ({ host, connection, clientId, runtimeGeneration }) => {
const desktopTransportFactory = createDesktopDaemonTransportFactory();
const webSocketConfig = { webSocketFactory: createAppWebSocketFactory() };
const appIdentity = resolveAppClientIdentity();
const base = {
suppressSendErrors: true,
clientId,
clientType: "mobile",
clientType: appIdentity.clientType,
clientInfo: appIdentity.clientInfo,
appVersion: resolveAppVersion() ?? undefined,
runtimeGeneration,
capabilities: appCapabilities,
@@ -598,7 +601,8 @@ function createDefaultDeps(
providerSnapshots: "wire",
createPluginClientBundleStore: createHostPluginClientBundleStore,
...(host.password ? { password: host.password } : {}),
localCredential: () => readDesktopManagedLocalCredential(connection),
localCredential: () =>
readDesktopManagedLocalCredential({ serverId: host.serverId, connection }),
} satisfies Omit<DaemonClientConfig, "url">;
if (connection.type === "routed") {
const origin = resolveOrigin(connection.originServerId);
@@ -690,7 +694,8 @@ function createDefaultDeps(
return connectToDaemon(connection, {
...(host.serverId ? { serverId: host.serverId } : {}),
...(host.password ? { password: host.password } : {}),
localCredential: () => readDesktopManagedLocalCredential(connection),
localCredential: () =>
readDesktopManagedLocalCredential({ serverId: host.serverId, connection }),
...(timeoutMs !== undefined ? { timeoutMs } : {}),
capabilities: appCapabilities,
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
+7 -5
View File
@@ -95,6 +95,7 @@ import {
type AppLanguage,
type SupportedLocale,
} from "@/i18n/locales";
import { PairDeviceHeaderAction } from "@/devices";
import {
HostDevicesPage,
HostToolsPage,
@@ -1479,11 +1480,12 @@ export default function SettingsScreen({ view }: SettingsScreenProps) {
const pluginGalleryServerId =
view.kind === "host" && view.section === "plugins" ? view.serverId : null;
const detailActions = useMemo(
() =>
pluginGalleryServerId ? <PluginGalleryMenu serverId={pluginGalleryServerId} /> : undefined,
[pluginGalleryServerId],
);
const devicesServerId = view.kind === "host" && view.section === "devices" ? view.serverId : null;
const detailActions = useMemo(() => {
if (pluginGalleryServerId) return <PluginGalleryMenu serverId={pluginGalleryServerId} />;
if (devicesServerId) return <PairDeviceHeaderAction serverId={devicesServerId} />;
return undefined;
}, [devicesServerId, pluginGalleryServerId]);
// The gallery and a plugin's page share one width, so opening a plugin keeps the page edges put.
const detailWidth = pluginGalleryServerId || pluginPage ? "wide" : "default";
@@ -35,7 +35,7 @@ import {
TerminalProfileEditModal,
} from "@/screens/settings/terminal-profile-edit-modal";
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
import { WaysToConnect } from "@/devices";
import { ConnectedDevicesView } from "@/devices";
import { useDaemonConfig } from "@/hooks/use-daemon-config";
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
import { useHostFeature } from "@/runtime/host-features";
@@ -237,7 +237,7 @@ export function HostDevicesPage({ serverId }: { serverId: string }) {
return <HostNotFound />;
}
return <WaysToConnect serverId={serverId} />;
return <ConnectedDevicesView serverId={serverId} />;
}
export function HostToolsPage({ serverId }: { serverId: string }) {
@@ -33,9 +33,7 @@ export function renderWorkspaceRouteGate(input: {
}): React.ReactNode {
switch (input.state.kind) {
case "loading":
return (
<WorkspaceLoading waitingFor={input.state.waitingFor} hostName={input.state.hostName} />
);
return <WorkspaceLoading waitingFor={input.state.waitingFor} />;
case "missing":
return (
<WorkspaceEmptyState
@@ -101,26 +99,19 @@ function getWorkspaceHostStateTitle(
/**
* The one loading state of a workspace, from the route waiting for its workspace to the content
* waiting for its tabs. Each stage puts the same spinner in the same place. The launch splash stays
* up while the cache can still deliver; a wait on the host shows here and says so.
* waiting for its tabs. The launch splash stays up while the cache can still deliver; after that
* the minimal spinner stays centered without text shifting it.
*/
export function WorkspaceLoading({
waitingFor,
hostName,
}: {
waitingFor: WorkspaceLoadingSource;
hostName: string;
}) {
export function WorkspaceLoading({ waitingFor }: { waitingFor: WorkspaceLoadingSource }) {
const { t } = useTranslation();
useNativeSplashHold(waitingFor === "cache");
if (waitingFor === "cache") return <LoadingState testID="workspace-loading" />;
return (
<LoadingState
testID="workspace-loading"
title={
accessibilityLabel={
waitingFor === "connection" ? t("workspace.route.connecting") : t("workspace.route.loading")
}
description={hostName}
/>
);
}
@@ -521,7 +521,6 @@ function parsePaneDirection(actionId: string): PaneDirection | null {
interface RenderWorkspaceContentInput {
isMissingWorkspaceDirectory: boolean;
activeTabDescriptor: WorkspaceTabDescriptor | null;
hostName: string;
hasHydratedWorkspaceLayoutStore: boolean;
hasHydratedAgents: boolean;
hasLoadedTerminals: boolean;
@@ -541,7 +540,6 @@ function renderWorkspaceContent(input: RenderWorkspaceContentInput): React.React
const {
isMissingWorkspaceDirectory,
activeTabDescriptor,
hostName,
hasHydratedWorkspaceLayoutStore,
hasHydratedAgents,
hasLoadedTerminals,
@@ -566,10 +564,10 @@ function renderWorkspaceContent(input: RenderWorkspaceContentInput): React.React
// The saved tabs come from local storage. Without them, the tabs wait on the host's agents
// and terminals.
if (!activeTabDescriptor && !hasHydratedWorkspaceLayoutStore) {
return <WorkspaceLoading waitingFor="cache" hostName={hostName} />;
return <WorkspaceLoading waitingFor="cache" />;
}
if (!activeTabDescriptor && (!hasHydratedAgents || !hasLoadedTerminals)) {
return <WorkspaceLoading waitingFor="workspace" hostName={hostName} />;
return <WorkspaceLoading waitingFor="workspace" />;
}
if (!activeTabDescriptor) {
return (
@@ -2793,7 +2791,6 @@ function WorkspaceScreenContent({
const content = renderWorkspaceContent({
isMissingWorkspaceDirectory,
activeTabDescriptor,
hostName,
hasHydratedWorkspaceLayoutStore,
hasHydratedAgents,
hasLoadedTerminals: terminalsQuery.isSuccess,
+2
View File
@@ -298,6 +298,7 @@ export interface DaemonServerInfo {
version: string | null;
machineKind?: string | null;
desktopManaged?: boolean;
permissions?: ServerInfoStatusPayload["permissions"];
capabilities?: ServerCapabilities;
features?: ServerInfoStatusPayload["features"];
}
@@ -311,6 +312,7 @@ export function toDaemonServerInfo(serverInfo: ServerInfoStatusPayload): DaemonS
...(serverInfo.desktopManaged !== undefined
? { desktopManaged: serverInfo.desktopManaged }
: {}),
...(serverInfo.permissions ? { permissions: serverInfo.permissions } : {}),
...(serverInfo.capabilities ? { capabilities: serverInfo.capabilities } : {}),
...(serverInfo.features ? { features: serverInfo.features } : {}),
};
@@ -1579,7 +1579,7 @@ describe("processTimelineResponse", () => {
});
});
it("performs bootstrap tail init with catch-up side effect", () => {
it("performs bootstrap tail init without a redundant catch-up when no live rows overtook it", () => {
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
@@ -1595,7 +1595,6 @@ describe("processTimelineResponse", () => {
},
});
// Bootstrap tail replaces
expect(result.tail.length).toBeGreaterThan(0);
expect(result.head).toEqual([]);
expect(result.cursorChanged).toBe(true);
@@ -1604,8 +1603,42 @@ describe("processTimelineResponse", () => {
startSeq: 1,
endSeq: 5,
});
expect(result.sideEffects.find((e) => e.type === "catch_up")).toBeUndefined();
});
it("performs bootstrap tail init with catch-up side effect when live head rows overtook the tail", () => {
const result = processTimelineResponse({
...baseTimelineInput,
isInitializing: true,
hasActiveInitDeferred: true,
initRequestDirection: "tail",
currentHead: [
{
id: "live-6",
kind: "assistant_message",
text: "live chunk past tail",
timestamp: new Date("2026-01-01T00:00:06.000Z"),
timelineCursor: { epoch: "epoch-1", anchorSeq: 6, seq: 6 },
},
],
payload: {
...baseTimelineInput.payload,
direction: "tail",
epoch: "epoch-1",
startCursor: { seq: 1 },
endCursor: { seq: 5 },
entries: [makeTimelineEntry(1, "first"), makeTimelineEntry(5, "last")],
},
});
expect(result.tail.length).toBeGreaterThan(0);
expect(result.cursorChanged).toBe(true);
expect(result.cursor).toEqual({
epoch: "epoch-1",
startSeq: 1,
endSeq: 5,
});
// Should have catch-up side effect
const catchUp = result.sideEffects.find((e) => e.type === "catch_up");
expect(catchUp).toBeDefined();
expect(catchUp!.type === "catch_up" && catchUp!.cursor).toEqual({
@@ -616,8 +616,17 @@ function applyTimelineReplacePath(args: {
}
: null;
const sideEffects: TimelineReducerSideEffect[] = [];
if (bootstrapPolicy.catchUpCursor) {
sideEffects.push({ type: "catch_up", cursor: bootstrapPolicy.catchUpCursor });
// Only schedule a follow-up catch-up after a bootstrap tail when live rows already overtook the
// snapshot while it was in flight; otherwise the live subscription delivers seq endSeq + 1 next.
const catchUpCursor = bootstrapPolicy.catchUpCursor;
if (
catchUpCursor &&
currentHead.some((item) => {
const itemCursor = item.timelineCursor;
return itemCursor?.epoch === catchUpCursor.epoch && itemCursor.seq > catchUpCursor.endSeq;
})
) {
sideEffects.push({ type: "catch_up", cursor: catchUpCursor });
}
return {
tail,
@@ -1821,6 +1821,37 @@ test("reconnecting reports reattaching instead of pending until the check answer
}
});
test("an opened chat without a cursor stays quiet for FRESHNESS_CHECK_QUIET_MS across subscribe and tail catch-up", async () => {
vi.useFakeTimers();
try {
const world = freshnessWorld();
world.sync.setConnected(true);
world.show("pane", ["agent-a"]);
const membership = await world.nextMembership();
expect(membership.cursors).toEqual({});
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("checking");
membership.succeed();
const fetch = await world.nextFetch("agent-a");
expect(fetch.request.direction).toBe("tail");
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("checking");
await vi.advanceTimersByTimeAsync(FRESHNESS_CHECK_QUIET_MS - 1);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("checking");
await vi.advanceTimersByTimeAsync(1);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("pending");
fetch.respond({ hasNewer: false });
await vi.advanceTimersByTimeAsync(0);
expect(world.sync.getAgentTimelineStatus("agent-a")).toBe("ready");
world.sync.dispose();
} finally {
vi.useRealTimers();
}
});
test("without the daemon capability nothing changes: no cursors, no checking, fetch on foreground", async () => {
const world = new TimelineWorld();
world.cursors.set("agent-a", { epoch: "epoch-a", endSeq: 42 });
@@ -760,6 +760,10 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
timer: ReturnType<typeof setTimeout> | null;
}
>();
// Opened chats without a cursor (for example, a display-only cache) cannot ask the daemon's
// freshness check, so they keep the same FRESHNESS_CHECK_QUIET_MS quiet window across their
// initial subscribe + tail catch-up before reporting "pending".
const openCatchUpQuiet = new Map<string, ReturnType<typeof setTimeout>>();
const listeners = new Set<() => void>();
let active = true;
let connected = false;
@@ -799,7 +803,28 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
for (const listener of listeners) listener();
};
const startOpenCatchUpQuiet = (agentId: string) => {
if (openCatchUpQuiet.has(agentId)) return;
const timer = setTimeout(() => {
openCatchUpQuiet.delete(agentId);
notifyListeners();
}, FRESHNESS_CHECK_QUIET_MS);
openCatchUpQuiet.set(agentId, timer);
};
const endOpenCatchUpQuiet = (agentId: string) => {
const timer = openCatchUpQuiet.get(agentId);
if (!timer) return;
clearTimeout(timer);
openCatchUpQuiet.delete(agentId);
};
const endAllOpenCatchUpQuiet = () => {
for (const agentId of openCatchUpQuiet.keys()) endOpenCatchUpQuiet(agentId);
};
const setVisibilityCatchUpReady = (agentId: string) => {
endOpenCatchUpQuiet(agentId);
const wasPending = visibilityCatchUpPending.delete(agentId);
const hadError = visibilityCatchUpErrors.delete(agentId);
const wasRetrying = manualRetries.delete(agentId);
@@ -812,6 +837,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const message = error instanceof Error ? error.message : String(error);
let changed = false;
for (const agentId of agentIds) {
endOpenCatchUpQuiet(agentId);
ports.onCatchUpSettled(agentId);
if (manualRetries.delete(agentId)) changed = true;
if (visibilityCatchUpPending.delete(agentId)) changed = true;
@@ -1081,11 +1107,15 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
const askDaemonAboutFreshness = (checked: string[]) => {
for (const agentId of checked) {
endOpenCatchUpQuiet(agentId);
startFreshnessCheck(agentId);
startFreshnessCheckDelay(agentId);
}
for (const agentId of freshnessChecks.keys()) {
if (!checked.includes(agentId)) endFreshnessCheck(agentId);
for (const [agentId, check] of freshnessChecks.entries()) {
if (checked.includes(agentId)) continue;
const shouldKeepOpenQuiet = check.reason === "open" && check.quiet;
endFreshnessCheck(agentId);
if (shouldKeepOpenQuiet) startOpenCatchUpQuiet(agentId);
}
};
@@ -1172,6 +1202,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
if (!nextDesired.includes(agentId)) {
cancelCatchUp(agentId);
endFreshnessCheck(agentId);
endOpenCatchUpQuiet(agentId);
visibilityCatchUpPending.delete(agentId);
visibilityCatchUpErrors.delete(agentId);
manualRetries.delete(agentId);
@@ -1204,6 +1235,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
if (check.reason === "reconnect") return "reattaching";
return check.quiet ? "checking" : "pending";
}
if (openCatchUpQuiet.has(agentId)) return "checking";
if (!ports.canCheckFreshness()) return "pending";
if (!connected) return "reattaching";
return isDesired(agentId) ? "pending" : "checking";
@@ -1312,6 +1344,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
membershipGeneration += 1;
freshnessCheckOwed = false;
endAllFreshnessChecks();
endAllOpenCatchUpQuiet();
for (const agentId of desired) cancelCatchUp(agentId);
return;
}
@@ -1352,6 +1385,7 @@ export function createViewedTimelineSync(ports: ViewedTimelineSyncPorts): Viewed
visibilityCatchUpErrors.clear();
manualRetries.clear();
endAllFreshnessChecks();
endAllOpenCatchUpQuiet();
notifyListeners();
listeners.clear();
},
@@ -1,7 +1,9 @@
import { describe, expect, it } from "vitest";
import { defaultHostAppearance } from "@/hosts/appearance";
import { parseHostTarget } from "@getpaseo/protocol/host-target";
import {
createRemoteSshHostConnection,
hostConnectionUri,
normalizeStoredHostProfile,
orderHostsLocalFirst,
pinRelayProtectedSecurityInProfiles,
@@ -717,3 +719,49 @@ describe("resolveActiveHostServerId", () => {
).toBe("srv_local");
});
});
describe("hostConnectionUri", () => {
it.each<[HostConnection, string]>([
[{ id: "d", type: "directTcp", endpoint: "10.0.0.5:6767" }, "tcp://10.0.0.5:6767"],
[
{ id: "d", type: "directTcp", endpoint: "[::1]:6767", useTls: true },
"tcp://[::1]:6767?ssl=true",
],
[{ id: "s", type: "directSocket", path: "/tmp/paseo.sock" }, "unix:///tmp/paseo.sock"],
[{ id: "p", type: "directPipe", path: "\\\\.\\pipe\\paseo" }, "pipe://\\\\.\\pipe\\paseo"],
[
{ id: "r", type: "remoteSsh", host: "me@box", sshPort: 2222, daemonPort: 7000 },
"ssh://me@box:2222?daemonPort=7000",
],
[
{
id: "relay",
type: "relay",
relayEndpoint: "relay.example.test:443",
daemonPublicKeyB64: "cHVibGljLWtleQ",
minimumSecurityMode: "protected",
},
"relay://relay.example.test:443/srv-host?key=cHVibGljLWtleQ&ssl=true&security=protected",
],
])("dials %o through %s", (connection, uri) => {
expect(hostConnectionUri(connection, "srv-host")).toBe(uri);
expect(() => parseHostTarget(uri)).not.toThrow();
});
it("has no address for a routed connection or an incomplete relay connection", () => {
expect(
hostConnectionUri({ id: "routed", type: "routed", originServerId: "srv-origin" }, "srv-host"),
).toBeNull();
expect(
hostConnectionUri(
{
id: "relay",
type: "relay",
relayEndpoint: "relay.example.test:443",
daemonPublicKeyB64: "cHVibGljLWtleQ",
},
"",
),
).toBeNull();
});
});
+43
View File
@@ -2,6 +2,9 @@ import type { ConnectionOffer } from "@getpaseo/protocol/connection-offer";
import {
normalizeHostPort,
normalizeLoopbackToLocalhost,
parseHostPort,
serializeConnectionUri,
serializeRelayConnectionUri,
shouldUseTlsForDefaultHostedRelay,
} from "@getpaseo/protocol/daemon-endpoints";
import {
@@ -10,6 +13,7 @@ import {
} from "@getpaseo/protocol/host-connection-schema";
import {
DEFAULT_SSH_DAEMON_PORT,
serializeSshTransportUri,
validatePort,
validateSshHost,
} from "@getpaseo/protocol/ssh-transport";
@@ -447,6 +451,45 @@ export function connectionFromListen(listen: string): HostConnection | null {
}
}
/**
* The host connection string (`@getpaseo/protocol/host-target` grammar) that dials
* this connection, or null for a routed connection, which has no address of its own.
*/
export function hostConnectionUri(connection: HostConnection, serverId: string): string | null {
switch (connection.type) {
case "directTcp":
return serializeConnectionUri({
...parseHostPort(connection.endpoint),
useTls: connection.useTls ?? false,
});
case "directSocket":
return `unix://${connection.path}`;
case "directPipe":
return `pipe://${connection.path}`;
case "remoteSsh":
return serializeSshTransportUri(connection);
case "relay":
if (!serverId || !connection.daemonPublicKeyB64) return null;
return serializeRelayConnectionUri({
offer: {
v: 2,
serverId,
daemonPublicKeyB64: connection.daemonPublicKeyB64,
relay: {
endpoint: connection.relayEndpoint,
useTls:
connection.useTls ?? shouldUseTlsForDefaultHostedRelay(connection.relayEndpoint),
},
...(connection.minimumSecurityMode
? { minimumSecurityMode: connection.minimumSecurityMode }
: {}),
},
});
case "routed":
return null;
}
}
export function relayConnectionFromOffer(offer: ConnectionOffer): RelayHostConnection {
// COMPAT(oldRelayOfferTls): added in v0.1.73, remove after 2026-11-10.
const useTls = offer.relay.useTls ?? shouldUseTlsForDefaultHostedRelay(offer.relay.endpoint);
+18 -4
View File
@@ -27,7 +27,7 @@ import { UsageWindowBar } from "./window-bar";
import { useRelativeTimeTick } from "./use-relative-time-tick";
function statusText(report: UsageReport, t: TFunction): string | null {
if (report.status === "available") return null;
if (report.status === "available" || report.status === "not_fetched") return null;
return report.status === "error"
? t("providerUsage.status.error")
: t("providerUsage.status.unavailable");
@@ -149,10 +149,19 @@ function UsageCardBody({
refreshState: UsageRefresh;
}) {
const { t } = useTranslation();
const { windows, balances, details, retained, successfulAt, forecastAt, messages } = report;
const { windows, balances, details, retained, successfulAt, forecastAt, messages, notice } =
report;
const footer = entry.account.label ?? null;
// A notice already says the report was never fetched.
const showsFreshness = showsFreshnessInline && !notice;
return (
<>
{notice ? (
<Text style={styles.notice} testID="usage-notice">
{notice}
</Text>
) : null}
{messages.length > 0 ? (
<Text style={styles.error} testID="usage-login-error">
{messages.join("\n")}
@@ -193,12 +202,12 @@ function UsageCardBody({
</View>
) : null}
{footer || showsFreshnessInline ? (
{footer || showsFreshness ? (
<View style={styles.footerRow}>
<Text style={styles.footer} numberOfLines={1}>
{footer}
</Text>
{showsFreshnessInline ? (
{showsFreshness ? (
<UsageFreshness
successfulAt={successfulAt}
retained={retained}
@@ -452,6 +461,11 @@ const styles = StyleSheet.create((theme) => ({
color: theme.colors.foreground,
fontSize: theme.fontSize.sm,
},
notice: {
color: theme.colors.foregroundMuted,
fontSize: theme.fontSize.sm,
lineHeight: theme.fontSize.sm * 1.4,
},
error: {
color: theme.colors.palette.red[300],
fontSize: theme.fontSize.sm,
+25
View File
@@ -301,6 +301,13 @@ describe("nextUsagePollDelayMs", () => {
nextUsagePollDelayMs({ ...schedule, reports: [failed], updatedAt: 10_000, now: 40_000 }),
).toBe(30_000);
});
it("never polls sooner for a manual report's error, which waits for the user's Refresh", () => {
const manualFailed: UsageReportEntry = { ...failed, refresh: "manual" };
expect(
nextUsagePollDelayMs({ ...schedule, reports: [manualFailed], updatedAt: 0, now: 5 }),
).toBe(300_000);
});
});
describe("upsertReport", () => {
@@ -429,6 +436,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
forecastAt: null,
retained: true,
messages: ["Rate limited"],
notice: null,
});
expect(resolveUsageReport({ ...failure, lastSuccessful: undefined }, i18n.t)).toEqual({
windows: [],
@@ -439,6 +447,7 @@ it("resolves retained usage and successful time without inventing old-daemon his
forecastAt: null,
retained: false,
messages: ["Rate limited"],
notice: null,
});
expect(resolveUsageReport(success, i18n.t)).toEqual({
windows: success.report.status === "available" ? success.report.windows : [],
@@ -449,6 +458,22 @@ it("resolves retained usage and successful time without inventing old-daemon his
forecastAt: success.fetchedAt,
retained: false,
messages: [],
notice: null,
});
});
it("asks for a Refresh, without an error, before a manual report's first fetch", () => {
const notFetched: UsageReportEntry = {
...entry({}),
sourceLabel: "Antigravity",
refresh: "manual",
report: { status: "not_fetched" },
};
expect(resolveUsageReport(notFetched, i18n.t)).toMatchObject({
windows: [],
successfulAt: null,
messages: [],
notice: "Not checked yet. Antigravity usage updates only when you refresh it.",
});
});
+25 -15
View File
@@ -110,7 +110,8 @@ export function applyPushedReport(
/**
* How long until the next poll, counted from the last time the reports were updated rather than
* from when the poller mounted, so hiding and showing the summary keeps the schedule. A failed
* report is polled again sooner; the daemon decides when a retry reaches the vendor.
* report is polled again sooner; the daemon decides when a retry reaches the vendor. A manual
* report changes only on the user's Refresh, so its failure is no reason to poll sooner.
*/
export function nextUsagePollDelayMs(input: {
reports: readonly UsageReportEntry[] | undefined;
@@ -119,7 +120,9 @@ export function nextUsagePollDelayMs(input: {
intervalMs: number;
errorIntervalMs: number;
}): number {
const failed = input.reports?.some((entry) => entry.report.status === "error") ?? false;
const failed =
input.reports?.some((entry) => entry.report.status === "error" && entry.refresh !== "manual") ??
false;
const interval = failed ? input.errorIntervalMs : input.intervalMs;
if (input.updatedAt <= 0) return interval;
return Math.max(1_000, interval - (input.now - input.updatedAt));
@@ -297,19 +300,9 @@ export function resolveUsageSnapshot(entry: UsageReportEntry): UsageSnapshot | n
/** Current outcome owns messages; only a successful poll owns values and freshness. */
export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
const available = entry.report.status === "available";
const notFetched = entry.report.status === "not_fetched";
const snapshot = resolveUsageSnapshot(entry);
const messages: string[] = [];
if (!available) {
if (entry.loginErrors)
messages.push(
...entry.loginErrors.map(
(login) => `${login.harness}: ${usageProblemText(login.report, t)}`,
),
);
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
else messages.push(usageProblemText(entry.report, t));
}
const messages = usageFailureMessages(entry, t);
const forecastAt =
snapshot && !snapshot.retained && !entry.forecastStale
? (snapshot.report.observedAt ?? snapshot.successfulAt)
@@ -323,10 +316,27 @@ export function resolveUsageReport(entry: UsageReportEntry, t: TFunction) {
successfulAt: snapshot?.successfulAt ?? null,
retained: snapshot?.retained ?? false,
messages,
/** Guidance that is not a failure, such as asking for the first Refresh of a manual report. */
notice: notFetched ? t("providerUsage.notFetched", { source: entry.sourceLabel }) : null,
};
}
function usageProblemText(report: UsageReport, t: TFunction): string {
/** Why the latest attempt failed, one line per login; empty unless it failed. */
function usageFailureMessages(entry: UsageReportEntry, t: TFunction): string[] {
const { report } = entry;
if (report.status !== "error" && report.status !== "unavailable") return [];
if (entry.loginErrors)
return entry.loginErrors.map(
(login) => `${login.harness}: ${usageProblemText(login.report, t)}`,
);
// COMPAT(usageLoginErrors): added in v0.11.0, remove after 2027-04-05 once daemon floor >= v0.11.0.
return [usageProblemText(report, t)];
}
function usageProblemText(
report: Exclude<UsageReport, { status: "not_fetched" }>,
t: TFunction,
): string {
if (report.status === "error") return report.error;
if (report.status === "unavailable") return usageCopy.problem(report.problem, new Date(), t);
return "";
+18 -2
View File
@@ -71,14 +71,15 @@ function createRuntime(options?: {
getServerInfo?: (serverId: string) => DaemonServerInfo | null;
}) {
const engine = options?.engine ?? createAudioEngineMock();
const deactivateKeepAwake = vi.fn().mockResolvedValue(undefined);
const runtime = createVoiceRuntime({
engine,
getServerInfo: options?.getServerInfo ?? (() => createServerInfo()),
activateKeepAwake: vi.fn().mockResolvedValue(undefined),
deactivateKeepAwake: vi.fn().mockResolvedValue(undefined),
deactivateKeepAwake,
});
return { runtime, engine };
return { runtime, engine, deactivateKeepAwake };
}
describe("voice runtime", () => {
@@ -482,6 +483,21 @@ describe("voice runtime", () => {
expect(runtime.shouldPlayVoiceAudio("server-1")).toBe(false);
});
it("releases the microphone and wake lock when the daemon rejects stopping voice mode", async () => {
const adapter = createSessionAdapter();
const { runtime, engine, deactivateKeepAwake } = createRuntime();
runtime.registerSession(adapter);
await runtime.startVoice("server-1", "agent-1");
vi.mocked(adapter.setVoiceMode).mockRejectedValue(new Error("socket closed"));
await expect(runtime.stopVoice()).rejects.toThrow("socket closed");
expect(engine.stopCapture).toHaveBeenCalled();
expect(deactivateKeepAwake).toHaveBeenCalled();
expect(runtime.getSnapshot().phase).toBe("disabled");
});
it("rolls daemon voice mode back when capture fails after enabling it", async () => {
const adapter = createSessionAdapter();
const engine = createAudioEngineMock();
+8 -4
View File
@@ -798,11 +798,15 @@ export function createVoiceRuntime(deps: VoiceRuntimeDeps): VoiceRuntime {
deps.engine.stop();
deps.engine.clearQueue();
activeSession?.adapter.setAssistantAudioPlaying(false);
if (activeSession) {
await activeSession.adapter.setVoiceMode(false);
try {
if (activeSession) {
await activeSession.adapter.setVoiceMode(false);
}
} finally {
// An unreachable daemon must not keep the microphone or the screen wake lock held.
await deps.engine.stopCapture().catch(() => undefined);
await deps.deactivateKeepAwake(KEEP_AWAKE_TAG).catch(() => undefined);
}
await deps.engine.stopCapture();
await deps.deactivateKeepAwake(KEEP_AWAKE_TAG).catch(() => undefined);
} finally {
if (state.generation === generation) {
resetToDisabledState();
@@ -25,7 +25,8 @@ function problemText(problem: UsageProblem): string {
return `Login rejected (HTTP ${problem.status}). ${remedy}`;
}
function failureText(report: UsageReport): string {
function failureText(report: UsageReportEntry["report"]): string {
if (report.status === "not_fetched") return "Not fetched yet. Run with --refresh to fetch it.";
if (report.status === "error") return report.error;
if (report.status === "unavailable") return problemText(report.problem);
return "-";
+38
View File
@@ -16,6 +16,7 @@ import {
} from "@getpaseo/protocol/binary-frames/host-route";
import { messageTooLargeError } from "./daemon-client-transport-utils.js";
import type { HostAdd, HostUpdate, HostDirectory } from "@getpaseo/protocol/hosts";
import type { DaemonClientsSnapshot, HelloClientInfo } from "@getpaseo/protocol/daemon-clients";
import type { PluginListingDetail, PluginListingIndex } from "@getpaseo/protocol/plugin-registry";
import { legacyUsageIcon } from "./legacy-usage-icons.js";
import { subscribeTimeline, type TimelineMessage } from "./timeline-subscription/index.js";
@@ -471,6 +472,8 @@ export interface DaemonClientConfig {
createPluginClientBundleStore?: (serverId: string) => PluginClientBundleStore;
clientType?: "mobile" | "browser" | "cli" | "mcp" | "hub";
appVersion?: string;
clientInfo?: HelloClientInfo;
hostLink?: boolean;
runtimeGeneration?: number | null;
password?: string;
localCredential?: () => string | undefined | Promise<string | undefined>;
@@ -2065,6 +2068,39 @@ export class DaemonClientCore {
return snapshot;
});
}
async listConnectedClients(options?: {
includeInternal?: boolean;
}): Promise<DaemonClientsSnapshot> {
const result = await this.sendCorrelatedSessionRequest({
message: {
type: "daemon.clients.list.request",
...(options?.includeInternal ? { includeInternal: true } : {}),
},
responseType: "daemon.clients.list.response",
});
return { sessions: result.sessions };
}
observeConnectedClients(options?: {
includeInternal?: boolean;
}): OwnedSubscription<DaemonClientsSnapshot> {
return this.owned.observe(async (accept) => {
const result = await this.sendCorrelatedSessionRequest({
message: {
type: "daemon.clients.list.request",
observe: true,
...(options?.includeInternal ? { includeInternal: true } : {}),
},
responseType: "daemon.clients.list.response",
});
if (!result.subscriptionId) throw new Error("Host omitted subscription identity");
const snapshot = {
sessions: result.sessions,
subscriptionId: result.subscriptionId,
};
accept(snapshot);
return snapshot;
});
}
async addHost(input: HostAdd) {
this.requireConnectedHosts();
return (
@@ -8014,6 +8050,8 @@ export class DaemonClientCore {
...this.config.capabilities,
},
...(this.config.appVersion ? { appVersion: this.config.appVersion } : {}),
...(this.config.clientInfo ? { clientInfo: this.config.clientInfo } : {}),
...(this.config.hostLink ? { hostLink: true } : {}),
});
} catch (error) {
const message = error instanceof Error ? error.message : "Failed to send hello message";
+8
View File
@@ -6,6 +6,14 @@ export type { AgentAddress } from "@getpaseo/protocol/addresses";
import { createHostActions, type PaseoHostActions } from "./hosts/index.js";
export type { PaseoHostActions } from "./hosts/index.js";
export type { HostAdd, HostUpdate, HostSummary, HostDirectory } from "@getpaseo/protocol/hosts";
export type {
DaemonClientsSnapshot,
DaemonSessionSummary,
DaemonSessionTransport,
HelloClientInfo,
HelloClientPlatform,
WSClientType,
} from "@getpaseo/protocol/daemon-clients";
import type { OwnedSubscription } from "./connection/index.js";
export type { OwnedSubscription, SubscriptionObserver } from "./connection/index.js";
import type { DaemonClientConfig } from "./daemon-client.js";
+114
View File
@@ -215,3 +215,117 @@ test("encrypted connector refuses legacy endpoint security on a later attempt on
expect(opened).toBe(false);
expect(legacyReceived).toEqual([]);
});
/** An origin daemon that admits one client, opens host routes, and echoes route text frames. */
async function fakeOriginDaemon() {
const server = await endpoint();
const hellos: { auth?: unknown }[] = [];
const routedServerIds: string[] = [];
const routedFrames: string[] = [];
const sockets: WebSocket[] = [];
const send = (socket: WebSocket, message: unknown) =>
socket.send(JSON.stringify({ type: "session", message }));
server.wss.on("connection", (socket) => {
sockets.push(socket);
socket.on("message", (raw, binary) => {
if (binary) return;
const frame = JSON.parse(raw.toString("utf8"));
if (frame.type === "hello") {
hellos.push(frame);
send(socket, {
type: "status",
payload: {
status: "server_info",
serverId: "srv-origin",
hostname: "origin",
version: "0.18.3",
features: { connectedHosts: true },
},
});
return;
}
const message = frame.type === "session" ? frame.message : null;
if (message?.type === "hosts.route.open.request") {
routedServerIds.push(message.serverId);
send(socket, {
type: "hosts.route.open.response",
payload: { requestId: message.requestId, routeId: "route-1" },
});
}
if (message?.type === "hosts.route.frame.request") {
routedFrames.push(message.data);
send(socket, {
type: "hosts.route.frame",
payload: { subscriptionId: message.routeId, data: `echo:${message.data}`, binary: false },
});
}
});
});
return {
listen: new URL(server.url).host,
hellos,
routedServerIds,
routedFrames,
live: () => sockets.filter((socket) => socket.readyState === WebSocket.OPEN).length,
};
}
test.each([
["the origin password", null, { kind: "password", password: "origin-secret" }],
["a local origin's credential", "local-token", { kind: "localCredential", token: "local-token" }],
])(
"a routed spec opens a host channel through its origin authenticated with %s, and closing it releases the origin session",
async (_name, localToken, auth) => {
const origin = await fakeOriginDaemon();
const askedListens: string[] = [];
const transport = createHostTransportFactory(
{
via: `tcp://${origin.listen}`,
serverId: "srv-destination",
originPassword: "origin-secret",
},
undefined,
{
localCredential: (listen) => {
askedListens.push(listen);
return localToken;
},
},
)({ url: "ws://host-connector/ws" });
cleanup.push(async () => transport.close());
const received: unknown[] = [];
transport.onMessage((data) => received.push(data));
const closed = new Promise<void>((resolve) => transport.onClose(() => resolve()));
await new Promise<void>((resolve) => transport.onOpen(resolve));
expect(askedListens).toEqual([origin.listen]);
expect(origin.hellos).toMatchObject([{ auth }]);
expect(origin.routedServerIds).toEqual(["srv-destination"]);
await transport.send("tunnel_hello");
await expect.poll(() => received).toEqual(["echo:tunnel_hello"]);
expect(origin.routedFrames).toEqual(["tunnel_hello"]);
transport.close();
await closed;
await expect.poll(() => origin.live()).toBe(0);
},
);
test("a routed spec whose origin is unreachable reports an error and closes", async () => {
const server = await endpoint();
const listen = new URL(server.url).host;
await new Promise<void>((resolve) => server.wss.close(() => resolve()));
for (const close of cleanup.splice(0).toReversed()) await close();
const transport = createHostTransportFactory(
{ via: listen, serverId: "srv-destination" },
undefined,
{
connectTimeoutMs: 2_000,
},
)({ url: "ws://host-connector/ws" });
const errors: unknown[] = [];
transport.onError((error) => errors.push(error));
await new Promise<void>((resolve) => transport.onClose(() => resolve()));
expect(errors).toHaveLength(1);
expect(() => transport.send("x")).toThrow("Host transport is unavailable");
});
+3 -1
View File
@@ -4,6 +4,8 @@ export { parseHostTarget } from "@getpaseo/protocol/host-target";
export type { SshTunnel, SshTunnelOptions } from "./ssh-tunnel.js";
export { createSshTunnel, resolveSshFailureDetail } from "./ssh-tunnel.js";
export { createHostTransportFactory, type HostTransportOptions } from "./transport.js";
export type { HostTransportSpec } from "@getpaseo/protocol/host-target";
export type { DaemonTransport } from "../daemon-client-transport-types.js";
export { createLeanHostClient } from "./lean.js";
import { parseHostTarget } from "@getpaseo/protocol/host-target";
@@ -13,7 +15,7 @@ import { createHostTransportFactory, type HostTransportOptions } from "./transpo
export function createHostClient(
connection: string,
config: Omit<DaemonClientConfig, "url"> & HostTransportOptions,
config: Omit<DaemonClientConfig, "url"> & Pick<HostTransportOptions, "webSocketAgent" | "sshEnv">,
budget?: HostTransportBudget,
): DaemonClient {
const target = parseHostTarget(connection);
+3 -1
View File
@@ -7,6 +7,8 @@ import { createHostTransportFactory, type HostTransportOptions } from "./transpo
export { parseHostTarget };
export { HostTransportBudget } from "./buffering.js";
export { createHostTransportFactory, type HostTransportOptions } from "./transport.js";
export type { HostTransportSpec } from "@getpaseo/protocol/host-target";
export type { DaemonTransport } from "../daemon-client-transport-types.js";
export type { SshTunnel, SshTunnelOptions } from "./ssh-tunnel.js";
export { createSshTunnel, resolveSshFailureDetail } from "./ssh-tunnel.js";
export { DaemonClientCore };
@@ -23,7 +25,7 @@ export {
*/
export function createLeanHostClient(
connection: string,
config: Omit<DaemonClientConfig, "url"> & HostTransportOptions,
config: Omit<DaemonClientConfig, "url"> & Pick<HostTransportOptions, "webSocketAgent" | "sshEnv">,
budget?: HostTransportBudget,
): DaemonClientCore {
const target = parseHostTarget(connection);
+193 -92
View File
@@ -1,7 +1,13 @@
import { randomUUID } from "node:crypto";
import { homedir } from "node:os";
import type { Agent } from "node:http";
import { WebSocket } from "ws";
import { parseHostTarget, type HostTarget } from "@getpaseo/protocol/host-target";
import {
localListenOfHostTarget,
parseHostTarget,
type HostTarget,
type HostTransportSpec,
} from "@getpaseo/protocol/host-target";
import type { SecurityMode } from "@getpaseo/relay/e2ee";
import { createWebSocketTransportFactory } from "../daemon-client-websocket-transport.js";
import type {
@@ -16,58 +22,154 @@ export interface HostTransportOptions {
webSocketAgent?: (url: string) => Agent | undefined;
/** Environment for the `ssh` child of ssh:// hosts; defaults to this process's environment. */
sshEnv?: NodeJS.ProcessEnv;
/**
* Reads the credential of the daemon on this machine listening on `listen`.
* A routed spec's origin session authenticates with it when `via` dials that address.
*/
localCredential?: (listen: string) => string | null | Promise<string | null>;
/** How long a routed spec's origin session may take to connect. */
connectTimeoutMs?: number;
}
/** A factory owns one attempt, including a fresh SSH process and its teardown. */
type DaemonTransportAttempt = Parameters<DaemonTransportFactory>[0];
interface AttemptScope {
readonly closed: boolean;
/** Runs `cleanup` when the attempt closes, most recent first; at once if it already closed. */
defer(cleanup: () => void): void;
}
/**
* A transport whose inner transport opens asynchronously. Handlers attach before
* it exists; closing at any point runs the attempt's deferred cleanups once.
*/
function deferredTransport(
open: (
scope: AttemptScope,
) => Promise<{ transport: DaemonTransport; describeError?: (error: unknown) => unknown } | null>,
): DaemonTransport {
const opens = new Set<() => void>();
const closes = new Set<(event?: unknown) => void>();
const errors = new Set<(event?: unknown) => void>();
const messages = new Set<(data: unknown, binary: boolean) => void>();
const cleanups: (() => void)[] = [];
let closed = false;
let closeEvent: unknown;
let transport: DaemonTransport | undefined;
const runCleanups = () => {
for (const cleanup of cleanups.splice(0).toReversed()) cleanup();
};
const close = (code?: number, reason?: string) => {
if (closed) return;
closed = true;
try {
transport?.close(code, reason);
} finally {
try {
runCleanups();
} finally {
for (const handler of closes) handler(closeEvent);
}
}
};
const scope: AttemptScope = {
get closed() {
return closed;
},
defer(cleanup) {
cleanups.push(cleanup);
if (closed) runCleanups();
},
};
void open(scope)
.then((opened) => {
if (!opened) return;
const { describeError = (error: unknown) => error } = opened;
transport = opened.transport;
transport.onOpen(() => {
if (!closed) for (const handler of opens) handler();
});
transport.onClose((event) => {
closeEvent = event;
close();
});
transport.onError((error) => {
if (closed) return;
const failure = describeError(error);
for (const handler of errors) handler(failure);
close();
});
transport.onMessage((data, binary) => {
if (!closed) for (const handler of messages) handler(data, binary);
});
return undefined;
})
.catch((error: unknown) => {
if (closed) return;
const failure = error instanceof Error ? error : new Error("Host transport failed");
for (const handler of errors) handler(failure);
close();
});
return {
get supportsDrain() {
return transport?.supportsDrain;
},
get maxFrameBytes() {
return transport?.maxFrameBytes;
},
send(data) {
if (closed || !transport) throw new Error("Host transport is unavailable");
return transport.send(data);
},
close,
onOpen(handler) {
opens.add(handler);
return () => opens.delete(handler);
},
onClose(handler) {
closes.add(handler);
return () => closes.delete(handler);
},
onError(handler) {
errors.add(handler);
return () => errors.delete(handler);
},
onMessage(handler) {
messages.add(handler);
return () => messages.delete(handler);
},
};
}
/**
* A factory owns one attempt, including a fresh SSH process — or, for a routed
* spec, a fresh origin session — and its teardown.
*/
export function createHostTransportFactory(
connection: string,
connection: HostTransportSpec,
budget = new HostTransportBudget(),
options: HostTransportOptions = {},
): DaemonTransportFactory {
if (typeof connection !== "string")
return createRoutedTransportFactory(connection, budget, options);
const target = parseHostTarget(connection);
// Rises to "protected" once the daemon negotiates it, so a later attempt
// cannot be downgraded to legacy endpoint security.
let securityFloor: SecurityMode | undefined =
target.kind === "socket" ? target.offer?.minimumSecurityMode : undefined;
return (attemptOptions) => {
const opens = new Set<() => void>();
const closes = new Set<(event?: unknown) => void>();
const errors = new Set<(event?: unknown) => void>();
const messages = new Set<(data: unknown, binary: boolean) => void>();
let closed = false;
let closeEvent: unknown;
let transport: DaemonTransport | undefined;
let teardown = () => {};
let disposeSocket = () => {};
let assertOutboundCapacity = (bytes: number) => budget.assertCapacity(bytes);
let sshTunnel: SshTunnel | null = null;
const close = (code?: number, reason?: string) => {
if (closed) return;
closed = true;
try {
transport?.close(code, reason);
} finally {
try {
disposeSocket();
teardown();
} finally {
for (const handler of closes) handler(closeEvent);
}
}
};
void (async () => {
return (attemptOptions) =>
deferredTransport(async (scope) => {
let sshTunnel: SshTunnel | null = null;
let socketTarget: Extract<HostTarget, { kind: "socket" }>;
if (target.kind === "ssh") {
const tunnel = await createSshTunnel(target.ssh, { env: options.sshEnv });
sshTunnel = tunnel;
teardown = () => tunnel.close();
scope.defer(() => tunnel.close());
socketTarget = parseHostTarget(tunnel.endpoint) as Extract<HostTarget, { kind: "socket" }>;
} else socketTarget = target;
if (closed) {
teardown();
return;
}
if (scope.closed) return null;
const socketPath = socketTarget.socketPath?.replace(/^~(?=\/)/, homedir());
let assertOutboundCapacity = (bytes: number) => budget.assertCapacity(bytes);
let factory = createWebSocketTransportFactory((url, socketOptions) => {
const socket = new WebSocket(
socketPath && url.startsWith("ws+unix:") ? `ws+unix://${socketPath}:/ws` : url,
@@ -79,7 +181,7 @@ export function createHostTransportFactory(
maxPayload: 100 * 1024 * 1024,
},
);
disposeSocket = () => socket.terminate();
scope.defer(() => socket.terminate());
assertOutboundCapacity = (bytes) => {
if (socket.bufferedAmount + bytes > 128 * 1024 * 1024) {
throw Object.assign(new Error("Host socket buffer limit reached"), {
@@ -126,10 +228,7 @@ export function createHostTransportFactory(
// Load relay E2EE crypto lazily so local TCP/Unix/SSH clients never import @getpaseo/relay.
const { createRelayE2eeTransportFactory } =
await import("../daemon-client-relay-e2ee-transport.js");
if (closed) {
teardown();
return;
}
if (scope.closed) return null;
factory = createRelayE2eeTransportFactory({
baseFactory: factory,
daemonPublicKeyB64: socketTarget.offer.daemonPublicKeyB64,
@@ -141,19 +240,11 @@ export function createHostTransportFactory(
assertOutboundCapacity: (bytes) => assertOutboundCapacity(bytes),
});
}
transport = factory({ ...attemptOptions, url: socketTarget.url });
transport.onOpen(() => {
if (!closed) for (const handler of opens) handler();
});
transport.onClose((event) => {
closeEvent = event;
close();
});
transport.onError((error) => {
if (closed) return;
const detail = sshTunnel?.failureDetail() ?? "";
const failure =
/permission denied|authentication failed|host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(
return {
transport: factory({ ...attemptOptions, url: socketTarget.url }),
describeError: (error) => {
const detail = sshTunnel?.failureDetail() ?? "";
return /permission denied|authentication failed|host key verification failed|REMOTE HOST IDENTIFICATION HAS CHANGED/i.test(
detail,
)
? Object.assign(
@@ -163,44 +254,54 @@ export function createHostTransportFactory(
{ code: "authentication_failed" },
)
: error;
for (const handler of errors) handler(failure);
close();
});
transport.onMessage((data, binary) => {
if (!closed) for (const handler of messages) handler(data, binary);
});
})().catch(() => {
for (const handler of errors) handler(new Error("Host transport failed"));
close();
},
};
});
}
/**
* A routed host has no address of its own: each attempt opens a client session
* to the origin daemon at `via`, then a host channel from the origin to `serverId`.
*/
function createRoutedTransportFactory(
spec: Exclude<HostTransportSpec, string>,
budget: HostTransportBudget,
options: HostTransportOptions,
): DaemonTransportFactory {
const listen = localListenOfHostTarget(parseHostTarget(spec.via));
const { localCredential } = options;
return (attemptOptions: DaemonTransportAttempt) =>
deferredTransport(async (scope) => {
// The full client loads the AOT protocol validator, so only routed specs import it.
const { createHostChannelTransport, createHostClient } = await import("./index.js");
if (scope.closed) return null;
const origin = createHostClient(
spec.via,
{
clientId: `host-route-${randomUUID()}`,
reconnect: { enabled: false },
...(options.connectTimeoutMs !== undefined
? { connectTimeoutMs: options.connectTimeoutMs }
: {}),
...(options.webSocketAgent ? { webSocketAgent: options.webSocketAgent } : {}),
...(options.sshEnv ? { sshEnv: options.sshEnv } : {}),
...(spec.originPassword ? { password: spec.originPassword } : {}),
...(listen && localCredential
? { localCredential: async () => (await localCredential(listen)) ?? undefined }
: {}),
},
budget,
);
scope.defer(() => void origin.close().catch(() => undefined));
await origin.connect();
if (scope.closed) return null;
return {
transport: createHostChannelTransport(
origin,
spec.serverId,
randomUUID(),
null,
)(attemptOptions),
};
});
return {
get supportsDrain() {
return transport?.supportsDrain;
},
get maxFrameBytes() {
return transport?.maxFrameBytes;
},
send(data) {
if (closed || !transport) throw new Error("Host transport is unavailable");
return transport.send(data);
},
close,
onOpen(handler) {
opens.add(handler);
return () => opens.delete(handler);
},
onClose(handler) {
closes.add(handler);
return () => closes.delete(handler);
},
onError(handler) {
errors.add(handler);
return () => errors.delete(handler);
},
onMessage(handler) {
messages.add(handler);
return () => messages.delete(handler);
},
};
};
}
@@ -12,7 +12,7 @@ import {
type BrowserProxyStatus,
type BrowserProxyStatusSnapshot,
} from "./internal/proxy-manager.js";
import { parseBrowserProxyTarget, type BrowserProxyTarget } from "./internal/target.js";
import { parseBrowserProxyTarget } from "./internal/target.js";
import {
openTunnelWireConnection,
type LocalCredentialReader,
@@ -27,7 +27,6 @@ export {
type BrowserProxyManager,
type BrowserProxyStatus,
type BrowserProxyStatusSnapshot,
type BrowserProxyTarget,
};
const TICKET_REQUEST_TIMEOUT_MS = 10_000;
@@ -13,7 +13,7 @@ import {
type BrowserProxySessionLike,
type BrowserProxyStatusSnapshot,
} from "./proxy-manager.js";
import type { BrowserProxyTarget, TunnelWireConnection } from "./tunnel-transport.js";
import type { TunnelWireConnection } from "./tunnel-transport.js";
function createFakeSession(resolveProxyResult?: (url: string, proxyRules: string) => string) {
const sessionObj: BrowserProxySessionLike & {
@@ -202,7 +202,7 @@ describe("BrowserProxyManager", () => {
});
managers.push(manager);
const target: BrowserProxyTarget = { type: "directTcp", endpoint: "10.0.0.5:6767" };
const target = "tcp://10.0.0.5:6767";
const ready = await manager.ensureHostProxy({ serverId: "remote-1", target });
const expectedPartition = getHostBrowserProxyPartition("remote-1");
@@ -261,7 +261,7 @@ describe("BrowserProxyManager", () => {
const ready = await manager.ensureHostProxy({
serverId: "remote-owner-check",
target: { type: "directTcp", endpoint: "10.0.0.9:6767" },
target: "tcp://10.0.0.9:6767",
});
const outcome = await new Promise<"closed_without_data" | "received_data">((resolve) => {
@@ -298,7 +298,7 @@ describe("BrowserProxyManager", () => {
const result = await manager.ensureHostProxy({
serverId: "remote-broken-proxy",
target: { type: "directTcp", endpoint: "10.0.0.10:6767" },
target: "tcp://10.0.0.10:6767",
});
expect(result.status).toBe("error");
@@ -331,7 +331,7 @@ describe("BrowserProxyManager", () => {
});
managers.push(manager);
const target: BrowserProxyTarget = { type: "directTcp", endpoint: "10.0.0.11:6767" };
const target = "tcp://10.0.0.11:6767";
const initialFail = await manager.ensureHostProxy({ serverId: "remote-flaky", target });
expect(initialFail.status).toBe("error");
expect(initialFail.socksPort).toBeNull();
@@ -9,7 +9,8 @@ import {
writeSocks5Reply,
} from "./socks5.js";
import { TunnelMuxClient } from "./tunnel-mux.js";
import { targetsEqual, type BrowserProxyTarget } from "./target.js";
import type { HostTransportSpec } from "@getpaseo/protocol/host-target";
import { targetsEqual } from "./target.js";
import { openTunnelWireConnection, type TunnelWireConnection } from "./tunnel-transport.js";
export type BrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting" | "error";
@@ -37,7 +38,7 @@ export interface BrowserProxyManagerDeps {
getSessionForPartition: (partition: string) => BrowserProxySessionLike;
verifySocketOwner?: SocketOwnerVerifier;
openTunnelWire?: (input: {
target: BrowserProxyTarget;
target: HostTransportSpec;
ticket: string;
}) => Promise<TunnelWireConnection>;
onStatusChange?: (status: BrowserProxyStatusSnapshot) => void;
@@ -49,13 +50,13 @@ export interface BrowserProxyManagerDeps {
export interface EnsureHostProxyInput {
serverId: string;
target: BrowserProxyTarget;
target: HostTransportSpec;
forceReconnect?: boolean;
}
export interface BrowserProxyManager {
ensureHostProxy(input: EnsureHostProxyInput): Promise<BrowserProxyStatusSnapshot>;
updateHostProxyTarget(input: { serverId: string; target: BrowserProxyTarget }): void;
updateHostProxyTarget(input: { serverId: string; target: HostTransportSpec }): void;
getHostProxyStatus(serverId: string): BrowserProxyStatusSnapshot | null;
isAllowedHostPartition(partition: string): boolean;
isProxiedSession(session: object): boolean;
@@ -67,7 +68,7 @@ export interface BrowserProxyManager {
interface HostProxyEntry {
readonly serverId: string;
readonly partition: string;
target: BrowserProxyTarget;
target: HostTransportSpec;
status: BrowserProxyStatus;
error: string | null;
socksServer: Server | null;
@@ -344,7 +345,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
}
}
function getOrCreateEntry(serverId: string, target: BrowserProxyTarget): HostProxyEntry {
function getOrCreateEntry(serverId: string, target: HostTransportSpec): HostProxyEntry {
const existing = entriesByServerId.get(serverId);
if (existing && !existing.disposed) {
if (!targetsEqual(existing.target, target)) {
@@ -424,7 +425,7 @@ export function createBrowserProxyManager(deps: BrowserProxyManagerDeps): Browse
}
}
function updateHostProxyTarget(input: { serverId: string; target: BrowserProxyTarget }): void {
function updateHostProxyTarget(input: { serverId: string; target: HostTransportSpec }): void {
const entry = entriesByServerId.get(input.serverId.trim());
if (!entry || entry.disposed) return;
if (!targetsEqual(entry.target, input.target)) {
@@ -1,114 +1,53 @@
import { describe, expect, test } from "vitest";
import { parseHostTarget } from "@getpaseo/protocol/host-target";
import {
hostConnectionOf,
parseBrowserProxyTarget,
targetsEqual,
type BrowserProxyTarget,
} from "./target.js";
import type { HostTransportSpec } from "@getpaseo/protocol/host-target";
import { parseBrowserProxyTarget, targetsEqual } from "./target.js";
const relay = {
type: "relay",
serverId: "srv-relay",
relayEndpoint: "relay.example.test:443",
useTls: true,
daemonPublicKeyB64: "cHVibGljLWtleQ",
minimumSecurityMode: "protected",
} as const;
const routedViaLocal = {
type: "routed",
serverId: "srv-dev",
originServerId: "srv-mac",
origin: { type: "directSocket", path: "/tmp/paseo.sock" },
} as const;
const relay =
"relay://relay.example.test:443/srv-relay?key=cHVibGljLWtleQ&ssl=true&security=protected";
const routedViaLocal = { via: "unix:///tmp/paseo.sock", serverId: "srv-dev" } as const;
describe("parseBrowserProxyTarget", () => {
test.each<[string, unknown, BrowserProxyTarget | null]>([
[
"direct TCP",
{ type: "directTcp", endpoint: " 10.0.0.5:6767 ", useTls: true, extra: 1 },
{ type: "directTcp", endpoint: "10.0.0.5:6767", useTls: true },
],
[
"remote SSH",
{ type: "remoteSsh", host: "me@box", sshPort: 2222, daemonPort: 7000 },
{ type: "remoteSsh", host: "me@box", sshPort: 2222, daemonPort: 7000 },
],
["relay", { ...relay }, relay],
["relay without a key", { ...relay, daemonPublicKeyB64: "" }, null],
test.each<[string, unknown, HostTransportSpec | null]>([
["direct TCP", " tcp://10.0.0.5:6767?ssl=true ", "tcp://10.0.0.5:6767?ssl=true"],
["remote SSH", "ssh://me@box:2222?daemonPort=7000", "ssh://me@box:2222?daemonPort=7000"],
["relay", relay, relay],
["an empty connection", "", null],
["an invalid connection", "tcp://10.0.0.5", null],
["routed via a local socket origin", routedViaLocal, routedViaLocal],
[
"routed via a password-protected remote TCP origin",
{
type: "routed",
serverId: "srv-b",
originServerId: "srv-a",
origin: { type: "directTcp", endpoint: "a.example.test:6767", password: "pw" },
},
{
type: "routed",
serverId: "srv-b",
originServerId: "srv-a",
origin: { type: "directTcp", endpoint: "a.example.test:6767", password: "pw" },
},
],
[
"routed via a relay origin",
{ type: "routed", serverId: "srv-b", originServerId: "srv-relay", origin: relay },
{ type: "routed", serverId: "srv-b", originServerId: "srv-relay", origin: relay },
{ via: "tcp://a.example.test:6767", serverId: "srv-b", originPassword: "pw", extra: 1 },
{ via: "tcp://a.example.test:6767", serverId: "srv-b", originPassword: "pw" },
],
[
"routed via a named pipe origin",
{
type: "routed",
serverId: "srv-b",
originServerId: "srv-a",
origin: { type: "directPipe", path: "\\\\.\\pipe\\paseo" },
},
{
type: "routed",
serverId: "srv-b",
originServerId: "srv-a",
origin: { type: "directPipe", path: "\\\\.\\pipe\\paseo" },
},
{ via: "pipe://\\\\.\\pipe\\paseo", serverId: "srv-b" },
{ via: "pipe://\\\\.\\pipe\\paseo", serverId: "srv-b" },
],
["routed without an origin", { type: "routed", serverId: "b", originServerId: "a" }, null],
[
"routed through another routed origin",
{ type: "routed", serverId: "c", originServerId: "b", origin: routedViaLocal },
null,
],
["directSocket as a top-level target", { type: "directSocket", path: "/tmp/p.sock" }, null],
["unknown type", { type: "carrier-pigeon" }, null],
["non-object", "directTcp", null],
["routed without an origin", { serverId: "srv-b" }, null],
["routed without a destination", { via: "tcp://a.example.test:6767", serverId: " " }, null],
["routed via an invalid origin", { via: "not a host", serverId: "srv-b" }, null],
["routed through another routed origin", { via: routedViaLocal, serverId: "srv-c" }, null],
["a number", 6767, null],
])("%s", (_name, raw, expected) => {
expect(parseBrowserProxyTarget(raw)).toEqual(expected);
});
test("keeps an origin password's surrounding whitespace verbatim", () => {
expect(
parseBrowserProxyTarget({
via: "tcp://a.example.test:6767",
serverId: "srv-b",
originPassword: " pw with spaces ",
}),
).toMatchObject({ originPassword: " pw with spaces " });
});
});
describe("targetsEqual", () => {
test.each<[string, BrowserProxyTarget, BrowserProxyTarget, boolean]>([
[
"direct TCP with default TLS",
{ type: "directTcp", endpoint: "10.0.0.5:6767" },
{ type: "directTcp", endpoint: "10.0.0.5:6767", useTls: false },
true,
],
[
"direct TCP with a different TLS mode",
{ type: "directTcp", endpoint: "10.0.0.5:6767" },
{ type: "directTcp", endpoint: "10.0.0.5:6767", useTls: true },
false,
],
[
"remote SSH with a different SSH port",
{ type: "remoteSsh", host: "box", sshPort: 22 },
{ type: "remoteSsh", host: "box", sshPort: 2222 },
false,
],
["identical relay", relay, { ...relay }, true],
["relay with a different key", relay, { ...relay, daemonPublicKeyB64: "b3RoZXI" }, false],
test.each<[string, HostTransportSpec, HostTransportSpec, boolean]>([
["identical connections", "tcp://10.0.0.5:6767", "tcp://10.0.0.5:6767", true],
["a different TLS mode", "tcp://10.0.0.5:6767", "tcp://10.0.0.5:6767?ssl=true", false],
["identical routed", routedViaLocal, structuredClone(routedViaLocal), true],
[
"routed to a different destination",
@@ -119,47 +58,18 @@ describe("targetsEqual", () => {
[
"routed through a different origin connection",
routedViaLocal,
{ ...routedViaLocal, origin: { type: "directTcp", endpoint: "127.0.0.1:6767" } },
{ ...routedViaLocal, via: "tcp://127.0.0.1:6767" },
false,
],
[
"routed with a changed origin password",
{ ...routedViaLocal, origin: { ...routedViaLocal.origin, password: "a" } },
{ ...routedViaLocal, origin: { ...routedViaLocal.origin, password: "b" } },
false,
],
[
"routed versus direct to the same server",
routedViaLocal,
{ type: "directTcp", endpoint: "10.0.0.5:6767" },
{ ...routedViaLocal, originPassword: "a" },
{ ...routedViaLocal, originPassword: "b" },
false,
],
["routed versus direct to the origin", routedViaLocal, routedViaLocal.via, false],
])("%s", (_name, left, right, expected) => {
expect(targetsEqual(left, right)).toBe(expected);
expect(targetsEqual(right, left)).toBe(expected);
});
});
test("keeps an origin password's surrounding whitespace verbatim", () => {
expect(
parseBrowserProxyTarget({
type: "routed",
serverId: "srv-b",
originServerId: "srv-a",
origin: { type: "directTcp", endpoint: "a.example.test:6767", password: " pw with spaces " },
}),
).toMatchObject({ origin: { password: " pw with spaces " } });
});
describe("hostConnectionOf for SSH hosts", () => {
test.each([
[{ host: "::1", sshPort: 2222 }, "ssh://[::1]:2222"],
[{ host: "[::1]", sshPort: 2222 }, "ssh://[::1]:2222"],
[{ host: "me@[::1]", daemonPort: 7000 }, "ssh://me@[::1]?daemonPort=7000"],
[{ host: "me@box" }, "ssh://me@box"],
])("%o dials %s", (target, expected) => {
const connection = hostConnectionOf({ type: "remoteSsh", ...target });
expect(connection).toBe(expected);
expect(parseHostTarget(connection).kind).toBe("ssh");
});
});
@@ -1,190 +1,39 @@
import {
buildDaemonWebSocketUrl,
serializeRelayConnectionUri,
shouldUseTlsForDefaultHostedRelay,
} from "@getpaseo/protocol/daemon-endpoints";
/** A daemon the desktop dials directly and sends `tunnel_hello` to. */
export type BrowserProxyDaemonTarget =
| {
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. Desktop main opens a full client
* session to it, so it carries the origin's own credentials.
*/
export type BrowserProxyOriginTarget = (
| BrowserProxyDaemonTarget
| { type: "directSocket"; path: string }
| { type: "directPipe"; path: string }
) & { password?: string };
export type BrowserProxyTarget =
| BrowserProxyDaemonTarget
| {
type: "routed";
serverId: string;
originServerId: string;
origin: BrowserProxyOriginTarget;
};
/** The `@getpaseo/client/node` host connection string that dials this daemon. */
export function hostConnectionOf(
target: BrowserProxyDaemonTarget | BrowserProxyOriginTarget,
): string {
switch (target.type) {
case "directSocket":
return `unix://${target.path}`;
case "directPipe":
return `pipe://${target.path}`;
case "directTcp":
return buildDaemonWebSocketUrl(target.endpoint, { useTls: target.useTls ?? false });
case "remoteSsh":
return sshConnectionOf(target);
case "relay":
return serializeRelayConnectionUri({
offer: {
v: 2,
serverId: target.serverId,
daemonPublicKeyB64: target.daemonPublicKeyB64,
relay: {
endpoint: target.relayEndpoint,
useTls: target.useTls ?? shouldUseTlsForDefaultHostedRelay(target.relayEndpoint),
},
...(target.minimumSecurityMode
? { minimumSecurityMode: target.minimumSecurityMode }
: {}),
},
});
}
}
function sshConnectionOf(target: Extract<BrowserProxyDaemonTarget, { type: "remoteSsh" }>): string {
const at = target.host.lastIndexOf("@");
const user = at >= 0 ? target.host.slice(0, at) : "";
const hostname = at >= 0 ? target.host.slice(at + 1) : target.host;
const authority = `${user ? `${encodeURIComponent(user)}@` : ""}${
hostname.includes(":") && !hostname.startsWith("[") ? `[${hostname}]` : hostname
}${target.sshPort !== undefined ? `:${target.sshPort}` : ""}`;
const query = target.daemonPort !== undefined ? `?daemonPort=${target.daemonPort}` : "";
return `ssh://${authority}${query}`;
}
/** The listen address a desktop-managed local daemon would record, if the origin can be local. */
export function localListenOf(origin: BrowserProxyOriginTarget): string | null {
switch (origin.type) {
case "directTcp":
return origin.endpoint;
case "directSocket":
return `unix://${origin.path}`;
case "directPipe":
return `pipe://${origin.path}`;
case "remoteSsh":
case "relay":
return null;
}
}
import { parseHostTarget, type HostTransportSpec } from "@getpaseo/protocol/host-target";
/** Two targets are equal when they dial the same daemon with the same credentials. */
export function targetsEqual(left: BrowserProxyTarget, right: BrowserProxyTarget): boolean {
export function targetsEqual(left: HostTransportSpec, right: HostTransportSpec): boolean {
return targetIdentity(left) === targetIdentity(right);
}
function targetIdentity(target: BrowserProxyTarget): string {
if (target.type !== "routed") return JSON.stringify([hostConnectionOf(target)]);
return JSON.stringify([
target.serverId,
target.originServerId,
hostConnectionOf(target.origin),
target.origin.password ?? null,
]);
function targetIdentity(target: HostTransportSpec): string {
if (typeof target === "string") return JSON.stringify([target]);
return JSON.stringify([target.via, target.serverId, target.originPassword ?? null]);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
function readNonEmptyString(value: unknown): string | null {
function readConnection(value: unknown): string | null {
if (typeof value !== "string") return null;
const trimmed = value.trim();
return trimmed.length > 0 ? trimmed : null;
}
function parseDaemonTarget(raw: Record<string, unknown>): BrowserProxyDaemonTarget | null {
if (raw.type === "directTcp") {
const endpoint = readNonEmptyString(raw.endpoint);
if (!endpoint) return null;
return {
type: "directTcp",
endpoint,
...(typeof raw.useTls === "boolean" ? { useTls: raw.useTls } : {}),
};
try {
parseHostTarget(value);
return value.trim();
} catch {
return null;
}
if (raw.type === "remoteSsh") {
const host = readNonEmptyString(raw.host);
if (!host) return null;
return {
type: "remoteSsh",
host,
...(typeof raw.sshPort === "number" ? { sshPort: raw.sshPort } : {}),
...(typeof raw.daemonPort === "number" ? { daemonPort: raw.daemonPort } : {}),
};
}
if (raw.type === "relay") {
const serverId = readNonEmptyString(raw.serverId);
const relayEndpoint = readNonEmptyString(raw.relayEndpoint);
const daemonPublicKeyB64 = readNonEmptyString(raw.daemonPublicKeyB64);
if (!serverId || !relayEndpoint || !daemonPublicKeyB64) return null;
return {
type: "relay",
serverId,
relayEndpoint,
...(typeof raw.useTls === "boolean" ? { useTls: raw.useTls } : {}),
daemonPublicKeyB64,
...(raw.minimumSecurityMode === "protected" ? { minimumSecurityMode: "protected" } : {}),
};
}
return null;
}
function parseOriginTarget(raw: unknown): BrowserProxyOriginTarget | null {
if (!isRecord(raw)) return null;
// Daemon passwords are compared verbatim, so surrounding whitespace is significant.
const password =
typeof raw.password === "string" && raw.password.length > 0 ? raw.password : null;
const credentials = password ? { password } : {};
if (raw.type === "directSocket" || raw.type === "directPipe") {
const path = readNonEmptyString(raw.path);
return path ? { type: raw.type, path, ...credentials } : null;
}
const daemon = parseDaemonTarget(raw);
return daemon ? { ...daemon, ...credentials } : null;
}
/** Validates a target received over IPC from the renderer. */
export function parseBrowserProxyTarget(raw: unknown): BrowserProxyTarget | null {
if (!isRecord(raw)) return null;
if (raw.type !== "routed") return parseDaemonTarget(raw);
const serverId = readNonEmptyString(raw.serverId);
const originServerId = readNonEmptyString(raw.originServerId);
const origin = parseOriginTarget(raw.origin);
if (!serverId || !originServerId || !origin) return null;
return { type: "routed", serverId, originServerId, origin };
export function parseBrowserProxyTarget(raw: unknown): HostTransportSpec | null {
if (!isRecord(raw)) return readConnection(raw);
const via = readConnection(raw.via);
const serverId = typeof raw.serverId === "string" ? raw.serverId.trim() : "";
if (!via || !serverId) return null;
// Daemon passwords are compared verbatim, so surrounding whitespace is significant.
const originPassword =
typeof raw.originPassword === "string" && raw.originPassword.length > 0
? raw.originPassword
: null;
return { via, serverId, ...(originPassword ? { originPassword } : {}) };
}
@@ -8,6 +8,8 @@ import { afterEach, describe, expect, test, vi } from "vitest";
import { WebSocket, WebSocketServer, type RawData } from "ws";
import { createHostChannelTransport, createHostClient } from "@getpaseo/client/node";
import { createPaseoApi } from "@getpaseo/client";
import { serializeRelayConnectionUri } from "@getpaseo/protocol/daemon-endpoints";
import type { HostTransportSpec } from "@getpaseo/protocol/host-target";
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
import {
decodeNetworkTunnelFrame,
@@ -23,7 +25,6 @@ import { hashDaemonPassword } from "../../../../../server/src/server/auth.js";
import { loadOrCreateDaemonKeyPair } from "../../../../../server/src/server/daemon-keypair.js";
import { readLocalCredential } from "../../../../../server/src/server/local-credential.js";
import { createBrowserProxyManager, type BrowserProxySessionLike } from "./proxy-manager.js";
import type { BrowserProxyTarget } from "./target.js";
import {
openTunnelWireConnection,
TunnelHandshakeError,
@@ -95,13 +96,7 @@ async function routedPair(options: { originPassword?: string } = {}) {
await routed.close();
}
};
return {
a,
b,
serverId,
originServerId: origin.getLastServerInfoMessage()!.serverId,
mintTicket,
};
return { a, b, serverId, mintTicket };
}
async function httpTarget(body: string): Promise<number> {
@@ -115,7 +110,7 @@ async function httpTarget(body: string): Promise<number> {
return (server.address() as AddressInfo).port;
}
async function open(target: BrowserProxyTarget, ticket: string, options = {}) {
async function open(target: HostTransportSpec, ticket: string, options = {}) {
const wire = await openTunnelWireConnection({ target, ticket, ...options });
cleanup.push(() => wire.close());
return wire;
@@ -259,10 +254,7 @@ describe("openTunnelWireConnection", () => {
test("direct TCP: tunnel_hello reaches the daemon and carries HTTP", async () => {
const port = await httpTarget("direct ok");
const b = await daemon();
const wire = await open(
{ type: "directTcp", endpoint: `127.0.0.1:${b.port}` },
await ticketFor(b),
);
const wire = await open(`tcp://127.0.0.1:${b.port}`, await ticketFor(b));
expect(wire.ready.maxFramePayloadBytes).toBe(64 * 1024);
expect(await httpGetThroughWire(wire, port)).toMatch(/^HTTP\/1\.1 200 OK[\s\S]*direct ok$/);
});
@@ -279,14 +271,15 @@ describe("openTunnelWireConnection", () => {
await relay.controlReady;
const { publicKeyB64 } = await loadOrCreateDaemonKeyPair(b.paseoHome);
const wire = await open(
{
type: "relay",
serverId: b.daemon.getServerId(),
relayEndpoint: relay.endpoint,
useTls: false,
daemonPublicKeyB64: publicKeyB64,
minimumSecurityMode: "protected",
},
serializeRelayConnectionUri({
offer: {
v: 2,
serverId: b.daemon.getServerId(),
daemonPublicKeyB64: publicKeyB64,
relay: { endpoint: relay.endpoint, useTls: false },
minimumSecurityMode: "protected",
},
}),
await ticketFor(b),
);
expect(await httpGetThroughWire(wire, port)).toMatch(/relay ok$/);
@@ -298,10 +291,7 @@ describe("openTunnelWireConnection", () => {
await fakeSshOnPath();
const port = await httpTarget("ssh ok");
const b = await daemon();
const wire = await open(
{ type: "remoteSsh", host: "fake-ssh.test", daemonPort: b.port },
await ticketFor(b),
);
const wire = await open(`ssh://fake-ssh.test?daemonPort=${b.port}`, await ticketFor(b));
expect(await httpGetThroughWire(wire, port)).toMatch(/ssh ok$/);
},
);
@@ -311,14 +301,9 @@ describe("openTunnelWireConnection", () => {
const pair = await routedPair({ originPassword: "origin-secret" });
const wire = await open(
{
type: "routed",
via: `tcp://127.0.0.1:${pair.a.port}`,
serverId: pair.serverId,
originServerId: pair.originServerId,
origin: {
type: "directTcp",
endpoint: `127.0.0.1:${pair.a.port}`,
password: "origin-secret",
},
originPassword: "origin-secret",
},
await pair.mintTicket(),
);
@@ -330,12 +315,7 @@ describe("openTunnelWireConnection", () => {
const pair = await routedPair({ originPassword: "origin-secret" });
const asked: string[] = [];
const wire = await open(
{
type: "routed",
serverId: pair.serverId,
originServerId: pair.originServerId,
origin: { type: "directTcp", endpoint: `127.0.0.1:${pair.a.port}` },
},
{ via: `tcp://127.0.0.1:${pair.a.port}`, serverId: pair.serverId },
await pair.mintTicket(),
{
localCredential: (listen: string) => {
@@ -350,15 +330,10 @@ describe("openTunnelWireConnection", () => {
test("routed: an invalid ticket rejects with tunnel_error and releases the origin session", async () => {
const pair = await routedPair();
const target: BrowserProxyTarget = {
type: "routed",
serverId: pair.serverId,
originServerId: pair.originServerId,
origin: { type: "directTcp", endpoint: `127.0.0.1:${pair.a.port}` },
};
const target = { via: `tcp://127.0.0.1:${pair.a.port}`, serverId: pair.serverId };
const forwarder = await cuttableForwarder(pair.a.port);
const rejected = await openTunnelWireConnection({
target: { ...target, origin: { type: "directTcp", endpoint: forwarder.endpoint } },
target: { ...target, via: `tcp://${forwarder.endpoint}` },
ticket: "not-a-valid-ticket",
}).catch((error: unknown) => error);
expect(rejected).toBeInstanceOf(TunnelHandshakeError);
@@ -375,10 +350,7 @@ describe("openTunnelWireConnection", () => {
const started = Date.now();
await expect(
openTunnelWireConnection({
target: {
type: "directTcp",
endpoint: `127.0.0.1:${(silent.address() as AddressInfo).port}`,
},
target: `tcp://127.0.0.1:${(silent.address() as AddressInfo).port}`,
ticket: "ticket",
timeoutMs: 300,
}),
@@ -394,7 +366,7 @@ describe("openTunnelWireConnection", () => {
await closeServer(closed);
await expect(
openTunnelWireConnection({
target: { type: "directTcp", endpoint: `127.0.0.1:${port}` },
target: `tcp://127.0.0.1:${port}`,
ticket: "ticket",
timeoutMs: 2_000,
}),
@@ -461,12 +433,7 @@ test("a routed browser proxy serves B's localhost through A over SOCKS5 and reco
const ready = await manager.ensureHostProxy({
serverId: pair.serverId,
target: {
type: "routed",
serverId: pair.serverId,
originServerId: pair.originServerId,
origin: { type: "directTcp", endpoint: forwarder.endpoint },
},
target: { via: `tcp://${forwarder.endpoint}`, serverId: pair.serverId },
});
expect(ready).toMatchObject({ status: "ready", socksPort: expect.any(Number) });
expect(await socks5HttpGet(ready.socksPort!, "localhost", port)).toMatch(/served by B$/);
@@ -1,19 +1,14 @@
import { randomUUID } from "node:crypto";
import type { DaemonTransport } from "@getpaseo/client/internal/daemon-client-transport-types";
import { createHostTransportFactory } from "@getpaseo/client/node/lean";
import {
createHostTransportFactory,
type DaemonTransport,
type HostTransportOptions,
type HostTransportSpec,
} from "@getpaseo/client/node/lean";
import {
WSTunnelHandshakeResponseSchema,
type WSTunnelHandshakeResponse,
} from "@getpaseo/protocol/messages";
import { buildSshSpawnEnv } from "../../../daemon/ssh-proxy.js";
import {
hostConnectionOf,
localListenOf,
type BrowserProxyDaemonTarget,
type BrowserProxyTarget,
} from "./target.js";
export type { BrowserProxyTarget } from "./target.js";
export interface TunnelReadyLimits {
maxFramePayloadBytes: number;
@@ -40,10 +35,10 @@ export class TunnelHandshakeError extends Error {
}
/** Returns the desktop-managed daemon's local credential when `listen` is that daemon. */
export type LocalCredentialReader = (listen: string) => string | null | Promise<string | null>;
export type LocalCredentialReader = NonNullable<HostTransportOptions["localCredential"]>;
export interface OpenTunnelWireInput {
target: BrowserProxyTarget;
target: HostTransportSpec;
ticket: string;
timeoutMs?: number;
localCredential?: LocalCredentialReader;
@@ -79,11 +74,11 @@ function toText(data: unknown): string {
/**
* Runs the `tunnel_hello` → `tunnel_ready` handshake on an unopened transport and
* switches it to binary tunnel frames. Owns the transport from here on: it closes
* it on handshake failure, timeout, or `close()`, and runs `onClosed` once after.
* it on handshake failure, timeout, or `close()`.
*/
export function openTunnelOnTransport(
function openTunnelOnTransport(
transport: DaemonTransport,
input: { ticket: string; timeoutMs: number; onClosed?: () => void },
input: { ticket: string; timeoutMs: number },
): Promise<TunnelWireConnection> {
const binaryListeners = new Set<(bytes: Uint8Array) => void>();
const closeListeners = new Set<(error?: Error) => void>();
@@ -109,7 +104,6 @@ export function openTunnelOnTransport(
} catch {
// Already closed.
}
input.onClosed?.();
for (const listener of closeListeners) listener(error);
closeListeners.clear();
binaryListeners.clear();
@@ -202,64 +196,14 @@ export function openTunnelOnTransport(
});
}
function openDaemonTransport(target: BrowserProxyDaemonTarget): DaemonTransport {
return createHostTransportFactory(hostConnectionOf(target), undefined, {
sshEnv: buildSshSpawnEnv(),
})({ url: TRANSPORT_URL });
}
/**
* A routed host has no address of its own: open a client session to its origin
* daemon, then a host channel from the origin to the routed host.
*/
async function openRoutedTunnel(
target: Extract<BrowserProxyTarget, { type: "routed" }>,
input: { ticket: string; timeoutMs: number; localCredential?: LocalCredentialReader },
): Promise<TunnelWireConnection> {
// The full client loads the AOT protocol validator; only routed tunnels need it.
const { createHostChannelTransport, createHostClient } = await import("@getpaseo/client/node");
const { origin } = target;
const listen = localListenOf(origin);
const readLocalCredential = input.localCredential;
const originClient = createHostClient(hostConnectionOf(origin), {
clientId: `browser-proxy-${randomUUID()}`,
reconnect: { enabled: false },
connectTimeoutMs: input.timeoutMs,
sshEnv: buildSshSpawnEnv(),
...(origin.password ? { password: origin.password } : {}),
...(listen && readLocalCredential
? { localCredential: async () => (await readLocalCredential(listen)) ?? undefined }
: {}),
});
const closeOrigin = () => {
void originClient.close().catch(() => undefined);
};
try {
await originClient.connect();
} catch (error) {
closeOrigin();
throw error;
}
const transport = createHostChannelTransport(
originClient,
target.serverId,
randomUUID(),
null,
)({ url: TRANSPORT_URL });
return await openTunnelOnTransport(transport, { ...input, onClosed: closeOrigin });
}
export async function openTunnelWireConnection(
input: OpenTunnelWireInput,
): Promise<TunnelWireConnection> {
const timeoutMs = input.timeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
const { target, ticket } = input;
if (target.type === "routed") {
return await openRoutedTunnel(target, {
ticket,
timeoutMs,
...(input.localCredential ? { localCredential: input.localCredential } : {}),
});
}
return await openTunnelOnTransport(openDaemonTransport(target), { ticket, timeoutMs });
const transport = createHostTransportFactory(input.target, undefined, {
sshEnv: buildSshSpawnEnv(),
connectTimeoutMs: timeoutMs,
...(input.localCredential ? { localCredential: input.localCredential } : {}),
})({ url: TRANSPORT_URL });
return await openTunnelOnTransport(transport, { ticket: input.ticket, timeoutMs });
}
+4 -6
View File
@@ -1,9 +1,7 @@
import { contextBridge, ipcRenderer, webUtils } from "electron";
import type { BrowserKeyboardPolicy } from "./features/browser-keyboard/index.js";
import type {
BrowserProxyStatusSnapshot,
BrowserProxyTarget,
} from "./features/browser-proxy/index.js";
import type { HostTransportSpec } from "@getpaseo/protocol/host-target";
import type { BrowserProxyStatusSnapshot } from "./features/browser-proxy/index.js";
import type { DesktopWindowChromeMode } from "./window/chrome.js";
// This preload runs in Electron's sandbox and is tsc-compiled (not bundled), so it MUST
@@ -151,14 +149,14 @@ contextBridge.exposeInMainWorld("paseoDesktop", {
}) => ipcRenderer.invoke("paseo:browser:clear-profile", input),
ensureHostProxy: (input: {
serverId: string;
target: BrowserProxyTarget;
target: HostTransportSpec;
forceReconnect?: boolean;
}) =>
ipcRenderer.invoke(
"paseo:browser-proxy:ensure-host",
input,
) as Promise<BrowserProxyStatusSnapshot>,
updateHostProxyTarget: (input: { serverId: string; target: BrowserProxyTarget }) =>
updateHostProxyTarget: (input: { serverId: string; target: HostTransportSpec }) =>
ipcRenderer.invoke("paseo:browser-proxy:update-target", input),
getHostProxyStatus: (serverId: string) =>
ipcRenderer.invoke(
+7
View File
@@ -92,6 +92,13 @@ export interface UsageSourceRegistration {
/** Provider IDs associated with this source, used as a hint for default visibility. */
providers?: readonly string[];
input: ZodType;
/**
* When Paseo calls `fetch`. "automatic" (the default) fetches when a client lists usage and
* refreshes the result every few minutes. "manual" fetches only when the user selects Refresh:
* lists show the last result, or a prompt to refresh before the first one, and a failure is
* not retried. Use it when each fetch costs the user something, such as a vendor's quota check.
*/
refresh?: "automatic" | "manual";
/** Accounts for this scope only. The same key in any scope identifies the same account. */
discover(scope: UsageScope): Promise<UsageAccount[]>;
/** Re-reads the login store; never writes it. */
+83
View File
@@ -0,0 +1,83 @@
import { z } from "zod";
import { DaemonPermissionSchema } from "./daemon-permissions.js";
export const WSClientTypeSchema = z.enum(["mobile", "browser", "cli", "mcp", "hub"]);
export type WSClientType = z.infer<typeof WSClientTypeSchema>;
export const HelloClientPlatformSchema = z.enum([
"macos",
"linux",
"windows",
"ios",
"android",
"web",
"unknown",
]);
export type HelloClientPlatform = z.infer<typeof HelloClientPlatformSchema>;
export const HelloClientInfoSchema = z.object({
name: z.string().max(128).optional(),
platform: HelloClientPlatformSchema.optional(),
});
export type HelloClientInfo = z.infer<typeof HelloClientInfoSchema>;
export const DaemonSessionTransportSchema = z.enum([
"local_ipc",
"local",
"tailscale",
"direct",
"relay",
"via",
"hub",
]);
export type DaemonSessionTransport = z.infer<typeof DaemonSessionTransportSchema>;
export const DaemonSessionSummarySchema = z.object({
sessionId: z.string(),
principalId: z.string(),
isCurrentSession: z.boolean(),
name: z.string().nullable(),
platform: z.string().nullable(),
clientType: WSClientTypeSchema,
appVersion: z.string().nullable(),
transport: DaemonSessionTransportSchema,
viaSessionId: z.string().optional(),
servesHostLink: z.boolean().optional(),
permissions: z.array(DaemonPermissionSchema),
connectedAt: z.string(),
socketCount: z.number().int().nonnegative(),
});
export type DaemonSessionSummary = z.infer<typeof DaemonSessionSummarySchema>;
export const DaemonClientsSnapshotSchema = z.object({
sessions: z.array(DaemonSessionSummarySchema),
});
export type DaemonClientsSnapshot = z.infer<typeof DaemonClientsSnapshotSchema>;
export const DaemonClientsListRequestSchema = z.object({
type: z.literal("daemon.clients.list.request"),
requestId: z.string(),
observe: z.boolean().optional(),
includeInternal: z.boolean().optional(),
});
export const DaemonClientsListResponseSchema = z.object({
type: z.literal("daemon.clients.list.response"),
payload: z.object({
requestId: z.string(),
subscriptionId: z.string().optional(),
sessions: z.array(DaemonSessionSummarySchema),
}),
});
export const DaemonClientsChangedSchema = z.object({
type: z.literal("daemon.clients.changed"),
payload: z.object({
subscriptionId: z.string(),
sessions: z.array(DaemonSessionSummarySchema),
}),
});
export type DaemonClientsListRequest = z.infer<typeof DaemonClientsListRequestSchema>;
export type DaemonClientsListResponse = z.infer<typeof DaemonClientsListResponseSchema>;
export type DaemonClientsChanged = z.infer<typeof DaemonClientsChangedSchema>;
@@ -0,0 +1,16 @@
import { z } from "zod";
export const DAEMON_PERMISSIONS = [
"daemon.read",
"daemon.manage",
"tunnel.manage",
"access.manage",
"workspace.read",
"workspace.write",
"workspace.manage",
"automation.manage",
"hub.execute",
] as const;
export const DaemonPermissionSchema = z.enum(DAEMON_PERMISSIONS);
export type DaemonPermission = z.infer<typeof DaemonPermissionSchema>;
+24 -1
View File
@@ -1,5 +1,5 @@
import { expect, test } from "vitest";
import { parseHostTarget } from "./host-target.js";
import { localListenOfHostTarget, parseHostTarget } from "./host-target.js";
test.each([
["127.0.0.1:6767", "tcp://127.0.0.1:6767"],
@@ -74,3 +74,26 @@ test("pairing offers cannot publish a credential-bearing or malformed relay auth
expect(() => parseHostTarget(url)).toThrow("Invalid host connection");
}
});
test.each([
["127.0.0.1:6767", "127.0.0.1:6767"],
["4321", "127.0.0.1:4321"],
["tcp://[::1]:4321?password=secret", "[::1]:4321"],
["tcp://example.com:6767?ssl=true", "example.com:6767"],
["ws://localhost:6767/ws", "localhost:6767"],
["wss://example.com/ws", "example.com:443"],
["unix:///tmp/paseo.sock", "unix:///tmp/paseo.sock"],
["/tmp/paseo.sock", "unix:///tmp/paseo.sock"],
["~/paseo.sock", "unix://~/paseo.sock"],
["pipe://\\\\.\\pipe\\paseo", "pipe://\\\\.\\pipe\\paseo"],
["\\\\.\\pipe\\paseo", "pipe://\\\\.\\pipe\\paseo"],
])("a daemon on this machine serving %s records listen address %s", (connection, listen) => {
expect(localListenOfHostTarget(parseHostTarget(connection))).toBe(listen);
});
test.each(["ssh://box?daemonPort=7000", "relay://relay.example.test:443/srv_test?key=public-key"])(
"%s does not dial a listen address directly",
(connection) => {
expect(localListenOfHostTarget(parseHostTarget(connection))).toBeNull();
},
);
+21
View File
@@ -20,6 +20,13 @@ export type HostTarget =
description: string;
};
/**
* How a Node client reaches a daemon: a host connection string it dials, or a
* host routed through the daemon that `via` dials. `originPassword` authenticates
* the client session to that origin daemon.
*/
export type HostTransportSpec = string | { via: string; serverId: string; originPassword?: string };
/** The shared saved-host and CLI grammar. Errors never echo credential-bearing input. */
export function parseHostTarget(input: string): HostTarget {
try {
@@ -33,6 +40,20 @@ export function parseHostTarget(input: string): HostTarget {
);
}
}
/**
* The listen address a daemon on this machine records (`host:port`, `unix://`,
* `pipe://`) when it serves this target, or null for targets that reach the
* daemon through SSH or a relay.
*/
export function localListenOfHostTarget(target: HostTarget): string | null {
if (target.kind !== "socket" || target.offer) return null;
if (target.socketPath) {
return `${target.url.startsWith("ws+unix:") ? "unix" : "pipe"}://${target.socketPath}`;
}
const url = new URL(target.url);
return `${url.hostname}:${url.port || (url.protocol === "wss:" ? 443 : 80)}`;
}
function parse(input: string): HostTarget {
if (!input) throw new Error("empty");
if (input.startsWith("ssh://")) {
+5
View File
@@ -1,4 +1,5 @@
import { z } from "zod";
import { DaemonPermissionSchema } from "./daemon-permissions.js";
export const HostMetadataSchema = z.record(z.string().max(256), z.string().max(4096));
export const HostAddSchema = z.object({
@@ -26,6 +27,10 @@ export const HostSummarySchema = z.object({
lastOnlineAt: z.string().nullable(),
nextRetryAt: z.string().nullable(),
error: z.object({ code: z.string(), message: z.string() }).nullable(),
// COMPAT(connectedClients): added in v0.19.0; older daemons omit version, permissions, and connectedAt.
version: z.string().nullable().optional(),
permissions: z.array(DaemonPermissionSchema).optional(),
connectedAt: z.string().nullable().optional(),
});
export const HostDirectorySchema = z.object({
self: z.object({ serverId: z.string(), label: z.string() }),

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