mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 12:46:55 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d1ee5dee63 | ||
|
|
1adabf70c8 | ||
|
|
87427c2aa1 | ||
|
|
cfa4536358 | ||
|
|
7f75b0e166 | ||
|
|
b0ca089d54 | ||
|
|
91e7713721 | ||
|
|
e20ea2aaf2 | ||
|
|
806214d285 | ||
|
|
e5edb6efd5 | ||
|
|
0a0544fa4f | ||
|
|
914143e8b0 |
+17
-11
@@ -236,17 +236,23 @@ wake-ups), or the child's own outstanding finish subscriptions as a caller. Hear
|
||||
crons, change-request watches, and other daemon background items never count: they are external
|
||||
triggers, not work the caller is waiting for.
|
||||
|
||||
Every turn end reports `finished` at once. When work is still pending, the notice names it and the
|
||||
subscription follows the child: each later turn end reports `finished` again, and the child settling
|
||||
with nothing pending sends a final `finished` and removes the subscription, even when the work
|
||||
drains without another turn. Reporting at once keeps a long-lived task, such as a dev server, from
|
||||
leaving the caller without the child's reply. Following is what lets the caller hear the reply a
|
||||
background task wakes up later ([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change
|
||||
that leaves work pending sends nothing. Errors, permission requests, and closes report as they
|
||||
happen. `followingSince` is stored when following starts, so a restart keeps following instead of
|
||||
waiting for another turn end. After 24 hours of following, the caller gets a final `finished` with
|
||||
the child's last reply and the subscription ends. Remote children and providers without the probe
|
||||
report their first turn end as a settled `finished`.
|
||||
Every turn end reports `finished` at once, unless the child already sent an agent message to its
|
||||
caller during that turn and started no further tool work afterwards. In that case the child's
|
||||
message already delivered its reply, so the redundant `finished` notice is skipped: a settled watch
|
||||
ends silently, and a watch with pending work keeps following silently until a later turn starts or
|
||||
the work drains. Starting another non-reporting tool call or a new turn clears that mark (plain text output after the
|
||||
message does not), and errors, permission requests, cancellations, and closes are never suppressed. When work is still
|
||||
pending on an unreported turn end, the notice names it and the subscription follows the child: each
|
||||
later turn end reports `finished` again, and the child settling with nothing pending sends a final
|
||||
`finished` and removes the subscription, even when the work drains without another turn. Reporting
|
||||
at once keeps a long-lived task, such as a dev server, from leaving the caller without the child's
|
||||
reply. Following is what lets the caller hear the reply a background task wakes up later
|
||||
([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change that leaves work pending
|
||||
sends nothing. Errors, permission requests, and closes report as they happen. `followingSince` is
|
||||
stored when following starts, so a restart keeps following instead of waiting for another turn end.
|
||||
After 24 hours of following, the caller gets a final `finished` with the child's last reply and the
|
||||
subscription ends. Remote children and providers without the probe report their first turn end as a
|
||||
settled `finished`.
|
||||
|
||||
Permission requests are notification checkpoints, not the end of that subscription. The caller is notified again after a permission response when the child finishes, errors, or requests another permission.
|
||||
The permission notification includes the normalized request plus the child and request IDs, so the caller can inspect it and respond without fetching agent status.
|
||||
|
||||
@@ -29,7 +29,7 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
- **The coalescer is leading + trailing.** The first delta after an idle window flushes synchronously; only the rest of the burst waits for the trailing timer. Reverting to trailing-only adds a full window to the first character of every turn. Same shape and the same reason as `TerminalOutputCoalescer`.
|
||||
- **The leading flush adds a canonical row, and that is fine.** A burst's first chunk lands as its own timeline row. `mergeAssistantChunks` / `mergeReasoningChunks` in `timeline-projection.ts` join contiguous same-turn rows, and clients read the projected timeline, so history is unaffected. Tests that assert on raw rows have to account for the extra row; tests that assert on what a client sees do not.
|
||||
- **The store holds the full text; only the rendered slice is paced.** Copy, selection, the chat outline, and scroll geometry all read the same string the user can see. Pacing the store instead would leave the bottom anchor chasing a content height that is ahead of the reveal.
|
||||
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. The native renderer keeps closed blocks in a stable head and sends the paced suffix to a separate tail view during streaming; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
|
||||
- **One source assistant message is one display row.** Presentation projects plugin output and caches unchanged history. The shared [Markdown renderer](markdown-renderer.md) owns rendering on every platform. Chat paces the visible source and applies a 32,000-character render cap on web; native keeps the complete message. While streaming, the renderer keeps closed blocks in head parts and sends the paced suffix to a separate tail; completion reunites them for selection. This stays inside the renderer, without promoting blocks into timeline history.
|
||||
- **Message identity survives completion.** Assistant row ids are source message ids. Plugin rows can replace a source, so find, scroll-to-message and history reveal still use `getStreamItemMessageId`. Width-specific measurements describe whole rendered messages.
|
||||
- **First sight of a text is revealed whole.** Only growth is paced. This is what makes history hydration, timeline replay, a virtualized row remounting on scroll, and an already-finished message all render complete on first paint without a special case for each.
|
||||
- **Leaving `phase: "streaming"` snaps the reveal.** A completed turn must never be left holding characters. `layoutStream` sets the phase, so anything outside the live head with an active turn is already complete.
|
||||
@@ -49,11 +49,19 @@ So arrival sets a _target_ and the reveal rate is derived from the backlog inste
|
||||
while text arrives, and release obsolete window caches as the reader reveals more history;
|
||||
window caches must stay bounded while their source timeline remains loaded.
|
||||
|
||||
## Native parsing cost
|
||||
## Markdown parsing cost
|
||||
|
||||
The native library reparses and measures its entire `markdown` prop on each update. During streaming, the renderer splits source at an mdast block boundary and memoizes the head, so per-frame updates parse only the tail. Boundary discovery runs when a source line completes, rather than on every reveal frame. The unfinished line and final parsed block stay in the tail, preserving list continuation, setext headings, tables and open fences. Reference-dependent source and HTML retain a larger tail because later source can change their meaning. A single long block therefore still carries its full parsing cost.
|
||||
Both engines reparse their entire `markdown` prop on each update: md4c in C++ on native, md4c in WASM plus a JSON tree on web. Source adaptation adds a full mdast parse for some text, such as any `&`, at about 1 µs per character. Rendering a growing reply whole on each reveal frame therefore makes the reply quadratic to stream.
|
||||
|
||||
Completion restores one native text view per Mermaid-delimited segment, so selection crosses prose paragraphs again. The head retains its trailing block margin while split. JS reveal remains the pacing source; native opacity animation stays disabled.
|
||||
While streaming, `createStreamingMarkdownSplitter` in `components/markdown/streaming.ts` splits the message into head parts and a tail, on every platform. The tail is the last block and the unfinished line, so list continuation, setext headings, tables and open fences render as they will when complete. Rules that keep the cost per frame flat as the reply grows:
|
||||
|
||||
- **Discovery is incremental.** The boundary moves only when a line completes, and each time the splitter parses only the source after the boundary. Blocks before it are closed and need no document context.
|
||||
- **Head parts are sealed at 2,000 characters.** Each completed block re-renders the head part it lands in. Only the last part grows, so that work stays bounded. A single head would re-render all closed blocks each time a block completes.
|
||||
- **The first part keeps its React key from the first frame to the completed message.** Completion re-renders it in place instead of remounting it, and the parts share one image occurrence key, so an image keeps its acquisition when its block moves into the head.
|
||||
|
||||
Two kinds of source fall back to a growing render, because later source can change how earlier source reads. A link definition can turn an earlier `[label]` into a link, so a message with one renders as one document until it completes. HTML needs its enclosing source, so HTML and every block after it stay in the tail. A single long block also carries its full cost.
|
||||
|
||||
Completion renders one view per Mermaid-delimited segment, so native selection crosses prose paragraphs again; while streaming it crosses only within a part. JS reveal remains the pacing source; native opacity animation stays disabled.
|
||||
|
||||
## Measuring
|
||||
|
||||
|
||||
@@ -2,11 +2,11 @@
|
||||
|
||||
Use `MarkdownRenderer` for chat replies, file previews, plans, pull requests and changelog content. It uses `react-native-enriched-markdown` on iOS, Android and web. Keep source adaptation and renderer configuration in `components/markdown`; consumers supply Markdown and, when needed, its file location.
|
||||
|
||||
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. Chat owns paced reveal, the web render cap, message identity and list measurement. Native renders completed messages together. While streaming, it keeps closed blocks in one head view and updates a separate tail, then reunites the text on completion. See [native parsing cost](agent-stream-performance.md#native-parsing-cost) for the boundary and pacing constraints.
|
||||
Native selection belongs to the library's text view. Keep an assistant message in one row so selection can cross paragraphs, headings and lists. Code blocks and tables use the library's native views and their selection behavior. Web uses browser selection over semantic HTML. Once its WASM parser is initialized, the library parses synchronously for the first commit of each mounted row; an empty interim row would corrupt virtualized measurements and move the reader. 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
|
||||
|
||||
|
||||
@@ -94,6 +94,11 @@ its value from the frame timestamp instead of replaying a 60 fps recording, so i
|
||||
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.
|
||||
|
||||
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 at once. The clock listens for that end and starts the decay again at the current
|
||||
time.
|
||||
|
||||
`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.
|
||||
|
||||
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,6 @@ import { flushSync } from "react-dom";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getStreamItemMessageId, type StreamItem } from "@/types/stream";
|
||||
@@ -77,14 +76,6 @@ const historyStartSlotStyle: CSSProperties = {
|
||||
};
|
||||
|
||||
const streamRowsHostStyle: CSSProperties = { position: "relative", width: "100%" };
|
||||
const initialFillStyle: CSSProperties = {
|
||||
position: "absolute",
|
||||
inset: 0,
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
pointerEvents: "none",
|
||||
};
|
||||
|
||||
// Rows and the live auxiliary (turn footer, pending permissions) center their content with
|
||||
// `alignSelf`, which only applies inside a flex container.
|
||||
@@ -439,6 +430,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange,
|
||||
onReadingPositionChange,
|
||||
onNearHistoryStart,
|
||||
@@ -707,6 +699,12 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
() => historyStartPagination.state.status === "settling",
|
||||
);
|
||||
const finishInitialFill = useStableEvent(() => historyStartPagination.reveal());
|
||||
const reportInitialHistoryVisibility = useStableEvent((visible: boolean) => {
|
||||
onInitialHistoryVisibilityChange?.(visible);
|
||||
});
|
||||
useLayoutEffect(() => {
|
||||
reportInitialHistoryVisibility(historyStartPaginationState.visible);
|
||||
}, [historyStartPaginationState.visible, reportInitialHistoryVisibility]);
|
||||
const rearmHistoryStartFromUserIntent = useStableEvent(() => historyStartPagination.rearm());
|
||||
const scheduleHistoryStartPrependSettle = useStableEvent(() => {
|
||||
let scheduler = historyStartSettleSchedulerRef.current;
|
||||
@@ -1750,11 +1748,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
{shouldRenderEmpty ? listEmptyComponent : null}
|
||||
</div>
|
||||
</div>
|
||||
{!historyStartPaginationState.visible ? (
|
||||
<div style={initialFillStyle}>
|
||||
<LoadingState testID="agent-initial-fill" title={t("agentPanel.states.loadingHistory")} />
|
||||
</div>
|
||||
) : null}
|
||||
{scrollEnabled && !isMobileBreakpoint ? (
|
||||
<DomOverlayScrollbar
|
||||
scrollContainerRef={scrollContainerRef}
|
||||
|
||||
@@ -94,6 +94,8 @@ export interface StreamRenderInput {
|
||||
isAuthoritativeHistoryReady: boolean;
|
||||
isInitialHistoryLoading?: boolean;
|
||||
revealInitialHistory?: boolean;
|
||||
/** When supplied, the host pane owns the full-pane initial-fill loading overlay. */
|
||||
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
|
||||
onNearBottomChange: (value: boolean) => void;
|
||||
// The history row under the top of the viewport, for surfaces that mark where the reader
|
||||
// is in the transcript. Only the web viewport measures it today.
|
||||
|
||||
@@ -258,6 +258,8 @@ export interface AgentStreamViewProps {
|
||||
isAuthoritativeHistoryReady?: boolean;
|
||||
isInitialHistoryLoading?: boolean;
|
||||
revealInitialHistory?: boolean;
|
||||
/** When supplied, the host pane owns the full-pane initial-fill loading overlay. */
|
||||
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
|
||||
/** Tail space required by a transparent overlay rendered at the bottom edge. */
|
||||
bottomOverlayTailClearance?: number;
|
||||
/** Bottom offset required for controls floating above that overlay. */
|
||||
@@ -357,6 +359,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady = true,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
bottomOverlayTailClearance = 0,
|
||||
bottomOverlayControlClearance,
|
||||
toast,
|
||||
@@ -1231,6 +1234,7 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange: nearBottom.set,
|
||||
onReadingPositionChange: handleReadingPositionChange,
|
||||
onNearHistoryStart: loadOlder,
|
||||
@@ -1384,6 +1388,9 @@ function agentStreamViewPropsEqual(
|
||||
if (left.revealInitialHistory !== right.revealInitialHistory) {
|
||||
reasons.push("revealInitialHistory");
|
||||
}
|
||||
if (left.onInitialHistoryVisibilityChange !== right.onInitialHistoryVisibilityChange) {
|
||||
reasons.push("onInitialHistoryVisibilityChange");
|
||||
}
|
||||
if (left.bottomOverlayTailClearance !== right.bottomOverlayTailClearance) {
|
||||
reasons.push("bottomOverlayTailClearance");
|
||||
}
|
||||
|
||||
@@ -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,28 @@ 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 it ends.
|
||||
function heldDriver() {
|
||||
let onEnd: ((result: { finished: boolean }) => void) | null = null;
|
||||
function end(finished: boolean) {
|
||||
const ended = onEnd;
|
||||
onEnd = null;
|
||||
ended?.({ finished });
|
||||
}
|
||||
const driver: ClockDriver = {
|
||||
start(ended) {
|
||||
onEnd = ended;
|
||||
},
|
||||
stop: () => end(false),
|
||||
};
|
||||
return {
|
||||
drive: () => driver,
|
||||
/** What the native driver does when two frames carry the same timestamp. */
|
||||
finish: () => end(true),
|
||||
running: () => onEnd !== null,
|
||||
};
|
||||
}
|
||||
|
||||
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]);
|
||||
@@ -120,4 +142,38 @@ describe("indicator clock", () => {
|
||||
|
||||
expect(read(shimmer)).toBe(0);
|
||||
});
|
||||
|
||||
test("a clock the driver ends under a running indicator starts again at the current time", () => {
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
nowMs = 37_650;
|
||||
driver.finish();
|
||||
|
||||
expect(driver.running()).toBe(true);
|
||||
expect(read(elapsedMs)).toBe(37_650);
|
||||
|
||||
stop();
|
||||
expect(driver.running()).toBe(false);
|
||||
});
|
||||
|
||||
test("a clock that starts again keeps a cycle with its own phase on its first step", () => {
|
||||
let nowMs = 0;
|
||||
const elapsedMs = new Animated.Value(0);
|
||||
const driver = heldDriver();
|
||||
const clock = createIndicatorClock(elapsedMs, () => nowMs, driver.drive);
|
||||
const stop = clock.run();
|
||||
|
||||
nowMs = 37_650;
|
||||
driver.finish();
|
||||
nowMs = 40_000;
|
||||
const shimmer = clock.cycle(41 * STEP_MS, { steps: 41, phase: "own" });
|
||||
elapsedMs.setValue(40_000);
|
||||
stop();
|
||||
|
||||
expect(read(shimmer)).toBeLessThan(STEP_MS);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -4,7 +4,7 @@ import { Animated } 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.
|
||||
// rate and never loops.
|
||||
const CLOCK_CONFIG = { velocity: 1, deceleration: 1 - 1e-12, useNativeDriver: true };
|
||||
|
||||
// The clock starts on a frame and advances a whole frame at a time, so at 60, 90 and 120 Hz a step
|
||||
@@ -41,6 +41,16 @@ export interface IndicatorClock {
|
||||
run(): () => void;
|
||||
}
|
||||
|
||||
/** What advances the clock's value until it is stopped. */
|
||||
export interface ClockDriver {
|
||||
start(onEnd: (result: { finished: boolean }) => void): void;
|
||||
stop(): void;
|
||||
}
|
||||
|
||||
function decayForever(elapsedMs: Animated.Value): ClockDriver {
|
||||
return Animated.decay(elapsedMs, CLOCK_CONFIG);
|
||||
}
|
||||
|
||||
/**
|
||||
* `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
|
||||
@@ -49,9 +59,10 @@ export interface IndicatorClock {
|
||||
export function createIndicatorClock(
|
||||
elapsedMs = new Animated.Value(0, { useNativeDriver: true }),
|
||||
now: () => number = () => performance.now(),
|
||||
drive: (elapsedMs: Animated.Value) => ClockDriver = decayForever,
|
||||
): IndicatorClock {
|
||||
let runners = 0;
|
||||
let ticking: Animated.CompositeAnimation | null = null;
|
||||
let ticking: ClockDriver | null = null;
|
||||
let startedAtMs = 0;
|
||||
|
||||
function currentStepStartMs(stepMs: number): number {
|
||||
@@ -61,6 +72,18 @@ export function createIndicatorClock(
|
||||
return Math.floor((now() - startedAtMs) / stepMs) * stepMs;
|
||||
}
|
||||
|
||||
// The driver ends a decay whose value did not move between two frames, and two frames that carry
|
||||
// the same millisecond are enough for that. Nothing tells the indicators, so the clock starts
|
||||
// again where the time is now.
|
||||
function tick() {
|
||||
elapsedMs.setValue(now() - startedAtMs);
|
||||
const driver = drive(elapsedMs);
|
||||
ticking = driver;
|
||||
driver.start(({ finished }) => {
|
||||
if (finished && ticking === driver) tick();
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
cycle(periodMs, { steps, phase = "shared" } = {}) {
|
||||
const stepMs = steps ? periodMs / steps : 0;
|
||||
@@ -76,16 +99,15 @@ export function createIndicatorClock(
|
||||
run() {
|
||||
runners += 1;
|
||||
if (!ticking) {
|
||||
elapsedMs.setValue(0);
|
||||
startedAtMs = now();
|
||||
ticking = Animated.decay(elapsedMs, CLOCK_CONFIG);
|
||||
ticking.start();
|
||||
tick();
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0) {
|
||||
ticking?.stop();
|
||||
const stopped = ticking;
|
||||
ticking = null;
|
||||
stopped?.stop();
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
@@ -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 |
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
`,
|
||||
).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,
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Platform } from "react-native";
|
||||
import { getElectronHost } from "@/desktop/electron/host";
|
||||
import type { BrowserKeyboardPolicy } from "@/keyboard";
|
||||
import type { IdentityColorName } from "@/styles/identity-colors";
|
||||
import type { HostTransportSpec } from "@getpaseo/protocol/host-target";
|
||||
import type { SessionInboundMessage, SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
|
||||
type BrowserAutomationExecuteRequest = Extract<
|
||||
@@ -172,44 +173,6 @@ export type BrowserProfileRemoveResult =
|
||||
| { ok: true }
|
||||
| { ok: false; code: "reserved" | "invalid" | "not_found" | "io" };
|
||||
|
||||
/** A daemon Electron main dials directly to open a network tunnel. */
|
||||
export type DesktopBrowserProxyDaemonTarget =
|
||||
| {
|
||||
type: "directTcp";
|
||||
endpoint: string;
|
||||
useTls?: boolean;
|
||||
}
|
||||
| {
|
||||
type: "remoteSsh";
|
||||
host: string;
|
||||
sshPort?: number;
|
||||
daemonPort?: number;
|
||||
}
|
||||
| {
|
||||
type: "relay";
|
||||
serverId: string;
|
||||
relayEndpoint: string;
|
||||
useTls?: boolean;
|
||||
daemonPublicKeyB64: string;
|
||||
minimumSecurityMode?: "protected";
|
||||
};
|
||||
|
||||
/** The daemon a routed host is reached through, with that daemon's own credentials. */
|
||||
export type DesktopBrowserProxyOriginTarget = (
|
||||
| DesktopBrowserProxyDaemonTarget
|
||||
| { type: "directSocket"; path: string }
|
||||
| { type: "directPipe"; path: string }
|
||||
) & { password?: string };
|
||||
|
||||
export type DesktopBrowserProxyTarget =
|
||||
| DesktopBrowserProxyDaemonTarget
|
||||
| {
|
||||
type: "routed";
|
||||
serverId: string;
|
||||
originServerId: string;
|
||||
origin: DesktopBrowserProxyOriginTarget;
|
||||
};
|
||||
|
||||
export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting" | "error";
|
||||
|
||||
export interface DesktopBrowserProxyStatusSnapshot {
|
||||
@@ -254,13 +217,10 @@ export interface DesktopBrowserBridge {
|
||||
}) => Promise<void>;
|
||||
ensureHostProxy?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
target: HostTransportSpec;
|
||||
forceReconnect?: boolean;
|
||||
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
|
||||
updateHostProxyTarget?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
}) => Promise<void>;
|
||||
updateHostProxyTarget?: (input: { serverId: string; target: HostTransportSpec }) => Promise<void>;
|
||||
getHostProxyStatus?: (serverId: string) => Promise<DesktopBrowserProxyStatusSnapshot | null>;
|
||||
releaseHostProxy?: (serverId: string) => Promise<void>;
|
||||
deliverProxyTicket?: (input: {
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import Constants from "expo-constants";
|
||||
import { Platform } from "react-native";
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
|
||||
function mapNativePlatform(os: string): HelloClientPlatform {
|
||||
if (os === "ios") return "ios";
|
||||
if (os === "android") return "android";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function resolveAppClientIdentity(): {
|
||||
clientType: "mobile" | "browser";
|
||||
clientInfo: HelloClientInfo;
|
||||
} {
|
||||
const deviceName = Constants.deviceName?.trim();
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
platform: mapNativePlatform(Platform.OS),
|
||||
...(deviceName ? { name: deviceName.slice(0, 128) } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
|
||||
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
|
||||
const normalized = raw?.toLowerCase();
|
||||
if (normalized === "darwin" || normalized === "macos") return "macos";
|
||||
if (normalized === "linux") return "linux";
|
||||
if (normalized === "win32" || normalized === "windows") return "windows";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function parseBrowserName(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) return undefined;
|
||||
if (/Edg\//.test(userAgent)) return "Edge";
|
||||
if (/Firefox\//.test(userAgent)) return "Firefox";
|
||||
if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) return "Chrome";
|
||||
if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) return "Safari";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolveAppClientIdentity(): {
|
||||
clientType: "mobile" | "browser";
|
||||
clientInfo: HelloClientInfo;
|
||||
} {
|
||||
if (getIsElectron()) {
|
||||
const desktop = getDesktopHost();
|
||||
const label = desktop?.browserHostLabel?.trim();
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
platform: mapDesktopPlatform(desktop?.platform),
|
||||
...(label ? { name: label.slice(0, 128) } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const browserName =
|
||||
typeof navigator !== "undefined" ? parseBrowserName(navigator.userAgent) : undefined;
|
||||
return {
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
platform: "web",
|
||||
...(browserName ? { name: browserName } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { TFunction } from "i18next";
|
||||
import type {
|
||||
DaemonClientsSnapshot,
|
||||
DaemonSessionSummary,
|
||||
DaemonSessionTransport,
|
||||
WSClientType,
|
||||
} from "@getpaseo/protocol/daemon-clients";
|
||||
import type { DaemonPermission } from "@getpaseo/protocol/messages";
|
||||
import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts";
|
||||
import {
|
||||
SettingsCard,
|
||||
SettingsCollapsibleRow,
|
||||
SettingsRow,
|
||||
SettingsSection,
|
||||
} from "@/components/settings";
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
|
||||
type StatusDotTone = "online" | "warning" | "error" | "offline";
|
||||
|
||||
function StatusDot({ tone }: { tone: StatusDotTone }) {
|
||||
return (
|
||||
<View style={styles.dotSlot}>
|
||||
<View
|
||||
style={[
|
||||
styles.dot,
|
||||
tone === "online" && styles.dotOnline,
|
||||
tone === "warning" && styles.dotWarning,
|
||||
tone === "error" && styles.dotError,
|
||||
tone === "offline" && styles.dotOffline,
|
||||
]}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const STATUS_DOTS: Record<StatusDotTone, React.ReactNode> = {
|
||||
online: <StatusDot tone="online" />,
|
||||
warning: <StatusDot tone="warning" />,
|
||||
error: <StatusDot tone="error" />,
|
||||
offline: <StatusDot tone="offline" />,
|
||||
};
|
||||
|
||||
function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[]; t: TFunction }) {
|
||||
const summary = summarizePermissions(permissions);
|
||||
let label: string;
|
||||
if (summary.kind === "full") {
|
||||
label = t("devices.scopes.fullAccess");
|
||||
} else if (summary.kind === "read_only") {
|
||||
label = t("devices.scopes.readOnly");
|
||||
} else if (summary.count === 1) {
|
||||
label = t("devices.scopes.countOne");
|
||||
} else {
|
||||
label = t("devices.scopes.countOther", { count: summary.count });
|
||||
}
|
||||
return <StatusBadge label={label} variant="muted" size="xs" />;
|
||||
}
|
||||
|
||||
function PermissionPillsRow({
|
||||
permissions,
|
||||
t,
|
||||
}: {
|
||||
permissions: readonly DaemonPermission[];
|
||||
t: TFunction;
|
||||
}) {
|
||||
return (
|
||||
<SettingsRow label={t("devices.details.permissions")}>
|
||||
<View style={styles.scopePills}>
|
||||
{permissions.length > 0 ? (
|
||||
permissions.map((permission) => (
|
||||
<StatusBadge key={permission} label={permission} variant="muted" size="xs" />
|
||||
))
|
||||
) : (
|
||||
<Text style={styles.nestedValue}>{t("devices.scopes.none")}</Text>
|
||||
)}
|
||||
</View>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFunction): string | null {
|
||||
if (!isoTimestamp) return null;
|
||||
const duration = formatConnectedDuration(isoTimestamp);
|
||||
if (!duration) return null;
|
||||
if (duration.kind === "just_now") return t("devices.time.justNow");
|
||||
if (duration.kind === "minutes") return t("devices.time.minutesAgo", { count: duration.count });
|
||||
if (duration.kind === "hours") return t("devices.time.hoursAgo", { count: duration.count });
|
||||
return t("devices.time.daysAgo", { count: duration.count });
|
||||
}
|
||||
|
||||
function formatTransportLabel(
|
||||
transport: DaemonSessionTransport,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
switch (transport) {
|
||||
case "local_ipc":
|
||||
case "local":
|
||||
return t("devices.transport.local");
|
||||
case "tailscale":
|
||||
return t("devices.transport.tailscale");
|
||||
case "relay":
|
||||
return t("devices.transport.relay");
|
||||
case "hub":
|
||||
return t("devices.transport.hub");
|
||||
case "via":
|
||||
return viaHostName
|
||||
? t("devices.transport.via", { host: viaHostName })
|
||||
: t("devices.transport.viaHost");
|
||||
case "direct":
|
||||
return t("devices.transport.direct");
|
||||
}
|
||||
}
|
||||
|
||||
function formatClientPlatformLabel(
|
||||
clientType: WSClientType,
|
||||
platform: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (platform === "ios") return "iOS";
|
||||
if (platform === "android") return "Android";
|
||||
if (platform === "macos" || platform === "linux" || platform === "windows") {
|
||||
return t("devices.kind.desktop");
|
||||
}
|
||||
if (clientType === "browser" || platform === "web") return t("devices.kind.web");
|
||||
if (clientType === "mobile") return t("devices.kind.mobile");
|
||||
if (clientType === "hub") return t("devices.kind.hub");
|
||||
if (clientType === "cli") return "CLI";
|
||||
return "MCP";
|
||||
}
|
||||
|
||||
function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
|
||||
if (session.isCurrentSession) return t("devices.connected.thisDevice");
|
||||
if (session.name) return session.name;
|
||||
return formatClientPlatformLabel(session.clientType, session.platform, t);
|
||||
}
|
||||
|
||||
function formatSessionHint(
|
||||
session: DaemonSessionSummary,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
const transport = formatTransportLabel(session.transport, viaHostName, t);
|
||||
const platform = formatClientPlatformLabel(session.clientType, session.platform, t);
|
||||
const detail = session.appVersion ? `${platform} ${session.appVersion}` : platform;
|
||||
return detail === transport ? transport : `${transport} · ${detail}`;
|
||||
}
|
||||
|
||||
function ConnectedClientRow({
|
||||
session,
|
||||
viaHostName,
|
||||
}: {
|
||||
session: DaemonSessionSummary;
|
||||
viaHostName: string | null;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tone: StatusDotTone = session.socketCount > 0 ? "online" : "warning";
|
||||
const connectedLabel = formatDurationLabel(session.connectedAt, t);
|
||||
const trailing = useMemo(
|
||||
() => <ScopePill permissions={session.permissions} t={t} />,
|
||||
[session.permissions, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={formatSessionTitle(session, t)}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={formatSessionHint(session, viaHostName, t)}
|
||||
trailing={trailing}
|
||||
testID={`devices-client-${session.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={session.permissions} t={t} />
|
||||
{connectedLabel ? (
|
||||
<SettingsRow label={t("devices.details.connected")}>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{session.socketCount === 0 ? (
|
||||
<SettingsRow label={t("devices.details.status")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
function InboundDaemonRow({
|
||||
daemon,
|
||||
routedSessions,
|
||||
}: {
|
||||
daemon: DaemonSessionSummary;
|
||||
routedSessions: readonly DaemonSessionSummary[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tone: StatusDotTone = daemon.socketCount > 0 ? "online" : "warning";
|
||||
const label = daemon.name ?? t("devices.hosts.unnamed");
|
||||
const transport = formatTransportLabel(daemon.transport, null, t);
|
||||
const hintParts = [t("devices.hosts.inbound"), transport];
|
||||
if (routedSessions.length > 0) {
|
||||
hintParts.push(t("devices.hosts.routedCount", { count: routedSessions.length }));
|
||||
}
|
||||
const connectedLabel = formatDurationLabel(daemon.connectedAt, t);
|
||||
const trailing = useMemo(
|
||||
() => <ScopePill permissions={daemon.permissions} t={t} />,
|
||||
[daemon.permissions, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={label}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={hintParts.join(" · ")}
|
||||
trailing={trailing}
|
||||
testID={`devices-inbound-host-${daemon.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={daemon.permissions} t={t} />
|
||||
{routedSessions.map((routed) => (
|
||||
<SettingsRow
|
||||
key={routed.sessionId}
|
||||
label={formatSessionTitle(routed, t)}
|
||||
hint={t("devices.hosts.routedSession")}
|
||||
>
|
||||
<ScopePill permissions={routed.permissions} t={t} />
|
||||
</SettingsRow>
|
||||
))}
|
||||
{daemon.appVersion ? (
|
||||
<SettingsRow label={t("devices.details.version")}>
|
||||
<Text style={styles.nestedValue}>{daemon.appVersion}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{connectedLabel ? (
|
||||
<SettingsRow label={t("devices.details.connected")}>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{daemon.socketCount === 0 ? (
|
||||
<SettingsRow label={t("devices.details.status")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
function outboundHostTone(status: HostSummary["status"]): StatusDotTone {
|
||||
switch (status) {
|
||||
case "online":
|
||||
return "online";
|
||||
case "connecting":
|
||||
return "warning";
|
||||
case "error":
|
||||
return "error";
|
||||
case "offline":
|
||||
case "disabled":
|
||||
return "offline";
|
||||
}
|
||||
}
|
||||
|
||||
function outboundHostStatusLabel(status: HostSummary["status"], t: TFunction): string | undefined {
|
||||
switch (status) {
|
||||
case "connecting":
|
||||
return t("devices.status.connecting");
|
||||
case "error":
|
||||
return t("devices.status.error");
|
||||
case "disabled":
|
||||
return t("devices.status.disabled");
|
||||
case "offline":
|
||||
return t("devices.status.offline");
|
||||
case "online":
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function OutboundHostRow({ host }: { host: HostSummary }) {
|
||||
const { t } = useTranslation();
|
||||
const tone = outboundHostTone(host.status);
|
||||
const label = host.label ?? host.serverId ?? host.targetDescription;
|
||||
const hintParts = [t("devices.hosts.outbound"), host.targetDescription];
|
||||
const statusSummary = outboundHostStatusLabel(host.status, t);
|
||||
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, t);
|
||||
const trailing = useMemo(
|
||||
() =>
|
||||
host.status === "online" && host.permissions ? (
|
||||
<ScopePill permissions={host.permissions} t={t} />
|
||||
) : undefined,
|
||||
[host.permissions, host.status, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<SettingsCollapsibleRow
|
||||
label={label}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={hintParts.join(" · ")}
|
||||
hintStatus={host.status === "error" ? "error" : undefined}
|
||||
summary={statusSummary}
|
||||
trailing={trailing}
|
||||
testID={`devices-outbound-host-${host.registrationId}`}
|
||||
>
|
||||
{host.permissions ? <PermissionPillsRow permissions={host.permissions} t={t} /> : null}
|
||||
{host.error ? (
|
||||
<SettingsRow label={t("devices.details.error")}>
|
||||
<Text style={styles.nestedError}>{host.error.message}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{host.version ? (
|
||||
<SettingsRow label={t("devices.details.version")}>
|
||||
<Text style={styles.nestedValue}>{host.version}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{connectedLabel ? (
|
||||
<SettingsRow
|
||||
label={
|
||||
host.status === "online"
|
||||
? t("devices.details.connected")
|
||||
: t("devices.details.lastSeen")
|
||||
}
|
||||
>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
|
||||
type ConnectedClientsLoadState =
|
||||
| { status: "loading" }
|
||||
| { status: "ready"; snapshot: DaemonClientsSnapshot }
|
||||
| { status: "error"; message: string };
|
||||
|
||||
function useConnectedClients(serverId: string, enabled: boolean): ConnectedClientsLoadState {
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const [state, setState] = useState<ConnectedClientsLoadState>({ status: "loading" });
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !client) {
|
||||
setState({ status: "loading" });
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
const observation = client.observeConnectedClients();
|
||||
const apply = (snapshot: DaemonClientsSnapshot) => {
|
||||
if (active) setState({ status: "ready", snapshot });
|
||||
};
|
||||
const unsubscribe = observation.subscribe({
|
||||
snapshot: apply,
|
||||
update: (message) => {
|
||||
if (message.type === "daemon.clients.changed") {
|
||||
apply({
|
||||
sessions: message.payload.sessions,
|
||||
});
|
||||
}
|
||||
},
|
||||
error: (err) => {
|
||||
if (!active) return;
|
||||
setState({
|
||||
status: "error",
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
},
|
||||
});
|
||||
void observation.ready.then(apply).catch((err: unknown) => {
|
||||
if (!active) return;
|
||||
setState({
|
||||
status: "error",
|
||||
message: err instanceof Error ? err.message : String(err),
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribe();
|
||||
void observation.release();
|
||||
};
|
||||
}, [client, enabled]);
|
||||
|
||||
return state;
|
||||
}
|
||||
|
||||
function useOutboundHosts(serverId: string, enabled: boolean): HostDirectory | null {
|
||||
const client = useHostRuntimeClient(serverId);
|
||||
const [directory, setDirectory] = useState<HostDirectory | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!enabled || !client) {
|
||||
setDirectory(null);
|
||||
return;
|
||||
}
|
||||
let active = true;
|
||||
const observation = client.observeHosts();
|
||||
const apply = (next: HostDirectory) => {
|
||||
if (active) setDirectory(next);
|
||||
};
|
||||
const unsubscribe = observation.subscribe({
|
||||
snapshot: apply,
|
||||
update: (message) => {
|
||||
if (message.type === "hosts.changed") apply(message.payload.directory);
|
||||
},
|
||||
});
|
||||
void observation.ready.then(apply).catch(() => undefined);
|
||||
|
||||
return () => {
|
||||
active = false;
|
||||
unsubscribe();
|
||||
void observation.release();
|
||||
};
|
||||
}, [client, enabled]);
|
||||
|
||||
return directory;
|
||||
}
|
||||
|
||||
const EMPTY_SESSIONS: readonly DaemonSessionSummary[] = [];
|
||||
|
||||
function ConnectedClientsCardBody({
|
||||
isOnline,
|
||||
hasServerInfo,
|
||||
supportsConnectedClients,
|
||||
canViewClients,
|
||||
clientsState,
|
||||
connectedClients,
|
||||
hostNameBySessionId,
|
||||
}: {
|
||||
isOnline: boolean;
|
||||
hasServerInfo: boolean;
|
||||
supportsConnectedClients: boolean;
|
||||
canViewClients: boolean;
|
||||
clientsState: ConnectedClientsLoadState;
|
||||
connectedClients: readonly DaemonSessionSummary[];
|
||||
hostNameBySessionId: ReadonlyMap<string, string | null>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const updateLink = useMemo(
|
||||
() => ({ href: UPDATES_DOCS_URL, label: t("devices.tailscale.updateDocs") }),
|
||||
[t],
|
||||
);
|
||||
|
||||
if (!isOnline) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.unavailable")}
|
||||
hint={t("workspace.terminal.hostDisconnected")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (hasServerInfo && !supportsConnectedClients) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.updateTitle")}
|
||||
hint={t("devices.connected.updateHint")}
|
||||
link={updateLink}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (!canViewClients) {
|
||||
return (
|
||||
<SettingsRow
|
||||
label={t("devices.connected.permissionTitle")}
|
||||
hint={t("devices.connected.permissionHint")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (clientsState.status === "loading") {
|
||||
return <SettingsRow label={t("devices.connected.loading")} />;
|
||||
}
|
||||
if (clientsState.status === "error") {
|
||||
return <SettingsRow label={t("devices.connected.errorTitle")} error={clientsState.message} />;
|
||||
}
|
||||
if (connectedClients.length === 0) {
|
||||
return <SettingsRow label={t("devices.connected.empty")} />;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
{connectedClients.map((entry) => (
|
||||
<ConnectedClientRow
|
||||
key={entry.sessionId}
|
||||
session={entry}
|
||||
viaHostName={
|
||||
entry.viaSessionId ? (hostNameBySessionId.get(entry.viaSessionId) ?? null) : null
|
||||
}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
|
||||
const isOnline = connectionStatus === "online";
|
||||
// COMPAT(connectedClients): added in v0.19.0, remove gate after 2027-06-01.
|
||||
const supportsConnectedClients = serverInfo?.features?.connectedClients === true;
|
||||
const supportsConnectedHosts = serverInfo?.features?.connectedHosts === true;
|
||||
const canViewClients =
|
||||
!serverInfo?.permissions || serverInfo.permissions.includes("access.manage");
|
||||
|
||||
const clientsState = useConnectedClients(
|
||||
serverId,
|
||||
isOnline && supportsConnectedClients && canViewClients,
|
||||
);
|
||||
const outboundDirectory = useOutboundHosts(serverId, isOnline && supportsConnectedHosts);
|
||||
|
||||
const sessions =
|
||||
clientsState.status === "ready" ? clientsState.snapshot.sessions : EMPTY_SESSIONS;
|
||||
const inboundDaemons = useMemo(
|
||||
() => sessions.filter((entry) => entry.servesHostLink === true),
|
||||
[sessions],
|
||||
);
|
||||
const connectedClients = useMemo(
|
||||
() => sessions.filter((entry) => !entry.servesHostLink),
|
||||
[sessions],
|
||||
);
|
||||
const hostNameBySessionId = useMemo(
|
||||
() => new Map(inboundDaemons.map((daemon) => [daemon.sessionId, daemon.name])),
|
||||
[inboundDaemons],
|
||||
);
|
||||
const routedByHostSessionId = useMemo(() => {
|
||||
const grouped = new Map<string, DaemonSessionSummary[]>();
|
||||
for (const entry of sessions) {
|
||||
if (!entry.viaSessionId) continue;
|
||||
const list = grouped.get(entry.viaSessionId);
|
||||
if (list) list.push(entry);
|
||||
else grouped.set(entry.viaSessionId, [entry]);
|
||||
}
|
||||
return grouped;
|
||||
}, [sessions]);
|
||||
|
||||
const outboundHosts = outboundDirectory?.hosts ?? [];
|
||||
const hasConnectedHosts = inboundDaemons.length > 0 || outboundHosts.length > 0;
|
||||
|
||||
return (
|
||||
<View>
|
||||
<SettingsSection title={t("devices.connected.title")}>
|
||||
<SettingsCard testID="devices-connected-clients-card">
|
||||
<ConnectedClientsCardBody
|
||||
isOnline={isOnline}
|
||||
hasServerInfo={Boolean(serverInfo)}
|
||||
supportsConnectedClients={supportsConnectedClients}
|
||||
canViewClients={canViewClients}
|
||||
clientsState={clientsState}
|
||||
connectedClients={connectedClients}
|
||||
hostNameBySessionId={hostNameBySessionId}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
|
||||
{isOnline && hasConnectedHosts ? (
|
||||
<SettingsSection title={t("devices.hosts.title")}>
|
||||
<SettingsCard testID="devices-connected-hosts-card">
|
||||
{inboundDaemons.map((daemon) => (
|
||||
<InboundDaemonRow
|
||||
key={daemon.sessionId}
|
||||
daemon={daemon}
|
||||
routedSessions={routedByHostSessionId.get(daemon.sessionId) ?? EMPTY_SESSIONS}
|
||||
/>
|
||||
))}
|
||||
{outboundHosts.map((host) => (
|
||||
<OutboundHostRow key={host.registrationId} host={host} />
|
||||
))}
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
dotSlot: {
|
||||
width: 10,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
dot: {
|
||||
width: 7,
|
||||
height: 7,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
},
|
||||
dotOnline: {
|
||||
backgroundColor: theme.colors.statusDotSuccess,
|
||||
},
|
||||
dotWarning: {
|
||||
backgroundColor: theme.colors.statusDotWarning,
|
||||
},
|
||||
dotError: {
|
||||
backgroundColor: theme.colors.statusDotDanger,
|
||||
},
|
||||
dotOffline: {
|
||||
backgroundColor: theme.colors.foregroundExtraMuted,
|
||||
},
|
||||
scopePills: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
justifyContent: "flex-end",
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
nestedValue: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
nestedError: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.statusDanger,
|
||||
},
|
||||
}));
|
||||
@@ -1,2 +1,4 @@
|
||||
export { ConnectedDevicesView } from "./connected-devices-view";
|
||||
export { PairDeviceHeaderAction } from "./pair-device-header-action";
|
||||
export { PairDeviceModal } from "./pair-device-modal";
|
||||
export { WaysToConnect } from "./ways-to-connect";
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import { Plus } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { PairDeviceSection } from "./pair-device-section";
|
||||
import { WaysToConnect } from "./ways-to-connect";
|
||||
|
||||
const SNAP_POINTS: string[] = ["72%", "92%"];
|
||||
const ThemedPlus = withUnistyles(Plus);
|
||||
const iconProps = (theme: Theme) => ({
|
||||
size: theme.iconSize.sm,
|
||||
color: theme.colors.foreground,
|
||||
});
|
||||
const plusIcon = <ThemedPlus uniProps={iconProps} />;
|
||||
|
||||
type PairStep = "ways" | "relay";
|
||||
|
||||
export function PairDeviceHeaderAction({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [visible, setVisible] = useState(false);
|
||||
const [step, setStep] = useState<PairStep>("ways");
|
||||
|
||||
const handleOpen = useCallback(() => {
|
||||
setStep("ways");
|
||||
setVisible(true);
|
||||
}, []);
|
||||
const handleClose = useCallback(() => {
|
||||
setVisible(false);
|
||||
}, []);
|
||||
const handleDismiss = useCallback(() => {
|
||||
setStep("ways");
|
||||
}, []);
|
||||
const handleOpenRelay = useCallback(() => setStep("relay"), []);
|
||||
const handleBackToWays = useCallback(() => setStep("ways"), []);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() =>
|
||||
step === "relay"
|
||||
? {
|
||||
title: t("devices.relay.title"),
|
||||
back: {
|
||||
onPress: handleBackToWays,
|
||||
label: t("common.actions.back"),
|
||||
},
|
||||
}
|
||||
: {
|
||||
title: t("settings.host.pairDevices.rowTitle"),
|
||||
},
|
||||
[handleBackToWays, step, t],
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="secondary"
|
||||
leftIcon={plusIcon}
|
||||
onPress={handleOpen}
|
||||
testID="devices-pair-button"
|
||||
>
|
||||
{t("settings.host.pairDevices.rowTitle")}
|
||||
</Button>
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible={visible}
|
||||
onClose={handleClose}
|
||||
onDismiss={handleDismiss}
|
||||
snapPoints={SNAP_POINTS}
|
||||
desktopMaxWidth={480}
|
||||
desktopHeight={520}
|
||||
testID={step === "relay" ? "devices-relay-pairing" : "devices-pair-sheet"}
|
||||
>
|
||||
{step === "relay" ? (
|
||||
<PairDeviceSection serverId={serverId} onClose={handleClose} />
|
||||
) : (
|
||||
<WaysToConnect serverId={serverId} onOpenRelay={handleOpenRelay} />
|
||||
)}
|
||||
</AdaptiveModalSheet>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { DAEMON_PERMISSIONS } from "@getpaseo/protocol/messages";
|
||||
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
|
||||
|
||||
describe("summarizePermissions", () => {
|
||||
it("detects full access, read-only, and custom scope counts", () => {
|
||||
expect(summarizePermissions(DAEMON_PERMISSIONS)).toEqual({ kind: "full" });
|
||||
expect(summarizePermissions(["daemon.read", "workspace.read"])).toEqual({
|
||||
kind: "read_only",
|
||||
});
|
||||
expect(summarizePermissions(["workspace.read"])).toEqual({ kind: "read_only" });
|
||||
expect(summarizePermissions(["hub.execute", "workspace.read"])).toEqual({
|
||||
kind: "count",
|
||||
count: 2,
|
||||
});
|
||||
expect(summarizePermissions([])).toEqual({ kind: "count", count: 0 });
|
||||
});
|
||||
});
|
||||
|
||||
describe("formatConnectedDuration", () => {
|
||||
const now = Date.parse("2026-11-28T15:00:00.000Z");
|
||||
|
||||
it("formats relative durations cleanly", () => {
|
||||
expect(formatConnectedDuration("2026-11-28T14:59:30.000Z", now)).toEqual({
|
||||
kind: "just_now",
|
||||
});
|
||||
expect(formatConnectedDuration("2026-11-28T14:46:00.000Z", now)).toEqual({
|
||||
kind: "minutes",
|
||||
count: 14,
|
||||
});
|
||||
expect(formatConnectedDuration("2026-11-28T13:00:00.000Z", now)).toEqual({
|
||||
kind: "hours",
|
||||
count: 2,
|
||||
});
|
||||
expect(formatConnectedDuration("2026-11-25T15:00:00.000Z", now)).toEqual({
|
||||
kind: "days",
|
||||
count: 3,
|
||||
});
|
||||
expect(formatConnectedDuration("not-a-date", now)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
import { DAEMON_PERMISSIONS, type DaemonPermission } from "@getpaseo/protocol/messages";
|
||||
|
||||
const READ_ONLY_PERMISSIONS: ReadonlySet<DaemonPermission> = new Set([
|
||||
"daemon.read",
|
||||
"workspace.read",
|
||||
]);
|
||||
|
||||
export type PermissionSummary =
|
||||
| { kind: "full" }
|
||||
| { kind: "read_only" }
|
||||
| { kind: "count"; count: number };
|
||||
|
||||
export function summarizePermissions(permissions: readonly DaemonPermission[]): PermissionSummary {
|
||||
const unique = new Set(permissions);
|
||||
if (unique.size >= DAEMON_PERMISSIONS.length) {
|
||||
return { kind: "full" };
|
||||
}
|
||||
if (unique.size > 0 && [...unique].every((permission) => READ_ONLY_PERMISSIONS.has(permission))) {
|
||||
return { kind: "read_only" };
|
||||
}
|
||||
return { kind: "count", count: unique.size };
|
||||
}
|
||||
|
||||
export function formatConnectedDuration(
|
||||
isoTimestamp: string,
|
||||
nowMs = Date.now(),
|
||||
): { kind: "just_now" } | { kind: "minutes" | "hours" | "days"; count: number } | null {
|
||||
const parsedMs = Date.parse(isoTimestamp);
|
||||
if (!Number.isFinite(parsedMs)) return null;
|
||||
const elapsedSeconds = Math.max(0, Math.floor((nowMs - parsedMs) / 1000));
|
||||
if (elapsedSeconds < 60) return { kind: "just_now" };
|
||||
const minutes = Math.floor(elapsedSeconds / 60);
|
||||
if (minutes < 60) return { kind: "minutes", count: minutes };
|
||||
const hours = Math.floor(minutes / 60);
|
||||
if (hours < 24) return { kind: "hours", count: hours };
|
||||
return { kind: "days", count: Math.floor(hours / 24) };
|
||||
}
|
||||
@@ -5,14 +5,26 @@ import { PairDeviceModal } from "./pair-device-modal";
|
||||
import { CONNECTIVITY_DOCS_URL } from "./pair-device-section";
|
||||
import { TailscaleRow } from "./tailscale-row";
|
||||
|
||||
export interface WaysToConnectProps {
|
||||
serverId: string;
|
||||
/** When provided, tapping Relay delegates to the caller (e.g., to advance inside an existing sheet) instead of opening a stacked modal. */
|
||||
onOpenRelay?: () => void;
|
||||
}
|
||||
|
||||
/**
|
||||
* The ways another device can connect to a host: Relay, which pairs through a QR code in a sheet,
|
||||
* and Tailscale, a switch and an address. Settings and the setup's phone step show this same block.
|
||||
*/
|
||||
export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
export function WaysToConnect({ serverId, onOpenRelay }: WaysToConnectProps) {
|
||||
const { t } = useTranslation();
|
||||
const [pairing, setPairing] = useState(false);
|
||||
const openPairing = useCallback(() => setPairing(true), []);
|
||||
const openPairing = useCallback(() => {
|
||||
if (onOpenRelay) {
|
||||
onOpenRelay();
|
||||
return;
|
||||
}
|
||||
setPairing(true);
|
||||
}, [onOpenRelay]);
|
||||
const closePairing = useCallback(() => setPairing(false), []);
|
||||
const docsLink = useMemo(
|
||||
() => ({
|
||||
@@ -34,12 +46,14 @@ export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
/>
|
||||
<TailscaleRow serverId={serverId} />
|
||||
</SettingsCard>
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
{onOpenRelay ? null : (
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
)}
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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: "تثبيت",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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: "ピン留め",
|
||||
|
||||
@@ -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: "고정",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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: "Закрепить",
|
||||
|
||||
@@ -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: "固定",
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 }),
|
||||
|
||||
@@ -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 }) {
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { renderHook } from "@testing-library/react";
|
||||
import type { ReactNode } from "react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { useWorkspaceTerminals } from "./use-workspace-terminals";
|
||||
|
||||
const noop = () => {};
|
||||
|
||||
function renderWorkspaceTerminals() {
|
||||
const queryClient = new QueryClient();
|
||||
const wrapper = ({ children }: { children: ReactNode }) => (
|
||||
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
|
||||
);
|
||||
const input = {
|
||||
client: null,
|
||||
isConnected: false,
|
||||
isRouteFocused: true,
|
||||
normalizedServerId: "server",
|
||||
normalizedWorkspaceId: "workspace",
|
||||
workspaceDirectory: null,
|
||||
workspaceScripts: [],
|
||||
hasHydratedWorkspaces: false,
|
||||
isMissingWorkspaceDirectory: false,
|
||||
onTerminalCreated: noop,
|
||||
onScriptTerminalSelected: noop,
|
||||
onWorkspacePathUnavailable: noop,
|
||||
onTerminalCreateQueued: noop,
|
||||
onTerminalCreateFailed: noop,
|
||||
};
|
||||
return renderHook(() => useWorkspaceTerminals(input), { wrapper });
|
||||
}
|
||||
|
||||
describe("useWorkspaceTerminals", () => {
|
||||
// Every workspace header and pane takes createTerminal through its menus, so a
|
||||
// new function on an unrelated render re-renders every pane.
|
||||
it("keeps createTerminal stable when the workspace screen re-renders", () => {
|
||||
const { result, rerender } = renderWorkspaceTerminals();
|
||||
const firstCreateTerminal = result.current.createTerminal;
|
||||
|
||||
rerender();
|
||||
|
||||
expect(result.current.createTerminal).toBe(firstCreateTerminal);
|
||||
});
|
||||
});
|
||||
@@ -178,15 +178,18 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
|
||||
onTerminalCreateFailed(error instanceof Error ? error.message : String(error));
|
||||
},
|
||||
});
|
||||
// useMutation returns a new object on every render; depend on its stable
|
||||
// mutate and its pending flag so createTerminal keeps its identity.
|
||||
const { mutate: mutateCreate, isPending: isCreatePending } = createMutation;
|
||||
useEffect(() => {
|
||||
if (!pendingCreateInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (canCreateNow && !createMutation.isPending) {
|
||||
if (canCreateNow && !isCreatePending) {
|
||||
const pendingInput = pendingCreateInput;
|
||||
setPendingCreateInput(null);
|
||||
createMutation.mutate(pendingInput);
|
||||
mutateCreate(pendingInput);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -196,21 +199,22 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
|
||||
}
|
||||
}, [
|
||||
canCreateNow,
|
||||
createMutation,
|
||||
hasHydratedWorkspaces,
|
||||
isCreatePending,
|
||||
isMissingWorkspaceDirectory,
|
||||
mutateCreate,
|
||||
onWorkspacePathUnavailable,
|
||||
pendingCreateInput,
|
||||
]);
|
||||
|
||||
const createTerminal = useCallback(
|
||||
(createInput: PendingTerminalCreateInput) => {
|
||||
if (createMutation.isPending || pendingCreateInput) {
|
||||
if (isCreatePending || pendingCreateInput) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (canCreateNow) {
|
||||
createMutation.mutate(createInput);
|
||||
mutateCreate(createInput);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -224,9 +228,10 @@ export function useWorkspaceTerminals(input: UseWorkspaceTerminalsInput) {
|
||||
},
|
||||
[
|
||||
canCreateNow,
|
||||
createMutation,
|
||||
hasHydratedWorkspaces,
|
||||
isCreatePending,
|
||||
isMissingWorkspaceDirectory,
|
||||
mutateCreate,
|
||||
onTerminalCreateQueued,
|
||||
onWorkspacePathUnavailable,
|
||||
pendingCreateInput,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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.",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -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 "";
|
||||
|
||||
@@ -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();
|
||||
|
||||
@@ -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 "-";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 });
|
||||
}
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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>;
|
||||
@@ -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();
|
||||
},
|
||||
);
|
||||
|
||||
@@ -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://")) {
|
||||
|
||||
@@ -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() }),
|
||||
|
||||
@@ -1,5 +1,18 @@
|
||||
import { AgentMessageSchema } from "./agent-message.js";
|
||||
import { AgentQueueCollection } from "./sync/resources.js";
|
||||
import {
|
||||
DAEMON_PERMISSIONS,
|
||||
DaemonPermissionSchema,
|
||||
type DaemonPermission,
|
||||
} from "./daemon-permissions.js";
|
||||
import {
|
||||
HelloClientInfoSchema,
|
||||
WSClientTypeSchema,
|
||||
DaemonClientsListRequestSchema,
|
||||
DaemonClientsListResponseSchema,
|
||||
DaemonClientsChangedSchema,
|
||||
} from "./daemon-clients.js";
|
||||
export * from "./daemon-clients.js";
|
||||
import {
|
||||
HostsListRequestSchema,
|
||||
HostsAddRequestSchema,
|
||||
@@ -177,19 +190,7 @@ export {
|
||||
// Mutable daemon config schemas (shared between server store and client)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
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>;
|
||||
export { DAEMON_PERMISSIONS, DaemonPermissionSchema, type DaemonPermission };
|
||||
|
||||
export const HexColorSchema = z
|
||||
.string()
|
||||
@@ -3826,6 +3827,7 @@ export const SubscriptionReleaseResponseSchema = z.object({
|
||||
});
|
||||
|
||||
export const SessionInboundMessageSchema = z.discriminatedUnion("type", [
|
||||
DaemonClientsListRequestSchema,
|
||||
HostsListRequestSchema,
|
||||
HostsAddRequestSchema,
|
||||
HostsUpdateRequestSchema,
|
||||
@@ -4316,6 +4318,8 @@ export const ServerInfoStatusPayloadSchema = z
|
||||
// COMPAT(daemonStatusRpc): added in v0.1.76, remove gate after 2026-11-18.
|
||||
daemonStatusRpc: z.boolean().optional(),
|
||||
tailscale: z.boolean().optional(),
|
||||
// COMPAT(connectedClients): added in v0.19.0, remove gate after 2027-06-01.
|
||||
connectedClients: z.boolean().optional(),
|
||||
// COMPAT(daemonConfigReload): added in v0.4.0, remove gate after 2027-02-14.
|
||||
daemonConfigReload: z.boolean().optional(),
|
||||
// COMPAT(speechSettings): added in v0.12.0, remove gate after 2027-04-18.
|
||||
@@ -7547,6 +7551,20 @@ export const UsageReportSchema = z.discriminatedUnion("status", [
|
||||
z.object({ status: z.literal("unavailable"), problem: UsageProblemSchema }),
|
||||
z.object({ status: z.literal("error"), error: z.string() }),
|
||||
]);
|
||||
/**
|
||||
* When a usage source fetches. "manual" fetches only on the user's Refresh, never on a list,
|
||||
* poll or observation. Absent means "automatic".
|
||||
*/
|
||||
export const UsageRefreshSchema = z.enum(["automatic", "manual"]);
|
||||
export type UsageRefresh = z.infer<typeof UsageRefreshSchema>;
|
||||
/**
|
||||
* A report's latest outcome. `not_fetched` is a manual source the user has not refreshed since the
|
||||
* daemon started; sources never return it.
|
||||
*/
|
||||
const UsageEntryReportSchema = z.discriminatedUnion("status", [
|
||||
...UsageReportSchema.options,
|
||||
z.object({ status: z.literal("not_fetched") }),
|
||||
]);
|
||||
export const UsageReportEntrySchema = z.object({
|
||||
id: z.string(),
|
||||
account: z.object({ label: z.string().optional() }),
|
||||
@@ -7556,7 +7574,9 @@ export const UsageReportEntrySchema = z.object({
|
||||
icon: z.string().optional(),
|
||||
/** Host hint for whether this report starts shown until the user overrides it. Absent means true. */
|
||||
defaultEnabled: z.boolean().optional(),
|
||||
report: UsageReportSchema,
|
||||
/** Absent means "automatic". */
|
||||
refresh: UsageRefreshSchema.optional(),
|
||||
report: UsageEntryReportSchema,
|
||||
// Successful completion time; fetchedAt remains the attempt timestamp for ordering.
|
||||
successfulAt: z.string().optional(),
|
||||
lastSuccessful: z
|
||||
@@ -8159,6 +8179,8 @@ export const AgentSkillsImportLegacySelectionResponseSchema = z.object({
|
||||
});
|
||||
|
||||
export const SessionOutboundMessageSchema = z.discriminatedUnion("type", [
|
||||
DaemonClientsListResponseSchema,
|
||||
DaemonClientsChangedSchema,
|
||||
HostsListResponseSchema,
|
||||
HostsChangedSchema,
|
||||
HostsAddResponseSchema,
|
||||
@@ -8965,11 +8987,12 @@ export const WSHelloMessageSchema = z.object({
|
||||
type: z.literal("hello"),
|
||||
sessionPermissions: z.array(DaemonPermissionSchema).optional(),
|
||||
routed: z.boolean().optional(),
|
||||
hostLink: z.boolean().optional(),
|
||||
producer: z
|
||||
.object({ serverId: z.string().min(1).max(256), sourceId: z.string().min(1).max(1024) })
|
||||
.optional(),
|
||||
clientId: z.string().min(1),
|
||||
clientType: z.enum(["mobile", "browser", "cli", "mcp", "hub"]),
|
||||
clientType: WSClientTypeSchema,
|
||||
protocolVersion: z.number().int(),
|
||||
auth: z
|
||||
.discriminatedUnion("kind", [
|
||||
@@ -8978,6 +9001,8 @@ export const WSHelloMessageSchema = z.object({
|
||||
])
|
||||
.optional(),
|
||||
appVersion: z.string().optional(),
|
||||
// COMPAT(connectedClients): added in v0.19.0; older clients omit clientInfo and older daemons ignore it.
|
||||
clientInfo: HelloClientInfoSchema.optional(),
|
||||
capabilities: z
|
||||
.object({
|
||||
voice: z.boolean().optional(),
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { buildSshTunnelArgs, parseSshTransportUri, validateSshHost } from "./ssh-transport.js";
|
||||
import {
|
||||
buildSshTunnelArgs,
|
||||
parseSshTransportUri,
|
||||
serializeSshTransportUri,
|
||||
validateSshHost,
|
||||
} from "./ssh-transport.js";
|
||||
|
||||
describe("SSH transport", () => {
|
||||
it("parses SSH targets with Paseo's default daemon port", () => {
|
||||
@@ -63,4 +68,23 @@ describe("SSH transport", () => {
|
||||
it.each(["", "-oProxyCommand=bad", "bad host"])("rejects unsafe SSH host %j", (host) => {
|
||||
expect(() => validateSshHost(host)).toThrow();
|
||||
});
|
||||
|
||||
it.each([
|
||||
[{ host: "build-box", daemonPort: 6767 }, "ssh://build-box"],
|
||||
[
|
||||
{ host: "deploy@example.com", sshPort: 2222, daemonPort: 7777 },
|
||||
"ssh://deploy@example.com:2222?daemonPort=7777",
|
||||
],
|
||||
[{ host: "::1", sshPort: 2222, daemonPort: 6767 }, "ssh://[::1]:2222"],
|
||||
[{ host: "[::1]", sshPort: 2222, daemonPort: 6767 }, "ssh://[::1]:2222"],
|
||||
[{ host: "me@[::1]", daemonPort: 7000 }, "ssh://me@[::1]?daemonPort=7000"],
|
||||
[{ host: "me@fe80::1", daemonPort: 6767 }, "ssh://me@[fe80::1]"],
|
||||
[{ host: "first.last+ci@box", daemonPort: 6767 }, "ssh://first.last%2Bci@box"],
|
||||
])("serializes %o as %s and parses it back", (target, uri) => {
|
||||
expect(serializeSshTransportUri(target)).toBe(uri);
|
||||
const parsed = parseSshTransportUri(uri);
|
||||
expect(serializeSshTransportUri(parsed)).toBe(uri);
|
||||
expect(parsed.sshPort).toBe(target.sshPort);
|
||||
expect(parsed.daemonPort).toBe(target.daemonPort);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -60,6 +60,26 @@ export function parseSshTransportUri(value: string): SshTransportTarget {
|
||||
};
|
||||
}
|
||||
|
||||
/** The `ssh://` URI that {@link parseSshTransportUri} reads back as this target. */
|
||||
export function serializeSshTransportUri(
|
||||
target: Omit<SshTransportTarget, "daemonPort"> & { daemonPort?: number },
|
||||
): string {
|
||||
const host = validateSshHost(target.host);
|
||||
const at = host.lastIndexOf("@");
|
||||
const user = at >= 0 ? host.slice(0, at) : "";
|
||||
const hostname = (at >= 0 ? host.slice(at + 1) : host).replace(/^\[(.*)\]$/u, "$1");
|
||||
const sshPort =
|
||||
target.sshPort === undefined ? "" : `:${validatePort(target.sshPort, "SSH port")}`;
|
||||
const daemonPort =
|
||||
target.daemonPort === undefined
|
||||
? DEFAULT_SSH_DAEMON_PORT
|
||||
: validatePort(target.daemonPort, "Daemon port");
|
||||
const query = daemonPort === DEFAULT_SSH_DAEMON_PORT ? "" : `?daemonPort=${daemonPort}`;
|
||||
return `ssh://${user ? `${encodeURIComponent(user)}@` : ""}${
|
||||
hostname.includes(":") ? `[${hostname}]` : hostname
|
||||
}${sshPort}${query}`;
|
||||
}
|
||||
|
||||
export function buildSshTunnelArgs(target: SshTransportTarget): string[] {
|
||||
const host = validateSshHost(target.host);
|
||||
const daemonPort = validatePort(target.daemonPort, "Daemon port");
|
||||
|
||||
@@ -8,7 +8,8 @@ import type { AgentToolResult } from "@getpaseo/plugin/server";
|
||||
import type { RuntimeCleanupCandidate } from "./idle-runtime-cleanup/index.js";
|
||||
import { AgentNotFoundError, ensureAgentLoaded } from "./agent-loading.js";
|
||||
import { AgentTurnBusyError, AgentTurnChangedError } from "./agent-prompt.js";
|
||||
import { lastAssistantMessageText, TimelineProjection } from "./timeline-projection.js";
|
||||
import { TimelineProjection } from "./timeline-projection.js";
|
||||
import { lastAssistantMessageText } from "./assistant-message.js";
|
||||
import type { PluginLifecycle } from "../plugins/lifecycle/index.js";
|
||||
import { describeHookAgent, publishAgentStream } from "../plugins/lifecycle/index.js";
|
||||
import { applyRecordPatch } from "../record-patch.js";
|
||||
|
||||
@@ -216,6 +216,14 @@ export interface AgentMessageDelivery {
|
||||
withdrawPending(recipientId: string, matches: (source: AgentPromptSource) => boolean): number;
|
||||
/** The recipient's saved queue changed. */
|
||||
onChange(listener: (recipientId: string) => void): () => void;
|
||||
/** A message was admitted to a recipient's queue. */
|
||||
onEnqueued(
|
||||
listener: (message: {
|
||||
recipientId: string;
|
||||
id: string;
|
||||
source: AgentPromptSource | null;
|
||||
}) => void,
|
||||
): () => void;
|
||||
/** A message left the queue without being delivered. */
|
||||
onWithdrawn(
|
||||
listener: (message: { recipientId: string; id: string }) => void | Promise<void>,
|
||||
@@ -335,6 +343,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
/** Store writes that no caller awaits. Shutdown waits for them. */
|
||||
const writes = new Set<Promise<void>>();
|
||||
const changeListeners = new Set<(recipientId: string) => void>();
|
||||
const enqueuedListeners = new Set<Parameters<AgentMessageDelivery["onEnqueued"]>[0]>();
|
||||
const withdrawnListeners = new Set<Parameters<AgentMessageDelivery["onWithdrawn"]>[0]>();
|
||||
let closed = false;
|
||||
let closing: Promise<void> | undefined;
|
||||
@@ -351,6 +360,19 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
for (const listener of changeListeners) listener(recipientId);
|
||||
}
|
||||
|
||||
function announceEnqueued(
|
||||
recipientId: string,
|
||||
id: string,
|
||||
source: AgentPromptSource | null,
|
||||
): void {
|
||||
for (const listener of enqueuedListeners)
|
||||
try {
|
||||
listener({ recipientId, id, source });
|
||||
} catch (error) {
|
||||
report(error, recipientId, [id]);
|
||||
}
|
||||
}
|
||||
|
||||
async function announceWithdrawn(recipientId: string, id: string): Promise<void> {
|
||||
for (const listener of withdrawnListeners)
|
||||
try {
|
||||
@@ -1059,6 +1081,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
// Its place is taken now, so a Stop or a prompt sent during the write finds it.
|
||||
if (item.state === "queued") admit(item);
|
||||
await item.saved;
|
||||
announceEnqueued(recipientId, id, source);
|
||||
return item.receipt;
|
||||
},
|
||||
sendDirect<Result extends PromptDispatchResult>(
|
||||
@@ -1167,6 +1190,10 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
changeListeners.add(listener);
|
||||
return () => changeListeners.delete(listener);
|
||||
},
|
||||
onEnqueued(listener) {
|
||||
enqueuedListeners.add(listener);
|
||||
return () => enqueuedListeners.delete(listener);
|
||||
},
|
||||
onWithdrawn(listener) {
|
||||
withdrawnListeners.add(listener);
|
||||
return () => withdrawnListeners.delete(listener);
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { AgentTimelineItem } from "./agent-sdk-types.js";
|
||||
import type { AgentTimelineRow } from "./agent-timeline-store-types.js";
|
||||
|
||||
type MessageRow = Pick<AgentTimelineRow, "item" | "turnId">;
|
||||
type AssistantMessage = Extract<AgentTimelineItem, { type: "assistant_message" }>;
|
||||
|
||||
/** A turn or message ID change starts a new reply, including in replayed history. */
|
||||
export function continuesAssistantMessage(previous: MessageRow, next: MessageRow): boolean {
|
||||
return (
|
||||
previous.item.type === "assistant_message" &&
|
||||
next.item.type === "assistant_message" &&
|
||||
previous.turnId === next.turnId &&
|
||||
(next.item.messageId === undefined || next.item.messageId === previous.item.messageId)
|
||||
);
|
||||
}
|
||||
|
||||
export function lastAssistantMessageText(rows: readonly MessageRow[]): string | null {
|
||||
function* newestFirst() {
|
||||
for (let index = rows.length - 1; index >= 0; index--) yield rows[index];
|
||||
}
|
||||
return readLastAssistantMessage(newestFirst());
|
||||
}
|
||||
|
||||
/** The row order lets durable backends load text only for chunks in the selected reply. */
|
||||
export function readLastAssistantMessage<Row extends MessageRow>(
|
||||
newestFirst: Iterable<Row>,
|
||||
readText: (row: Row, item: AssistantMessage) => string = (_row, item) => item.text,
|
||||
): string | null {
|
||||
const chunks: string[] = [];
|
||||
let next: { item: AssistantMessage; turnId: string | undefined } | undefined;
|
||||
|
||||
for (const row of newestFirst) {
|
||||
const { item, turnId } = row;
|
||||
if (next && !continuesAssistantMessage(row, next)) {
|
||||
// A notice can interrupt a stream. Only a matching message ID can join chunks across it.
|
||||
if (
|
||||
item.type === "notification" &&
|
||||
next.item.messageId !== undefined &&
|
||||
(turnId === undefined || turnId === next.turnId)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
}
|
||||
if (item.type === "assistant_message") {
|
||||
chunks.push(readText(row, item));
|
||||
next = { item, turnId };
|
||||
}
|
||||
}
|
||||
return chunks.length ? chunks.toReversed().join("") : null;
|
||||
}
|
||||
+180
-1
@@ -17,6 +17,7 @@ import {
|
||||
createJsonFinishSubscriptionStore,
|
||||
type FinishMessages,
|
||||
type FinishObservation,
|
||||
type FinishObservationReportTracker,
|
||||
type FinishSubscription,
|
||||
type FinishSubscriptions,
|
||||
type PendingWork,
|
||||
@@ -38,13 +39,19 @@ class Observation implements FinishObservation {
|
||||
childAgentId: string;
|
||||
result: ReturnType<typeof deferred<FinishObservationResult>>;
|
||||
}> = [];
|
||||
trackers = new Map<string, FinishObservationReportTracker>();
|
||||
permission = deferred<void>();
|
||||
opening: Promise<void> = Promise.resolve();
|
||||
openedSignals: AbortSignal[] = [];
|
||||
/** Work that will start each child's next turn by itself, as the local host reports it. */
|
||||
work = new Map<string, PendingWork[]>();
|
||||
async open(record: FinishSubscription, signal: AbortSignal) {
|
||||
async open(
|
||||
record: FinishSubscription,
|
||||
signal: AbortSignal,
|
||||
reportTracker?: FinishObservationReportTracker,
|
||||
) {
|
||||
this.openedSignals.push(signal);
|
||||
if (reportTracker) this.trackers.set(record.childAgentId, reportTracker);
|
||||
await this.opening;
|
||||
return { next: () => this.wait(record.childAgentId, signal), close: async () => {} };
|
||||
}
|
||||
@@ -70,6 +77,7 @@ class Delivery implements FinishMessages {
|
||||
/** Prompts as the recipient's provider receives them, inside their envelope. */
|
||||
enqueued: string[] = [];
|
||||
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
|
||||
enqueuedListeners = new Set<Parameters<FinishMessages["onEnqueued"]>[0]>();
|
||||
async enqueue(message: Parameters<FinishMessages["enqueue"]>[0]) {
|
||||
this.prompts.push(message.text);
|
||||
this.enqueued.push(
|
||||
@@ -81,6 +89,12 @@ class Delivery implements FinishMessages {
|
||||
);
|
||||
const acknowledgment = deferred<"steered">();
|
||||
this.acknowledgments.push(acknowledgment);
|
||||
for (const listener of this.enqueuedListeners)
|
||||
listener({
|
||||
recipientId: message.recipientId,
|
||||
id: message.messageId ?? "notification",
|
||||
source: message.source ?? null,
|
||||
});
|
||||
return {
|
||||
status: "queued" as const,
|
||||
messageId: "notification",
|
||||
@@ -95,6 +109,10 @@ class Delivery implements FinishMessages {
|
||||
hasPending() {
|
||||
return false;
|
||||
}
|
||||
onEnqueued(listener: Parameters<FinishMessages["onEnqueued"]>[0]) {
|
||||
this.enqueuedListeners.add(listener);
|
||||
return () => this.enqueuedListeners.delete(listener);
|
||||
}
|
||||
async waitForDispatch() {}
|
||||
}
|
||||
const homes: string[] = [];
|
||||
@@ -889,3 +907,164 @@ test("daemon-level agentMessages.withdraw cancels a pending FinishSubscription v
|
||||
await agentMessages.close();
|
||||
}
|
||||
});
|
||||
|
||||
describe("suppressing redundant finished notices after an explicit child report", () => {
|
||||
test("a child that messages its caller and finishes cleanly ends the watch without a finished notice", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
await state.delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
text: "Here is the full report.",
|
||||
source: { kind: "agent-message", agentId: "child", title: "Child" },
|
||||
});
|
||||
expect(state.delivery.prompts).toHaveLength(1);
|
||||
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "Sent report to parent."));
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
expect(state.service.hasPendingForCaller("parent")).toBe(false);
|
||||
expect(state.delivery.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("an error or close after a child message is still delivered", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
await state.delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
text: "Partial update",
|
||||
source: { kind: "agent-message", agentId: "child", title: "Child" },
|
||||
});
|
||||
|
||||
state.observation.waits[0]!.result.resolve(outcome("error", "child", "Crashed afterwards"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("errored");
|
||||
state.delivery.acknowledgments[1]!.resolve("steered");
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
});
|
||||
|
||||
test("a pending follow-up subscription is not marked reported by the previous turn's message", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
// Parent queued a follow-up prompt whose watch is still waiting for dispatch.
|
||||
const nextTurn = await state.service.register(intent, true);
|
||||
|
||||
// Child finishes turn 1 by reporting to parent.
|
||||
await state.delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
text: "Turn 1 report",
|
||||
source: { kind: "agent-message", agentId: "child", title: "Child" },
|
||||
});
|
||||
|
||||
// Follow-up dispatches and supersedes turn 1's watch.
|
||||
nextTurn.accept();
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
|
||||
// Turn 2 finishes without sending another explicit message: parent must be notified.
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle", "child", "Turn 2 final answer"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
|
||||
expect(state.delivery.prompts[1]).toContain("Turn 2 final answer");
|
||||
});
|
||||
|
||||
test("a child that reports while pending work remains follows silently and notifies when a later turn finishes", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
await state.delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
text: "Started the background build",
|
||||
source: { kind: "agent-message", agentId: "child", title: "Child" },
|
||||
});
|
||||
state.observation.work.set("child", ["background work"]);
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "Sent update to parent."));
|
||||
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
expect(state.delivery.prompts).toHaveLength(1);
|
||||
|
||||
// Background work wakes the child for a new turn, which clears the prior turn's report.
|
||||
state.observation.trackers.get("child")!.onActivity({ type: "turn_started" });
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[1]!.result.resolve(outcome("idle", "child", "Build passed"));
|
||||
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Agent child (Child) finished.");
|
||||
expect(state.delivery.prompts[1]).toContain("Build passed");
|
||||
});
|
||||
|
||||
test("a child that reports while pending work remains ends silently if that work clears without another turn", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
await state.delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
text: "Done (background server still running)",
|
||||
source: { kind: "agent-message", agentId: "child", title: "Child" },
|
||||
});
|
||||
state.observation.work.set("child", ["background work"]);
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "Sent report to parent."));
|
||||
await until(() => state.observation.waits.length === 2);
|
||||
|
||||
state.observation.work.set("child", []);
|
||||
state.observation.waits[1]!.result.resolve({
|
||||
...outcome("idle", "child", "Sent report to parent."),
|
||||
workChanged: true,
|
||||
});
|
||||
await expect.poll(async () => (await state.store.list()).length).toBe(0);
|
||||
expect(state.delivery.prompts).toHaveLength(1);
|
||||
});
|
||||
|
||||
test("remote child report suppresses redundant finished even when a pre-send tool frame arrives late, and still clears on post-send work", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register({
|
||||
callerAgentId: "parent",
|
||||
childAgentId: "remote-child",
|
||||
serverId: "remote-host",
|
||||
});
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
const tracker = state.observation.trackers.get("remote-child")!;
|
||||
|
||||
// Remote send_agent_message arrives before earlier observation stream frames drain.
|
||||
await state.delivery.enqueue({
|
||||
recipientId: "parent",
|
||||
text: "Remote report",
|
||||
source: { kind: "agent-message", agentId: "remote-child", serverId: "remote-host" },
|
||||
});
|
||||
// Turn 1's own turn_started arriving late over the observation stream must not clear the report.
|
||||
tracker.onActivity({ type: "turn_started" });
|
||||
tracker.onActivity({ type: "tool_call", callId: "old-read", name: "Read", status: "running" });
|
||||
tracker.onActivity({
|
||||
type: "tool_call",
|
||||
callId: "old-read",
|
||||
name: "Read",
|
||||
status: "completed",
|
||||
});
|
||||
tracker.onActivity({
|
||||
type: "tool_call",
|
||||
callId: "send-1",
|
||||
name: "mcp__paseo__send_agent_prompt",
|
||||
status: "running",
|
||||
});
|
||||
tracker.onActivity({
|
||||
type: "tool_call",
|
||||
callId: "send-1",
|
||||
name: "mcp__paseo__send_agent_prompt",
|
||||
status: "completed",
|
||||
});
|
||||
expect(tracker.isReported()).toBe(true);
|
||||
|
||||
// Subsequent tool work after the send tool clears the mark.
|
||||
tracker.onActivity({ type: "tool_call", callId: "bash-2", name: "Bash", status: "running" });
|
||||
expect(tracker.isReported()).toBe(false);
|
||||
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "remote-child", "Done after bash"));
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Done after bash");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
type FollowOutcome,
|
||||
type Notice,
|
||||
} from "./internal/following.js";
|
||||
import { createReportTracker, type ReportTracker } from "./internal/report-tracker.js";
|
||||
export { createJsonFinishSubscriptionStore } from "./internal/json-store.js";
|
||||
|
||||
export interface FinishSubscription {
|
||||
@@ -52,10 +53,15 @@ export interface FinishObservationSession {
|
||||
/** What finish subscriptions need from message delivery. */
|
||||
export type FinishMessages = Pick<
|
||||
AgentMessageDelivery,
|
||||
"dispatchOf" | "enqueue" | "hasPending" | "waitForDispatch"
|
||||
"dispatchOf" | "enqueue" | "hasPending" | "onEnqueued" | "waitForDispatch"
|
||||
>;
|
||||
export type FinishObservationReportTracker = Pick<ReportTracker, "onActivity" | "isReported">;
|
||||
export interface FinishObservation {
|
||||
open(subscription: FinishSubscription, signal: AbortSignal): Promise<FinishObservationSession>;
|
||||
open(
|
||||
subscription: FinishSubscription,
|
||||
signal: AbortSignal,
|
||||
reportTracker?: FinishObservationReportTracker,
|
||||
): Promise<FinishObservationSession>;
|
||||
/** The child's own pending work. Empty when its host cannot tell, as for remote children. */
|
||||
pendingWork(subscription: FinishSubscription): readonly PendingWork[];
|
||||
}
|
||||
@@ -93,11 +99,14 @@ interface Watch {
|
||||
decision: Promise<boolean>;
|
||||
decide(accepted: boolean): void;
|
||||
pending: boolean;
|
||||
reportTracker: ReportTracker;
|
||||
task?: Promise<void>;
|
||||
/** Decides a followed child's state again; see `createFollowing`. */
|
||||
recheck?(): void;
|
||||
}
|
||||
function key(record: FinishSubscription): string {
|
||||
function key(
|
||||
record: Pick<FinishSubscription, "callerAgentId" | "childAgentId" | "serverId">,
|
||||
): string {
|
||||
return JSON.stringify([record.callerAgentId, record.childAgentId, record.serverId]);
|
||||
}
|
||||
const DEFAULT_FOLLOW_LIMIT_MS = 24 * 60 * 60_000;
|
||||
@@ -108,8 +117,29 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
const watches = new Map<string, Set<Watch>>();
|
||||
let closed = false;
|
||||
let recovering = true;
|
||||
let unsubscribeEnqueued: (() => void) | undefined;
|
||||
const registering = new Map<string, number>();
|
||||
let mutations = Promise.resolve();
|
||||
function normalizeServerId(serverId: string | undefined): string | undefined {
|
||||
return serverId === deps.serverId ? undefined : serverId;
|
||||
}
|
||||
function ensureMessageSubscription(): void {
|
||||
if (unsubscribeEnqueued || closed) return;
|
||||
unsubscribeEnqueued = deps.messages().onEnqueued(({ recipientId, source }) => {
|
||||
if (source?.kind !== "agent-message") return;
|
||||
const group = watches.get(
|
||||
key({
|
||||
callerAgentId: recipientId,
|
||||
childAgentId: source.agentId,
|
||||
serverId: normalizeServerId(source.serverId),
|
||||
}),
|
||||
);
|
||||
if (!group) return;
|
||||
for (const watch of group) {
|
||||
if (!watch.pending) watch.reportTracker.markReported();
|
||||
}
|
||||
});
|
||||
}
|
||||
function serialize<T>(action: () => Promise<T>): Promise<T> {
|
||||
const result = mutations.then(action);
|
||||
mutations = result.then(
|
||||
@@ -123,7 +153,14 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
const decision = new Promise<boolean>((resolve) => {
|
||||
decide = resolve;
|
||||
});
|
||||
const watch: Watch = { records, controller: new AbortController(), pending, decision, decide };
|
||||
const watch: Watch = {
|
||||
records,
|
||||
controller: new AbortController(),
|
||||
pending,
|
||||
decision,
|
||||
decide,
|
||||
reportTracker: createReportTracker({ remote: Boolean(records[0]!.serverId) }),
|
||||
};
|
||||
const group = watches.get(key(records[0]!)) ?? new Set<Watch>();
|
||||
group.add(watch);
|
||||
watches.set(key(records[0]!), group);
|
||||
@@ -367,6 +404,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
store: deps.store,
|
||||
limitMs: deps.followLimitMs ?? DEFAULT_FOLLOW_LIMIT_MS,
|
||||
pendingWork: () => pendingWork(record),
|
||||
reportedToCaller: () => watch.reportTracker.isReported(),
|
||||
onTurnCompleted: () => watch.reportTracker.onActivity({ type: "turn_completed" }),
|
||||
reasonFor,
|
||||
});
|
||||
watch.recheck = following.recheck;
|
||||
@@ -379,7 +418,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
let warned = false;
|
||||
async function observeNext(): Promise<FollowOutcome | undefined> {
|
||||
try {
|
||||
observation ??= await deps.open(record, signal);
|
||||
observation ??= await deps.open(record, signal, watch.reportTracker);
|
||||
const result = await following.next(abortable(observation.next(), signal), signal);
|
||||
remoteFailures = 0;
|
||||
return result;
|
||||
@@ -477,6 +516,7 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
},
|
||||
start: () =>
|
||||
serialize(async () => {
|
||||
ensureMessageSubscription();
|
||||
const groups = new Map<string, FinishSubscription[]>();
|
||||
for (const record of await deps.store.list()) {
|
||||
const records = groups.get(key(record)) ?? [];
|
||||
@@ -490,9 +530,10 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
registering.set(input.callerAgentId, (registering.get(input.callerAgentId) ?? 0) + 1);
|
||||
return serialize(async () => {
|
||||
if (closed) throw new Error("Finish subscriptions are closed");
|
||||
ensureMessageSubscription();
|
||||
const record: FinishSubscription = {
|
||||
...input,
|
||||
serverId: input.serverId === deps.serverId ? undefined : input.serverId,
|
||||
serverId: normalizeServerId(input.serverId),
|
||||
id: randomUUID(),
|
||||
};
|
||||
await deps.store.put(record);
|
||||
@@ -523,6 +564,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
}),
|
||||
async close() {
|
||||
closed = true;
|
||||
unsubscribeEnqueued?.();
|
||||
unsubscribeEnqueued = undefined;
|
||||
await mutations;
|
||||
for (const group of watches.values())
|
||||
for (const watch of group) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user