mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-01 12:46:55 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d6c943c8d7 |
+11
-17
@@ -236,23 +236,17 @@ 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, 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`.
|
||||
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`.
|
||||
|
||||
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. 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.
|
||||
- **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.
|
||||
- **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,19 +49,11 @@ 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.
|
||||
|
||||
## Markdown parsing cost
|
||||
## Native 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.
|
||||
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.
|
||||
|
||||
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.
|
||||
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.
|
||||
|
||||
## 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. 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.
|
||||
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.
|
||||
|
||||
## 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 parts 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 and tail) use the same gap through `MarkdownBlockStack`. Do not give a block type its own margins; change the gap.
|
||||
|
||||
## Links and images
|
||||
|
||||
@@ -58,7 +58,7 @@ On iOS a newly mounted Markdown view paints empty for a frame or more after it i
|
||||
|
||||
Android measurements use a size-only, 512-entry LRU across view unmounts, matching the library’s existing iOS cache. Scrolling back through history can reuse layout sizes without parsing those rows again. Content, layout props and width identify each entry; font-scale changes and native layout invalidation discard affected sizes. The cache retains no views or spans.
|
||||
|
||||
While `streaming` is true, `stabilizeStreamingMarkdown` in `components/markdown/streaming.ts` closes unfinished inline constructs (code spans, emphasis, strikethrough, links) and withholds incomplete block prefixes (headings, Setext underlines after paragraphs, list/task markers, empty quotes and admonitions, opening and partial closing code fences, unconfirmed tables, images and HTML tags/comments) before `prepareMarkdownSource` runs. Incomplete links render with link styling through `PENDING_MARKDOWN_LINK` without becoming interactive anchors or opening link actions until their destination closes. Completed text bypasses stabilization and uses the same component and engine as history. Find and scroll-to-message address source message ids; selection-copy understands semantic HTML and the web code component's copy metadata.
|
||||
The library determines how incomplete Markdown appears during streaming. Completed text uses the same component and engine as history. Find and scroll-to-message address source message ids; selection-copy understands semantic HTML and the web code component's copy metadata.
|
||||
|
||||
## Verification
|
||||
|
||||
|
||||
@@ -94,11 +94,6 @@ 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,10 +172,9 @@ 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 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
|
||||
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
|
||||
alone cannot certify that the displayed conversation is current. The timeline owner publishes freshness; the view renders it without a toast timer or a
|
||||
separate resume workflow.
|
||||
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
sha256-04BfmBEaEZy3ohSi3Z8S3/a3xBsLKhls+8mcjJ0Y2/A=
|
||||
sha256-ZVIrRfb7oyTwx7kz6F51hs/ctT45qUdZM4v0QRLW9zA=
|
||||
|
||||
Generated
-1
@@ -39975,7 +39975,6 @@
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@getpaseo/cli": "*",
|
||||
"@getpaseo/client": "*",
|
||||
"@getpaseo/server": "*",
|
||||
"electron-log": "^5.4.3",
|
||||
"electron-updater": "^6.6.2",
|
||||
|
||||
@@ -14,7 +14,6 @@ import {
|
||||
answerFreshnessCheck,
|
||||
commitTimelineTurnsWhileDisconnected,
|
||||
disconnectViewedTimeline,
|
||||
expectCleanLoadingSurfaces,
|
||||
expectEmptyChatSynced,
|
||||
expectPromptAndWholeReply,
|
||||
expectResumeAnsweredWithoutFetch,
|
||||
@@ -30,10 +29,8 @@ import {
|
||||
seedStreamingReplyAgent,
|
||||
sendPromptWhileDisconnected,
|
||||
stopStreamingReply,
|
||||
waitForDisplayOnlyTimelineCache,
|
||||
waitForResumeAnswer,
|
||||
reopenAppWatchingForUpdatingToast,
|
||||
watchColdAndReloadLoadingSurfaces,
|
||||
watchForUpdatingToast,
|
||||
} from "../support/helpers/timeline-resume";
|
||||
|
||||
@@ -179,36 +176,4 @@ 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
expectHostBadgeIconOnly,
|
||||
expectHostBadgeName,
|
||||
expectHostBadgeTinted,
|
||||
expectHostSelectorStatusIcon,
|
||||
expectNoHostBadge,
|
||||
leaveHostAppearanceSettings,
|
||||
openHostAppearanceSettings,
|
||||
@@ -117,29 +116,14 @@ test("customizes a host badge and preserves its appearance after reload", async
|
||||
expect(widths.content).toBeLessThanOrEqual(widths.client);
|
||||
});
|
||||
|
||||
await test.step("preview a color and icon and apply them to the sidebar badge, host selectors, and host popover", async () => {
|
||||
await test.step("preview a color and icon and apply them to the sidebar badge and host popover", async () => {
|
||||
await openHostAppearanceSettings(page, badge.serverId);
|
||||
await chooseHostColor(page, "Teal");
|
||||
await chooseHostIcon(page, "Laptop");
|
||||
await expectHostAppearancePreview(page, { serverId: badge.serverId, hostName, color: "teal" });
|
||||
|
||||
// The Settings sidebar host selector shows the host's resolved icon badged with its status dot.
|
||||
const settingsHostPicker = page.getByTestId("settings-host-picker");
|
||||
await settingsHostPicker.click();
|
||||
await page.getByTestId(`settings-host-picker-item-${badge.serverId}`).click();
|
||||
await expectHostSelectorStatusIcon(settingsHostPicker, { color: "teal" });
|
||||
|
||||
await leaveHostAppearanceSettings(page);
|
||||
await expectHostBadgeTinted(page, { ...badge, hostName, color: "teal" });
|
||||
|
||||
// The New Workspace host selector also shows the host icon with its status dot.
|
||||
await page.getByTestId("sidebar-global-new-workspace").click();
|
||||
const newWorkspaceHostTrigger = page.getByTestId("host-picker-trigger");
|
||||
await expect(newWorkspaceHostTrigger).toBeVisible();
|
||||
await newWorkspaceHostTrigger.click();
|
||||
await page.getByTestId(`new-workspace-host-picker-option-${badge.serverId}`).click();
|
||||
await expectHostSelectorStatusIcon(newWorkspaceHostTrigger, { color: "teal" });
|
||||
|
||||
await page.getByTestId("sidebar-hosts-trigger").click();
|
||||
const hostRow = page.getByTestId(`sidebar-host-row-${badge.serverId}`);
|
||||
await expect(hostRow).toBeVisible();
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import { createHostClient } from "@getpaseo/client/node";
|
||||
import { expect } from "@playwright/test";
|
||||
import { gotoAppShell, openSettings } from "../support/helpers/app";
|
||||
import {
|
||||
addDirectHostFromSettings,
|
||||
@@ -26,51 +24,11 @@ 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 },
|
||||
@@ -123,7 +81,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(180_000);
|
||||
test.setTimeout(120_000);
|
||||
if (!baseURL) throw new Error("Expected the app base URL");
|
||||
const daemon = await startTailscaleTestDaemon(baseURL);
|
||||
try {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
import path from "node:path";
|
||||
import { expect } from "../support/fixtures";
|
||||
import {
|
||||
test,
|
||||
expectStillBrowsing,
|
||||
@@ -24,59 +22,3 @@ test("installs a listed plugin from Browse and uninstalls it from either of its
|
||||
await openFromInstalledTab(page);
|
||||
await uninstallFromPage(page);
|
||||
});
|
||||
|
||||
test("shows scorecard progressive disclosure, updates, custom links, and related plugins", async ({
|
||||
page,
|
||||
directoryHost,
|
||||
}) => {
|
||||
const captureDir = process.env.PASEO_CAPTURE_DIR;
|
||||
if (captureDir) {
|
||||
await page.emulateMedia({ colorScheme: "dark" });
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 960 });
|
||||
await openDirectory(page, directoryHost);
|
||||
await openListingPage(page);
|
||||
|
||||
await expect(page.getByText("Related plugins", { exact: true })).toBeVisible();
|
||||
await expect(page.getByTestId("plugin-related-acme/pr-radar")).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-overview.png") });
|
||||
}
|
||||
|
||||
// Open Scorecard tab and expand a capability row.
|
||||
await page.getByTestId("plugin-page-tab-scorecard").click();
|
||||
await expect(page.getByText("This plugin is actively maintained.")).toBeVisible();
|
||||
const panelRow = page.getByRole("button", { name: /Workspace panel/ });
|
||||
await panelRow.click();
|
||||
await expect(page.getByText(/index\.client\.ts/)).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-scorecard.png") });
|
||||
}
|
||||
|
||||
// Open Updates tab and custom actions menu.
|
||||
await page.getByTestId("plugin-page-tab-updates").click();
|
||||
await expect(page.getByText("v1.2.0", { exact: true })).toBeVisible();
|
||||
await expect(page.getByText("c81a4f2", { exact: true })).toBeVisible();
|
||||
await page.getByTestId("plugin-actions-acme/directory-example").click();
|
||||
await expect(page.getByText("Documentation", { exact: true })).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-desktop-updates.png") });
|
||||
}
|
||||
await page.keyboard.press("Escape");
|
||||
|
||||
// Verify compact mobile layout on the same listing page.
|
||||
await page.setViewportSize({ width: 390, height: 844 });
|
||||
await page.getByTestId("plugin-page-tab-scorecard").click();
|
||||
await expect(page.getByText("This plugin is actively maintained.")).toBeVisible();
|
||||
|
||||
if (captureDir) {
|
||||
await page.waitForTimeout(300);
|
||||
await page.screenshot({ path: path.join(captureDir, "live-app-mobile-scorecard.png") });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -34,9 +34,7 @@ function report(input: {
|
||||
sourceLabel: input.sourceLabel,
|
||||
icon: ICON,
|
||||
report:
|
||||
input.report.status === "error" ||
|
||||
input.report.status === "unavailable" ||
|
||||
input.report.status === "not_fetched"
|
||||
input.report.status === "error" || input.report.status === "unavailable"
|
||||
? input.report
|
||||
: {
|
||||
status: "available",
|
||||
@@ -140,45 +138,6 @@ 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();
|
||||
|
||||
@@ -17,7 +17,6 @@ import { getServerId } from "../support/helpers/server-id";
|
||||
import {
|
||||
clickArchiveWorkspaceMenuItem,
|
||||
expectWorkspaceAbsentFromSidebar,
|
||||
selectSidebarStatusGrouping,
|
||||
} from "../support/helpers/sidebar";
|
||||
import { createTempGitRepo } from "../support/helpers/workspace";
|
||||
import {
|
||||
@@ -101,7 +100,7 @@ async function clickRowArchiveButton(page: Page, workspaceId: string): Promise<v
|
||||
}
|
||||
|
||||
function rowArchivePendingIndicator(page: Page, workspaceId: string) {
|
||||
return workspaceRow(page, workspaceId).getByTestId("workspace-archive-pending-indicator");
|
||||
return workspaceRow(page, workspaceId).getByTestId("workspace-status-indicator-loading");
|
||||
}
|
||||
|
||||
async function cycleThemeAndWaitForSidebar(page: Page, workspaceId: string): Promise<void> {
|
||||
@@ -373,38 +372,19 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
expect(existsSync(path.join(worktree.workspaceDirectory, "DIRTY.md"))).toBe(true);
|
||||
});
|
||||
|
||||
test("the row shows a trailing archive spinner without changing status or shifting layout", async ({
|
||||
test("the row shows the archive as pending from the press until the host answers", async ({
|
||||
page,
|
||||
}) => {
|
||||
const worktree = await createWorktree("archive-risk-pending");
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
const row = workspaceRow(page, worktree.workspaceId);
|
||||
const title = page.getByTestId(
|
||||
`sidebar-workspace-title-${getServerId()}:${worktree.workspaceId}`,
|
||||
);
|
||||
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toHaveCount(0);
|
||||
await expect(row.getByTestId("workspace-status-indicator-done")).toBeVisible();
|
||||
|
||||
const idleRowBox = await row.boundingBox();
|
||||
const idleTitleBox = await title.boundingBox();
|
||||
expect(idleRowBox).not.toBeNull();
|
||||
expect(idleTitleBox).not.toBeNull();
|
||||
|
||||
statusRequest.arm();
|
||||
await clickRowArchiveButton(page, worktree.workspaceId);
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await expect(rowArchivePendingIndicator(page, worktree.workspaceId)).toBeVisible();
|
||||
// Leading status must stay done — never turn into the Working status ring.
|
||||
await expect(row.getByTestId("workspace-status-indicator-done")).toBeVisible();
|
||||
await expect(row.getByTestId("workspace-status-indicator-loading")).toHaveCount(0);
|
||||
await expect(row.getByTestId("workspace-status-indicator-running")).toHaveCount(0);
|
||||
|
||||
const archivingRowBox = await row.boundingBox();
|
||||
const archivingTitleBox = await title.boundingBox();
|
||||
expect(archivingRowBox).toEqual(idleRowBox);
|
||||
expect(archivingTitleBox).toEqual(idleTitleBox);
|
||||
expect(statusRequest.archiveRequests()).toBe(0);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
@@ -414,50 +394,6 @@ test.describe("Workspace archive risk warning for worktree backing", () => {
|
||||
await expect(undoButton(page)).toBeVisible();
|
||||
});
|
||||
|
||||
test("status grouping keeps the row in its original group with no Working badge while archiving", async ({
|
||||
page,
|
||||
}) => {
|
||||
const worktree = await createWorktree("archive-risk-status-pending");
|
||||
const statusRequest = await holdCheckoutStatusRequest(page, worktree);
|
||||
await openSidebarRow(page, worktree.workspaceId);
|
||||
await selectSidebarStatusGrouping(page);
|
||||
|
||||
const doneRows = page.getByTestId("sidebar-status-group-rows-done");
|
||||
const row = doneRows.getByTestId(
|
||||
`sidebar-workspace-row-${getServerId()}:${worktree.workspaceId}`,
|
||||
);
|
||||
const title = row.getByTestId(
|
||||
`sidebar-workspace-title-${getServerId()}:${worktree.workspaceId}`,
|
||||
);
|
||||
await expect(row).toBeVisible();
|
||||
await expect(row.getByTestId("project-status-badge")).toHaveCount(0);
|
||||
|
||||
const idleRowBox = await row.boundingBox();
|
||||
const idleTitleBox = await title.boundingBox();
|
||||
expect(idleRowBox).not.toBeNull();
|
||||
expect(idleTitleBox).not.toBeNull();
|
||||
|
||||
statusRequest.arm();
|
||||
await row.hover();
|
||||
await rowArchiveButton(page, worktree.workspaceId).click();
|
||||
await statusRequest.waitForHeld();
|
||||
try {
|
||||
await expect(row.getByTestId("workspace-archive-pending-indicator")).toBeVisible();
|
||||
// Must remain in the Done group and never gain a Working status ring badge.
|
||||
await expect(row).toBeVisible();
|
||||
await expect(row.getByTestId("project-status-badge")).toHaveCount(0);
|
||||
|
||||
const archivingRowBox = await row.boundingBox();
|
||||
const archivingTitleBox = await title.boundingBox();
|
||||
expect(archivingRowBox).toEqual(idleRowBox);
|
||||
expect(archivingTitleBox).toEqual(idleTitleBox);
|
||||
} finally {
|
||||
statusRequest.release();
|
||||
}
|
||||
|
||||
await expectWorkspaceAbsentFromSidebar(page, worktree.workspaceId);
|
||||
});
|
||||
|
||||
test("a worktree holding only new files warns when the repository hides untracked files", async ({
|
||||
page,
|
||||
}) => {
|
||||
|
||||
@@ -13,8 +13,6 @@ 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"));
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expect, type Locator, type Page } from "@playwright/test";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import { identityForeground, type IdentityColorName } from "@/styles/identity-colors";
|
||||
import { openSettings } from "./app";
|
||||
import { buildSeededHost } from "./daemon-registry";
|
||||
@@ -289,20 +289,6 @@ export async function expectHostAppearancePreview(
|
||||
);
|
||||
}
|
||||
|
||||
export async function expectHostSelectorStatusIcon(
|
||||
trigger: Locator,
|
||||
options?: { color?: IdentityColorName },
|
||||
): Promise<void> {
|
||||
const icon = trigger.getByTestId("host-status-icon");
|
||||
await expect(icon).toBeVisible({ timeout: 15_000 });
|
||||
await expect(icon.getByTestId("host-status-icon-dot")).toBeVisible();
|
||||
const svg = icon.locator("svg");
|
||||
await expect(svg).toBeVisible();
|
||||
if (options?.color) {
|
||||
await expect(svg).toHaveAttribute("stroke", identityForeground(options.color, "light"));
|
||||
}
|
||||
}
|
||||
|
||||
// The auto-seed fixture rewrites the host registry on every navigation. Setting the
|
||||
// disable-once flag to the current nonce makes it skip exactly one reload, which is what proves
|
||||
// the appearance survived rather than being reseeded.
|
||||
|
||||
@@ -66,56 +66,6 @@ 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,
|
||||
@@ -124,9 +74,9 @@ export async function preparePairingHost(
|
||||
await openAppOnPairingHost(page, daemon, additionalHosts);
|
||||
await openSettings(page);
|
||||
await openSettingsHost(page, daemon.serverId);
|
||||
await expect(page.getByTestId("devices-pair-button")).toHaveCount(0);
|
||||
await expect(page.getByTestId("devices-relay")).toHaveCount(0);
|
||||
await openSettingsHostSection(page, daemon.serverId, "devices");
|
||||
await openPairDeviceWaysSheet(page);
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
}
|
||||
|
||||
/** Loads the app afresh with `daemon` as its first host, then opens the setup's Mobile step. */
|
||||
@@ -235,12 +185,10 @@ export async function cancelTailscaleTurnOff(page: Page, address: string): Promi
|
||||
*/
|
||||
export async function confirmTailscaleTurnOff(page: Page, address: string): Promise<void> {
|
||||
const question = answerNextDialog(page, "accept");
|
||||
const sheet = page.getByTestId("devices-pair-sheet");
|
||||
const scope = (await sheet.isVisible()) ? sheet : page;
|
||||
await scope.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
await page.getByRole("switch", { name: "Tailscale", exact: true }).click();
|
||||
expect(await question).toBe(TURN_OFF_QUESTION);
|
||||
await expect(scope.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(scope.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expect(page.getByText("Host is not connected", { exact: true })).toBeVisible();
|
||||
await expect(page.getByRole("switch", { name: "Tailscale", exact: true })).toHaveCount(0);
|
||||
await expectHostUnreachableAt(address);
|
||||
}
|
||||
|
||||
@@ -424,12 +372,9 @@ function deliverInOrderAfter(delay: () => number, deliver: (message: string | Bu
|
||||
}
|
||||
|
||||
export async function expectTailscaleUpdateRequired(page: Page): Promise<void> {
|
||||
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();
|
||||
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();
|
||||
}
|
||||
|
||||
export async function expectTailscaleUnavailable(page: Page): Promise<void> {
|
||||
@@ -515,7 +460,6 @@ 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();
|
||||
}
|
||||
@@ -635,14 +579,9 @@ 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 openPairDeviceWaysSheet(page);
|
||||
await expect(page.getByTestId("devices-relay")).toBeVisible();
|
||||
}
|
||||
|
||||
export async function openRelaySecurityDocs(page: Page): Promise<void> {
|
||||
|
||||
@@ -80,38 +80,17 @@ async function createListedPlugin(root: string) {
|
||||
git("add", "-A");
|
||||
git("commit", "-m", "initial");
|
||||
const date = "2026-10-03T00:00:00.000Z";
|
||||
const commit = git("rev-parse", "HEAD");
|
||||
return {
|
||||
id: LISTING.id,
|
||||
name: LISTING.name,
|
||||
description: LISTING.description,
|
||||
license: "MIT",
|
||||
requirements: { paseo: ">=0.8.0" },
|
||||
categories: ["tools"],
|
||||
author: {
|
||||
github: "acme",
|
||||
name: "Acme",
|
||||
bio: "Building developer workflow plugins for Paseo.",
|
||||
website: "https://acme.dev",
|
||||
},
|
||||
repository: { url: "https://github.com/acme/directory-example", commit },
|
||||
author: { github: "acme", name: "Acme" },
|
||||
repository: { url: "https://github.com/acme/directory-example" },
|
||||
artifact: {
|
||||
kind: "git",
|
||||
remote: pathToFileURL(repository).href,
|
||||
commit,
|
||||
},
|
||||
links: [
|
||||
{ label: "Documentation", url: "https://acme.dev/docs", icon: "book" },
|
||||
{
|
||||
label: "Changelog",
|
||||
url: "https://github.com/acme/directory-example/releases",
|
||||
icon: "changelog",
|
||||
},
|
||||
],
|
||||
funding: [{ platform: "github", url: "https://github.com/sponsors/acme" }],
|
||||
scorecardSummary: {
|
||||
health: { grade: "excellent" },
|
||||
review: { status: "passed", score: 4, noteCount: 0 },
|
||||
commit: git("rev-parse", "HEAD"),
|
||||
},
|
||||
media: [],
|
||||
submittedAt: date,
|
||||
@@ -122,169 +101,21 @@ async function createListedPlugin(root: string) {
|
||||
};
|
||||
}
|
||||
|
||||
function createRelatedFixtures(date: string) {
|
||||
const specs = [
|
||||
[
|
||||
"acme/pr-radar",
|
||||
"PR Radar",
|
||||
"Monitors pull requests and CI checks across connected hosts.",
|
||||
1400,
|
||||
],
|
||||
[
|
||||
"acme/commit-diff",
|
||||
"Commit Diff",
|
||||
"Compact commit history and inline file tree diff viewer.",
|
||||
980,
|
||||
],
|
||||
[
|
||||
"acme/sidebar-plus",
|
||||
"Sidebar Plus",
|
||||
"Groups workspaces into folders with custom status pills.",
|
||||
1120,
|
||||
],
|
||||
[
|
||||
"acme/linear-sync",
|
||||
"Linear Sync",
|
||||
"Attaches Linear tickets to workspaces from slash commands.",
|
||||
860,
|
||||
],
|
||||
[
|
||||
"acme/worktree-guard",
|
||||
"Worktree Guard",
|
||||
"Fast-forwards base branches before creating new worktrees.",
|
||||
740,
|
||||
],
|
||||
[
|
||||
"acme/usage-meter",
|
||||
"Usage Meter",
|
||||
"Shows live token usage and session pacing in the sidebar.",
|
||||
650,
|
||||
],
|
||||
] as const;
|
||||
return specs.map(([id, name, description, installs]) => ({
|
||||
id,
|
||||
name,
|
||||
description,
|
||||
license: "MIT",
|
||||
categories: ["tools"],
|
||||
author: { github: "acme", name: "Acme" },
|
||||
repository: { url: `https://github.com/${id}` },
|
||||
artifact: { kind: "git", remote: `https://github.com/${id}.git`, commit: "a".repeat(40) },
|
||||
scorecardSummary: {
|
||||
health: { grade: "good" },
|
||||
review: { status: "passed", score: 4, noteCount: 0 },
|
||||
},
|
||||
media: [],
|
||||
submittedAt: date,
|
||||
reviewedAt: date,
|
||||
updatedAt: date,
|
||||
publishedAt: date,
|
||||
installs,
|
||||
}));
|
||||
}
|
||||
|
||||
async function startRegistry(listing: Record<string, unknown>) {
|
||||
const date = "2026-10-03T00:00:00.000Z";
|
||||
const commit = (listing.artifact as { commit: string }).commit;
|
||||
const related = createRelatedFixtures(date);
|
||||
const detailDocument = {
|
||||
...listing,
|
||||
readme: `# ${LISTING.name}\n\n${LISTING.overview}\n\n## Capabilities\n\n- Adds a lightweight review checklist panel to every workspace.\n- Works across Desktop, Web, and Mobile without extra setup.`,
|
||||
health: {
|
||||
grade: "excellent",
|
||||
summary: "This plugin is actively maintained.",
|
||||
signals: [
|
||||
{
|
||||
id: "hygiene",
|
||||
summary: "Overview, MIT license, and Paseo version requirement present.",
|
||||
},
|
||||
{
|
||||
id: "maintenance",
|
||||
summary: "Last commit 2 days ago. 64 commits in the past year.",
|
||||
},
|
||||
{
|
||||
id: "responsiveness",
|
||||
summary: "Closed 94% of 18 issues. 2 active contributors.",
|
||||
},
|
||||
{ id: "adoption", summary: "1.2k installations, 86 stars." },
|
||||
],
|
||||
},
|
||||
review: {
|
||||
status: "passed",
|
||||
score: 4,
|
||||
reviewedAt: date,
|
||||
reviewUrl: "https://github.com/getpaseo/plugins/pull/2410",
|
||||
policyUrl: "https://github.com/getpaseo/plugins/blob/main/REVIEW.md",
|
||||
platforms: ["desktop", "web", "ios", "android"],
|
||||
notes: [],
|
||||
passed: [
|
||||
{ id: "integrity", summary: "Artifact matches pinned Git commit hash." },
|
||||
{ id: "lockfile", summary: "No external runtime dependencies or install scripts." },
|
||||
{ id: "obfuscation", summary: "No obfuscation detected." },
|
||||
{ id: "network", summary: "No suspicious network or exfiltration patterns found." },
|
||||
],
|
||||
capabilities: [
|
||||
{
|
||||
id: "cap.workspace",
|
||||
label: "Workspace panel",
|
||||
summary: "Renders a checklist tab inside Paseo workspaces.",
|
||||
details:
|
||||
"Registers a client workspace panel via @getpaseo/plugin/client in index.client.ts.",
|
||||
},
|
||||
{
|
||||
id: "cap.storage",
|
||||
label: "Plugin settings",
|
||||
summary: "Stores checklist templates in plugin-scoped settings.",
|
||||
details:
|
||||
"Uses registerSettings with Zod schema validation; writes no files outside plugin storage.",
|
||||
},
|
||||
],
|
||||
},
|
||||
history: [
|
||||
{
|
||||
label: "v1.2.0",
|
||||
kind: "git",
|
||||
commit,
|
||||
tag: "v1.2.0",
|
||||
publishedAt: date,
|
||||
url: "https://github.com/acme/directory-example/releases/tag/v1.2.0",
|
||||
reviewUrl: "https://github.com/getpaseo/plugins/pull/2410",
|
||||
},
|
||||
{
|
||||
label: "v1.1.0",
|
||||
kind: "git",
|
||||
commit: "b".repeat(40),
|
||||
tag: "v1.1.0",
|
||||
publishedAt: "2026-09-20T00:00:00.000Z",
|
||||
url: "https://github.com/acme/directory-example/releases/tag/v1.1.0",
|
||||
reviewUrl: "https://github.com/getpaseo/plugins/pull/2180",
|
||||
},
|
||||
{
|
||||
label: "c81a4f2",
|
||||
kind: "git",
|
||||
commit: "c81a4f2".padEnd(40, "0"),
|
||||
publishedAt: "2026-09-05T00:00:00.000Z",
|
||||
url: `https://github.com/acme/directory-example/commit/${"c81a4f2".padEnd(40, "0")}`,
|
||||
},
|
||||
],
|
||||
};
|
||||
const documents: Record<string, unknown> = {
|
||||
"/index.json": {
|
||||
schemaVersion: 1,
|
||||
registry: { name: "Local", url: "http://127.0.0.1" },
|
||||
categories: [{ slug: "tools", label: "Tools" }],
|
||||
plugins: [listing, ...related],
|
||||
plugins: [listing],
|
||||
featured: [],
|
||||
generatedAt: date,
|
||||
generatedAt: "2026-10-03T00:00:00.000Z",
|
||||
},
|
||||
[`/plugins/${LISTING.id}.json`]: {
|
||||
...listing,
|
||||
readme: `# ${LISTING.name}\n\n${LISTING.overview}`,
|
||||
},
|
||||
[`/plugins/${LISTING.id}.json`]: detailDocument,
|
||||
};
|
||||
for (const item of related) {
|
||||
documents[`/plugins/${item.id}.json`] = {
|
||||
...item,
|
||||
readme: `# ${item.name}\n\n${item.description}`,
|
||||
};
|
||||
}
|
||||
const server = createServer((request, response) => {
|
||||
const document = request.url ? documents[request.url] : undefined;
|
||||
if (!document) {
|
||||
|
||||
@@ -45,10 +45,7 @@ export async function requestStreamingMarkdown(agent: StreamingMarkdownAgent): P
|
||||
|
||||
export async function expectUnfinishedBold(page: Page): Promise<void> {
|
||||
const message = page.getByTestId("assistant-message").last();
|
||||
const bold = message.locator("strong");
|
||||
await expect(bold).toContainText("Bold");
|
||||
await expect(bold).toHaveCSS("font-weight", "700");
|
||||
await expect(message).not.toContainText("*");
|
||||
await expect(message.locator(".enrm-text")).toContainText("Bold");
|
||||
await expect(message).not.toContainText("stays bold");
|
||||
}
|
||||
|
||||
@@ -61,7 +58,6 @@ export async function expectUnfinishedLink(
|
||||
await agent.stream.showThrough("**Bold text stays bold** and [Paseo docs");
|
||||
await expect(message).toContainText("Paseo docs");
|
||||
await expect(message.getByRole("link", { name: "Paseo docs" })).toHaveCount(0);
|
||||
await expect(message).not.toContainText("[");
|
||||
await expect(message).not.toContainText("https:");
|
||||
await captureMarkdown(page, testInfo, "unfinished-link");
|
||||
}
|
||||
|
||||
@@ -324,124 +324,6 @@ 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,
|
||||
|
||||
@@ -3,19 +3,16 @@ import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Folder, FolderPlus, Plus } from "lucide-react-native";
|
||||
import { AdaptiveModalSheet, type SheetKeyboard } from "@/components/adaptive-modal-sheet";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { HostPicker } from "@/components/hosts/host-picker";
|
||||
import { GitHubIcon } from "@/components/icons/github-icon";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useAddHost } from "@/hosts/add-host";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import {
|
||||
FieldTrigger,
|
||||
type FieldTriggerInteractionState,
|
||||
} from "@/screens/new-workspace/form/field-trigger";
|
||||
import { FieldTrigger } from "@/screens/new-workspace/form/field-trigger";
|
||||
import {
|
||||
useAddProjectFlowStore,
|
||||
type AddProjectFlowRequest,
|
||||
@@ -365,12 +362,7 @@ function HostPill({
|
||||
const [open, setOpen] = useState(false);
|
||||
const openPicker = useCallback(() => setOpen(true), []);
|
||||
const label = hosts.find((host) => host.serverId === hostId)?.label ?? hostId;
|
||||
const renderIcon = useCallback(
|
||||
({ backdrop }: FieldTriggerInteractionState) => (
|
||||
<HostStatusIcon serverId={hostId} size="sm" backdrop={backdrop} />
|
||||
),
|
||||
[hostId],
|
||||
);
|
||||
const icon = useMemo(() => <HostStatusDot serverId={hostId} />, [hostId]);
|
||||
return (
|
||||
<HostPicker
|
||||
hosts={hosts}
|
||||
@@ -391,7 +383,7 @@ function HostPill({
|
||||
label="Host"
|
||||
accessibilityLabel="Project host"
|
||||
tooltip="Host"
|
||||
icon={renderIcon}
|
||||
icon={icon}
|
||||
value={label}
|
||||
onPress={openPicker}
|
||||
disabled={disabled}
|
||||
|
||||
@@ -2,7 +2,6 @@ import { useActivatedStore } from "@/sync";
|
||||
import { createAgentQueueModel, type AgentQueueModel, type AgentQueueSnapshot } from "./model";
|
||||
|
||||
export type { AgentQueueModel, AgentQueueSnapshot } from "./model";
|
||||
export { optimisticEnqueueAgentMessage } from "./overlays";
|
||||
|
||||
/** Observes one agent's queue while the caller is mounted in a visible panel. */
|
||||
export function useAgentQueue(
|
||||
|
||||
@@ -101,47 +101,14 @@ test("marks a row busy while it is withdrawn, then hides it ahead of the host up
|
||||
test("hides a withdrawn row even when an older update overtakes the answer", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
|
||||
daemon.holdCommands();
|
||||
const result = model.withdraw("a");
|
||||
await daemon.publish("agent", queueOf("a", "b", "c"));
|
||||
daemon.releaseCommands();
|
||||
await result;
|
||||
await daemon.settle();
|
||||
|
||||
expect(rowIds()).toEqual(["b", "c"]);
|
||||
});
|
||||
|
||||
test("optimistic cancel hides the row immediately and restores it if the host refuses", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
|
||||
daemon.holdCommands();
|
||||
const pending = model.withdraw("a", { optimistic: true });
|
||||
expect(rowIds()).toEqual(["b"]);
|
||||
|
||||
daemon.refuseWithdrawals("already_dispatching");
|
||||
daemon.releaseCommands();
|
||||
expect(await pending).toEqual({ withdrawn: false, reason: "already_dispatching" });
|
||||
expect(rowIds()).toEqual(["a", "b"]);
|
||||
});
|
||||
|
||||
test("optimistic promote marks the row dispatching, clears held, and rolls back if refused", async () => {
|
||||
const { daemon, model } = await observeQueue({
|
||||
held: true,
|
||||
items: [queuedItem("a", { held: true }), queuedItem("b", { seq: 2, held: true })],
|
||||
});
|
||||
|
||||
daemon.holdCommands();
|
||||
const pending = model.promote("b", "interrupt");
|
||||
expect(model.getSnapshot().held).toBe(false);
|
||||
expect(model.getSnapshot().items.find((item) => item.id === "b")?.state).toBe("dispatching");
|
||||
|
||||
daemon.refusePromotions("already_dispatching");
|
||||
daemon.releaseCommands();
|
||||
expect(await pending).toEqual({ promoted: false, reason: "already_dispatching" });
|
||||
expect(model.getSnapshot().held).toBe(true);
|
||||
expect(model.getSnapshot().items.find((item) => item.id === "b")?.state).toBe("queued");
|
||||
});
|
||||
|
||||
test("keeps the row when the host already started sending it", async () => {
|
||||
const { daemon, model, rowIds } = await observeQueue();
|
||||
daemon.refuseWithdrawals("already_dispatching");
|
||||
|
||||
@@ -7,7 +7,6 @@ import {
|
||||
hostRuntimeSyncHost,
|
||||
type SyncClient,
|
||||
} from "@/sync";
|
||||
import { optimisticPromoteAgentQueueItem, optimisticRemoveAgentQueueItem } from "./overlays";
|
||||
|
||||
type AgentQueueClient = SyncClient &
|
||||
Pick<DaemonClient, "withdrawAgentQueueItem" | "promoteAgentQueueItem">;
|
||||
@@ -18,12 +17,13 @@ export interface AgentQueueSnapshot {
|
||||
held: boolean;
|
||||
/** Admission order. The first row is sent next. */
|
||||
items: readonly PaseoAgentQueueItem[];
|
||||
/** Rows with a command or optimistic enqueue in flight. */
|
||||
/** Rows with a command in flight. */
|
||||
busy: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* One agent's queue as the host holds it, with optimistic overlays for in-flight queue commands.
|
||||
* One agent's queue as the host holds it. The host is the only writer: a command changes
|
||||
* nothing here until the host answers it.
|
||||
*/
|
||||
export function createAgentQueueModel({
|
||||
serverId,
|
||||
@@ -45,21 +45,21 @@ export function createAgentQueueModel({
|
||||
active: initialActive,
|
||||
});
|
||||
let busy: ReadonlySet<string> = new Set();
|
||||
let view: { source: unknown; busy: ReadonlySet<string>; snapshot: AgentQueueSnapshot } | null =
|
||||
null;
|
||||
// Rows the host confirmed it removed. A later change to a row arrives as a new row object.
|
||||
const withdrawn = new WeakSet<PaseoAgentQueueItem>();
|
||||
let view: { source: unknown; snapshot: AgentQueueSnapshot } | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
const getSnapshot = (): AgentQueueSnapshot => {
|
||||
const source = store.getSnapshot();
|
||||
if (view?.source !== source || view.busy !== busy) {
|
||||
if (view?.source !== source) {
|
||||
view = {
|
||||
source,
|
||||
busy,
|
||||
snapshot: {
|
||||
status: source.status,
|
||||
held: source.data?.meta.held ?? false,
|
||||
items: source.data?.items ?? [],
|
||||
busy: mergeSets(busy, source.pending),
|
||||
items: source.data?.items.filter((item) => !withdrawn.has(item)) ?? [],
|
||||
busy,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -76,19 +76,20 @@ export function createAgentQueueModel({
|
||||
return client;
|
||||
};
|
||||
|
||||
// The row as the host last sent it, which an update during a command may have replaced.
|
||||
const hide = (messageId: string) => {
|
||||
const row = store.getSnapshot().data?.items.find((entry) => entry.id === messageId);
|
||||
if (row) withdrawn.add(row);
|
||||
};
|
||||
|
||||
/** Runs one command per row at a time. Returns null when the row cannot take one. */
|
||||
const command = async <T>(
|
||||
messageId: string,
|
||||
run: (client: AgentQueueClient) => Promise<T>,
|
||||
): Promise<T | null> => {
|
||||
const snapshot = getSnapshot();
|
||||
const row = snapshot.items.find((entry) => entry.id === messageId);
|
||||
if (!row || row.state === "dispatching" || snapshot.busy.has(messageId)) return null;
|
||||
const client = connected();
|
||||
const command = async <T>(messageId: string, run: () => Promise<T>): Promise<T | null> => {
|
||||
const row = getSnapshot().items.find((entry) => entry.id === messageId);
|
||||
if (!row || row.state === "dispatching" || busy.has(messageId)) return null;
|
||||
busy = new Set(busy).add(messageId);
|
||||
changed();
|
||||
try {
|
||||
return await run(client);
|
||||
return await run();
|
||||
} finally {
|
||||
const next = new Set(busy);
|
||||
next.delete(messageId);
|
||||
@@ -109,48 +110,19 @@ export function createAgentQueueModel({
|
||||
},
|
||||
setActive: store.setActive,
|
||||
retry: store.retry,
|
||||
withdraw: (messageId: string, options?: { optimistic?: boolean }) =>
|
||||
command(messageId, async (client) => {
|
||||
if (options?.optimistic) {
|
||||
const overlay = optimisticRemoveAgentQueueItem(client, agentId, messageId);
|
||||
try {
|
||||
const result = await client.withdrawAgentQueueItem(agentId, messageId);
|
||||
if (result.withdrawn) overlay.commit();
|
||||
else overlay.rollback();
|
||||
return result;
|
||||
} catch (error) {
|
||||
overlay.rollback();
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
const result = await client.withdrawAgentQueueItem(agentId, messageId);
|
||||
withdraw: (messageId: string) =>
|
||||
command(messageId, async () => {
|
||||
const result = await connected().withdrawAgentQueueItem(agentId, messageId);
|
||||
// The host confirmed the removal. Hide the row now so it is not pressable again
|
||||
// between this answer and the next update.
|
||||
if (result.withdrawn) optimisticRemoveAgentQueueItem(client, agentId, messageId).commit();
|
||||
if (result.withdrawn) hide(messageId);
|
||||
return result;
|
||||
}),
|
||||
promote: (messageId: string, activeTurnBehavior: ActiveTurnBehavior) =>
|
||||
command(messageId, async (client) => {
|
||||
const overlay = optimisticPromoteAgentQueueItem(client, agentId, messageId);
|
||||
try {
|
||||
const result = await client.promoteAgentQueueItem(agentId, messageId, activeTurnBehavior);
|
||||
if (result.promoted) overlay.commit();
|
||||
else overlay.rollback();
|
||||
return result;
|
||||
} catch (error) {
|
||||
overlay.rollback();
|
||||
throw error;
|
||||
}
|
||||
}),
|
||||
command(messageId, async () =>
|
||||
connected().promoteAgentQueueItem(agentId, messageId, activeTurnBehavior),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
function mergeSets(left: ReadonlySet<string>, right: ReadonlySet<string>): ReadonlySet<string> {
|
||||
if (left.size === 0) return right;
|
||||
if (right.size === 0) return left;
|
||||
const merged = new Set(left);
|
||||
for (const value of right) merged.add(value);
|
||||
return merged;
|
||||
}
|
||||
|
||||
export type AgentQueueModel = ReturnType<typeof createAgentQueueModel>;
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
import {
|
||||
AgentQueueCollection,
|
||||
type CollectionState,
|
||||
type PaseoAgentQueueItem,
|
||||
type SyncOptimisticHandle,
|
||||
} from "@getpaseo/client";
|
||||
import type { SyncClient } from "@/sync";
|
||||
|
||||
type QueueCollectionState = CollectionState<PaseoAgentQueueItem, { held: boolean }>;
|
||||
|
||||
function buildQueueState(
|
||||
byId: Map<string, PaseoAgentQueueItem>,
|
||||
meta: { held: boolean },
|
||||
): QueueCollectionState {
|
||||
const items = Array.from(byId.values());
|
||||
if (AgentQueueCollection.compare) items.sort(AgentQueueCollection.compare);
|
||||
return { items, byId, meta };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a newly queued message immediately in FIFO order and clears any paused banner until the
|
||||
* host confirms or rejects the send.
|
||||
*/
|
||||
export function optimisticEnqueueAgentMessage(
|
||||
client: Pick<SyncClient, "sync">,
|
||||
agentId: string,
|
||||
item: Omit<PaseoAgentQueueItem, "seq">,
|
||||
): SyncOptimisticHandle {
|
||||
return client.sync(AgentQueueCollection, { agentId }).optimistic({
|
||||
key: item.id,
|
||||
apply: (state) => {
|
||||
if (state?.byId.has(item.id)) return state;
|
||||
let maxSeq = 0;
|
||||
if (state) {
|
||||
for (const existing of state.items) {
|
||||
if (existing.seq > maxSeq) maxSeq = existing.seq;
|
||||
}
|
||||
}
|
||||
const byId = new Map(state?.byId);
|
||||
byId.set(item.id, { ...item, seq: maxSeq + 1 });
|
||||
return buildQueueState(byId, { held: false });
|
||||
},
|
||||
settled: (authoritative) => authoritative.byId.has(item.id),
|
||||
});
|
||||
}
|
||||
|
||||
/** Hides a withdrawn or cancelled row until the host update removes it. */
|
||||
export function optimisticRemoveAgentQueueItem(
|
||||
client: Pick<SyncClient, "sync">,
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
): SyncOptimisticHandle {
|
||||
return client.sync(AgentQueueCollection, { agentId }).optimistic({
|
||||
apply: (state) => {
|
||||
if (!state || !state.byId.has(messageId)) return state;
|
||||
const byId = new Map(state.byId);
|
||||
byId.delete(messageId);
|
||||
return {
|
||||
items: state.items.filter((item) => item.id !== messageId),
|
||||
byId,
|
||||
meta: state.meta,
|
||||
};
|
||||
},
|
||||
settled: (authoritative) => !authoritative.byId.has(messageId),
|
||||
});
|
||||
}
|
||||
|
||||
/** Marks a promoted row dispatching and clears any paused banner while the host dispatches it. */
|
||||
export function optimisticPromoteAgentQueueItem(
|
||||
client: Pick<SyncClient, "sync">,
|
||||
agentId: string,
|
||||
messageId: string,
|
||||
): SyncOptimisticHandle {
|
||||
return client.sync(AgentQueueCollection, { agentId }).optimistic({
|
||||
apply: (state) => {
|
||||
if (!state) return state;
|
||||
const existing = state.byId.get(messageId);
|
||||
if (!existing) return state;
|
||||
if (existing.state === "dispatching" && !state.meta.held) return state;
|
||||
const byId = new Map(state.byId);
|
||||
byId.set(messageId, { ...existing, state: "dispatching", held: false });
|
||||
return buildQueueState(byId, { held: false });
|
||||
},
|
||||
settled: (authoritative) => {
|
||||
const item = authoritative.byId.get(messageId);
|
||||
return !item || item.state === "dispatching";
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -26,6 +26,7 @@ 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";
|
||||
@@ -122,6 +123,15 @@ 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;
|
||||
@@ -149,7 +159,6 @@ function NativeStreamViewport(props: StreamRenderInput & { strategy: StreamStrat
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange,
|
||||
onNearHistoryStart,
|
||||
isLoadingOlderHistory,
|
||||
@@ -256,12 +265,6 @@ 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;
|
||||
@@ -808,6 +811,11 @@ 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,6 +19,7 @@ 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";
|
||||
@@ -76,6 +77,14 @@ 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.
|
||||
@@ -430,7 +439,6 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange,
|
||||
onReadingPositionChange,
|
||||
onNearHistoryStart,
|
||||
@@ -699,12 +707,6 @@ 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;
|
||||
@@ -1748,6 +1750,11 @@ 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,8 +94,6 @@ 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,8 +258,6 @@ 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. */
|
||||
@@ -359,7 +357,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady = true,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
bottomOverlayTailClearance = 0,
|
||||
bottomOverlayControlClearance,
|
||||
toast,
|
||||
@@ -1234,7 +1231,6 @@ const AgentStreamViewComponent = forwardRef<AgentStreamViewHandle, AgentStreamVi
|
||||
isAuthoritativeHistoryReady,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
onNearBottomChange: nearBottom.set,
|
||||
onReadingPositionChange: handleReadingPositionChange,
|
||||
onNearHistoryStart: loadOlder,
|
||||
@@ -1388,9 +1384,6 @@ 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");
|
||||
}
|
||||
|
||||
@@ -2,15 +2,16 @@ import { useCallback, useMemo, useRef, useState, type ReactElement } from "react
|
||||
import { Text, View } from "react-native";
|
||||
import { Server } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { ComboboxTrigger, type ComboboxTriggerState } from "@/components/ui/combobox-trigger";
|
||||
import { HOST_STATUS_DOT_SIZE } from "@/components/host-status-dot";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { mapLayout } from "@/components/ui/control-sizing";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { density } from "@/styles/density";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
import {
|
||||
ALL_HOSTS_OPTION_ID,
|
||||
getHostPickerLabel,
|
||||
HostPicker,
|
||||
HostStatusDotSlot,
|
||||
type HostPickerHost,
|
||||
} from "@/components/hosts/host-picker";
|
||||
|
||||
@@ -64,8 +65,12 @@ export function HostFilter({
|
||||
const handleFilterOpen = useCallback(() => setIsFilterOpen(true), []);
|
||||
const showsAllHosts = selectedHost === ALL_HOSTS_OPTION_ID;
|
||||
const slotStyle = useMemo(
|
||||
() => [styles.triggerSlot, hang && styles.triggerSlotHang, hang && styles.glyphHang],
|
||||
[hang],
|
||||
() => [
|
||||
styles.triggerSlot,
|
||||
hang && styles.triggerSlotHang,
|
||||
hang && (showsAllHosts ? styles.glyphHang : styles.dotHang),
|
||||
],
|
||||
[hang, showsAllHosts],
|
||||
);
|
||||
|
||||
const triggerStyle = useCallback(
|
||||
@@ -77,26 +82,6 @@ export function HostFilter({
|
||||
[],
|
||||
);
|
||||
|
||||
const renderTriggerContent = useCallback(
|
||||
({ hovered, pressed }: ComboboxTriggerState) => (
|
||||
<>
|
||||
{showsAllHosts ? (
|
||||
<ThemedServer size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
|
||||
) : (
|
||||
<HostStatusIcon
|
||||
serverId={selectedHost}
|
||||
size="sm"
|
||||
backdrop={hovered || pressed ? "surface2" : "surface0"}
|
||||
/>
|
||||
)}
|
||||
<Text style={styles.label} numberOfLines={1}>
|
||||
{selectedHostLabel}
|
||||
</Text>
|
||||
</>
|
||||
),
|
||||
[selectedHost, selectedHostLabel, showsAllHosts],
|
||||
);
|
||||
|
||||
return (
|
||||
<HostPicker
|
||||
hosts={hosts}
|
||||
@@ -120,7 +105,14 @@ export function HostFilter({
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={`Filter: ${selectedHostLabel}`}
|
||||
>
|
||||
{renderTriggerContent}
|
||||
{showsAllHosts ? (
|
||||
<ThemedServer size={ICON_SIZE.sm} uniProps={mutedColorMapping} />
|
||||
) : (
|
||||
<HostStatusDotSlot serverId={selectedHost} />
|
||||
)}
|
||||
<Text style={styles.label} numberOfLines={1}>
|
||||
{selectedHostLabel}
|
||||
</Text>
|
||||
</ComboboxTrigger>
|
||||
</View>
|
||||
</HostPicker>
|
||||
@@ -140,10 +132,14 @@ const styles = StyleSheet.create((theme) => ({
|
||||
triggerSlotHang: {
|
||||
marginVertical: mapLayout(density.tightRowHeight, (height) => (LABEL_LINE - height) / 2),
|
||||
},
|
||||
// Hangs the padding, so the leading glyph's box sits on the rail.
|
||||
// Hangs the padding, so the server glyph's box sits on the rail.
|
||||
glyphHang: {
|
||||
marginLeft: -theme.spacing[2],
|
||||
},
|
||||
// Hangs the padding and the dot's inset in its icon slot, so the dot's ink sits on the rail.
|
||||
dotHang: {
|
||||
marginLeft: -(theme.spacing[2] + (ICON_SIZE.sm - HOST_STATUS_DOT_SIZE) / 2),
|
||||
},
|
||||
// The Settings host trigger: a borderless row that fills on hover and press.
|
||||
trigger: {
|
||||
flexShrink: 1,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useCallback, useMemo, type ReactElement } from "react";
|
||||
import { View } from "react-native";
|
||||
import { HostStatusDot } from "@/components/host-status-dot";
|
||||
import { MenuItem } from "@/components/ui/menu";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
|
||||
interface HostMenuItemProps {
|
||||
serverId: string;
|
||||
@@ -13,7 +14,7 @@ interface HostMenuItemProps {
|
||||
statusTestID?: string;
|
||||
}
|
||||
|
||||
/** A host as a menu option: its resolved icon with live status dot leads, and the chosen host carries the check. */
|
||||
/** A host as a menu option: its live status dot leads, and the chosen host carries the check. */
|
||||
export function HostMenuItem({
|
||||
serverId,
|
||||
label,
|
||||
@@ -26,12 +27,9 @@ export function HostMenuItem({
|
||||
const handleSelect = useCallback(() => onSelect(serverId), [onSelect, serverId]);
|
||||
const leading = useMemo(
|
||||
() => (
|
||||
<HostStatusIcon
|
||||
serverId={serverId}
|
||||
size="sm"
|
||||
backdrop="surface1"
|
||||
statusTestID={statusTestID}
|
||||
/>
|
||||
<View testID={statusTestID}>
|
||||
<HostStatusDot serverId={serverId} />
|
||||
</View>
|
||||
),
|
||||
[serverId, statusTestID],
|
||||
);
|
||||
|
||||
@@ -54,6 +54,14 @@ export interface HostPickerHost {
|
||||
label: string;
|
||||
}
|
||||
|
||||
export function HostStatusDotSlot({ serverId }: { serverId: string }): ReactElement {
|
||||
return (
|
||||
<View style={styles.statusDotSlot}>
|
||||
<HostStatusDot serverId={serverId} />
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export interface HostPickerOptionProps {
|
||||
serverId: string;
|
||||
label: string;
|
||||
@@ -407,6 +415,12 @@ export function HostPicker({
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
statusDotSlot: {
|
||||
width: theme.iconSize.sm,
|
||||
height: theme.iconSize.sm,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
rowEnvelope: {
|
||||
position: "relative",
|
||||
},
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Animated } from "react-native";
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { type ClockDriver, createIndicatorClock } from "./clock";
|
||||
import { createIndicatorClock } from "./clock";
|
||||
|
||||
const PERIOD_MS = 900;
|
||||
const STEPS = 27;
|
||||
@@ -35,28 +35,6 @@ 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]);
|
||||
@@ -142,38 +120,4 @@ 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 loops.
|
||||
// rate and never ends or 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,16 +41,6 @@ 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
|
||||
@@ -59,10 +49,9 @@ function decayForever(elapsedMs: Animated.Value): ClockDriver {
|
||||
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: ClockDriver | null = null;
|
||||
let ticking: Animated.CompositeAnimation | null = null;
|
||||
let startedAtMs = 0;
|
||||
|
||||
function currentStepStartMs(stepMs: number): number {
|
||||
@@ -72,18 +61,6 @@ 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;
|
||||
@@ -99,15 +76,16 @@ export function createIndicatorClock(
|
||||
run() {
|
||||
runners += 1;
|
||||
if (!ticking) {
|
||||
elapsedMs.setValue(0);
|
||||
startedAtMs = now();
|
||||
tick();
|
||||
ticking = Animated.decay(elapsedMs, CLOCK_CONFIG);
|
||||
ticking.start();
|
||||
}
|
||||
return () => {
|
||||
runners -= 1;
|
||||
if (runners === 0) {
|
||||
const stopped = ticking;
|
||||
ticking?.stop();
|
||||
ticking = null;
|
||||
stopped?.stop();
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { useContext } from "react";
|
||||
import { createContext, useContext } from "react";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { MarkdownStreamingContext } from "../../streaming-context";
|
||||
import { MermaidFenceHost } from "./host";
|
||||
export { splitMermaidFences } from "./segments";
|
||||
export const MermaidStreamingContext = createContext(false);
|
||||
const ThemedHost = withUnistyles(MermaidFenceHost);
|
||||
const styles = (theme: Theme) => ({
|
||||
inheritedStyles: {
|
||||
@@ -14,6 +14,6 @@ const styles = (theme: Theme) => ({
|
||||
textStyle: { backgroundColor: theme.colors.surface2, padding: 12, borderRadius: 8 },
|
||||
});
|
||||
export function MermaidFence({ code }: { code: string }) {
|
||||
const streaming = useContext(MarkdownStreamingContext);
|
||||
const streaming = useContext(MermaidStreamingContext);
|
||||
return <ThemedHost code={code} phase={streaming ? "streaming" : "complete"} uniProps={styles} />;
|
||||
}
|
||||
|
||||
@@ -43,11 +43,8 @@ export function useMarkdownSource(
|
||||
forgeReferencePattern?: string;
|
||||
external?: boolean;
|
||||
} = {},
|
||||
/** Identity of this occurrence's image acquisitions. Defaults to one per call site. */
|
||||
occurrence?: string,
|
||||
) {
|
||||
const ownOccurrence = useId();
|
||||
const occurrenceKey = occurrence ?? ownOccurrence;
|
||||
const occurrenceKey = useId();
|
||||
const { commandNames, forgeReferencePattern, external } = links;
|
||||
const prepared = useMemo(
|
||||
() =>
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { memo, useId, useMemo, useRef, useState, type ComponentProps } from "react";
|
||||
import { memo, useMemo, useState, type ComponentProps } from "react";
|
||||
import { EnrichedMarkdownText, type LinkPressEvent } from "react-native-enriched-markdown";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
@@ -21,15 +21,10 @@ import { LinkMenu, useLinkMenuLongPress, type LinkMenuSubject } from "./link-men
|
||||
import { WEB_RENDERERS } from "./renderers";
|
||||
import { createMarkdownStyles } from "./styles";
|
||||
import { PENDING_MARKDOWN_IMAGE } from "./source";
|
||||
import {
|
||||
createStreamingMarkdownSplitter,
|
||||
createStreamingMarkdownStabilizer,
|
||||
PENDING_MARKDOWN_LINK,
|
||||
} from "./streaming";
|
||||
import { MarkdownStreamingContext } from "./streaming-context";
|
||||
import { splitStreamingMarkdown } from "./streaming";
|
||||
import { useMarkdownSource, type MarkdownImageContext } from "./images";
|
||||
|
||||
import { MermaidFence, splitMermaidFences } from "./fence/mermaid";
|
||||
import { MermaidFence, MermaidStreamingContext, splitMermaidFences } from "./fence/mermaid";
|
||||
|
||||
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
|
||||
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
@@ -73,60 +68,24 @@ export interface MarkdownRendererProps extends MarkdownImageContext {
|
||||
|
||||
/** All Markdown surfaces share the same engine and source adaptation. */
|
||||
export const MarkdownRenderer = memo(function MarkdownRenderer(props: MarkdownRendererProps) {
|
||||
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 streaming = !isWeb && !!props.streaming;
|
||||
// Only completed lines affect block closure. Do not run mdast on every reveal frame.
|
||||
const completeLines = streaming ? props.text.slice(0, props.text.lastIndexOf("\n") + 1) : "";
|
||||
const boundary = useMemo(
|
||||
() => splitStreamingMarkdown(completeLines, true).head.length,
|
||||
[completeLines],
|
||||
);
|
||||
const Part = props.agentCommands ? CommandMarkdownPart : MarkdownPart;
|
||||
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;
|
||||
if (!streaming || boundary === 0) return <Part {...props} />;
|
||||
return (
|
||||
<MarkdownBlockStack>
|
||||
{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}
|
||||
<Part {...props} text={props.text.slice(0, boundary)} />
|
||||
<Part {...props} text={props.text.slice(boundary)} />
|
||||
</MarkdownBlockStack>
|
||||
);
|
||||
});
|
||||
|
||||
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 CommandMarkdownPart = memo(function CommandMarkdownPart(props: MarkdownRendererProps) {
|
||||
const commandHints = useAgentCommandHints();
|
||||
return <MarkdownPart {...props} commandHints={commandHints} />;
|
||||
});
|
||||
@@ -149,14 +108,12 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
muted = false,
|
||||
selectable = true,
|
||||
streaming = false,
|
||||
preStabilized = false,
|
||||
onLinkPress,
|
||||
agentCommands: _agentCommands,
|
||||
external = false,
|
||||
commandHints = null,
|
||||
imageOccurrence,
|
||||
...imageContext
|
||||
}: MarkdownPartProps & { commandHints?: CommandHints | null }) {
|
||||
}: MarkdownRendererProps & { commandHints?: CommandHints | null }) {
|
||||
const environment = useAssistantFileLinkEnvironment();
|
||||
const actions = useAssistantFileLinkActions();
|
||||
const workspaceForgeShorthand = useForgeShorthand();
|
||||
@@ -168,13 +125,8 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
(environmentMatchesHost && environment.client?.readFile
|
||||
? { readFile: environment.client.readFile.bind(environment.client) }
|
||||
: undefined);
|
||||
const stabilizerRef = useRef<ReturnType<typeof createStreamingMarkdownStabilizer> | null>(null);
|
||||
const stabilizedText = useMemo(() => {
|
||||
if (!streaming || preStabilized) return text;
|
||||
return (stabilizerRef.current ??= createStreamingMarkdownStabilizer()).stabilize(text);
|
||||
}, [streaming, preStabilized, text]);
|
||||
const { markdown, imageSources, linkRecognition, linkSource } = useMarkdownSource(
|
||||
stabilizedText,
|
||||
text,
|
||||
{
|
||||
workspaceRoot: environmentMatchesHost ? environment.workspaceRoot : undefined,
|
||||
serverId: environment.serverId,
|
||||
@@ -186,12 +138,10 @@ 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.
|
||||
const readLink = useStableEvent(({ url, sourceType }: LinkPressEvent): ReadMarkdownLink => {
|
||||
if (streaming && url === PENDING_MARKDOWN_LINK) return { kind: "inert" };
|
||||
if (external) {
|
||||
// The parser still autolinks bare http, www and email text; only https links open.
|
||||
const safe = pluginOverviewUrl(url);
|
||||
@@ -238,7 +188,7 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
[markdown],
|
||||
);
|
||||
return (
|
||||
<MarkdownStreamingContext.Provider value={streaming}>
|
||||
<MermaidStreamingContext.Provider value={streaming}>
|
||||
<LinkMenu describeLink={describeLink}>
|
||||
<MarkdownBlockStack imageSources={imageSources}>
|
||||
{segments.map((segment) =>
|
||||
@@ -267,6 +217,6 @@ const MarkdownPart = memo(function MarkdownPart({
|
||||
</MarkdownBlockStack>
|
||||
</LinkMenu>
|
||||
{image ? <AttachmentLightbox source={image} onClose={closeImage} /> : null}
|
||||
</MarkdownStreamingContext.Provider>
|
||||
</MermaidStreamingContext.Provider>
|
||||
);
|
||||
});
|
||||
|
||||
@@ -4,8 +4,6 @@ import { createRoot, type Root } from "react-dom/client";
|
||||
import { afterEach, beforeEach, expect, it } from "vitest";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { WEB_RENDERERS } from "./renderers.web";
|
||||
import { PENDING_MARKDOWN_LINK } from "./streaming";
|
||||
import { MarkdownStreamingContext } from "./streaming-context";
|
||||
|
||||
const Link = WEB_RENDERERS.link;
|
||||
const LINK_TEXT = "src/index.ts";
|
||||
@@ -61,32 +59,3 @@ it("leaves an authored link wrapped", () => {
|
||||
const anchor = renderAnchor({ url: "https://example.test/doc", sourceType: "markdown" });
|
||||
expect(anchor.hasAttribute("data-paseo-markdown-recognized-link")).toBe(false);
|
||||
});
|
||||
|
||||
const PENDING_LINK = { url: PENDING_MARKDOWN_LINK, sourceType: "markdown" as const };
|
||||
const PENDING_ANCHOR_PROPS = {
|
||||
href: PENDING_MARKDOWN_LINK,
|
||||
style: { color: "rgb(56, 189, 248)" },
|
||||
};
|
||||
|
||||
it("renders a pending streaming link as a non-interactive link-styled span", () => {
|
||||
if (!Link) {
|
||||
throw new Error("Expected a web link renderer");
|
||||
}
|
||||
const client = new QueryClient();
|
||||
act(() =>
|
||||
root.render(
|
||||
<QueryClientProvider client={client}>
|
||||
<MarkdownStreamingContext.Provider value={true}>
|
||||
<Link link={PENDING_LINK} anchorProps={PENDING_ANCHOR_PROPS}>
|
||||
Paseo docs
|
||||
</Link>
|
||||
</MarkdownStreamingContext.Provider>
|
||||
</QueryClientProvider>,
|
||||
),
|
||||
);
|
||||
expect(container.querySelector("a")).toBeNull();
|
||||
const span = container.querySelector("span");
|
||||
expect(span?.textContent).toBe("Paseo docs");
|
||||
expect(span?.style.color).toBe("rgb(56, 189, 248)");
|
||||
expect(span?.style.overflowWrap).toBe("anywhere");
|
||||
});
|
||||
|
||||
@@ -2,7 +2,6 @@ import { Text } from "react-native";
|
||||
import {
|
||||
forwardRef,
|
||||
useCallback,
|
||||
useContext,
|
||||
useMemo,
|
||||
useState,
|
||||
type ComponentProps,
|
||||
@@ -24,8 +23,6 @@ import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
import { useOpenLinkMenu } from "./link-menu";
|
||||
import { MermaidFence } from "./fence/mermaid";
|
||||
import { isRecognizedLink, markdownLinkSource } from "./source";
|
||||
import { PENDING_MARKDOWN_LINK } from "./streaming";
|
||||
import { MarkdownStreamingContext } from "./streaming-context";
|
||||
import { WebBlockquote } from "./quote-block.web";
|
||||
|
||||
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
|
||||
@@ -45,26 +42,7 @@ function WebCodeBlock({ code, language }: CodeBlockRendererProps) {
|
||||
// The library styles links inline, so a stylesheet :hover rule cannot underline them.
|
||||
const LINK_HOVER_STYLE = { textDecoration: "underline" } as const;
|
||||
|
||||
function PendingWebLink({
|
||||
anchorProps,
|
||||
children,
|
||||
}: Pick<LinkRendererProps, "anchorProps" | "children">) {
|
||||
const style = useMemo(
|
||||
() => ({ ...anchorProps.style, overflowWrap: "anywhere" as const }),
|
||||
[anchorProps.style],
|
||||
);
|
||||
return <span style={style}>{children}</span>;
|
||||
}
|
||||
|
||||
function WebLink(props: LinkRendererProps) {
|
||||
const streaming = useContext(MarkdownStreamingContext);
|
||||
if (streaming && props.link.url === PENDING_MARKDOWN_LINK) {
|
||||
return <PendingWebLink anchorProps={props.anchorProps}>{props.children}</PendingWebLink>;
|
||||
}
|
||||
return <InteractiveWebLink {...props} />;
|
||||
}
|
||||
|
||||
function InteractiveWebLink({ link, anchorProps, children }: LinkRendererProps) {
|
||||
function WebLink({ link, anchorProps, children }: LinkRendererProps) {
|
||||
const forgeShorthand = useForgeShorthand();
|
||||
// A forge reference like `#12` carries its web URL so hover, copy and new-tab opens work.
|
||||
const forgeUrl = link.sourceType === "text" ? forgeShorthand?.resolve(link.url) : null;
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
/** Shared streaming state for Markdown sub-renderers (pending links, Mermaid diagrams). */
|
||||
export const MarkdownStreamingContext = createContext(false);
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,76 +1,15 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import { recognizeTextLinks } from "react-native-enriched-markdown/src/web/recognizeTextLinks";
|
||||
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,
|
||||
stabilizeStreamingMarkdown,
|
||||
} from "./streaming";
|
||||
import { splitStreamingMarkdown } from "./streaming";
|
||||
|
||||
/** 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", () => {
|
||||
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: "" });
|
||||
});
|
||||
it("commits earlier blocks only after the following source line is complete", () => {
|
||||
expect(splitOnce("First.\n\nSecond").head).toBe("");
|
||||
expect(splitOnce("First.\n\nSecond\n")).toEqual({
|
||||
expect(splitStreamingMarkdown("First.\n\nSecond", true).head).toBe("");
|
||||
expect(splitStreamingMarkdown("First.\n\nSecond\n", true)).toEqual({
|
||||
head: "First.\n\n",
|
||||
tail: "Second\n",
|
||||
});
|
||||
@@ -85,462 +24,48 @@ describe("streaming Markdown split", () => {
|
||||
"| A | B |\n| --- | --- |\n| x | y |\n",
|
||||
"```ts\nconst value = 1;\n```\n",
|
||||
"<div>\nbody\n\nmore\n</div>\n",
|
||||
"- [x] done\n- [ ] open\n",
|
||||
"[label]\n\n[label]: /target\n",
|
||||
"[label]: /target\n\n[label]\n",
|
||||
])("keeps an unfinished construct together: %s", (block) => {
|
||||
const prefix = "Introduction.\n\n";
|
||||
const source = prefix + block;
|
||||
const split = splitOnce(source);
|
||||
const split = splitStreamingMarkdown(source, true);
|
||||
expect(split.head.length).toBeLessThanOrEqual(prefix.length);
|
||||
expect(split.head + split.tail).toBe(source);
|
||||
let previous = 0;
|
||||
for (const { text, head } of streamSplits(source)) {
|
||||
expect(head.length, `prefix ${text.length} of ${source}`).toBeGreaterThanOrEqual(previous);
|
||||
previous = head.length;
|
||||
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;
|
||||
}
|
||||
});
|
||||
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(splitOnce(`Intro.\n\n${tail}`)).toEqual({ head: "Intro.\n\n", tail });
|
||||
expect(splitStreamingMarkdown(`Intro.\n\n${tail}`, true)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail,
|
||||
});
|
||||
}
|
||||
});
|
||||
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("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("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", () => {
|
||||
it("never retreats or loses source across every prefix of mixed Markdown", () => {
|
||||
const fixture = readFileSync(new URL("./streaming.fixture.md", import.meta.url), "utf8");
|
||||
let previous = 0;
|
||||
for (const { text, head, tail } of streamSplits(fixture)) {
|
||||
expect(head.length, `prefix ${text.length}`).toBeGreaterThanOrEqual(previous);
|
||||
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);
|
||||
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 };
|
||||
|
||||
function collectNodes(node: ASTNode, result: ASTNode[] = []): ASTNode[] {
|
||||
result.push(node);
|
||||
node.children?.forEach((child) => collectNodes(child, result));
|
||||
return result;
|
||||
}
|
||||
|
||||
describe("stabilizeStreamingMarkdown — inline code spans", () => {
|
||||
it("withholds dangling opening backticks and closes open inline code spans", () => {
|
||||
expect(stabilizeStreamingMarkdown("Use `")).toBe("Use ");
|
||||
expect(stabilizeStreamingMarkdown("Use ``")).toBe("Use ");
|
||||
expect(stabilizeStreamingMarkdown("Use `inlineblock")).toBe("Use `inlineblock`");
|
||||
expect(stabilizeStreamingMarkdown("Use `inlineblock`")).toBe("Use `inlineblock`");
|
||||
expect(stabilizeStreamingMarkdown("Use ``foo ` bar")).toBe("Use ``foo ` bar``");
|
||||
expect(stabilizeStreamingMarkdown("Use ``foo ` bar`")).toBe("Use ``foo ` bar``");
|
||||
expect(stabilizeStreamingMarkdown("Use ``foo ` bar``")).toBe("Use ``foo ` bar``");
|
||||
});
|
||||
|
||||
it("ignores escaped backticks and leaves closed spans alone", () => {
|
||||
expect(stabilizeStreamingMarkdown("Use \\`literal")).toBe("Use \\`literal");
|
||||
expect(stabilizeStreamingMarkdown("Use `a` and `b")).toBe("Use `a` and `b`");
|
||||
});
|
||||
|
||||
it("lets inline-code file paths resolve before the closing backtick arrives", async () => {
|
||||
const stabilized = stabilizeStreamingMarkdown(
|
||||
"Open `packages/app/src/components/markdown/renderer.tsx",
|
||||
);
|
||||
expect(stabilized).toBe("Open `packages/app/src/components/markdown/renderer.tsx`");
|
||||
const prepared = prepareMarkdownSource(stabilized, "/repo");
|
||||
const ast = recognizeTextLinks(
|
||||
await parseMarkdown(prepared.render(), STREAM_FLAGS),
|
||||
prepared.linkRecognition.text,
|
||||
prepared.linkRecognition.inlineCode,
|
||||
);
|
||||
const links = collectNodes(ast).filter((node) => node.type === "Link");
|
||||
expect(links.map((link) => link.attributes?.url)).toEqual([
|
||||
"packages/app/src/components/markdown/renderer.tsx",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — emphasis, strong, and strikethrough", () => {
|
||||
it("withholds bare openers, closes across spaces, and strips partial closers", async () => {
|
||||
expect(stabilizeStreamingMarkdown("This is *")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is **")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is ***")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is ~~")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is _")).toBe("This is ");
|
||||
expect(stabilizeStreamingMarkdown("This is __")).toBe("This is ");
|
||||
|
||||
expect(stabilizeStreamingMarkdown("This is **bold")).toBe("This is **bold**");
|
||||
expect(stabilizeStreamingMarkdown("This is **very ")).toBe("This is **very** ");
|
||||
expect(stabilizeStreamingMarkdown("This is **bold*")).toBe("This is **bold**");
|
||||
expect(stabilizeStreamingMarkdown("This is **bold**")).toBe("This is **bold**");
|
||||
expect(stabilizeStreamingMarkdown("This is ***bold italic*")).toBe("This is ***bold italic***");
|
||||
expect(stabilizeStreamingMarkdown("This is ***bold italic**")).toBe(
|
||||
"This is ***bold italic***",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("This is ~~strike~")).toBe("This is ~~strike~~");
|
||||
expect(stabilizeStreamingMarkdown("This is __under_")).toBe("This is __under__");
|
||||
|
||||
// Trailing space inside open bold must still parse as Strong in MD4C.
|
||||
const ast = await parseMarkdown(stabilizeStreamingMarkdown("This is **very "), STREAM_FLAGS);
|
||||
expect(collectNodes(ast).some((node) => node.type === "Strong")).toBe(true);
|
||||
});
|
||||
|
||||
it("closes nested inline constructs in LIFO order", () => {
|
||||
expect(stabilizeStreamingMarkdown("**bold and *italic")).toBe("**bold and *italic***");
|
||||
expect(stabilizeStreamingMarkdown("**bold and *italic* more")).toBe(
|
||||
"**bold and *italic* more**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("**using `code")).toBe("**using `code`**");
|
||||
expect(stabilizeStreamingMarkdown("**using `")).toBe("**using** ");
|
||||
expect(stabilizeStreamingMarkdown("**see [the `config")).toBe(
|
||||
`**see [the \`config\`](${PENDING_MARKDOWN_LINK})**`,
|
||||
);
|
||||
});
|
||||
|
||||
it("does not misread intraword underscores, multiplication, or single tildes", () => {
|
||||
expect(stabilizeStreamingMarkdown("Use my_var_name")).toBe("Use my_var_name");
|
||||
expect(stabilizeStreamingMarkdown("Use my_")).toBe("Use my_");
|
||||
expect(stabilizeStreamingMarkdown("Result is 2 * 3")).toBe("Result is 2 * 3");
|
||||
expect(stabilizeStreamingMarkdown("Result is 2*3")).toBe("Result is 2*3");
|
||||
expect(stabilizeStreamingMarkdown("Takes ~50ms in ~/dev")).toBe("Takes ~50ms in ~/dev");
|
||||
expect(stabilizeStreamingMarkdown("Escaped \\*text")).toBe("Escaped \\*text");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — links, images, and reference definitions", () => {
|
||||
it("stabilizes links across every streaming stage without leaking URLs", () => {
|
||||
expect(stabilizeStreamingMarkdown("See [")).toBe("See ");
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs]")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs](")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs](https://example.com/very/long/url")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs][ref")).toBe(
|
||||
`See [Paseo docs](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("See [Paseo docs](https://example.com/doc)")).toBe(
|
||||
"See [Paseo docs](https://example.com/doc)",
|
||||
);
|
||||
});
|
||||
|
||||
it("handles nested formatting, balanced parens in URLs, identifier brackets, and CJK", () => {
|
||||
expect(stabilizeStreamingMarkdown("See [`src/foo.ts")).toBe(
|
||||
`See [\`src/foo.ts\`](${PENDING_MARKDOWN_LINK})`,
|
||||
);
|
||||
expect(
|
||||
stabilizeStreamingMarkdown("See [Wiki](https://en.wikipedia.org/wiki/Function_(math"),
|
||||
).toBe(`See [Wiki](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(
|
||||
stabilizeStreamingMarkdown("See [Wiki](https://en.wikipedia.org/wiki/Function_(math))"),
|
||||
).toBe("See [Wiki](https://en.wikipedia.org/wiki/Function_(math))");
|
||||
expect(stabilizeStreamingMarkdown("Check arr[0")).toBe("Check arr[0");
|
||||
expect(stabilizeStreamingMarkdown("Check arr[0]")).toBe("Check arr[0]");
|
||||
expect(stabilizeStreamingMarkdown("查看[文档")).toBe(`查看[文档](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(stabilizeStreamingMarkdown("See [TODO] next")).toBe("See [TODO] next");
|
||||
});
|
||||
|
||||
it("withholds incomplete images and reference definitions without affecting exclamation marks", () => {
|
||||
expect(stabilizeStreamingMarkdown("Done!")).toBe("Done!");
|
||||
expect(stabilizeStreamingMarkdown("See ).toBe("See ");
|
||||
expect(stabilizeStreamingMarkdown("See ")).toBe(
|
||||
"See ",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Intro.\n\n[ref]: https://example.com")).toBe("Intro.\n\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — headings, lists, blockquotes, and admonitions", () => {
|
||||
it("withholds unfinished ATX headings and empty heading formatting", () => {
|
||||
expect(stabilizeStreamingMarkdown("#")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("##")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("## ")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("## **")).toBe("");
|
||||
expect(stabilizeStreamingMarkdown("## Title")).toBe("## Title");
|
||||
expect(stabilizeStreamingMarkdown("## **Title")).toBe("## **Title**");
|
||||
expect(stabilizeStreamingMarkdown("#hashtag")).toBe("#hashtag");
|
||||
});
|
||||
|
||||
it("prevents a bullet list dash after a paragraph from flashing as a Setext H2", async () => {
|
||||
for (const prefix of ["Steps:\n-", "Steps:\n- ", "Steps:\n--", "Steps:\n="]) {
|
||||
const stabilized = stabilizeStreamingMarkdown(prefix);
|
||||
expect(stabilized).toBe("Steps:\n");
|
||||
const ast = await parseMarkdown(stabilized, STREAM_FLAGS);
|
||||
expect(ast.children?.map((node) => node.type)).toEqual(["Paragraph"]);
|
||||
}
|
||||
const listAst = await parseMarkdown(
|
||||
stabilizeStreamingMarkdown("Steps:\n- First"),
|
||||
STREAM_FLAGS,
|
||||
);
|
||||
expect(listAst.children?.map((node) => node.type)).toEqual(["Paragraph", "UnorderedList"]);
|
||||
});
|
||||
|
||||
it("withholds empty list markers, task checkboxes, thematic break prefixes, and bare ***", () => {
|
||||
for (const input of [
|
||||
"-",
|
||||
"- ",
|
||||
"- [",
|
||||
"- [ ",
|
||||
"- [x",
|
||||
"- [ ]",
|
||||
"- [ ] ",
|
||||
"1",
|
||||
"1.",
|
||||
"1. ",
|
||||
"1. **",
|
||||
"--",
|
||||
"***",
|
||||
"___",
|
||||
]) {
|
||||
expect(stabilizeStreamingMarkdown(input), input).toBe("");
|
||||
}
|
||||
expect(stabilizeStreamingMarkdown("- Item")).toBe("- Item");
|
||||
expect(stabilizeStreamingMarkdown("- [ ] Task")).toBe("- [ ] Task");
|
||||
expect(stabilizeStreamingMarkdown("- [Link")).toBe(`- [Link](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(stabilizeStreamingMarkdown("1. **First")).toBe("1. **First**");
|
||||
expect(stabilizeStreamingMarkdown("100 items")).toBe("100 items");
|
||||
});
|
||||
|
||||
it("withholds empty new blockquotes and incomplete admonitions until body text arrives", () => {
|
||||
for (const input of [
|
||||
">",
|
||||
"> ",
|
||||
"> [",
|
||||
"> [!",
|
||||
"> [!NOTE",
|
||||
"> [!NOTE]",
|
||||
"> [!NOTE]\n",
|
||||
"> [!NOTE]\n> ",
|
||||
]) {
|
||||
expect(stabilizeStreamingMarkdown(input), input).toBe("");
|
||||
}
|
||||
expect(stabilizeStreamingMarkdown("> [Click")).toBe(`> [Click](${PENDING_MARKDOWN_LINK})`);
|
||||
expect(stabilizeStreamingMarkdown("> [!NOTE]\n> Body")).toBe("> [!NOTE]\n> Body");
|
||||
expect(stabilizeStreamingMarkdown("> Line 1\n>")).toBe("> Line 1\n>");
|
||||
});
|
||||
});
|
||||
|
||||
describe("stabilizeStreamingMarkdown — fences, tables, HTML, and full prefix stability", () => {
|
||||
it("withholds opening fences until content arrives and partial closing fences in quotes/lists", () => {
|
||||
for (const input of [
|
||||
"Intro\n\n`",
|
||||
"Intro\n\n``",
|
||||
"Intro\n\n```",
|
||||
"Intro\n\n```mermaid",
|
||||
"Intro\n\n```mermaid\n",
|
||||
]) {
|
||||
expect(stabilizeStreamingMarkdown(input), input).toBe("Intro\n\n");
|
||||
}
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```mermaid\ngraph LR")).toBe(
|
||||
"Intro\n\n```mermaid\ngraph LR",
|
||||
);
|
||||
// Inline syntax inside open code fences stays verbatim.
|
||||
expect(stabilizeStreamingMarkdown("```ts\nconst s = `template **not bold")).toBe(
|
||||
"```ts\nconst s = `template **not bold",
|
||||
);
|
||||
// Partial closing fences inside top-level, blockquotes, and deep list items.
|
||||
expect(stabilizeStreamingMarkdown("```ts\nconst a = 1;\n``")).toBe("```ts\nconst a = 1;\n");
|
||||
expect(stabilizeStreamingMarkdown("```ts\nconst a = 1;\n`` ")).toBe("```ts\nconst a = 1;\n`` ");
|
||||
expect(stabilizeStreamingMarkdown("> ```ts\n> const a = 1;\n> ``")).toBe(
|
||||
"> ```ts\n> const a = 1;\n",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("10. ```ts\n const a = 1;\n ``")).toBe(
|
||||
"10. ```ts\n const a = 1;\n",
|
||||
);
|
||||
});
|
||||
|
||||
it("withholds unconfirmed table headers, partial separators, and incomplete body rows", () => {
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- |")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- | --- |")).toBe(
|
||||
"Intro\n\n| A | B |\n| --- | --- |",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- | --- |\n| 1 | t")).toBe(
|
||||
"Intro\n\n| A | B |\n| --- | --- |\n",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n| A | B |\n| --- | --- |\n| 1 | 2 |")).toBe(
|
||||
"Intro\n\n| A | B |\n| --- | --- |\n| 1 | 2 |",
|
||||
);
|
||||
// Non-table pipe text falls through once line 2 is not a separator.
|
||||
expect(stabilizeStreamingMarkdown("| bitwise\nnot a table")).toBe("| bitwise\nnot a table");
|
||||
});
|
||||
|
||||
it("withholds incomplete HTML tags and comments without touching math comparisons", () => {
|
||||
expect(stabilizeStreamingMarkdown("Before<br")).toBe("Before");
|
||||
expect(stabilizeStreamingMarkdown("Before<!-- hidden")).toBe("Before");
|
||||
expect(stabilizeStreamingMarkdown("a < b && c > d")).toBe("a < b && c > d");
|
||||
expect(stabilizeStreamingMarkdown("List<string")).toBe("List<string");
|
||||
});
|
||||
|
||||
it("stays idempotent and produces jump-free MD4C ASTs across every character prefix", async () => {
|
||||
const sample = [
|
||||
"## Summary of `MarkdownRenderer`",
|
||||
"",
|
||||
"Check **important details** and [Paseo docs](https://example.com/very/long/documentation) plus `packages/app/src/components/markdown/renderer.tsx`.",
|
||||
"",
|
||||
"Here are the next steps:",
|
||||
"- First item with ~~old~~ and *new*",
|
||||
"- [ ] Task item",
|
||||
"",
|
||||
"1. **Ordered** item",
|
||||
"",
|
||||
"> [!NOTE]",
|
||||
"> Helpful callout body.",
|
||||
"",
|
||||
"```mermaid",
|
||||
"graph LR",
|
||||
"A --> B",
|
||||
"```",
|
||||
"",
|
||||
"| Stage | Result |",
|
||||
"| --- | --- |",
|
||||
"| Step 1 | Ready |",
|
||||
"| Step 2 | Done |",
|
||||
"",
|
||||
"Finished.",
|
||||
].join("\n");
|
||||
|
||||
const incremental = createStreamingMarkdownStabilizer();
|
||||
for (let end = 0; end <= sample.length; end++) {
|
||||
const prefix = sample.slice(0, end);
|
||||
const stabilized = stabilizeStreamingMarkdown(prefix);
|
||||
// Incremental checkpoint must match cold stabilization on every prefix.
|
||||
expect(incremental.stabilize(prefix), `incremental parity at ${end}`).toBe(stabilized);
|
||||
// Idempotence invariant
|
||||
expect(stabilizeStreamingMarkdown(stabilized), `idempotent at ${end}`).toBe(stabilized);
|
||||
|
||||
if (!stabilized) continue;
|
||||
const ast = await parseMarkdown(
|
||||
prepareMarkdownSource(stabilized, "/repo").render(),
|
||||
STREAM_FLAGS,
|
||||
);
|
||||
const nodes = collectNodes(ast);
|
||||
|
||||
for (const node of nodes) {
|
||||
// Never emit empty headings, blockquotes, admonitions, code blocks, or list items.
|
||||
if (
|
||||
node.type === "Heading" ||
|
||||
node.type === "Blockquote" ||
|
||||
node.type === "Admonition" ||
|
||||
node.type === "CodeBlock" ||
|
||||
node.type === "ListItem"
|
||||
) {
|
||||
expect(
|
||||
(node.children?.length ?? 0) > 0,
|
||||
`non-empty ${node.type} at prefix ${end}: ${JSON.stringify(stabilized)}`,
|
||||
).toBe(true);
|
||||
}
|
||||
// Mermaid opening fence never flashes as a partial-language non-mermaid CodeBlock.
|
||||
if (node.type === "CodeBlock") {
|
||||
expect(node.attributes?.language, `code language at ${end}`).toBe("mermaid");
|
||||
}
|
||||
// "Here are the next steps:" never explodes into a Setext heading.
|
||||
if (node.type === "Heading") {
|
||||
const text = collectNodes(node)
|
||||
.map((child) => child.content ?? "")
|
||||
.join("");
|
||||
expect(text, `no setext explosion at ${end}`).not.toContain("Here are the next steps");
|
||||
}
|
||||
// Raw Markdown delimiters and URLs never leak into prose text nodes.
|
||||
if (node.type === "Text") {
|
||||
const content = node.content ?? "";
|
||||
expect(content, `no raw ** at ${end}`).not.toContain("**");
|
||||
expect(content, `no raw backtick at ${end}`).not.toContain("`");
|
||||
expect(content, `no raw URL leak at ${end}`).not.toContain("https://example.com");
|
||||
expect(content, `no raw table pipe at ${end}`).not.toContain("| Stage");
|
||||
expect(content, `no raw admonition tag at ${end}`).not.toContain("[!NOTE");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Switching to an unrelated or shorter message resets the checkpoint cleanly.
|
||||
expect(incremental.stabilize("```ts\nconst x = 1;\n`")).toBe("```ts\nconst x = 1;\n");
|
||||
expect(incremental.stabilize("Plain\nCheck `inline")).toBe("Plain\nCheck `inline`");
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
@@ -1,104 +1,32 @@
|
||||
import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { Nodes, Root } from "mdast";
|
||||
import type { Nodes } from "mdast";
|
||||
|
||||
export {
|
||||
createStreamingMarkdownStabilizer,
|
||||
PENDING_MARKDOWN_LINK,
|
||||
stabilizeStreamingMarkdown,
|
||||
} from "./streaming-stabilize";
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// 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.
|
||||
// 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") return true;
|
||||
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);
|
||||
}
|
||||
|
||||
// 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 = "";
|
||||
/** 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, {
|
||||
extensions: [gfmTable()],
|
||||
mdastExtensions: [gfmTableFromMarkdown()],
|
||||
});
|
||||
let boundary = 0;
|
||||
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;
|
||||
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;
|
||||
}
|
||||
|
||||
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),
|
||||
};
|
||||
};
|
||||
return { head: text.slice(0, boundary), tail: text.slice(boundary) };
|
||||
}
|
||||
|
||||
@@ -137,9 +137,9 @@ export function PageTitle({
|
||||
descriptionTestID,
|
||||
}: PageTitleProps) {
|
||||
return (
|
||||
<View style={styles.titleBlock}>
|
||||
<View style={styles.titleBlock} testID={testID}>
|
||||
<View style={styles.titleRow}>
|
||||
<View style={styles.titleParts} testID={testID}>
|
||||
<View style={styles.titleParts}>
|
||||
{parent ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
|
||||
@@ -19,7 +19,7 @@ import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-moda
|
||||
import { ComboboxItem } from "@/components/ui/combobox";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { CombinedModelSelector } from "@/components/combined-model-selector";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
|
||||
import { createControlGeometry, type ControlSize } from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
@@ -659,13 +659,6 @@ function ScheduleTargetFields({
|
||||
(input: SelectFieldRenderOptionInput<string>) => <ThinkingOptionItem {...input} />,
|
||||
[],
|
||||
);
|
||||
const hostTriggerLeading = useMemo(
|
||||
() =>
|
||||
state.selectedServerId ? (
|
||||
<HostStatusIcon serverId={state.selectedServerId} size="md" backdrop="surface2" />
|
||||
) : null,
|
||||
[state.selectedServerId],
|
||||
);
|
||||
const modelTriggerLeading = useMemo(
|
||||
() => <ProviderGlyph provider={state.selectedProvider} serverId={state.selectedServerId} />,
|
||||
[state.selectedProvider, state.selectedServerId],
|
||||
@@ -721,7 +714,6 @@ function ScheduleTargetFields({
|
||||
searchable={false}
|
||||
title="Host"
|
||||
size={controlSize}
|
||||
triggerLeading={hostTriggerLeading}
|
||||
triggerTestID="schedule-host-trigger"
|
||||
renderOption={renderHostOption}
|
||||
/>
|
||||
@@ -960,16 +952,7 @@ function HostOptionItem({
|
||||
active,
|
||||
onPress,
|
||||
}: SelectFieldRenderOptionInput<string>): ReactElement {
|
||||
const leadingSlot = useMemo(
|
||||
() => (
|
||||
<HostStatusIcon
|
||||
serverId={option.value}
|
||||
size="md"
|
||||
backdrop={active ? "surface1" : "surface0"}
|
||||
/>
|
||||
),
|
||||
[active, option.value],
|
||||
);
|
||||
const leadingSlot = useMemo(() => <HostStatusDotSlot serverId={option.value} />, [option.value]);
|
||||
|
||||
return (
|
||||
<ComboboxItem
|
||||
|
||||
@@ -6,8 +6,6 @@ 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;
|
||||
@@ -15,8 +13,6 @@ 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;
|
||||
@@ -32,12 +28,10 @@ interface SettingsCollapsibleRowProps {
|
||||
*/
|
||||
export function SettingsCollapsibleRow({
|
||||
label,
|
||||
leading,
|
||||
hint,
|
||||
hintStatus,
|
||||
summary,
|
||||
control,
|
||||
trailing,
|
||||
accessibilityLabel,
|
||||
defaultExpanded = false,
|
||||
testID,
|
||||
@@ -56,12 +50,10 @@ 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,8 +36,6 @@ 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. */
|
||||
@@ -77,7 +75,6 @@ export function SettingsRowHeader({
|
||||
hintStatus,
|
||||
summary,
|
||||
summaryLeading,
|
||||
trailing,
|
||||
onPress,
|
||||
disabled,
|
||||
expanded = false,
|
||||
@@ -138,14 +135,6 @@ 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}
|
||||
@@ -261,10 +250,6 @@ 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,
|
||||
|
||||
@@ -288,7 +288,6 @@ interface WorkspaceRowInnerProps {
|
||||
drag?: () => void;
|
||||
isDragging: boolean;
|
||||
isArchiving: boolean;
|
||||
showArchiveIndicator: boolean;
|
||||
isCreating?: boolean;
|
||||
dragHandleProps?: DraggableListDragHandleProps;
|
||||
menuController: ReturnType<typeof useContextMenu> | null;
|
||||
@@ -621,7 +620,6 @@ function WorkspaceRowRightGroup({
|
||||
isHovered,
|
||||
isTouchPlatform,
|
||||
isCreating,
|
||||
showArchiveIndicator,
|
||||
isSelectionMode,
|
||||
showShortcutBadge,
|
||||
shortcutNumber,
|
||||
@@ -644,7 +642,6 @@ function WorkspaceRowRightGroup({
|
||||
isHovered: boolean;
|
||||
isTouchPlatform: boolean;
|
||||
isCreating: boolean;
|
||||
showArchiveIndicator: boolean;
|
||||
isSelectionMode: boolean;
|
||||
showShortcutBadge: boolean;
|
||||
shortcutNumber: number | null;
|
||||
@@ -670,7 +667,6 @@ function WorkspaceRowRightGroup({
|
||||
trailingPresentation,
|
||||
showKebab: showKebabInSlot,
|
||||
showArchiveButton,
|
||||
showArchivingSpinner,
|
||||
showScrim,
|
||||
renderSlot,
|
||||
reserveSlotWidth,
|
||||
@@ -682,7 +678,6 @@ function WorkspaceRowRightGroup({
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
showArchiveIndicator,
|
||||
});
|
||||
const kebab = useOpenKebabMenuVisibility(showKebabInSlot);
|
||||
|
||||
@@ -705,7 +700,6 @@ function WorkspaceRowRightGroup({
|
||||
scrimBackdrop={showScrim ? backdrop : undefined}
|
||||
workspaceKey={workspace.workspaceKey}
|
||||
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
|
||||
showArchiveIndicator={showArchivingSpinner}
|
||||
>
|
||||
{onArchive ? (
|
||||
<SidebarWorkspaceMenu
|
||||
@@ -1084,7 +1078,6 @@ function WorkspaceRowInner({
|
||||
drag,
|
||||
isDragging,
|
||||
isArchiving,
|
||||
showArchiveIndicator,
|
||||
isCreating = false,
|
||||
dragHandleProps,
|
||||
menuController,
|
||||
@@ -1146,7 +1139,6 @@ function WorkspaceRowInner({
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const isDesktop = !isTouchPlatform;
|
||||
@@ -1214,9 +1206,8 @@ function WorkspaceRowInner({
|
||||
serviceSummary={serviceSummary}
|
||||
backdrop={backdrop}
|
||||
isHovered={isHovered}
|
||||
isLoading={isCreating}
|
||||
isLoading={isArchiving || isCreating}
|
||||
isCreating={isCreating}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
@@ -1230,7 +1221,6 @@ function WorkspaceRowInner({
|
||||
isHovered={isHovered}
|
||||
isTouchPlatform={isTouchPlatform}
|
||||
isCreating={isCreating}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
shortcutNumber={shortcutNumber}
|
||||
@@ -1317,8 +1307,6 @@ function WorkspaceRowWithMenu({
|
||||
});
|
||||
const isArchiving =
|
||||
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
|
||||
const showArchiveIndicator =
|
||||
workspace.archivingAt !== null || archiveController.isShowingArchiveIndicator;
|
||||
|
||||
const handleArchive = useCallback(() => {
|
||||
if (isArchiving) {
|
||||
@@ -1377,12 +1365,11 @@ function WorkspaceRowWithMenu({
|
||||
drag={drag}
|
||||
isDragging={isDragging}
|
||||
isArchiving={isArchiving}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isCreating={isCreating}
|
||||
dragHandleProps={dragHandleProps}
|
||||
menuController={null}
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={showArchiveIndicator ? "pending" : "idle"}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
Settings,
|
||||
} from "lucide-react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { HostStatusDotSlot } from "@/components/hosts/host-picker";
|
||||
import type { SidebarFooterAction } from "@/components/sidebar-footer-layout";
|
||||
import {
|
||||
DropdownMenu,
|
||||
@@ -232,10 +232,7 @@ function HostRow({
|
||||
() => onOpenHostSettings(serverId),
|
||||
[onOpenHostSettings, serverId],
|
||||
);
|
||||
const leading = useMemo(
|
||||
() => <HostStatusIcon serverId={serverId} size="sm" backdrop="surface1" />,
|
||||
[serverId],
|
||||
);
|
||||
const leading = useMemo(() => <HostStatusDotSlot serverId={serverId} />, [serverId]);
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
testID={`sidebar-host-row-${serverId}`}
|
||||
|
||||
@@ -743,8 +743,6 @@ function StatusWorkspaceRowWithMenu({
|
||||
});
|
||||
const isArchiving =
|
||||
workspace.archivingAt !== null || isHidingWorkspace || archiveController.isConfirming;
|
||||
const showArchiveIndicator =
|
||||
workspace.archivingAt !== null || archiveController.isShowingArchiveIndicator;
|
||||
|
||||
const handleArchive = useCallback(() => {
|
||||
if (isArchiving) return;
|
||||
@@ -799,9 +797,8 @@ function StatusWorkspaceRowWithMenu({
|
||||
showShortcutBadge={showShortcutBadge}
|
||||
onPress={onPress}
|
||||
isArchiving={isArchiving}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
archiveLabel={t("sidebar.workspace.actions.archive")}
|
||||
archiveStatus={showArchiveIndicator ? "pending" : "idle"}
|
||||
archiveStatus={isArchiving ? "pending" : "idle"}
|
||||
archivePendingLabel={t("sidebar.workspace.actions.archiving")}
|
||||
onSelectWorkspace={handleSelectWorkspace}
|
||||
onArchive={handleArchive}
|
||||
@@ -835,7 +832,6 @@ interface StatusWorkspaceRowInnerProps {
|
||||
showShortcutBadge: boolean;
|
||||
onPress: () => void;
|
||||
isArchiving: boolean;
|
||||
showArchiveIndicator: boolean;
|
||||
archiveLabel?: string;
|
||||
archiveStatus?: "idle" | "pending" | "success";
|
||||
archivePendingLabel?: string;
|
||||
@@ -886,7 +882,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
showShortcutBadge,
|
||||
onPress,
|
||||
isArchiving,
|
||||
showArchiveIndicator,
|
||||
archiveLabel,
|
||||
archiveStatus = "idle",
|
||||
archivePendingLabel,
|
||||
@@ -954,7 +949,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
isDragging={isDragging}
|
||||
isEditingTitle={isEditingTitle}
|
||||
isSelectionMode={isSelectionMode}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
>
|
||||
{({ isHovered, contextMenuOpen, onContextMenuOpenChange, hoverHandlers }) => {
|
||||
const showShortcut = showShortcutBadge && shortcutNumber !== null;
|
||||
@@ -962,7 +956,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
trailingPresentation,
|
||||
showKebab: showKebabInSlot,
|
||||
showArchiveButton,
|
||||
showArchivingSpinner,
|
||||
showScrim,
|
||||
renderSlot,
|
||||
reserveSlotWidth,
|
||||
@@ -974,7 +967,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode,
|
||||
showArchiveIndicator,
|
||||
});
|
||||
const workspaceRowStyle = getStatusWorkspaceRowStyle({
|
||||
selected: rowSelected,
|
||||
@@ -1041,8 +1033,7 @@ function StatusWorkspaceRowInnerContent({
|
||||
serviceSummary={serviceSummary}
|
||||
backdrop={backdrop}
|
||||
isHovered={isHovered}
|
||||
isLoading={false}
|
||||
showArchiveIndicator={showArchiveIndicator}
|
||||
isLoading={isArchiving}
|
||||
isSelectionMode={isSelectionMode}
|
||||
isBulkSelected={isBulkSelected}
|
||||
shortcutNumber={shortcutNumber}
|
||||
@@ -1058,7 +1049,6 @@ function StatusWorkspaceRowInnerContent({
|
||||
trailingPresentation={trailingPresentation}
|
||||
showKebab={showKebabInSlot}
|
||||
showArchiveButton={showArchiveButton}
|
||||
showArchivingSpinner={showArchivingSpinner}
|
||||
showScrim={showScrim}
|
||||
reserveSlotWidth={reserveSlotWidth}
|
||||
isPinned={isPinned}
|
||||
@@ -1093,7 +1083,6 @@ function StatusWorkspaceActionSlot({
|
||||
trailingPresentation,
|
||||
showKebab,
|
||||
showArchiveButton,
|
||||
showArchivingSpinner,
|
||||
showScrim,
|
||||
reserveSlotWidth,
|
||||
isPinned,
|
||||
@@ -1116,7 +1105,6 @@ function StatusWorkspaceActionSlot({
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
showArchiveButton: boolean;
|
||||
showArchivingSpinner: boolean;
|
||||
showScrim: boolean;
|
||||
reserveSlotWidth: boolean;
|
||||
isPinned?: boolean;
|
||||
@@ -1148,7 +1136,6 @@ function StatusWorkspaceActionSlot({
|
||||
scrimBackdrop={showScrim ? backdrop : undefined}
|
||||
workspaceKey={workspace.workspaceKey}
|
||||
onArchiveButtonPress={showArchiveButton ? onArchive : undefined}
|
||||
showArchiveIndicator={showArchivingSpinner}
|
||||
>
|
||||
{kebab.showKebab && onArchive ? (
|
||||
<SidebarWorkspaceMenu
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
import { memo, useMemo, useCallback, useState, type ReactNode } from "react";
|
||||
import { Text, View, type ViewStyle } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Check, CircleAlert, Folder, FolderGit2, Monitor } from "lucide-react-native";
|
||||
import { bySizing } from "@/components/ui/control-geometry";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { ProjectStatusIndicator } from "@/components/sidebar/project-leading-visual";
|
||||
import type { SidebarSurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import {
|
||||
@@ -46,20 +44,15 @@ const needsInputColorMapping = (theme: Theme) => ({
|
||||
const checkedIconMapping = (theme: Theme) => ({
|
||||
color: theme.colors.accentForeground,
|
||||
});
|
||||
const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
const ThemedCheck = withUnistyles(Check);
|
||||
const ThemedCircleAlert = withUnistyles(CircleAlert);
|
||||
const ThemedLoadingSpinner = withUnistyles(LoadingSpinner);
|
||||
|
||||
export function SidebarWorkspaceRowFrame({
|
||||
workspace,
|
||||
isDragging = false,
|
||||
isEditingTitle = false,
|
||||
isSelectionMode = false,
|
||||
showArchiveIndicator = false,
|
||||
children,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
@@ -68,7 +61,6 @@ export function SidebarWorkspaceRowFrame({
|
||||
isEditingTitle?: boolean;
|
||||
/** Hover cards would cover neighbouring rows while the user clicks through a selection. */
|
||||
isSelectionMode?: boolean;
|
||||
showArchiveIndicator?: boolean;
|
||||
children: (input: {
|
||||
isHovered: boolean;
|
||||
contextMenuOpen: boolean;
|
||||
@@ -96,7 +88,7 @@ export function SidebarWorkspaceRowFrame({
|
||||
workspace={workspace}
|
||||
prHint={workspace.prHint}
|
||||
isDragging={isDragging}
|
||||
disabled={contextMenuOpen || isEditingTitle || isSelectionMode || showArchiveIndicator}
|
||||
disabled={contextMenuOpen || isEditingTitle || isSelectionMode}
|
||||
>
|
||||
{children({
|
||||
isHovered: isHovered && !contextMenuOpen && !isDragging && !isEditingTitle,
|
||||
@@ -118,7 +110,6 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered,
|
||||
isLoading,
|
||||
isCreating = false,
|
||||
showArchiveIndicator = false,
|
||||
isSelectionMode = false,
|
||||
isBulkSelected = false,
|
||||
shortcutNumber = null,
|
||||
@@ -138,8 +129,6 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
isHovered: boolean;
|
||||
isLoading: boolean;
|
||||
isCreating?: boolean;
|
||||
/** Dims the row's status, title, and metadata while keeping the trailing spinner crisp. */
|
||||
showArchiveIndicator?: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
isBulkSelected?: boolean;
|
||||
shortcutNumber?: number | null;
|
||||
@@ -162,17 +151,8 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
styles.workspaceBranchText,
|
||||
(isHovered || isBulkSelected) && styles.workspaceBranchTextHovered,
|
||||
isCreating && styles.workspaceBranchTextCreating,
|
||||
showArchiveIndicator && styles.workspaceBranchTextArchiving,
|
||||
],
|
||||
[isHovered, isBulkSelected, isCreating, showArchiveIndicator],
|
||||
);
|
||||
const leadingWrapperStyle = useMemo(
|
||||
() => [styles.leadingVisualWrapper, showArchiveIndicator && styles.archivingDimmed],
|
||||
[showArchiveIndicator],
|
||||
);
|
||||
const metaWrapperStyle = useMemo(
|
||||
() => (showArchiveIndicator ? styles.archivingDimmed : undefined),
|
||||
[showArchiveIndicator],
|
||||
[isHovered, isBulkSelected, isCreating],
|
||||
);
|
||||
|
||||
let leadingVisual: ReactNode;
|
||||
@@ -206,7 +186,7 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
return (
|
||||
<View style={styles.workspaceRowContent}>
|
||||
<View style={styles.workspaceRowMain}>
|
||||
<View style={leadingWrapperStyle}>{leadingVisual}</View>
|
||||
{leadingVisual}
|
||||
<View style={styles.workspaceContentColumn}>
|
||||
<View style={styles.workspaceTitleRow}>
|
||||
{titleEditor ? (
|
||||
@@ -222,18 +202,16 @@ export const SidebarWorkspaceRowContent = memo(function SidebarWorkspaceRowConte
|
||||
)}
|
||||
<View style={sidebarWorkspaceRowStyles.rowRight}>{children}</View>
|
||||
</View>
|
||||
<View style={metaWrapperStyle}>
|
||||
<WorkspaceMetaRow
|
||||
backdrop={backdrop}
|
||||
currentBranch={workspace.currentBranch}
|
||||
projectName={leadingProjectName}
|
||||
hostBadge={hostBadge ?? null}
|
||||
prHint={workspace.prHint}
|
||||
serviceSummary={serviceSummary}
|
||||
labels={labels}
|
||||
workspace={workspace}
|
||||
/>
|
||||
</View>
|
||||
<WorkspaceMetaRow
|
||||
backdrop={backdrop}
|
||||
currentBranch={workspace.currentBranch}
|
||||
projectName={leadingProjectName}
|
||||
hostBadge={hostBadge ?? null}
|
||||
prHint={workspace.prHint}
|
||||
serviceSummary={serviceSummary}
|
||||
labels={labels}
|
||||
workspace={workspace}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
{!isSelectionMode && showShortcutBadge && shortcutNumber !== null ? (
|
||||
@@ -444,7 +422,6 @@ export function resolveTrailingActionVisibility({
|
||||
isTouchPlatform,
|
||||
showShortcut,
|
||||
isSelectionMode = false,
|
||||
showArchiveIndicator = false,
|
||||
}: {
|
||||
workspace: SidebarWorkspaceEntry;
|
||||
trailing: SidebarWorkspaceTrailing;
|
||||
@@ -453,42 +430,20 @@ export function resolveTrailingActionVisibility({
|
||||
isTouchPlatform: boolean;
|
||||
showShortcut: boolean;
|
||||
isSelectionMode?: boolean;
|
||||
showArchiveIndicator?: boolean;
|
||||
}): {
|
||||
trailingPresentation: SidebarWorkspaceTrailingPresentation;
|
||||
showKebab: boolean;
|
||||
showArchiveButton: boolean;
|
||||
showArchivingSpinner: boolean;
|
||||
showScrim: boolean;
|
||||
renderSlot: boolean;
|
||||
reserveSlotWidth: boolean;
|
||||
} {
|
||||
const hasTrailing = hasSidebarWorkspaceTrailing({ workspace, trailing });
|
||||
const allowRowActions = hasArchiveAction && !isSelectionMode;
|
||||
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints and the
|
||||
// archiving spinner conceal content while retaining its width, so desktop rows do not shift.
|
||||
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
|
||||
// The slot only holds width for something that permanently sits in it. Trailing content
|
||||
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
||||
// no scrim to let it overlay the title. Keeping this invariant across archiving ensures the
|
||||
// title column never changes width.
|
||||
const reserveSlotWidth = hasContent || (allowRowActions && isTouchPlatform);
|
||||
|
||||
if (showArchiveIndicator) {
|
||||
return {
|
||||
trailingPresentation: hasContent ? "hidden" : "absent",
|
||||
showKebab: false,
|
||||
showArchiveButton: false,
|
||||
showArchivingSpinner: true,
|
||||
// On a pointer row without trailing content, scrim the title tail behind the spinner
|
||||
// using the row's current backdrop so the title never reflows.
|
||||
showScrim: !hasContent && !isTouchPlatform,
|
||||
renderSlot: true,
|
||||
reserveSlotWidth,
|
||||
};
|
||||
}
|
||||
|
||||
const showKebab = Boolean(allowRowActions && (isHovered || isTouchPlatform)) && !showShortcut;
|
||||
// Touch permanently replaces the stats with the menu. Only temporary shortcut hints
|
||||
// conceal content while retaining its width, so desktop rows do not shift.
|
||||
const hasContent = hasTrailing && !(allowRowActions && isTouchPlatform);
|
||||
let trailingPresentation: SidebarWorkspaceTrailingPresentation = "absent";
|
||||
if (hasContent) trailingPresentation = showShortcut ? "hidden" : "visible";
|
||||
return {
|
||||
@@ -497,13 +452,16 @@ export function resolveTrailingActionVisibility({
|
||||
// One-click archive is a pointer affordance: on touch it would sit a few pixels from the
|
||||
// kebab and turn a miss into an archive.
|
||||
showArchiveButton: showKebab && isHovered && !isTouchPlatform,
|
||||
showArchivingSpinner: false,
|
||||
// The scrim paints the row's own hover background, so it can only be drawn on a hovered
|
||||
// row — over an unhovered one the gradient fades to the wrong color. That is also why
|
||||
// touch, which shows the kebab without ever hovering, never gets one.
|
||||
showScrim: showKebab && isHovered,
|
||||
renderSlot: allowRowActions || hasTrailing,
|
||||
reserveSlotWidth,
|
||||
// The slot only holds width for something that permanently sits in it. Trailing content
|
||||
// does; the kebab only does on touch, where there is no hover for it to appear on and so
|
||||
// no scrim to let it overlay the title. Everywhere else the width goes back to the title
|
||||
// and the kebab fades in over its tail.
|
||||
reserveSlotWidth: hasContent || (allowRowActions && isTouchPlatform),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -547,7 +505,6 @@ export function SidebarWorkspaceTrailingActionOverlay({
|
||||
scrimBackdrop,
|
||||
workspaceKey,
|
||||
onArchiveButtonPress,
|
||||
showArchiveIndicator = false,
|
||||
children,
|
||||
}: {
|
||||
visible: boolean;
|
||||
@@ -559,36 +516,8 @@ export function SidebarWorkspaceTrailingActionOverlay({
|
||||
* the scrim widens to cover it rather than the slot reserving its width.
|
||||
*/
|
||||
onArchiveButtonPress?: () => void;
|
||||
/** Replaces hover actions with a neutral spinner in the same trailing slot. */
|
||||
showArchiveIndicator?: boolean;
|
||||
children: ReactNode;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
if (showArchiveIndicator) {
|
||||
return (
|
||||
<>
|
||||
{scrimBackdrop ? (
|
||||
<TrailingActionScrim
|
||||
backdrop={scrimBackdrop}
|
||||
width={SCRIM_WIDTH}
|
||||
testID="sidebar-workspace-trailing-scrim"
|
||||
/>
|
||||
) : null}
|
||||
<View
|
||||
style={sidebarWorkspaceRowStyles.trailingActionOverlay}
|
||||
testID="workspace-archive-pending-indicator"
|
||||
>
|
||||
<View style={styles.archivingSpinnerSlot}>
|
||||
<ThemedLoadingSpinner
|
||||
size={14}
|
||||
uniProps={foregroundMutedColorMapping}
|
||||
accessibilityLabel={t("sidebar.workspace.actions.archiving")}
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!visible || !children) return null;
|
||||
return (
|
||||
<>
|
||||
@@ -625,18 +554,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
gap: theme.spacing[2],
|
||||
width: "100%",
|
||||
},
|
||||
leadingVisualWrapper: {
|
||||
flexShrink: 0,
|
||||
},
|
||||
archivingDimmed: {
|
||||
opacity: 0.55,
|
||||
},
|
||||
archivingSpinnerSlot: {
|
||||
width: 18,
|
||||
height: TITLE_LINE_HEIGHT,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
},
|
||||
workspaceContentColumn: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
@@ -724,9 +641,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
workspaceBranchTextHovered: {
|
||||
opacity: 1,
|
||||
},
|
||||
workspaceBranchTextArchiving: {
|
||||
opacity: 0.45,
|
||||
},
|
||||
statusDotNeedsInput: {
|
||||
backgroundColor: getStatusDotColor({ theme, bucket: "needs_input" }) ?? undefined,
|
||||
borderColor: theme.colors.surface0,
|
||||
|
||||
@@ -27,19 +27,17 @@ const chevronColorMapping = (theme: Theme) => ({
|
||||
color: theme.colors.foregroundMuted,
|
||||
});
|
||||
|
||||
export interface ComboboxTriggerState {
|
||||
interface TriggerState {
|
||||
pressed: boolean;
|
||||
hovered: boolean;
|
||||
focused: boolean;
|
||||
}
|
||||
|
||||
type TriggerStyleProp =
|
||||
| StyleProp<ViewStyle>
|
||||
| ((state: ComboboxTriggerState) => StyleProp<ViewStyle>);
|
||||
type TriggerStyleProp = StyleProp<ViewStyle> | ((state: TriggerState) => StyleProp<ViewStyle>);
|
||||
|
||||
interface ComboboxTriggerProps extends Omit<PressableProps, "style" | "children"> {
|
||||
style?: TriggerStyleProp;
|
||||
children?: ReactNode | ((state: ComboboxTriggerState) => ReactNode);
|
||||
children?: ReactNode;
|
||||
chevron?: ReactNode | null;
|
||||
tooltip?: ReactNode;
|
||||
// Fill the Pressable's width and use the standard sidebar-row gap, so the
|
||||
@@ -79,13 +77,6 @@ export const ComboboxTrigger = forwardRef<View, ComboboxTriggerProps>(function C
|
||||
);
|
||||
|
||||
const rowStyle = useMemo(() => [styles.row, block && styles.rowBlock], [block]);
|
||||
const chevronElement =
|
||||
chevron !== null &&
|
||||
(chevron ?? (
|
||||
<View style={styles.chevronContainer}>
|
||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={chevronColorMapping} />
|
||||
</View>
|
||||
));
|
||||
|
||||
const button = (
|
||||
<Pressable
|
||||
@@ -96,19 +87,15 @@ export const ComboboxTrigger = forwardRef<View, ComboboxTriggerProps>(function C
|
||||
onBlur={handleBlur}
|
||||
{...props}
|
||||
>
|
||||
{typeof children === "function" ? (
|
||||
({ pressed, hovered = false }: PressableStateCallbackType & { hovered?: boolean }) => (
|
||||
<View style={rowStyle}>
|
||||
{children({ pressed, hovered, focused })}
|
||||
{chevronElement}
|
||||
</View>
|
||||
)
|
||||
) : (
|
||||
<View style={rowStyle}>
|
||||
{children}
|
||||
{chevronElement}
|
||||
</View>
|
||||
)}
|
||||
<View style={rowStyle}>
|
||||
{children}
|
||||
{chevron !== null &&
|
||||
(chevron ?? (
|
||||
<View style={styles.chevronContainer}>
|
||||
<ThemedChevronDown size={ICON_SIZE.sm} uniProps={chevronColorMapping} />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</Pressable>
|
||||
);
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { View } from "react-native";
|
||||
import { Text, 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,15 +9,17 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
});
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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.
|
||||
*/
|
||||
export function LoadingState({
|
||||
accessibilityLabel,
|
||||
title,
|
||||
description,
|
||||
testID,
|
||||
}: {
|
||||
/** What the wait is for, announced by screen readers only. */
|
||||
accessibilityLabel?: string;
|
||||
/** What the wait is for. Leave it out while the wait is too short to read. */
|
||||
title?: string;
|
||||
description?: string;
|
||||
testID?: string;
|
||||
}) {
|
||||
return (
|
||||
@@ -25,8 +27,14 @@ export function LoadingState({
|
||||
<ThemedLoadingSpinner
|
||||
size="small"
|
||||
uniProps={foregroundMutedColorMapping}
|
||||
accessibilityLabel={accessibilityLabel}
|
||||
accessibilityLabel={title}
|
||||
/>
|
||||
{title ? (
|
||||
<View style={styles.textStack}>
|
||||
<Text style={styles.title}>{title}</Text>
|
||||
{description ? <Text style={styles.description}>{description}</Text> : null}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
@@ -36,6 +44,23 @@ 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",
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -838,100 +838,6 @@ describe("enqueueComposerAgentMessage", () => {
|
||||
enqueueComposerAgentMessage({ client, agentId: "agent", text: "hello", attachments: [] }),
|
||||
).rejects.toBe(rejection);
|
||||
});
|
||||
|
||||
it("shows an optimistic row immediately during upload and send, disables it while pending, and reconciles or rolls back cleanly", async () => {
|
||||
const { createAgentQueueModel } = await import("@/agent-queue/model");
|
||||
const { queuedItem, startAgentQueueDaemon } = await import("@/test/agent-queue-daemon");
|
||||
const daemon = await startAgentQueueDaemon();
|
||||
try {
|
||||
await daemon.publish("agent", {
|
||||
held: true,
|
||||
items: [queuedItem("existing", { seq: 1, held: true })],
|
||||
});
|
||||
const model = createAgentQueueModel({
|
||||
serverId: "host",
|
||||
agentId: "agent",
|
||||
host: daemon.host,
|
||||
});
|
||||
model.subscribe(() => {});
|
||||
await daemon.settle();
|
||||
expect(model.getSnapshot().held).toBe(true);
|
||||
|
||||
let releaseUpload!: () => void;
|
||||
const uploadGate = new Promise<void>((resolve) => {
|
||||
releaseUpload = resolve;
|
||||
});
|
||||
let sentMessageId = "";
|
||||
let sendFailure: Error | null = null;
|
||||
const sendClient: Parameters<typeof enqueueComposerAgentMessage>[0]["client"] = {
|
||||
...createFakeSendClient(),
|
||||
sync: daemon.client.sync,
|
||||
sendAgentMessage: async (_agentId, text, options) => {
|
||||
sentMessageId = options.messageId;
|
||||
if (sendFailure) throw sendFailure;
|
||||
await daemon.publish("agent", {
|
||||
held: false,
|
||||
items: [
|
||||
queuedItem("existing", { seq: 1 }),
|
||||
queuedItem(options.messageId, { seq: 2, text, attachments: options.attachments }),
|
||||
],
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
// Row appears immediately while image upload is still in flight, clears held, and is busy.
|
||||
const pending = enqueueComposerAgentMessage({
|
||||
client: sendClient,
|
||||
agentId: "agent",
|
||||
text: "follow up",
|
||||
attachments: [{ kind: "image", metadata: imageWithId("img-1") }],
|
||||
uploadImages: async (images) => {
|
||||
await uploadGate;
|
||||
return passthroughUploadImages(images);
|
||||
},
|
||||
});
|
||||
|
||||
const duringUpload = model.getSnapshot();
|
||||
expect(duringUpload.held).toBe(false);
|
||||
expect(duringUpload.items).toHaveLength(2);
|
||||
expect(duringUpload.items[1]).toMatchObject({
|
||||
text: "follow up",
|
||||
state: "queued",
|
||||
attachments: [expect.objectContaining({ id: "img-1", role: "image" })],
|
||||
});
|
||||
expect(duringUpload.busy.has(duringUpload.items[1]!.id)).toBe(true);
|
||||
|
||||
releaseUpload();
|
||||
await pending;
|
||||
await daemon.settle();
|
||||
|
||||
// Reconciled cleanly to authoritative server row with zero duplicates and busy cleared.
|
||||
const firstMessageId = sentMessageId;
|
||||
expect(model.getSnapshot().items.map((item) => item.id)).toEqual([
|
||||
"existing",
|
||||
firstMessageId,
|
||||
]);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
|
||||
// A failed send rolls back its optimistic row immediately.
|
||||
sendFailure = new Error("Send rejected");
|
||||
await expect(
|
||||
enqueueComposerAgentMessage({
|
||||
client: sendClient,
|
||||
agentId: "agent",
|
||||
text: "will fail",
|
||||
attachments: [],
|
||||
}),
|
||||
).rejects.toThrow("Send rejected");
|
||||
expect(model.getSnapshot().items.map((item) => item.id)).toEqual([
|
||||
"existing",
|
||||
firstMessageId,
|
||||
]);
|
||||
expect(model.getSnapshot().busy).toEqual(new Set());
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("attachments restored from a queued message", () => {
|
||||
|
||||
@@ -2,8 +2,6 @@ import type { SelectedFile } from "@/attachments/selected-file";
|
||||
import { prepareImageAttachmentsForSend } from "@/attachments/service";
|
||||
import { FILE_UPLOAD_MAX_BYTES } from "@/attachments/upload-limit";
|
||||
import type { AgentProvider, ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { optimisticEnqueueAgentMessage } from "@/agent-queue";
|
||||
import type { SyncClient } from "@/sync";
|
||||
import type {
|
||||
ActiveTurnBehavior,
|
||||
AgentActiveTurnBehavior,
|
||||
@@ -88,7 +86,6 @@ export interface ComposerSendClient {
|
||||
error: string | null;
|
||||
}>;
|
||||
getLastServerInfoMessage: () => { features?: { uploadedImageAttachments?: boolean } } | null;
|
||||
sync?: SyncClient["sync"];
|
||||
}
|
||||
|
||||
export interface ComposerCancelClient {
|
||||
@@ -332,53 +329,10 @@ function separateUploadedImages(attachments: AgentAttachment[]) {
|
||||
return { images: images ?? [], attachments: rest };
|
||||
}
|
||||
|
||||
function buildOptimisticQueueItem(input: {
|
||||
messageId: string;
|
||||
text: string;
|
||||
wirePayload: ReturnType<typeof splitComposerAttachmentsForSubmit>;
|
||||
stagedProviderSwitch: StagedProviderSwitch | null | undefined;
|
||||
canSwitchProvider: boolean;
|
||||
}) {
|
||||
const attachments: AgentAttachment[] = [
|
||||
...input.wirePayload.attachments,
|
||||
...input.wirePayload.images.map(
|
||||
(image): UploadedFileAttachment => ({
|
||||
type: "uploaded_file",
|
||||
id: image.id,
|
||||
fileName: image.fileName ?? "image",
|
||||
mimeType: image.mimeType,
|
||||
size: 0,
|
||||
path: "",
|
||||
role: "image",
|
||||
}),
|
||||
),
|
||||
];
|
||||
const sw = input.canSwitchProvider ? input.stagedProviderSwitch : null;
|
||||
const providerSwitch = sw
|
||||
? {
|
||||
provider: sw.provider,
|
||||
...(sw.model !== null ? { model: sw.model } : {}),
|
||||
...(sw.modeId !== null ? { modeId: sw.modeId } : {}),
|
||||
...(sw.thinkingOptionId !== null ? { thinkingOptionId: sw.thinkingOptionId } : {}),
|
||||
...(sw.providerOptions ? { providerOptions: sw.providerOptions } : {}),
|
||||
}
|
||||
: undefined;
|
||||
return {
|
||||
id: input.messageId,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
text: input.text,
|
||||
...(attachments.length > 0 ? { attachments } : {}),
|
||||
...(providerSwitch ? { providerSwitch } : {}),
|
||||
sender: { kind: "user" as const },
|
||||
held: false,
|
||||
state: "queued" as const,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Hands a message to the host's queue. The timeline gets no row until the host dispatches it;
|
||||
* until then the queue track shows it optimistically while the send is in flight. A staged
|
||||
* provider switch goes with the message: the host switches when the message's turn comes.
|
||||
* until then the queue track shows it. A staged provider switch goes with the message: the host
|
||||
* switches when the message's turn comes.
|
||||
*/
|
||||
export async function enqueueComposerAgentMessage(
|
||||
input: Omit<
|
||||
@@ -391,44 +345,23 @@ export async function enqueueComposerAgentMessage(
|
||||
const wirePayload = splitComposerAttachmentsForSubmit(input.attachments, {
|
||||
format: input.attachmentSubmitFormat,
|
||||
});
|
||||
const messageId = generateMessageId();
|
||||
const optimistic = input.client.sync
|
||||
? optimisticEnqueueAgentMessage(
|
||||
{ sync: input.client.sync },
|
||||
input.agentId,
|
||||
buildOptimisticQueueItem({
|
||||
messageId,
|
||||
text,
|
||||
wirePayload,
|
||||
stagedProviderSwitch: input.stagedProviderSwitch,
|
||||
canSwitchProvider: Boolean(input.client.switchAgentProvider),
|
||||
}),
|
||||
)
|
||||
: null;
|
||||
try {
|
||||
const imagePayload = await prepareImagePayload(input, wirePayload.images);
|
||||
const queued = {
|
||||
messageId,
|
||||
activeTurnBehavior: "queue" as const,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
};
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
await input.client.switchAgentProvider(input.agentId, {
|
||||
...input.stagedProviderSwitch,
|
||||
...queued,
|
||||
text,
|
||||
});
|
||||
optimistic?.commit();
|
||||
input.onProviderSwitchQueued?.();
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, text, queued);
|
||||
optimistic?.commit();
|
||||
} catch (error) {
|
||||
optimistic?.rollback();
|
||||
throw error;
|
||||
const imagePayload = await prepareImagePayload(input, wirePayload.images);
|
||||
const queued = {
|
||||
messageId: generateMessageId(),
|
||||
activeTurnBehavior: "queue" as const,
|
||||
...(imagePayload.images ? { images: imagePayload.images } : {}),
|
||||
attachments: [...wirePayload.attachments, ...(imagePayload.attachments ?? [])],
|
||||
};
|
||||
if (input.stagedProviderSwitch && input.client.switchAgentProvider) {
|
||||
await input.client.switchAgentProvider(input.agentId, {
|
||||
...input.stagedProviderSwitch,
|
||||
...queued,
|
||||
text,
|
||||
});
|
||||
input.onProviderSwitchQueued?.();
|
||||
return;
|
||||
}
|
||||
await input.client.sendAgentMessage(input.agentId, text, queued);
|
||||
}
|
||||
|
||||
export interface OpenComposerAttachmentInput {
|
||||
|
||||
@@ -40,7 +40,7 @@ export async function editQueuedMessage(
|
||||
}
|
||||
|
||||
export async function cancelQueuedMessage(input: WithdrawInput): Promise<void> {
|
||||
const result = await input.model.withdraw(input.messageId, { optimistic: true });
|
||||
const result = await input.model.withdraw(input.messageId);
|
||||
if (result && !result.withdrawn) input.alreadySending();
|
||||
}
|
||||
|
||||
|
||||
@@ -659,7 +659,7 @@ describe("mountBrowserAutomationHandler", () => {
|
||||
readHostBrowserRouting: () => ({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
}),
|
||||
prepareHostBrowserPartition: async (serverId) => {
|
||||
preparedServers.push(serverId);
|
||||
|
||||
@@ -641,6 +641,28 @@ function BrowserProxyStatusPanel({
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "routed_unsupported") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
<View style={styles.proxyAlertFrame}>
|
||||
<Alert
|
||||
variant="info"
|
||||
title={t("workspace.browser.proxy.routedTitle")}
|
||||
description={t("workspace.browser.proxy.routedDescription")}
|
||||
>
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={onBrowseLocally}
|
||||
testID="browser-proxy-browse-locally"
|
||||
>
|
||||
{t("workspace.browser.proxy.browseLocally")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
if (state.kind === "host_offline") {
|
||||
return (
|
||||
<View style={styles.proxyStatusContainer} testID="browser-proxy-status">
|
||||
|
||||
@@ -9,22 +9,14 @@ import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import {
|
||||
classifyHostBrowserRouting,
|
||||
routedOriginServerId,
|
||||
shouldOpenUrlInProxiedWorkspaceBrowser,
|
||||
toBrowserRoutingHost,
|
||||
type BrowserRoutingHost,
|
||||
type ClassifyHostBrowserRoutingInput,
|
||||
type HostBrowserRouting,
|
||||
} from "./classify";
|
||||
|
||||
type SupportedTarget = Extract<HostBrowserRouting, { support: "supported" }>["target"];
|
||||
|
||||
const statusByServerId = new Map<string, DesktopBrowserProxyStatusSnapshot>();
|
||||
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 }>();
|
||||
const lastHostConnectionStatus = new Map<string, string>();
|
||||
let bridgeInstalled = false;
|
||||
|
||||
function notifyStatusListeners(serverId: string): void {
|
||||
@@ -112,121 +104,57 @@ export function installBrowserProxyRendererBridge(): void {
|
||||
});
|
||||
|
||||
const store = getHostRuntimeStore();
|
||||
const reconcileTrackedHosts = () => {
|
||||
store.subscribeAll(() => {
|
||||
const currentHosts = new Set(store.getHosts().map((host) => host.serverId));
|
||||
for (const serverId of trackedHostIds) {
|
||||
if (!currentHosts.has(serverId)) {
|
||||
trackedHostIds.delete(serverId);
|
||||
lastTunnelPathStatus.delete(serverId);
|
||||
lastSentTargetKey.delete(serverId);
|
||||
routingSnapshots.delete(serverId);
|
||||
lastHostConnectionStatus.delete(serverId);
|
||||
statusByServerId.delete(serverId);
|
||||
notifyStatusListeners(serverId);
|
||||
void desktop.browser?.releaseHostProxy?.(serverId).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
const nextPathStatus = readTunnelPathStatus(serverId);
|
||||
const prevPathStatus = lastTunnelPathStatus.get(serverId);
|
||||
lastTunnelPathStatus.set(serverId, nextPathStatus);
|
||||
const nextConnectionStatus = store.getSnapshot(serverId)?.connectionStatus ?? "offline";
|
||||
const prevConnectionStatus = lastHostConnectionStatus.get(serverId);
|
||||
lastHostConnectionStatus.set(serverId, nextConnectionStatus);
|
||||
|
||||
const routing = readHostBrowserRouting(serverId);
|
||||
if (routing.kind !== "remote" || routing.support !== "supported") continue;
|
||||
if (prevPathStatus !== undefined && prevPathStatus !== "online") {
|
||||
// The tunnel path (the host, and its origin when routed) just recovered after a
|
||||
// drop; replace any half-open tunnel while keeping the fixed local SOCKS5 port
|
||||
// and mounted webview intact.
|
||||
void ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: routing.target,
|
||||
forceReconnect: true,
|
||||
}).catch(() => {});
|
||||
continue;
|
||||
}
|
||||
const targetKey = JSON.stringify(routing.target);
|
||||
if (lastSentTargetKey.get(serverId) === targetKey) continue;
|
||||
lastSentTargetKey.set(serverId, targetKey);
|
||||
void desktop.browser
|
||||
?.updateHostProxyTarget?.({ serverId, target: routing.target })
|
||||
.catch(() => {});
|
||||
}
|
||||
};
|
||||
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;
|
||||
}
|
||||
if (routing.kind === "remote" && routing.support === "supported") {
|
||||
if (prevConnectionStatus !== undefined && prevConnectionStatus !== "online") {
|
||||
// Control session just recovered after a drop; replace any half-open tunnel socket
|
||||
// immediately while keeping the fixed local SOCKS5 port and mounted webview intact.
|
||||
void ensureHostBrowserProxy({
|
||||
serverId,
|
||||
target: routing.target,
|
||||
forceReconnect: true,
|
||||
}).catch(() => {});
|
||||
} else {
|
||||
void desktop.browser
|
||||
?.updateHostProxyTarget?.({ serverId, target: routing.target })
|
||||
.catch(() => {});
|
||||
}
|
||||
}
|
||||
}),
|
||||
];
|
||||
return () => {
|
||||
for (const unsubscribe of unsubscribes) unsubscribe();
|
||||
};
|
||||
}
|
||||
|
||||
function readBrowserRoutingHost(serverId: string): BrowserRoutingHost {
|
||||
const runtimeStore = getHostRuntimeStore();
|
||||
return toBrowserRoutingHost({
|
||||
serverId,
|
||||
profile: runtimeStore.getHosts().find((entry) => entry.serverId === serverId) ?? null,
|
||||
snapshot: runtimeStore.getSnapshot(serverId),
|
||||
serverInfo: useSessionStore.getState().sessions[serverId]?.serverInfo ?? null,
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 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 { ...host, origin: originServerId ? readBrowserRoutingHost(originServerId) : null };
|
||||
}
|
||||
|
||||
export function readHostBrowserRouting(serverId: string): HostBrowserRouting {
|
||||
return classifyHostBrowserRouting(readBrowserRoutingInput(serverId));
|
||||
}
|
||||
const runtimeStore = getHostRuntimeStore();
|
||||
const host = runtimeStore.getHosts().find((entry) => entry.serverId === serverId) ?? null;
|
||||
const snapshot = runtimeStore.getSnapshot(serverId);
|
||||
const serverInfo = useSessionStore.getState().sessions[serverId]?.serverInfo ?? null;
|
||||
const supportsNetworkTunnel =
|
||||
serverInfo !== null ? serverInfo.features?.networkTunnel === true : null;
|
||||
|
||||
/** {@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 { connectionStatus: status, origin } = readBrowserRoutingInput(serverId);
|
||||
const originStatus = origin?.connectionStatus ?? "online";
|
||||
return status === "online" && originStatus === "online" ? "online" : `${status}/${originStatus}`;
|
||||
return classifyHostBrowserRouting({
|
||||
serverId,
|
||||
connections: host?.connections ?? [],
|
||||
activeConnection: snapshot?.activeConnection ?? null,
|
||||
activeConnectionId: snapshot?.activeConnectionId ?? null,
|
||||
connectionStatus: snapshot?.connectionStatus ?? "offline",
|
||||
supportsNetworkTunnel,
|
||||
});
|
||||
}
|
||||
|
||||
export function shouldRouteWorkspaceUrlToProxiedBrowser(input: {
|
||||
@@ -267,7 +195,9 @@ export function subscribeBrowserProxyStatus(serverId: string, listener: () => vo
|
||||
|
||||
export async function ensureHostBrowserProxy(input: {
|
||||
serverId: string;
|
||||
target: SupportedTarget;
|
||||
target: NonNullable<
|
||||
Extract<HostBrowserRouting, { kind: "remote"; support: "supported" }>["target"]
|
||||
>;
|
||||
forceReconnect?: boolean;
|
||||
}): Promise<DesktopBrowserProxyStatusSnapshot | null> {
|
||||
installBrowserProxyRendererBridge();
|
||||
@@ -276,8 +206,10 @@ export async function ensureHostBrowserProxy(input: {
|
||||
return null;
|
||||
}
|
||||
trackedHostIds.add(input.serverId);
|
||||
lastTunnelPathStatus.set(input.serverId, readTunnelPathStatus(input.serverId));
|
||||
lastSentTargetKey.set(input.serverId, JSON.stringify(input.target));
|
||||
const currentStatus = getHostRuntimeStore().getSnapshot(input.serverId)?.connectionStatus;
|
||||
if (currentStatus) {
|
||||
lastHostConnectionStatus.set(input.serverId, currentStatus);
|
||||
}
|
||||
const snapshot = await ensureHostProxy(input);
|
||||
setCachedStatus(snapshot);
|
||||
return snapshot;
|
||||
@@ -287,7 +219,12 @@ export type PrepareHostBrowserPartitionResult =
|
||||
| { ok: true; partition: string; isRemoteHost: boolean }
|
||||
| {
|
||||
ok: false;
|
||||
reason: "daemon_update_required" | "host_offline" | "host_connecting" | "proxy_error";
|
||||
reason:
|
||||
| "daemon_update_required"
|
||||
| "routed_unsupported"
|
||||
| "host_offline"
|
||||
| "host_connecting"
|
||||
| "proxy_error";
|
||||
message: string;
|
||||
};
|
||||
|
||||
@@ -317,6 +254,13 @@ export async function prepareHostBrowserPartition(
|
||||
message: "Update this host daemon to browse through the host proxy.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "routed_unsupported") {
|
||||
return {
|
||||
ok: false,
|
||||
reason: "routed_unsupported",
|
||||
message: "Browser proxying is not available for multi-hop routed hosts.",
|
||||
};
|
||||
}
|
||||
if (routing.support === "host_connecting") {
|
||||
return {
|
||||
ok: false,
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { HostConnection, HostProfile } from "@/types/host-connection";
|
||||
import { defaultHostAppearance } from "@/hosts/appearance";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
import {
|
||||
classifyHostBrowserRouting,
|
||||
routedOriginServerId,
|
||||
toBrowserRoutingHost,
|
||||
type BrowserRoutingHost,
|
||||
extractBrowserProxyTarget,
|
||||
isLoopbackBrowserUrl,
|
||||
isLoopbackHost,
|
||||
@@ -68,11 +64,17 @@ describe("classifyHostBrowserRouting", () => {
|
||||
const relayConn: HostConnection = {
|
||||
id: "relay:relay.paseo.sh",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
};
|
||||
const routedConn: HostConnection = {
|
||||
id: "routed:origin-1",
|
||||
type: "routed",
|
||||
originServerId: "origin-1",
|
||||
};
|
||||
|
||||
it("classifies local socket, pipe, and loopback directTcp connections as local", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
@@ -81,8 +83,7 @@ describe("classifyHostBrowserRouting", () => {
|
||||
activeConnection: { type: "directSocket", endpoint: "/tmp/paseo.sock", display: "socket" },
|
||||
activeConnectionId: localSocket.id,
|
||||
connectionStatus: "online",
|
||||
features: { networkTunnel: true },
|
||||
origin: null,
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
|
||||
@@ -97,8 +98,7 @@ describe("classifyHostBrowserRouting", () => {
|
||||
},
|
||||
activeConnectionId: localTcp.id,
|
||||
connectionStatus: "online",
|
||||
features: { networkTunnel: true },
|
||||
origin: null,
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "local" });
|
||||
});
|
||||
@@ -115,23 +115,32 @@ describe("classifyHostBrowserRouting", () => {
|
||||
},
|
||||
activeConnectionId: remoteTcp.id,
|
||||
connectionStatus: "online",
|
||||
features: { networkTunnel: true },
|
||||
origin: null,
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
target: { type: "directTcp", endpoint: "10.0.0.5:6767" },
|
||||
});
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-ssh", remoteSsh)).toBe("ssh://devbox:2222");
|
||||
expect(extractBrowserProxyTarget("remote-ssh", remoteSsh)).toEqual({
|
||||
type: "remoteSsh",
|
||||
host: "devbox",
|
||||
sshPort: 2222,
|
||||
daemonPort: 6767,
|
||||
});
|
||||
|
||||
expect(extractBrowserProxyTarget("remote-relay", relayConn)).toBe(
|
||||
"relay://relay.paseo.sh:443/remote-relay?key=AAAA&ssl=true&security=protected",
|
||||
);
|
||||
expect(extractBrowserProxyTarget("remote-relay", relayConn)).toEqual({
|
||||
type: "relay",
|
||||
serverId: "remote-relay",
|
||||
relayEndpoint: "relay.paseo.sh",
|
||||
useTls: true,
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
minimumSecurityMode: "protected",
|
||||
});
|
||||
});
|
||||
|
||||
it("fails closed for old daemons, connecting hosts, and offline remote hosts", () => {
|
||||
it("fails closed for old daemons, routed hosts, connecting hosts, and offline remote hosts", () => {
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "old-daemon",
|
||||
@@ -143,11 +152,21 @@ describe("classifyHostBrowserRouting", () => {
|
||||
},
|
||||
activeConnectionId: remoteTcp.id,
|
||||
connectionStatus: "online",
|
||||
features: {},
|
||||
origin: null,
|
||||
supportsNetworkTunnel: false,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "daemon_update_required" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "routed-host",
|
||||
connections: [routedConn],
|
||||
activeConnection: { type: "routed", endpoint: "origin-1", display: "via origin-1" },
|
||||
activeConnectionId: routedConn.id,
|
||||
connectionStatus: "online",
|
||||
supportsNetworkTunnel: true,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "routed_unsupported" });
|
||||
|
||||
expect(
|
||||
classifyHostBrowserRouting({
|
||||
serverId: "offline-remote",
|
||||
@@ -155,8 +174,7 @@ describe("classifyHostBrowserRouting", () => {
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus: "offline",
|
||||
features: null,
|
||||
origin: null,
|
||||
supportsNetworkTunnel: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "host_offline" });
|
||||
|
||||
@@ -167,8 +185,7 @@ describe("classifyHostBrowserRouting", () => {
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus: "connecting",
|
||||
features: null,
|
||||
origin: null,
|
||||
supportsNetworkTunnel: null,
|
||||
}),
|
||||
).toEqual({ kind: "remote", support: "host_connecting" });
|
||||
});
|
||||
@@ -177,7 +194,7 @@ describe("classifyHostBrowserRouting", () => {
|
||||
const supportedRemote = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
};
|
||||
const oldRemote = { kind: "remote" as const, support: "daemon_update_required" as const };
|
||||
const local = { kind: "local" as const };
|
||||
@@ -219,205 +236,3 @@ describe("classifyHostBrowserRouting", () => {
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyHostBrowserRouting for routed hosts", () => {
|
||||
const capable = { networkTunnel: true, routedNetworkTunnel: true };
|
||||
const viaOrigin: HostConnection = { id: "via:srv-a", type: "routed", originServerId: "srv-a" };
|
||||
const routedHost: BrowserRoutingHost = {
|
||||
serverId: "srv-b",
|
||||
connections: [viaOrigin],
|
||||
activeConnection: { type: "routed", endpoint: "srv-a", display: "via srv-a" },
|
||||
activeConnectionId: viaOrigin.id,
|
||||
connectionStatus: "online",
|
||||
features: capable,
|
||||
};
|
||||
const localSocketOrigin: BrowserRoutingHost = {
|
||||
serverId: "srv-a",
|
||||
connections: [{ id: "socket:/tmp/paseo.sock", type: "directSocket", path: "/tmp/paseo.sock" }],
|
||||
activeConnection: { type: "directSocket", endpoint: "/tmp/paseo.sock", display: "socket" },
|
||||
activeConnectionId: "socket:/tmp/paseo.sock",
|
||||
connectionStatus: "online",
|
||||
features: capable,
|
||||
};
|
||||
const classify = (host: Partial<BrowserRoutingHost>, origin: BrowserRoutingHost | null) =>
|
||||
classifyHostBrowserRouting({ ...routedHost, ...host, origin });
|
||||
|
||||
it("routes through a local origin daemon", () => {
|
||||
expect(classify({}, localSocketOrigin)).toEqual({
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: { via: "unix:///tmp/paseo.sock", serverId: "srv-b" },
|
||||
});
|
||||
});
|
||||
|
||||
it("routes through a loopback TCP origin instead of treating the routed host as local", () => {
|
||||
const origin: BrowserRoutingHost = {
|
||||
...localSocketOrigin,
|
||||
connections: [{ id: "direct:127.0.0.1:6767", type: "directTcp", endpoint: "127.0.0.1:6767" }],
|
||||
activeConnection: {
|
||||
type: "directTcp",
|
||||
endpoint: "127.0.0.1:6767",
|
||||
display: "127.0.0.1:6767",
|
||||
},
|
||||
activeConnectionId: "direct:127.0.0.1:6767",
|
||||
};
|
||||
expect(classify({}, origin)).toMatchObject({
|
||||
support: "supported",
|
||||
target: { via: "tcp://127.0.0.1:6767", serverId: "srv-b" },
|
||||
});
|
||||
});
|
||||
|
||||
it("carries a remote origin's password for TCP, SSH, and relay origins", () => {
|
||||
const remote = (connection: HostConnection): BrowserRoutingHost => ({
|
||||
serverId: "srv-a",
|
||||
password: "origin-secret",
|
||||
connections: [connection],
|
||||
activeConnection: null,
|
||||
activeConnectionId: connection.id,
|
||||
connectionStatus: "online",
|
||||
features: capable,
|
||||
});
|
||||
expect(
|
||||
classify(
|
||||
{},
|
||||
remote({ id: "tcp", type: "directTcp", endpoint: "a.example:6767", useTls: true }),
|
||||
),
|
||||
).toMatchObject({
|
||||
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: { via: "ssh://me@a:2222", originPassword: "origin-secret" },
|
||||
});
|
||||
expect(
|
||||
classify(
|
||||
{},
|
||||
remote({
|
||||
id: "relay",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
daemonPublicKeyB64: "AAAA",
|
||||
}),
|
||||
),
|
||||
).toMatchObject({
|
||||
target: {
|
||||
via: "relay://relay.paseo.sh:443/srv-a?key=AAAA&ssl=true",
|
||||
originPassword: "origin-secret",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["connecting", "host_connecting"],
|
||||
["idle", "host_connecting"],
|
||||
["offline", "host_offline"],
|
||||
["error", "host_offline"],
|
||||
] as const)("follows an origin that is %s", (connectionStatus, support) => {
|
||||
expect(classify({}, { ...localSocketOrigin, connectionStatus })).toEqual({
|
||||
kind: "remote",
|
||||
support,
|
||||
});
|
||||
});
|
||||
|
||||
it("is offline when the origin host is unknown or is itself routed", () => {
|
||||
expect(classify({}, null)).toEqual({ kind: "remote", support: "host_offline" });
|
||||
const routedOrigin: BrowserRoutingHost = {
|
||||
...localSocketOrigin,
|
||||
connections: [{ id: "via:srv-z", type: "routed", originServerId: "srv-z" }],
|
||||
activeConnection: { type: "routed", endpoint: "srv-z", display: "via srv-z" },
|
||||
activeConnectionId: "via:srv-z",
|
||||
};
|
||||
expect(classify({}, routedOrigin)).toEqual({ kind: "remote", support: "host_offline" });
|
||||
});
|
||||
|
||||
it("follows the routed host's own connection status before the origin's", () => {
|
||||
expect(classify({ connectionStatus: "connecting" }, localSocketOrigin)).toEqual({
|
||||
kind: "remote",
|
||||
support: "host_connecting",
|
||||
});
|
||||
expect(
|
||||
classify(
|
||||
{ activeConnection: null, activeConnectionId: null, connectionStatus: "offline" },
|
||||
null,
|
||||
),
|
||||
).toEqual({ kind: "remote", support: "host_offline" });
|
||||
});
|
||||
|
||||
it.each([
|
||||
["the routed host lacks routedNetworkTunnel", { features: { networkTunnel: true } }, capable],
|
||||
["the routed host lacks networkTunnel", { features: { routedNetworkTunnel: true } }, capable],
|
||||
["the routed host's server info is unknown", { features: null }, capable],
|
||||
["the origin lacks routedNetworkTunnel", {}, { networkTunnel: true }],
|
||||
["the origin's server info is unknown", {}, null],
|
||||
] as const)("requires a daemon update when %s", (_name, host, originFeatures) => {
|
||||
expect(classify(host, { ...localSocketOrigin, features: originFeatures })).toEqual({
|
||||
kind: "remote",
|
||||
support: "daemon_update_required",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("toBrowserRoutingHost", () => {
|
||||
const profile: HostProfile = {
|
||||
serverId: "srv-a",
|
||||
password: "origin-secret",
|
||||
label: "A",
|
||||
appearance: defaultHostAppearance(),
|
||||
lifecycle: {},
|
||||
connections: [{ id: "tcp", type: "directTcp", endpoint: "a.example:6767" }],
|
||||
preferredConnectionId: null,
|
||||
createdAt: "2026-12-01T00:00:00.000Z",
|
||||
updatedAt: "2026-12-01T00:00:00.000Z",
|
||||
};
|
||||
|
||||
it("reads the profile, runtime snapshot, and server info features of one host", () => {
|
||||
expect(
|
||||
toBrowserRoutingHost({
|
||||
serverId: "srv-a",
|
||||
profile,
|
||||
snapshot: {
|
||||
activeConnection: { type: "directTcp", endpoint: "a.example:6767", display: "a" },
|
||||
activeConnectionId: "tcp",
|
||||
connectionStatus: "online",
|
||||
},
|
||||
serverInfo: { features: { networkTunnel: true, routedNetworkTunnel: true } },
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv-a",
|
||||
password: "origin-secret",
|
||||
connections: profile.connections,
|
||||
activeConnection: { type: "directTcp", endpoint: "a.example:6767", display: "a" },
|
||||
activeConnectionId: "tcp",
|
||||
connectionStatus: "online",
|
||||
features: { networkTunnel: true, routedNetworkTunnel: true },
|
||||
});
|
||||
});
|
||||
|
||||
it("treats a missing snapshot as offline and missing server info as unknown features", () => {
|
||||
expect(
|
||||
toBrowserRoutingHost({ serverId: "srv-x", profile: null, snapshot: null, serverInfo: null }),
|
||||
).toEqual({
|
||||
serverId: "srv-x",
|
||||
connections: [],
|
||||
activeConnection: null,
|
||||
activeConnectionId: null,
|
||||
connectionStatus: "offline",
|
||||
features: null,
|
||||
});
|
||||
expect(
|
||||
toBrowserRoutingHost({ serverId: "srv-x", profile: null, snapshot: null, serverInfo: {} })
|
||||
.features,
|
||||
).toEqual({});
|
||||
});
|
||||
|
||||
it("names the origin only for a routed active connection", () => {
|
||||
expect(routedOriginServerId({ type: "routed", endpoint: "srv-a", display: "via srv-a" })).toBe(
|
||||
"srv-a",
|
||||
);
|
||||
expect(routedOriginServerId({ type: "directSocket", endpoint: "/s", display: "socket" })).toBe(
|
||||
null,
|
||||
);
|
||||
expect(routedOriginServerId(null)).toBe(null);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,12 +1,7 @@
|
||||
import { parseHostPort } from "@getpaseo/protocol/daemon-endpoints";
|
||||
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 { hostConnectionUri, type HostConnection, type HostProfile } from "@/types/host-connection";
|
||||
import type { DesktopBrowserProxyTarget } from "@/desktop/host";
|
||||
import type { ActiveConnection, HostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
|
||||
const IPV4_LOOPBACK_PATTERN = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||
|
||||
@@ -55,70 +50,58 @@ export function isLocalHostConnection(connection: HostConnection | ActiveConnect
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The connection Electron main dials to tunnel to this host, or null when it is local. */
|
||||
export function extractBrowserProxyTarget(
|
||||
serverId: string,
|
||||
connection: HostConnection,
|
||||
): string | null {
|
||||
if (isLocalHostConnection(connection)) return null;
|
||||
return hostConnectionUri(connection, serverId);
|
||||
): DesktopBrowserProxyTarget | null {
|
||||
if (connection.type === "directTcp") {
|
||||
if (isLoopbackDirectTcpEndpoint(connection.endpoint)) {
|
||||
return null;
|
||||
}
|
||||
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;
|
||||
}
|
||||
|
||||
export type HostBrowserRouting =
|
||||
| { kind: "local" }
|
||||
| { kind: "remote"; support: "supported"; target: HostTransportSpec }
|
||||
| { kind: "remote"; support: "supported"; target: DesktopBrowserProxyTarget }
|
||||
| { kind: "remote"; support: "daemon_update_required" }
|
||||
| { kind: "remote"; support: "routed_unsupported" }
|
||||
| { kind: "remote"; support: "host_connecting" }
|
||||
| { kind: "remote"; support: "host_offline" };
|
||||
|
||||
type UnsupportedRouting = Exclude<HostBrowserRouting, { kind: "local" } | { support: "supported" }>;
|
||||
|
||||
export interface BrowserRoutingFeatures {
|
||||
networkTunnel?: boolean;
|
||||
routedNetworkTunnel?: boolean;
|
||||
}
|
||||
|
||||
/** One host as browser routing sees it: saved profile, live connection, and daemon features. */
|
||||
export interface BrowserRoutingHost {
|
||||
export interface ClassifyHostBrowserRoutingInput {
|
||||
serverId: string;
|
||||
password?: string;
|
||||
connections: readonly HostConnection[];
|
||||
activeConnection: ActiveConnection | null;
|
||||
activeConnectionId: string | null;
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
/** Null until the host's server_info arrives. */
|
||||
features: BrowserRoutingFeatures | null;
|
||||
}
|
||||
|
||||
export interface ClassifyHostBrowserRoutingInput extends BrowserRoutingHost {
|
||||
/** The host a routed active connection goes through, or null when it is unknown. */
|
||||
origin: BrowserRoutingHost | null;
|
||||
}
|
||||
|
||||
export function toBrowserRoutingHost(input: {
|
||||
serverId: string;
|
||||
profile: Pick<HostProfile, "connections" | "password"> | null;
|
||||
snapshot: Pick<
|
||||
HostRuntimeSnapshot,
|
||||
"activeConnection" | "activeConnectionId" | "connectionStatus"
|
||||
> | null;
|
||||
serverInfo: Pick<DaemonServerInfo, "features"> | null;
|
||||
}): BrowserRoutingHost {
|
||||
const { serverId, profile, snapshot, serverInfo } = input;
|
||||
return {
|
||||
serverId,
|
||||
...(profile?.password ? { password: profile.password } : {}),
|
||||
connections: profile?.connections ?? [],
|
||||
activeConnection: snapshot?.activeConnection ?? null,
|
||||
activeConnectionId: snapshot?.activeConnectionId ?? null,
|
||||
connectionStatus: snapshot?.connectionStatus ?? "offline",
|
||||
features: serverInfo ? (serverInfo.features ?? {}) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The origin host's serverId when the host is connected through another daemon. */
|
||||
export function routedOriginServerId(activeConnection: ActiveConnection | null): string | null {
|
||||
return activeConnection?.type === "routed" ? activeConnection.endpoint : null;
|
||||
supportsNetworkTunnel: boolean | null;
|
||||
}
|
||||
|
||||
function findMatchingHostConnection(
|
||||
@@ -144,89 +127,45 @@ function findMatchingHostConnection(
|
||||
return null;
|
||||
}
|
||||
|
||||
function unavailableWhileDisconnected(host: BrowserRoutingHost): UnsupportedRouting | null {
|
||||
if (host.connectionStatus === "connecting" || host.connectionStatus === "idle") {
|
||||
return { kind: "remote", support: "host_connecting" };
|
||||
}
|
||||
if (host.connectionStatus !== "online") {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
return 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,
|
||||
);
|
||||
return connection ? hostConnectionUri(connection, origin.serverId) : null;
|
||||
}
|
||||
|
||||
function classifyRoutedHost(
|
||||
host: BrowserRoutingHost,
|
||||
originServerId: string,
|
||||
origin: BrowserRoutingHost | null,
|
||||
): HostBrowserRouting {
|
||||
const hostUnavailable = unavailableWhileDisconnected(host);
|
||||
if (hostUnavailable) return hostUnavailable;
|
||||
if (!origin || origin.serverId !== originServerId) {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
const originUnavailable = unavailableWhileDisconnected(origin);
|
||||
if (originUnavailable) return originUnavailable;
|
||||
|
||||
// COMPAT(routedNetworkTunnel): added in v0.18.3, remove gate after 2027-06-01.
|
||||
// Both daemons must pass tunnel_hello through the host channel.
|
||||
if (
|
||||
host.features?.networkTunnel !== true ||
|
||||
host.features.routedNetworkTunnel !== true ||
|
||||
origin.features?.routedNetworkTunnel !== true
|
||||
) {
|
||||
return { kind: "remote", support: "daemon_update_required" };
|
||||
}
|
||||
|
||||
const via = originConnectionOf(origin);
|
||||
if (!via) {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
return {
|
||||
kind: "remote",
|
||||
support: "supported",
|
||||
target: {
|
||||
via,
|
||||
serverId: host.serverId,
|
||||
...(origin.password ? { originPassword: origin.password } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function classifyHostBrowserRouting(
|
||||
input: ClassifyHostBrowserRoutingInput,
|
||||
): HostBrowserRouting {
|
||||
const { origin, ...host } = input;
|
||||
const { serverId, connections, activeConnection, activeConnectionId, features } = host;
|
||||
const {
|
||||
serverId,
|
||||
connections,
|
||||
activeConnection,
|
||||
activeConnectionId,
|
||||
connectionStatus,
|
||||
supportsNetworkTunnel,
|
||||
} = input;
|
||||
|
||||
if (activeConnection) {
|
||||
if (isLocalHostConnection(activeConnection)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
const originServerId = routedOriginServerId(activeConnection);
|
||||
if (originServerId) {
|
||||
return classifyRoutedHost(host, originServerId, origin);
|
||||
if (activeConnection.type === "routed") {
|
||||
return { kind: "remote", support: "routed_unsupported" };
|
||||
}
|
||||
} else if (connections.length === 0 || connections.some(isLocalHostConnection)) {
|
||||
} else {
|
||||
// No active connection yet (connecting/offline). Distinguish local hosts from remote
|
||||
// hosts using saved connection definitions so remote tabs fail closed during startup.
|
||||
return { kind: "local" };
|
||||
if (connections.length === 0 || connections.some(isLocalHostConnection)) {
|
||||
return { kind: "local" };
|
||||
}
|
||||
if (connections.every((conn) => conn.type === "routed")) {
|
||||
return { kind: "remote", support: "routed_unsupported" };
|
||||
}
|
||||
}
|
||||
|
||||
const hostUnavailable = unavailableWhileDisconnected(host);
|
||||
if (hostUnavailable) return hostUnavailable;
|
||||
if (connectionStatus === "connecting" || connectionStatus === "idle") {
|
||||
return { kind: "remote", support: "host_connecting" };
|
||||
}
|
||||
if (connectionStatus !== "online") {
|
||||
return { kind: "remote", support: "host_offline" };
|
||||
}
|
||||
|
||||
// COMPAT(networkTunnel): added in v0.18.0, remove after 2027-05-26 once daemon floor >= v0.18.0.
|
||||
if (features?.networkTunnel !== true) {
|
||||
if (supportsNetworkTunnel !== true) {
|
||||
return { kind: "remote", support: "daemon_update_required" };
|
||||
}
|
||||
|
||||
|
||||
@@ -99,7 +99,7 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
const supportedRouting = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: "tcp://10.0.0.5:6767",
|
||||
target: { type: "directTcp" as const, endpoint: "10.0.0.5:6767" },
|
||||
};
|
||||
|
||||
expect(
|
||||
@@ -180,83 +180,4 @@ describe("resolveBrowserProxyPaneState", () => {
|
||||
retry: noop,
|
||||
});
|
||||
});
|
||||
|
||||
describe("routed hosts", () => {
|
||||
const routedTarget = { via: "unix:///tmp/paseo.sock", serverId: "srv-dev" };
|
||||
const input = {
|
||||
effectiveRoutingMode: "host" as const,
|
||||
localPartition: "persist:paseo-browser",
|
||||
hostLabel: "dev",
|
||||
ensureError: null,
|
||||
onRetry: noop,
|
||||
};
|
||||
|
||||
it("connects through the origin, then mounts the routed host's own partition", () => {
|
||||
const routing = {
|
||||
kind: "remote" as const,
|
||||
support: "supported" as const,
|
||||
target: routedTarget,
|
||||
};
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({ ...input, routing, proxyStatusSnapshot: null }),
|
||||
).toEqual({
|
||||
kind: "connecting",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "dev",
|
||||
isReconnecting: false,
|
||||
});
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...input,
|
||||
routing,
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-dev",
|
||||
partition: "persist:paseo-browser-host-dev",
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41000,
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "ready",
|
||||
partition: "persist:paseo-browser-host-dev",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "dev",
|
||||
proxyStatus: "ready",
|
||||
});
|
||||
});
|
||||
|
||||
it("shows the update prompt when the origin or routed daemon lacks routed tunnels", () => {
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...input,
|
||||
routing: { kind: "remote", support: "daemon_update_required" },
|
||||
proxyStatusSnapshot: null,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "daemon_update_required",
|
||||
isRemoteHost: true,
|
||||
effectiveRoutingMode: "host",
|
||||
hostLabel: "dev",
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps a prepared routed partition mounted while its origin reconnects", () => {
|
||||
expect(
|
||||
resolveBrowserProxyPaneState({
|
||||
...input,
|
||||
routing: { kind: "remote", support: "host_connecting" },
|
||||
proxyStatusSnapshot: {
|
||||
serverId: "srv-dev",
|
||||
partition: "persist:paseo-browser-host-dev",
|
||||
status: "ready",
|
||||
error: null,
|
||||
socksPort: 41000,
|
||||
},
|
||||
}),
|
||||
).toMatchObject({ kind: "ready", proxyStatus: "reconnecting" });
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,17 +2,16 @@ 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 { useHosts } from "@/runtime/host-runtime";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { normalizeHostLabel } from "@/types/host-connection";
|
||||
import {
|
||||
ensureHostBrowserProxy,
|
||||
getCachedBrowserProxyStatus,
|
||||
getHostBrowserRoutingSnapshot,
|
||||
installBrowserProxyRendererBridge,
|
||||
subscribeBrowserProxyStatus,
|
||||
subscribeHostBrowserRouting,
|
||||
} from "./bridge";
|
||||
import type { HostBrowserRouting } from "./classify";
|
||||
import { classifyHostBrowserRouting } from "./classify";
|
||||
|
||||
export type BrowserProxyPaneState =
|
||||
| {
|
||||
@@ -36,6 +35,12 @@ export type BrowserProxyPaneState =
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "routed_unsupported";
|
||||
isRemoteHost: true;
|
||||
effectiveRoutingMode: "host";
|
||||
hostLabel: string;
|
||||
}
|
||||
| {
|
||||
kind: "host_offline";
|
||||
isRemoteHost: true;
|
||||
@@ -61,7 +66,10 @@ function hasPreparedHostPartition(
|
||||
}
|
||||
|
||||
function resolveRemoteUnavailablePaneState(
|
||||
support: Exclude<Extract<HostBrowserRouting, { kind: "remote" }>["support"], "supported">,
|
||||
support: Exclude<
|
||||
Extract<ReturnType<typeof classifyHostBrowserRouting>, { kind: "remote" }>["support"],
|
||||
"supported"
|
||||
>,
|
||||
hostLabel: string,
|
||||
proxyStatusSnapshot: ReturnType<typeof getCachedBrowserProxyStatus>,
|
||||
): BrowserProxyPaneState {
|
||||
@@ -107,7 +115,7 @@ function resolvePreparedHostPaneStatus(
|
||||
}
|
||||
|
||||
export function resolveBrowserProxyPaneState(input: {
|
||||
routing: HostBrowserRouting;
|
||||
routing: ReturnType<typeof classifyHostBrowserRouting>;
|
||||
effectiveRoutingMode: BrowserRoutingMode;
|
||||
localPartition: string;
|
||||
hostLabel: string;
|
||||
@@ -187,11 +195,11 @@ export function useHostBrowserProxy(input: {
|
||||
[hosts, serverId],
|
||||
);
|
||||
const hostLabel = normalizeHostLabel(host?.label, serverId);
|
||||
const routing = useSyncExternalStore(
|
||||
useCallback((onChange) => subscribeHostBrowserRouting(serverId, onChange), [serverId]),
|
||||
() => getHostBrowserRoutingSnapshot(serverId),
|
||||
() => getHostBrowserRoutingSnapshot(serverId),
|
||||
);
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const supportsNetworkTunnel = useSessionStore((state) => {
|
||||
const serverInfo = state.sessions[serverId]?.serverInfo ?? null;
|
||||
return serverInfo !== null ? serverInfo.features?.networkTunnel === true : null;
|
||||
});
|
||||
|
||||
const proxyStatusSnapshot = useSyncExternalStore(
|
||||
useCallback((onChange) => subscribeBrowserProxyStatus(serverId, onChange), [serverId]),
|
||||
@@ -202,6 +210,26 @@ export function useHostBrowserProxy(input: {
|
||||
const [retryCounter, setRetryCounter] = useState(0);
|
||||
const [ensureError, setEnsureError] = useState<string | null>(null);
|
||||
|
||||
const routing = useMemo(
|
||||
() =>
|
||||
classifyHostBrowserRouting({
|
||||
serverId,
|
||||
connections: host?.connections ?? [],
|
||||
activeConnection: runtimeSnapshot?.activeConnection ?? null,
|
||||
activeConnectionId: runtimeSnapshot?.activeConnectionId ?? null,
|
||||
connectionStatus: runtimeSnapshot?.connectionStatus ?? "offline",
|
||||
supportsNetworkTunnel,
|
||||
}),
|
||||
[
|
||||
host?.connections,
|
||||
runtimeSnapshot?.activeConnection,
|
||||
runtimeSnapshot?.activeConnectionId,
|
||||
runtimeSnapshot?.connectionStatus,
|
||||
serverId,
|
||||
supportsNetworkTunnel,
|
||||
],
|
||||
);
|
||||
|
||||
const effectiveRoutingMode = resolveBrowserRoutingMode(
|
||||
{ routingMode },
|
||||
routing.kind === "remote",
|
||||
|
||||
@@ -1,16 +1,29 @@
|
||||
import { localListenOfHostTarget, parseHostTarget } from "@getpaseo/protocol/host-target";
|
||||
import { hostConnectionUri, type HostConnection } from "@/types/host-connection";
|
||||
import 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(
|
||||
host: { serverId: string; connection: HostConnection },
|
||||
connection: HostConnection,
|
||||
invoke: (listen: string) => Promise<unknown> = async (listen) =>
|
||||
getDesktopHost()?.invoke?.("desktop_local_credential", { listen }),
|
||||
): Promise<string | undefined> {
|
||||
const uri = hostConnectionUri(host.connection, host.serverId);
|
||||
const listen = uri ? localListenOfHostTarget(parseHostTarget(uri)) : null;
|
||||
const listen = connectionListen(connection);
|
||||
if (!listen) return undefined;
|
||||
const credential = await invoke(listen);
|
||||
return typeof credential === "string" ? credential : undefined;
|
||||
|
||||
@@ -2,7 +2,6 @@ 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<
|
||||
@@ -173,6 +172,27 @@ export type BrowserProfileRemoveResult =
|
||||
| { ok: true }
|
||||
| { ok: false; code: "reserved" | "invalid" | "not_found" | "io" };
|
||||
|
||||
export type DesktopBrowserProxyTarget =
|
||||
| {
|
||||
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";
|
||||
};
|
||||
|
||||
export type DesktopBrowserProxyStatus = "idle" | "connecting" | "ready" | "reconnecting" | "error";
|
||||
|
||||
export interface DesktopBrowserProxyStatusSnapshot {
|
||||
@@ -217,10 +237,13 @@ export interface DesktopBrowserBridge {
|
||||
}) => Promise<void>;
|
||||
ensureHostProxy?: (input: {
|
||||
serverId: string;
|
||||
target: HostTransportSpec;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
forceReconnect?: boolean;
|
||||
}) => Promise<DesktopBrowserProxyStatusSnapshot>;
|
||||
updateHostProxyTarget?: (input: { serverId: string; target: HostTransportSpec }) => Promise<void>;
|
||||
updateHostProxyTarget?: (input: {
|
||||
serverId: string;
|
||||
target: DesktopBrowserProxyTarget;
|
||||
}) => Promise<void>;
|
||||
getHostProxyStatus?: (serverId: string) => Promise<DesktopBrowserProxyStatusSnapshot | null>;
|
||||
releaseHostProxy?: (serverId: string) => Promise<void>;
|
||||
deliverProxyTicket?: (input: {
|
||||
|
||||
@@ -1,23 +0,0 @@
|
||||
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) } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
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 } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,612 +0,0 @@
|
||||
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,4 +1,2 @@
|
||||
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";
|
||||
|
||||
@@ -1,83 +0,0 @@
|
||||
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>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -1,41 +0,0 @@
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -1,37 +0,0 @@
|
||||
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,26 +5,14 @@ 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, onOpenRelay }: WaysToConnectProps) {
|
||||
export function WaysToConnect({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const [pairing, setPairing] = useState(false);
|
||||
const openPairing = useCallback(() => {
|
||||
if (onOpenRelay) {
|
||||
onOpenRelay();
|
||||
return;
|
||||
}
|
||||
setPairing(true);
|
||||
}, [onOpenRelay]);
|
||||
const openPairing = useCallback(() => setPairing(true), []);
|
||||
const closePairing = useCallback(() => setPairing(false), []);
|
||||
const docsLink = useMemo(
|
||||
() => ({
|
||||
@@ -46,14 +34,12 @@ export function WaysToConnect({ serverId, onOpenRelay }: WaysToConnectProps) {
|
||||
/>
|
||||
<TailscaleRow serverId={serverId} />
|
||||
</SettingsCard>
|
||||
{onOpenRelay ? null : (
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
)}
|
||||
<PairDeviceModal
|
||||
serverId={serverId}
|
||||
visible={pairing}
|
||||
onClose={closePairing}
|
||||
testID="devices-relay-pairing"
|
||||
/>
|
||||
</SettingsSection>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -291,8 +291,6 @@ function useWorkspaceScreenArchiveController({
|
||||
...controller,
|
||||
isArchiving:
|
||||
workspaceDescriptor?.archivingAt != null || isHidingWorkspace || controller.isConfirming,
|
||||
showArchiveIndicator:
|
||||
workspaceDescriptor?.archivingAt != null || controller.isShowingArchiveIndicator,
|
||||
canArchive: canArchiveWorkspace(workspaceDescriptor, archiveRisk),
|
||||
};
|
||||
}
|
||||
@@ -786,7 +784,7 @@ export function useGitActions({
|
||||
},
|
||||
"archive-workspace": {
|
||||
disabled: !archiveController.canArchive || archiveController.isArchiving,
|
||||
status: archiveController.showArchiveIndicator ? "pending" : "idle",
|
||||
status: archiveController.isArchiving ? "pending" : "idle",
|
||||
icon: icons.archive,
|
||||
handler: handleArchiveWorkspace,
|
||||
},
|
||||
@@ -836,7 +834,6 @@ export function useGitActions({
|
||||
mergeFromBaseStatus,
|
||||
archiveController.canArchive,
|
||||
archiveController.isArchiving,
|
||||
archiveController.showArchiveIndicator,
|
||||
handleCommit,
|
||||
handlePull,
|
||||
handlePush,
|
||||
|
||||
@@ -132,14 +132,12 @@ export function buildWorktreeArchiveConfirmationMessage(
|
||||
export async function confirmRiskyWorktreeArchive(
|
||||
input: WorktreeArchiveConfirmationInput,
|
||||
labels: WorktreeArchiveWarningLabels = DEFAULT_WORKTREE_ARCHIVE_WARNING_LABELS,
|
||||
options?: { onPromptOpen?: () => void },
|
||||
): Promise<boolean> {
|
||||
const message = buildWorktreeArchiveConfirmationMessage(input, labels);
|
||||
if (!message) {
|
||||
return true;
|
||||
}
|
||||
|
||||
options?.onPromptOpen?.();
|
||||
return await confirmDialog({
|
||||
title: labels.title(input.workspaceName),
|
||||
message,
|
||||
|
||||
@@ -13,7 +13,6 @@ import {
|
||||
} from "lucide-react-native";
|
||||
import { withUnistyles } from "react-native-unistyles";
|
||||
import { DEFAULT_HOST_ICON, HOST_COLORS, type HostColor, type HostIcon } from "@/hosts/appearance";
|
||||
import { densityIconProps, type DensityIconSize } from "@/styles/density";
|
||||
import { identityForeground } from "@/styles/identity-colors";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
@@ -28,7 +27,6 @@ const ThemedCpu = withUnistyles(Cpu);
|
||||
const ThemedTerminal = withUnistyles(Terminal);
|
||||
|
||||
const mutedMapping = (theme: Theme) => ({ color: theme.colors.foregroundMuted });
|
||||
const DENSITY_ICON_SIZES: readonly DensityIconSize[] = ["xs", "sm", "md", "lg"];
|
||||
|
||||
// One stable uniProps mapping per host color for the life of the module — a fresh identity on
|
||||
// every render makes withUnistyles re-subscribe each pass. Reading `theme.colorScheme` inside the
|
||||
@@ -44,130 +42,36 @@ const HOST_ICON_MAPPINGS: Record<HostColor, (theme: Theme) => { color: string }>
|
||||
return byColor;
|
||||
})();
|
||||
|
||||
const DENSITY_HOST_ICON_MAPPINGS: Record<
|
||||
DensityIconSize,
|
||||
Record<HostColor, (theme: Theme, rt: { breakpoint?: string }) => { color: string; size: number }>
|
||||
> = (() => {
|
||||
const bySize = {} as Record<
|
||||
DensityIconSize,
|
||||
Record<
|
||||
HostColor,
|
||||
(theme: Theme, rt: { breakpoint?: string }) => { color: string; size: number }
|
||||
>
|
||||
>;
|
||||
for (const densitySize of DENSITY_ICON_SIZES) {
|
||||
const byColor = {} as Record<
|
||||
HostColor,
|
||||
(theme: Theme, rt: { breakpoint?: string }) => { color: string; size: number }
|
||||
>;
|
||||
for (const color of HOST_COLORS) {
|
||||
byColor[color] = densityIconProps(densitySize, HOST_ICON_MAPPINGS[color]);
|
||||
}
|
||||
bySize[densitySize] = byColor;
|
||||
}
|
||||
return bySize;
|
||||
})();
|
||||
|
||||
export function HostIconGlyph({
|
||||
icon = DEFAULT_HOST_ICON,
|
||||
color = "none",
|
||||
size = 16,
|
||||
densitySize,
|
||||
strokeWidth,
|
||||
style,
|
||||
}: {
|
||||
icon?: HostIcon;
|
||||
color?: HostColor;
|
||||
size?: number;
|
||||
densitySize?: DensityIconSize;
|
||||
strokeWidth?: number;
|
||||
style?: StyleProp<ViewStyle>;
|
||||
}): ReactElement {
|
||||
const uniProps = densitySize
|
||||
? DENSITY_HOST_ICON_MAPPINGS[densitySize][color]
|
||||
: HOST_ICON_MAPPINGS[color];
|
||||
const resolvedSize = densitySize ? undefined : size;
|
||||
const uniProps = HOST_ICON_MAPPINGS[color];
|
||||
switch (icon) {
|
||||
case "laptop":
|
||||
return (
|
||||
<ThemedLaptop
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedLaptop size={size} style={style} uniProps={uniProps} />;
|
||||
case "desktop":
|
||||
return (
|
||||
<ThemedMonitor
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedMonitor size={size} style={style} uniProps={uniProps} />;
|
||||
case "mini":
|
||||
return (
|
||||
<ThemedComputer
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedComputer size={size} style={style} uniProps={uniProps} />;
|
||||
case "workstation":
|
||||
return (
|
||||
<ThemedPcCase
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedPcCase size={size} style={style} uniProps={uniProps} />;
|
||||
case "cloud":
|
||||
return (
|
||||
<ThemedCloud
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedCloud size={size} style={style} uniProps={uniProps} />;
|
||||
case "container":
|
||||
return (
|
||||
<ThemedContainer
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedContainer size={size} style={style} uniProps={uniProps} />;
|
||||
case "board":
|
||||
return (
|
||||
<ThemedCpu
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedCpu size={size} style={style} uniProps={uniProps} />;
|
||||
case "terminal":
|
||||
return (
|
||||
<ThemedTerminal
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedTerminal size={size} style={style} uniProps={uniProps} />;
|
||||
case "server":
|
||||
return (
|
||||
<ThemedServer
|
||||
size={resolvedSize}
|
||||
strokeWidth={strokeWidth}
|
||||
style={style}
|
||||
uniProps={uniProps}
|
||||
/>
|
||||
);
|
||||
return <ThemedServer size={size} style={style} uniProps={uniProps} />;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,14 +10,13 @@ import {
|
||||
type HostConnectionKind,
|
||||
} from "@/hosts/connection-display";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { formatLatency } from "@/utils/latency";
|
||||
|
||||
export { HostIconGlyph, HostStatusIcon };
|
||||
export { HostIconGlyph };
|
||||
|
||||
const CONNECTION_GLYPH_SIZE = 11;
|
||||
|
||||
|
||||
@@ -1,116 +0,0 @@
|
||||
import React, { act } from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { ALL_HOSTS_OPTION_ID } from "@/components/hosts/host-picker";
|
||||
import { HostFilter } from "@/components/hosts/host-filter";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
|
||||
interface Mounted {
|
||||
root: Root;
|
||||
container: HTMLDivElement;
|
||||
}
|
||||
|
||||
const mountedRoots: Mounted[] = [];
|
||||
const noopSelectHost = () => undefined;
|
||||
|
||||
function mount(element: React.ReactElement): HTMLDivElement {
|
||||
const container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
const root = createRoot(container);
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: { queries: { retry: false } },
|
||||
});
|
||||
act(() => root.render(<QueryClientProvider client={queryClient}>{element}</QueryClientProvider>));
|
||||
mountedRoots.push({ root, container });
|
||||
return container;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
for (const mounted of mountedRoots.splice(0)) {
|
||||
act(() => mounted.root.unmount());
|
||||
mounted.container.remove();
|
||||
}
|
||||
const store = getHostRuntimeStore();
|
||||
for (const host of Array.from(store.getHosts())) {
|
||||
await store.removeHost(host.serverId);
|
||||
}
|
||||
useSessionStore.setState({ sessions: {} });
|
||||
});
|
||||
|
||||
describe("HostStatusIcon", () => {
|
||||
it("renders a sized icon container with an absolutely positioned corner status dot", () => {
|
||||
const container = mount(
|
||||
<HostStatusIcon serverId="srv_unknown" size="sm" backdrop="surface0" />,
|
||||
);
|
||||
|
||||
const root = container.querySelector('[data-testid="host-status-icon"]');
|
||||
const dot = container.querySelector('[data-testid="host-status-icon-dot"]');
|
||||
|
||||
expect(root).not.toBeNull();
|
||||
expect(dot).not.toBeNull();
|
||||
|
||||
const rootStyle = getComputedStyle(root!);
|
||||
expect(rootStyle.width).toBe("14px");
|
||||
expect(rootStyle.height).toBe("14px");
|
||||
expect(rootStyle.position).toBe("relative");
|
||||
|
||||
const dotStyle = getComputedStyle(dot!);
|
||||
expect(dotStyle.position).toBe("absolute");
|
||||
expect(dotStyle.width).toBe("8px");
|
||||
expect(dotStyle.height).toBe("8px");
|
||||
expect(dotStyle.right).toBe("-2px");
|
||||
expect(dotStyle.bottom).toBe("-2px");
|
||||
expect(dotStyle.borderTopWidth).toBe("1px");
|
||||
// Unregistered serverId defaults to "connecting" (warning) with surface0 knockout ring.
|
||||
expect(dotStyle.backgroundColor).toBe("rgb(217, 119, 6)");
|
||||
expect(dotStyle.borderTopColor).toBe("rgb(255, 255, 255)");
|
||||
});
|
||||
|
||||
it("matches container size and knockout ring border to size and backdrop props", () => {
|
||||
const container = mount(
|
||||
<HostStatusIcon serverId="srv_backdrop" size="md" backdrop="surface2" />,
|
||||
);
|
||||
|
||||
const root = container.querySelector('[data-testid="host-status-icon"]');
|
||||
const dot = container.querySelector('[data-testid="host-status-icon-dot"]');
|
||||
|
||||
expect(getComputedStyle(root!).width).toBe("16px");
|
||||
expect(getComputedStyle(root!).height).toBe("16px");
|
||||
expect(getComputedStyle(dot!).borderTopColor).toBe("rgb(244, 244, 245)");
|
||||
});
|
||||
|
||||
it("renders HostStatusIcon on HostFilter when a specific host is selected, not for All hosts", () => {
|
||||
const hosts = [
|
||||
{ serverId: "srv_one", label: "MacBook Pro" },
|
||||
{ serverId: "srv_two", label: "Devbox" },
|
||||
];
|
||||
const container = mount(
|
||||
<HostFilter
|
||||
hosts={hosts}
|
||||
selectedHost="srv_two"
|
||||
onSelectHost={noopSelectHost}
|
||||
triggerTestID="test-host-filter"
|
||||
/>,
|
||||
);
|
||||
|
||||
const trigger = container.querySelector('[data-testid="test-host-filter"]');
|
||||
expect(trigger).not.toBeNull();
|
||||
expect(trigger!.querySelector('[data-testid="host-status-icon"]')).not.toBeNull();
|
||||
expect(trigger!.querySelector('[data-testid="host-status-icon-dot"]')).not.toBeNull();
|
||||
|
||||
const allHostsContainer = mount(
|
||||
<HostFilter
|
||||
hosts={hosts}
|
||||
selectedHost={ALL_HOSTS_OPTION_ID}
|
||||
onSelectHost={noopSelectHost}
|
||||
triggerTestID="test-host-filter-all"
|
||||
/>,
|
||||
);
|
||||
const allTrigger = allHostsContainer.querySelector('[data-testid="test-host-filter-all"]');
|
||||
expect(allTrigger).not.toBeNull();
|
||||
expect(allTrigger!.querySelector('[data-testid="host-status-icon"]')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,167 +0,0 @@
|
||||
import { useMemo, type ReactElement } from "react";
|
||||
import { View, type ViewStyle } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { defaultHostAppearance, resolveHostIcon } from "@/hosts/appearance";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import {
|
||||
useHostRuntimeConnectionStatus,
|
||||
useHosts,
|
||||
type HostRuntimeConnectionStatus,
|
||||
} from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { densityIconBox } from "@/styles/density";
|
||||
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import { STATUS_INDICATOR_DOT_SIZE } from "@/utils/status-indicator-geometry";
|
||||
|
||||
export type HostStatusIconSize = "sm" | "md";
|
||||
|
||||
const STATUS_DOT_OFFSET = -2;
|
||||
|
||||
export interface HostStatusIconProps {
|
||||
serverId: string;
|
||||
/** Icon size. `"sm"` is 14px, `"md"` is 16px (or touch-scaled when `density` is set). */
|
||||
size?: HostStatusIconSize;
|
||||
/** Follow touch/pointer density sizing (e.g. Settings sidebar rows) without `useUnistyles()`. */
|
||||
density?: boolean;
|
||||
/** Surface behind the icon so the status dot's 1px knockout ring blends cleanly. */
|
||||
backdrop?: SurfaceBackdrop;
|
||||
strokeWidth?: number;
|
||||
testID?: string;
|
||||
statusTestID?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A host's resolved device icon badged with its live connection status dot in the bottom-right
|
||||
* corner. Used in single-slot host selectors, triggers, and menu items so the user sees both which
|
||||
* host is selected and whether it is reachable.
|
||||
*/
|
||||
export function HostStatusIcon({
|
||||
serverId,
|
||||
size = "sm",
|
||||
density = false,
|
||||
backdrop = "surface0",
|
||||
strokeWidth,
|
||||
testID = "host-status-icon",
|
||||
statusTestID = "host-status-icon-dot",
|
||||
}: HostStatusIconProps): ReactElement {
|
||||
const hosts = useHosts();
|
||||
const status = useHostRuntimeConnectionStatus(serverId);
|
||||
const detectedMachineKind = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.serverInfo?.machineKind ?? null,
|
||||
);
|
||||
const appearance = useMemo(
|
||||
() =>
|
||||
hosts.find((candidate) => candidate.serverId === serverId)?.appearance ??
|
||||
defaultHostAppearance(),
|
||||
[hosts, serverId],
|
||||
);
|
||||
const resolvedIcon = resolveHostIcon({ appearance, detectedMachineKind });
|
||||
|
||||
return (
|
||||
<View style={[styles.container, containerSizeStyle(size, density)]} testID={testID}>
|
||||
<HostIconGlyph
|
||||
icon={resolvedIcon}
|
||||
color={appearance.color}
|
||||
size={size === "md" ? ICON_SIZE.md : ICON_SIZE.sm}
|
||||
densitySize={density ? size : undefined}
|
||||
strokeWidth={strokeWidth}
|
||||
/>
|
||||
<View
|
||||
testID={statusTestID}
|
||||
style={[styles.statusDot, statusStyle(status), backdropStyle(backdrop)]}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function containerSizeStyle(size: HostStatusIconSize, density: boolean): ViewStyle {
|
||||
if (density) {
|
||||
return size === "md" ? styles.containerDensityMd : styles.containerDensitySm;
|
||||
}
|
||||
return size === "md" ? styles.containerMd : styles.containerSm;
|
||||
}
|
||||
|
||||
function statusStyle(status: HostRuntimeConnectionStatus): ViewStyle {
|
||||
if (status === "online") return styles.dotOnline;
|
||||
if (status === "connecting") return styles.dotConnecting;
|
||||
return styles.dotOffline;
|
||||
}
|
||||
|
||||
function backdropStyle(backdrop: SurfaceBackdrop): ViewStyle {
|
||||
switch (backdrop) {
|
||||
case "surface0":
|
||||
return styles.backdropSurface0;
|
||||
case "surface1":
|
||||
return styles.backdropSurface1;
|
||||
case "surface2":
|
||||
return styles.backdropSurface2;
|
||||
case "surfaceSidebar":
|
||||
return styles.backdropSurfaceSidebar;
|
||||
case "surfaceSidebarHover":
|
||||
return styles.backdropSurfaceSidebarHover;
|
||||
case "surfaceSidebarSelected":
|
||||
return styles.backdropSurfaceSidebarSelected;
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
container: {
|
||||
position: "relative",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexShrink: 0,
|
||||
},
|
||||
containerSm: {
|
||||
width: ICON_SIZE.sm,
|
||||
height: ICON_SIZE.sm,
|
||||
},
|
||||
containerMd: {
|
||||
width: ICON_SIZE.md,
|
||||
height: ICON_SIZE.md,
|
||||
},
|
||||
containerDensitySm: {
|
||||
width: densityIconBox("sm"),
|
||||
height: densityIconBox("sm"),
|
||||
},
|
||||
containerDensityMd: {
|
||||
width: densityIconBox("md"),
|
||||
height: densityIconBox("md"),
|
||||
},
|
||||
statusDot: {
|
||||
position: "absolute",
|
||||
right: STATUS_DOT_OFFSET,
|
||||
bottom: STATUS_DOT_OFFSET,
|
||||
width: STATUS_INDICATOR_DOT_SIZE,
|
||||
height: STATUS_INDICATOR_DOT_SIZE,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
borderWidth: 1,
|
||||
},
|
||||
dotOnline: {
|
||||
backgroundColor: theme.colors.statusSuccess,
|
||||
},
|
||||
dotConnecting: {
|
||||
backgroundColor: theme.colors.statusWarning,
|
||||
},
|
||||
dotOffline: {
|
||||
backgroundColor: theme.colors.statusDanger,
|
||||
},
|
||||
backdropSurface0: {
|
||||
borderColor: theme.colors.surface0,
|
||||
},
|
||||
backdropSurface1: {
|
||||
borderColor: theme.colors.surface1,
|
||||
},
|
||||
backdropSurface2: {
|
||||
borderColor: theme.colors.surface2,
|
||||
},
|
||||
backdropSurfaceSidebar: {
|
||||
borderColor: theme.colors.surfaceSidebar,
|
||||
},
|
||||
backdropSurfaceSidebarHover: {
|
||||
borderColor: theme.colors.surfaceSidebarHover,
|
||||
},
|
||||
backdropSurfaceSidebarSelected: {
|
||||
borderColor: theme.colors.surfaceSidebarSelected,
|
||||
},
|
||||
}));
|
||||
@@ -737,6 +737,8 @@ export const ar: TranslationResources = {
|
||||
reconnecting: "جارٍ إعادة الاتصال بـ {{hostName}}...",
|
||||
updateTitle: "حدّث {{hostName}} للتصفح عبر هذا المضيف",
|
||||
updateDescription: "لا يدعم هذا المضيف وكيل المتصفح بعد.",
|
||||
routedTitle: "وكيل المتصفح غير متاح للمضيفين الموجَّهين",
|
||||
routedDescription: "اتصل مباشرة بهذا المضيف أو تصفح محلياً.",
|
||||
offlineTitle: "{{hostName}} غير متصل",
|
||||
offlineDescription: "انتظر إعادة اتصال المضيف أو تصفح محلياً.",
|
||||
errorTitle: "تعذر الاتصال بوكيل المتصفح",
|
||||
@@ -2019,71 +2021,6 @@ 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: {
|
||||
@@ -2486,7 +2423,6 @@ export const ar: TranslationResources = {
|
||||
options: "الإعدادات",
|
||||
host: "المضيف",
|
||||
refreshFailed: "تعذّر تحديث الاستخدام",
|
||||
notFetched: "لم يتم التحقق بعد. لا يتم تحديث استخدام {{source}} إلا عند تحديثه.",
|
||||
noHosts: "لا توجد مضيفات متصلة",
|
||||
agentError: "تعذّر تحميل الاستخدام: {{reason}}",
|
||||
pin: "تثبيت",
|
||||
|
||||
@@ -736,6 +736,8 @@ export const en = {
|
||||
reconnecting: "Reconnecting to {{hostName}}...",
|
||||
updateTitle: "Update {{hostName}} to browse through this host",
|
||||
updateDescription: "This host does not support browser proxying yet.",
|
||||
routedTitle: "Browser proxy is not available for routed hosts",
|
||||
routedDescription: "Connect directly to this host or browse locally.",
|
||||
offlineTitle: "{{hostName}} is offline",
|
||||
offlineDescription: "Wait for the host to reconnect or browse locally.",
|
||||
errorTitle: "Could not connect browser proxy",
|
||||
@@ -2049,71 +2051,6 @@ 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: {
|
||||
@@ -2516,7 +2453,6 @@ 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",
|
||||
|
||||
@@ -743,6 +743,8 @@ export const es: TranslationResources = {
|
||||
reconnecting: "Reconectando con {{hostName}}...",
|
||||
updateTitle: "Actualiza {{hostName}} para navegar a través de este host",
|
||||
updateDescription: "Este host todavía no admite el proxy del navegador.",
|
||||
routedTitle: "El proxy del navegador no está disponible para hosts enrutados",
|
||||
routedDescription: "Conéctate directamente a este host o navega localmente.",
|
||||
offlineTitle: "{{hostName}} está desconectado",
|
||||
offlineDescription: "Espera a que el host se reconecte o navega localmente.",
|
||||
errorTitle: "No se pudo conectar el proxy del navegador",
|
||||
@@ -2073,71 +2075,6 @@ 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: {
|
||||
@@ -2542,7 +2479,6 @@ 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",
|
||||
|
||||
@@ -743,6 +743,8 @@ export const fr: TranslationResources = {
|
||||
reconnecting: "Reconnexion à {{hostName}}...",
|
||||
updateTitle: "Mettez à jour {{hostName}} pour naviguer via cet hôte",
|
||||
updateDescription: "Cet hôte ne prend pas encore en charge le proxy du navigateur.",
|
||||
routedTitle: "Le proxy du navigateur n’est pas disponible pour les hôtes routés",
|
||||
routedDescription: "Connectez-vous directement à cet hôte ou naviguez en local.",
|
||||
offlineTitle: "{{hostName}} est hors ligne",
|
||||
offlineDescription: "Attendez la reconnexion de l’hôte ou naviguez en local.",
|
||||
errorTitle: "Impossible de connecter le proxy du navigateur",
|
||||
@@ -2070,71 +2072,6 @@ 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: {
|
||||
@@ -2541,8 +2478,6 @@ 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",
|
||||
|
||||
@@ -743,6 +743,8 @@ export const ja: TranslationResources = {
|
||||
reconnecting: "{{hostName}} に再接続中...",
|
||||
updateTitle: "このホスト経由で閲覧するには {{hostName}} を更新してください",
|
||||
updateDescription: "このホストはまだブラウザプロキシに対応していません。",
|
||||
routedTitle: "ルーティングされたホストではブラウザプロキシを利用できません",
|
||||
routedDescription: "このホストに直接接続するか、ローカルで閲覧してください。",
|
||||
offlineTitle: "{{hostName}} はオフラインです",
|
||||
offlineDescription: "ホストの再接続を待つか、ローカルで閲覧してください。",
|
||||
errorTitle: "ブラウザプロキシに接続できませんでした",
|
||||
@@ -2040,71 +2042,6 @@ 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: {
|
||||
@@ -2511,7 +2448,6 @@ export const ja: TranslationResources = {
|
||||
options: "設定",
|
||||
host: "ホスト",
|
||||
refreshFailed: "使用状況を更新できません",
|
||||
notFetched: "まだ確認していません。{{source}} の使用状況は、更新したときだけ更新されます。",
|
||||
noHosts: "接続中のホストがありません",
|
||||
agentError: "使用状況を読み込めません: {{reason}}",
|
||||
pin: "ピン留め",
|
||||
|
||||
@@ -738,6 +738,8 @@ export const ko: TranslationResources = {
|
||||
reconnecting: "{{hostName}}에 다시 연결 중...",
|
||||
updateTitle: "이 호스트를 통해 탐색하려면 {{hostName}}을(를) 업데이트하세요",
|
||||
updateDescription: "이 호스트는 아직 브라우저 프록시를 지원하지 않습니다.",
|
||||
routedTitle: "라우팅된 호스트에서는 브라우저 프록시를 사용할 수 없습니다",
|
||||
routedDescription: "이 호스트에 직접 연결하거나 로컬로 탐색하세요.",
|
||||
offlineTitle: "{{hostName}}이(가) 오프라인입니다",
|
||||
offlineDescription: "호스트가 다시 연결될 때까지 기다리거나 로컬로 탐색하세요.",
|
||||
errorTitle: "브라우저 프록시에 연결할 수 없습니다",
|
||||
@@ -2031,71 +2033,6 @@ 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: {
|
||||
@@ -2498,7 +2435,6 @@ export const ko: TranslationResources = {
|
||||
options: "설정",
|
||||
host: "호스트",
|
||||
refreshFailed: "사용량을 새로 고칠 수 없습니다",
|
||||
notFetched: "아직 확인하지 않았습니다. {{source}} 사용량은 새로 고칠 때만 업데이트됩니다.",
|
||||
noHosts: "연결된 호스트가 없습니다",
|
||||
agentError: "사용량을 불러올 수 없습니다: {{reason}}",
|
||||
pin: "고정",
|
||||
|
||||
@@ -38,9 +38,6 @@ export const pluginGallery = {
|
||||
repository: "Repository",
|
||||
showMore: "Show more",
|
||||
browse: "Browse plugins",
|
||||
reportBug: "Report a bug",
|
||||
viewOnNpm: "View on npm",
|
||||
sponsor: "Sponsor",
|
||||
},
|
||||
off: { title: "Plugins are off on {{host}}" },
|
||||
empty: { noMatches: "No plugins match" },
|
||||
@@ -57,85 +54,9 @@ export const pluginGallery = {
|
||||
warningTitle: "Runs with your access on {{host}}",
|
||||
warningDescription: "Plugins are not sandboxed. Install only code you trust.",
|
||||
turnsOn: "Plugins are not sandboxed. Installing also turns plugins on.",
|
||||
reviewNotesWarning:
|
||||
"This version has {{count}} review notes. Check Scorecard before installing.",
|
||||
},
|
||||
update: { updated: "{{name}} updated", updatedMany: "{{count}} plugins updated" },
|
||||
details: {
|
||||
license: "License",
|
||||
updated: "Updated",
|
||||
published: "Published",
|
||||
compatibility: "Compatibility",
|
||||
platforms: "Platforms",
|
||||
platformNames: {
|
||||
desktop: "Desktop",
|
||||
web: "Web",
|
||||
mobile: "Mobile",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "Open image",
|
||||
author: "Author",
|
||||
morePlugins: "{{count}} plugins",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "Settings",
|
||||
overview: "Overview",
|
||||
scorecard: "Scorecard",
|
||||
updates: "Updates",
|
||||
updatesCount: "Updates · {{count}}",
|
||||
details: "Details",
|
||||
},
|
||||
updateHostRequired: "Update your Paseo host to view plugin scorecards and revision history.",
|
||||
scorecard: {
|
||||
notice:
|
||||
"Automated and AI-assisted review of version {{version}}. A passing review is not a security guarantee.",
|
||||
reviewPolicy: "Review policy",
|
||||
health: "Health",
|
||||
review: "Review",
|
||||
healthGrades: {
|
||||
excellent: "Excellent",
|
||||
good: "Good",
|
||||
fair: "Fair",
|
||||
low: "Low",
|
||||
},
|
||||
reviewStatuses: {
|
||||
passed: "Passed",
|
||||
passed_with_notes: "Passed with notes",
|
||||
unreviewed: "Unreviewed",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "Hygiene",
|
||||
maintenance: "Maintenance",
|
||||
responsiveness: "Responsiveness",
|
||||
adoption: "Adoption",
|
||||
},
|
||||
groups: {
|
||||
notes: "Review notes",
|
||||
passed: "Passed",
|
||||
capabilities: "Capabilities & Access",
|
||||
},
|
||||
noIssues: "No issues found in review of version {{version}}.",
|
||||
notesCount: "{{count}} review notes found for version {{version}}.",
|
||||
unreviewedSummary: "This version has not completed a full structured review yet.",
|
||||
reviewPr: "Review PR",
|
||||
baselineTitle: "Reviewed on {{date}}",
|
||||
baselineBody:
|
||||
"This listing passed registry review before structured scorecards were enabled.",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "Current pin",
|
||||
githubRelease: "GitHub release",
|
||||
commitSnapshot: "Commit snapshot",
|
||||
npmPackage: "npm package",
|
||||
viewAllReleases: "View all releases on GitHub",
|
||||
viewRepository: "View repository",
|
||||
},
|
||||
related: {
|
||||
title: "Related plugins",
|
||||
},
|
||||
},
|
||||
details: { license: "License", updated: "Updated", openImage: "Open image" },
|
||||
missing: "This plugin is not installed or listed",
|
||||
},
|
||||
ar: {
|
||||
@@ -176,9 +97,6 @@ export const pluginGallery = {
|
||||
repository: "المستودع",
|
||||
showMore: "عرض المزيد",
|
||||
browse: "تصفّح الإضافات",
|
||||
reportBug: "الإبلاغ عن خطأ",
|
||||
viewOnNpm: "عرض على npm",
|
||||
sponsor: "رعاية",
|
||||
},
|
||||
off: { title: "الإضافات متوقفة على {{host}}" },
|
||||
empty: { noMatches: "لا توجد إضافات مطابقة" },
|
||||
@@ -195,77 +113,9 @@ export const pluginGallery = {
|
||||
warningTitle: "تعمل بصلاحياتك على {{host}}",
|
||||
warningDescription: "الإضافات غير معزولة. ثبّت فقط التعليمات البرمجية التي تثق بها.",
|
||||
turnsOn: "الإضافات غير معزولة. يؤدي التثبيت أيضًا إلى تشغيل الإضافات.",
|
||||
reviewNotesWarning:
|
||||
"يحتوي هذا الإصدار على {{count}} ملاحظات مراجعة. تحقق من بطاقة التقييم قبل التثبيت.",
|
||||
},
|
||||
update: { updated: "تم تحديث {{name}}", updatedMany: "تم تحديث {{count}} إضافات" },
|
||||
details: {
|
||||
license: "الترخيص",
|
||||
updated: "آخر تحديث",
|
||||
published: "تاريخ النشر",
|
||||
compatibility: "التوافق",
|
||||
platforms: "المنصات",
|
||||
platformNames: {
|
||||
desktop: "سطح المكتب",
|
||||
web: "الويب",
|
||||
mobile: "الهاتف",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "فتح الصورة",
|
||||
author: "المؤلف",
|
||||
morePlugins: "{{count}} إضافات",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "الإعدادات",
|
||||
overview: "نظرة عامة",
|
||||
scorecard: "بطاقة التقييم",
|
||||
updates: "التحديثات",
|
||||
updatesCount: "التحديثات · {{count}}",
|
||||
details: "التفاصيل",
|
||||
},
|
||||
updateHostRequired: "حدّث مضيف Paseo لعرض بطاقة التقييم وسجل الإصدارات.",
|
||||
scorecard: {
|
||||
notice:
|
||||
"مراجعة آلية وبمساعدة الذكاء الاصطناعي للإصدار {{version}}. اجتياز المراجعة ليس ضمانًا أمنيًا.",
|
||||
reviewPolicy: "سياسة المراجعة",
|
||||
health: "الصحة",
|
||||
review: "المراجعة",
|
||||
healthGrades: { excellent: "ممتاز", good: "جيد", fair: "متوسط", low: "منخفض" },
|
||||
reviewStatuses: {
|
||||
passed: "ناجحة",
|
||||
passed_with_notes: "ناجحة مع ملاحظات",
|
||||
unreviewed: "غير مراجَعة",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "الاكتمال",
|
||||
maintenance: "الصيانة",
|
||||
responsiveness: "الاستجابة",
|
||||
adoption: "الانتشار",
|
||||
},
|
||||
groups: {
|
||||
notes: "ملاحظات المراجعة",
|
||||
passed: "الفحوصات الناجحة",
|
||||
capabilities: "القدرات والوصول",
|
||||
},
|
||||
noIssues: "لم يتم العثور على مشكلات في مراجعة الإصدار {{version}}.",
|
||||
notesCount: "تم العثور على {{count}} ملاحظات مراجعة للإصدار {{version}}.",
|
||||
unreviewedSummary: "لم يكمل هذا الإصدار مراجعة منظّمة كاملة بعد.",
|
||||
reviewPr: "طلب المراجعة",
|
||||
baselineTitle: "تمت المراجعة في {{date}}",
|
||||
baselineBody: "اجتازت هذه الإضافة مراجعة السجل قبل تفعيل بطاقات التقييم المنظمة.",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "الإصدار الحالي",
|
||||
githubRelease: "إصدار GitHub",
|
||||
commitSnapshot: "لقطة التزام",
|
||||
npmPackage: "حزمة npm",
|
||||
viewAllReleases: "عرض كل الإصدارات على GitHub",
|
||||
viewRepository: "عرض المستودع",
|
||||
},
|
||||
related: { title: "إضافات ذات صلة" },
|
||||
},
|
||||
details: { license: "الترخيص", updated: "آخر تحديث", openImage: "فتح الصورة" },
|
||||
missing: "هذه الإضافة غير مثبّتة وغير مدرجة",
|
||||
},
|
||||
es: {
|
||||
@@ -306,9 +156,6 @@ export const pluginGallery = {
|
||||
repository: "Repositorio",
|
||||
showMore: "Mostrar más",
|
||||
browse: "Explorar plugins",
|
||||
reportBug: "Informar un error",
|
||||
viewOnNpm: "Ver en npm",
|
||||
sponsor: "Patrocinar",
|
||||
},
|
||||
off: { title: "Los plugins están desactivados en {{host}}" },
|
||||
empty: { noMatches: "Ningún plugin coincide" },
|
||||
@@ -325,79 +172,9 @@ export const pluginGallery = {
|
||||
warningTitle: "Se ejecuta con tu acceso en {{host}}",
|
||||
warningDescription: "Los plugins no están aislados. Instala solo código de confianza.",
|
||||
turnsOn: "Los plugins no están aislados. Instalar también activa los plugins.",
|
||||
reviewNotesWarning:
|
||||
"Esta versión tiene {{count}} notas de revisión. Revisa la evaluación antes de instalar.",
|
||||
},
|
||||
update: { updated: "{{name}} actualizado", updatedMany: "{{count}} plugins actualizados" },
|
||||
details: {
|
||||
license: "Licencia",
|
||||
updated: "Actualizado",
|
||||
published: "Publicado",
|
||||
compatibility: "Compatibilidad",
|
||||
platforms: "Plataformas",
|
||||
platformNames: {
|
||||
desktop: "Escritorio",
|
||||
web: "Web",
|
||||
mobile: "Móvil",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "Abrir imagen",
|
||||
author: "Autor",
|
||||
morePlugins: "{{count}} plugins",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "Ajustes",
|
||||
overview: "Resumen",
|
||||
scorecard: "Evaluación",
|
||||
updates: "Versiones",
|
||||
updatesCount: "Versiones · {{count}}",
|
||||
details: "Detalles",
|
||||
},
|
||||
updateHostRequired:
|
||||
"Actualiza tu host de Paseo para ver las tarjetas de evaluación y el historial de versiones.",
|
||||
scorecard: {
|
||||
notice:
|
||||
"Revisión automatizada y asistida por IA de la versión {{version}}. Aprobarla no es una garantía de seguridad.",
|
||||
reviewPolicy: "Política de revisión",
|
||||
health: "Salud",
|
||||
review: "Revisión",
|
||||
healthGrades: { excellent: "Excelente", good: "Buena", fair: "Aceptable", low: "Baja" },
|
||||
reviewStatuses: {
|
||||
passed: "Aprobada",
|
||||
passed_with_notes: "Aprobada con notas",
|
||||
unreviewed: "Sin revisar",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "Higiene",
|
||||
maintenance: "Mantenimiento",
|
||||
responsiveness: "Respuesta",
|
||||
adoption: "Adopción",
|
||||
},
|
||||
groups: {
|
||||
notes: "Notas de revisión",
|
||||
passed: "Comprobaciones aprobadas",
|
||||
capabilities: "Capacidades y acceso",
|
||||
},
|
||||
noIssues: "No se encontraron problemas al revisar la versión {{version}}.",
|
||||
notesCount: "Se encontraron {{count}} notas al revisar la versión {{version}}.",
|
||||
unreviewedSummary: "Esta versión aún no tiene una revisión estructurada completa.",
|
||||
reviewPr: "PR de revisión",
|
||||
baselineTitle: "Revisado el {{date}}",
|
||||
baselineBody:
|
||||
"Este plugin aprobó la revisión antes de activar las evaluaciones detalladas.",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "Versión actual",
|
||||
githubRelease: "Release de GitHub",
|
||||
commitSnapshot: "Instantánea del commit",
|
||||
npmPackage: "Paquete npm",
|
||||
viewAllReleases: "Ver todas las releases en GitHub",
|
||||
viewRepository: "Ver repositorio",
|
||||
},
|
||||
related: { title: "Plugins relacionados" },
|
||||
},
|
||||
details: { license: "Licencia", updated: "Actualizado", openImage: "Abrir imagen" },
|
||||
missing: "Este plugin no está instalado ni publicado",
|
||||
},
|
||||
fr: {
|
||||
@@ -442,9 +219,6 @@ export const pluginGallery = {
|
||||
repository: "Dépôt",
|
||||
showMore: "Afficher plus",
|
||||
browse: "Parcourir les plugins",
|
||||
reportBug: "Signaler un bug",
|
||||
viewOnNpm: "Voir sur npm",
|
||||
sponsor: "Soutenir",
|
||||
},
|
||||
off: { title: "Les plugins sont désactivés sur {{host}}" },
|
||||
empty: { noMatches: "Aucun plugin ne correspond" },
|
||||
@@ -461,78 +235,9 @@ export const pluginGallery = {
|
||||
warningTitle: "S’exécute avec vos accès sur {{host}}",
|
||||
warningDescription: "Les plugins ne sont pas isolés. N’installez que du code de confiance.",
|
||||
turnsOn: "Les plugins ne sont pas isolés. L’installation active aussi les plugins.",
|
||||
reviewNotesWarning:
|
||||
"Cette version comporte {{count}} notes de revue. Consultez la fiche avant d’installer.",
|
||||
},
|
||||
update: { updated: "{{name}} mis à jour", updatedMany: "{{count}} plugins mis à jour" },
|
||||
details: {
|
||||
license: "Licence",
|
||||
updated: "Mis à jour",
|
||||
published: "Publié",
|
||||
compatibility: "Compatibilité",
|
||||
platforms: "Plateformes",
|
||||
platformNames: {
|
||||
desktop: "Bureau",
|
||||
web: "Web",
|
||||
mobile: "Mobile",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "Ouvrir l’image",
|
||||
author: "Auteur",
|
||||
morePlugins: "{{count}} plugins",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "Paramètres",
|
||||
overview: "Présentation",
|
||||
scorecard: "Fiche",
|
||||
updates: "Versions",
|
||||
updatesCount: "Versions · {{count}}",
|
||||
details: "Détails",
|
||||
},
|
||||
updateHostRequired:
|
||||
"Mettez à jour votre hôte Paseo pour afficher les fiches d’évaluation et l’historique des versions.",
|
||||
scorecard: {
|
||||
notice:
|
||||
"Revue automatisée et assistée par IA de la version {{version}} . Une revue validée ne constitue pas une garantie de sécurité.",
|
||||
reviewPolicy: "Politique de revue",
|
||||
health: "Santé",
|
||||
review: "Revue",
|
||||
healthGrades: { excellent: "Excellente", good: "Bonne", fair: "Correcte", low: "Faible" },
|
||||
reviewStatuses: {
|
||||
passed: "Validée",
|
||||
passed_with_notes: "Validée avec notes",
|
||||
unreviewed: "Non vérifiée",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "Hygiène",
|
||||
maintenance: "Maintenance",
|
||||
responsiveness: "Réactivité",
|
||||
adoption: "Adoption",
|
||||
},
|
||||
groups: {
|
||||
notes: "Notes de revue",
|
||||
passed: "Vérifications validées",
|
||||
capabilities: "Capacités et accès",
|
||||
},
|
||||
noIssues: "Aucun problème détecté lors de la revue de la version {{version}} .",
|
||||
notesCount: "{{count}} notes de revue pour la version {{version}} .",
|
||||
unreviewedSummary: "Cette version n’a pas encore fait l’objet d’une revue structurée.",
|
||||
reviewPr: "PR de revue",
|
||||
baselineTitle: "Vérifié le {{date}}",
|
||||
baselineBody: "Ce plugin a passé la revue du registre avant les fiches détaillées.",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "Version épinglée",
|
||||
githubRelease: "Release GitHub",
|
||||
commitSnapshot: "Instantané du commit",
|
||||
npmPackage: "Paquet npm",
|
||||
viewAllReleases: "Voir toutes les releases sur GitHub",
|
||||
viewRepository: "Voir le dépôt",
|
||||
},
|
||||
related: { title: "Plugins associés" },
|
||||
},
|
||||
details: { license: "Licence", updated: "Mis à jour", openImage: "Ouvrir l’image" },
|
||||
missing: "Ce plugin n’est ni installé ni publié",
|
||||
},
|
||||
ja: {
|
||||
@@ -581,9 +286,6 @@ export const pluginGallery = {
|
||||
repository: "リポジトリ",
|
||||
showMore: "さらに表示",
|
||||
browse: "プラグインを見つける",
|
||||
reportBug: "バグを報告",
|
||||
viewOnNpm: "npm で表示",
|
||||
sponsor: "スポンサー",
|
||||
},
|
||||
off: { title: "{{host}} ではプラグインがオフです" },
|
||||
empty: { noMatches: "一致するプラグインはありません" },
|
||||
@@ -602,80 +304,12 @@ export const pluginGallery = {
|
||||
"プラグインはサンドボックス化されていません。信頼できるコードのみインストールしてください。",
|
||||
turnsOn:
|
||||
"プラグインはサンドボックス化されていません。インストールするとプラグインもオンになります。",
|
||||
reviewNotesWarning:
|
||||
"このバージョンには {{count}} 件のレビュー注記があります。インストール前に確認してください。",
|
||||
},
|
||||
update: {
|
||||
updated: "{{name}} をアップデートしました",
|
||||
updatedMany: "{{count}} 個のプラグインをアップデートしました",
|
||||
},
|
||||
details: {
|
||||
license: "ライセンス",
|
||||
updated: "更新日",
|
||||
published: "公開日",
|
||||
compatibility: "互換性",
|
||||
platforms: "プラットフォーム",
|
||||
platformNames: {
|
||||
desktop: "デスクトップ",
|
||||
web: "Web",
|
||||
mobile: "モバイル",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "画像を開く",
|
||||
author: "作者",
|
||||
morePlugins: "{{count}} 件のプラグイン",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "設定",
|
||||
overview: "概要",
|
||||
scorecard: "スコアカード",
|
||||
updates: "更新履歴",
|
||||
updatesCount: "更新履歴 · {{count}}",
|
||||
details: "詳細",
|
||||
},
|
||||
updateHostRequired:
|
||||
"プラグインのスコアカードと更新履歴を表示するには、Paseo ホストを更新してください。",
|
||||
scorecard: {
|
||||
notice: "バージョン {{version}} の自動・AI補助レビューです。通過は安全保証ではありません。",
|
||||
reviewPolicy: "レビューポリシー",
|
||||
health: "健全性",
|
||||
review: "レビュー",
|
||||
healthGrades: { excellent: "優秀", good: "良好", fair: "普通", low: "低" },
|
||||
reviewStatuses: {
|
||||
passed: "通過",
|
||||
passed_with_notes: "注記付きで通過",
|
||||
unreviewed: "未レビュー",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "整備状況",
|
||||
maintenance: "メンテナンス",
|
||||
responsiveness: "対応速度",
|
||||
adoption: "採用状況",
|
||||
},
|
||||
groups: {
|
||||
notes: "レビュー注記",
|
||||
passed: "通過したチェック",
|
||||
capabilities: "機能とアクセス",
|
||||
},
|
||||
noIssues: "バージョン {{version}} のレビューで問題は見つかりませんでした。",
|
||||
notesCount: "バージョン {{version}} のレビューに {{count}} 件の注記があります。",
|
||||
unreviewedSummary: "このバージョンの構造化レビューはまだ完了していません。",
|
||||
reviewPr: "レビュー PR",
|
||||
baselineTitle: "{{date}} にレビュー済み",
|
||||
baselineBody: "このプラグインはスコアカード導入前にレジストリレビューを通過しています。",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "現在のピン",
|
||||
githubRelease: "GitHub リリース",
|
||||
commitSnapshot: "コミットスナップショット",
|
||||
npmPackage: "npm パッケージ",
|
||||
viewAllReleases: "GitHub ですべてのリリースを見る",
|
||||
viewRepository: "リポジトリを見る",
|
||||
},
|
||||
related: { title: "関連プラグイン" },
|
||||
},
|
||||
details: { license: "ライセンス", updated: "更新日", openImage: "画像を開く" },
|
||||
missing: "このプラグインはインストールも公開もされていません",
|
||||
},
|
||||
ko: {
|
||||
@@ -716,9 +350,6 @@ export const pluginGallery = {
|
||||
repository: "저장소",
|
||||
showMore: "더 보기",
|
||||
browse: "플러그인 찾아보기",
|
||||
reportBug: "버그 신고",
|
||||
viewOnNpm: "npm에서 보기",
|
||||
sponsor: "후원하기",
|
||||
},
|
||||
off: { title: "{{host}}에서 플러그인이 꺼져 있습니다" },
|
||||
empty: { noMatches: "일치하는 플러그인이 없습니다" },
|
||||
@@ -735,76 +366,9 @@ export const pluginGallery = {
|
||||
warningTitle: "{{host}}에서 사용자 권한으로 실행됩니다",
|
||||
warningDescription: "플러그인은 격리되지 않습니다. 신뢰하는 코드만 설치하세요.",
|
||||
turnsOn: "플러그인은 격리되지 않습니다. 설치하면 플러그인도 켜집니다.",
|
||||
reviewNotesWarning: "이 버전에 검토 참고 사항 {{count}}건이 있습니다. 설치 전 확인하세요.",
|
||||
},
|
||||
update: { updated: "{{name}} 업데이트됨", updatedMany: "플러그인 {{count}}개 업데이트됨" },
|
||||
details: {
|
||||
license: "라이선스",
|
||||
updated: "업데이트",
|
||||
published: "게시일",
|
||||
compatibility: "호환성",
|
||||
platforms: "플랫폼",
|
||||
platformNames: {
|
||||
desktop: "데스크톱",
|
||||
web: "웹",
|
||||
mobile: "모바일",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "이미지 열기",
|
||||
author: "작성자",
|
||||
morePlugins: "플러그인 {{count}}개",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "설정",
|
||||
overview: "개요",
|
||||
scorecard: "점수표",
|
||||
updates: "업데이트",
|
||||
updatesCount: "업데이트 · {{count}}",
|
||||
details: "세부 정보",
|
||||
},
|
||||
updateHostRequired: "플러그인 스코어카드와 버전 기록을 보려면 Paseo 호스트를 업데이트하세요.",
|
||||
scorecard: {
|
||||
notice:
|
||||
"버전 {{version}}의 자동 및 AI 보조 검토 결과입니다. 통과가 보안 보장을 의미하지는 않습니다.",
|
||||
reviewPolicy: "검토 정책",
|
||||
health: "상태",
|
||||
review: "검토",
|
||||
healthGrades: { excellent: "우수", good: "양호", fair: "보통", low: "낮음" },
|
||||
reviewStatuses: {
|
||||
passed: "통과",
|
||||
passed_with_notes: "참고 사항 있음",
|
||||
unreviewed: "미검토",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "기본 정보",
|
||||
maintenance: "유지 관리",
|
||||
responsiveness: "응답성",
|
||||
adoption: "사용 현황",
|
||||
},
|
||||
groups: {
|
||||
notes: "검토 참고 사항",
|
||||
passed: "통과한 항목",
|
||||
capabilities: "기능 및 접근 권한",
|
||||
},
|
||||
noIssues: "버전 {{version}} 검토에서 문제가 발견되지 않았습니다.",
|
||||
notesCount: "버전 {{version}} 검토에서 참고 사항 {{count}}건이 있습니다.",
|
||||
unreviewedSummary: "이 버전의 구조화된 검토가 아직 완료되지 않았습니다.",
|
||||
reviewPr: "검토 PR",
|
||||
baselineTitle: "{{date}} 검토 완료",
|
||||
baselineBody: "이 플러그인은 구조화된 점수표 도입 전에 레지스트리 검토를 통과했습니다.",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "현재 고정 버전",
|
||||
githubRelease: "GitHub 릴리스",
|
||||
commitSnapshot: "커밋 스냅샷",
|
||||
npmPackage: "npm 패키지",
|
||||
viewAllReleases: "GitHub에서 모든 릴리스 보기",
|
||||
viewRepository: "저장소 보기",
|
||||
},
|
||||
related: { title: "관련 플러그인" },
|
||||
},
|
||||
details: { license: "라이선스", updated: "업데이트", openImage: "이미지 열기" },
|
||||
missing: "이 플러그인은 설치되지 않았고 등록되어 있지도 않습니다",
|
||||
},
|
||||
"pt-BR": {
|
||||
@@ -845,9 +409,6 @@ export const pluginGallery = {
|
||||
repository: "Repositório",
|
||||
showMore: "Mostrar mais",
|
||||
browse: "Explorar plugins",
|
||||
reportBug: "Reportar bug",
|
||||
viewOnNpm: "Ver no npm",
|
||||
sponsor: "Patrocinar",
|
||||
},
|
||||
off: { title: "Os plugins estão desativados em {{host}}" },
|
||||
empty: { noMatches: "Nenhum plugin corresponde" },
|
||||
@@ -864,79 +425,9 @@ export const pluginGallery = {
|
||||
warningTitle: "Roda com o seu acesso em {{host}}",
|
||||
warningDescription: "Plugins não são isolados. Instale apenas código confiável.",
|
||||
turnsOn: "Plugins não são isolados. Instalar também ativa os plugins.",
|
||||
reviewNotesWarning:
|
||||
"Esta versão tem {{count}} notas de revisão. Confira a avaliação antes de instalar.",
|
||||
},
|
||||
update: { updated: "{{name}} atualizado", updatedMany: "{{count}} plugins atualizados" },
|
||||
details: {
|
||||
license: "Licença",
|
||||
updated: "Atualizado",
|
||||
published: "Publicado",
|
||||
compatibility: "Compatibilidade",
|
||||
platforms: "Plataformas",
|
||||
platformNames: {
|
||||
desktop: "Desktop",
|
||||
web: "Web",
|
||||
mobile: "Celular",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "Abrir imagem",
|
||||
author: "Autor",
|
||||
morePlugins: "{{count}} plugins",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "Configurações",
|
||||
overview: "Visão geral",
|
||||
scorecard: "Avaliação",
|
||||
updates: "Versões",
|
||||
updatesCount: "Versões · {{count}}",
|
||||
details: "Detalhes",
|
||||
},
|
||||
updateHostRequired:
|
||||
"Atualize seu host Paseo para ver os cartões de avaliação e o histórico de versões.",
|
||||
scorecard: {
|
||||
notice:
|
||||
"Revisão automatizada e assistida por IA da versão {{version}}. Aprovação não é garantia de segurança.",
|
||||
reviewPolicy: "Política de revisão",
|
||||
health: "Saúde",
|
||||
review: "Revisão",
|
||||
healthGrades: { excellent: "Excelente", good: "Boa", fair: "Regular", low: "Baixa" },
|
||||
reviewStatuses: {
|
||||
passed: "Aprovada",
|
||||
passed_with_notes: "Aprovada com notas",
|
||||
unreviewed: "Não revisada",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "Higiene",
|
||||
maintenance: "Manutenção",
|
||||
responsiveness: "Resposta",
|
||||
adoption: "Adoção",
|
||||
},
|
||||
groups: {
|
||||
notes: "Notas de revisão",
|
||||
passed: "Verificações aprovadas",
|
||||
capabilities: "Capacidades e acesso",
|
||||
},
|
||||
noIssues: "Nenhum problema encontrado na revisão da versão {{version}}.",
|
||||
notesCount: "{{count}} notas encontradas na revisão da versão {{version}}.",
|
||||
unreviewedSummary: "Esta versão ainda não concluiu uma revisão estruturada.",
|
||||
reviewPr: "PR da revisão",
|
||||
baselineTitle: "Revisado em {{date}}",
|
||||
baselineBody:
|
||||
"Este plugin passou na revisão do registro antes das avaliações estruturadas.",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "Versão fixada",
|
||||
githubRelease: "Release no GitHub",
|
||||
commitSnapshot: "Snapshot do commit",
|
||||
npmPackage: "Pacote npm",
|
||||
viewAllReleases: "Ver todas as releases no GitHub",
|
||||
viewRepository: "Ver repositório",
|
||||
},
|
||||
related: { title: "Plugins relacionados" },
|
||||
},
|
||||
details: { license: "Licença", updated: "Atualizado", openImage: "Abrir imagem" },
|
||||
missing: "Este plugin não está instalado nem publicado",
|
||||
},
|
||||
ru: {
|
||||
@@ -985,9 +476,6 @@ export const pluginGallery = {
|
||||
repository: "Репозиторий",
|
||||
showMore: "Показать ещё",
|
||||
browse: "Обзор плагинов",
|
||||
reportBug: "Сообщить об ошибке",
|
||||
viewOnNpm: "Открыть на npm",
|
||||
sponsor: "Поддержать",
|
||||
},
|
||||
off: { title: "Плагины выключены на {{host}}" },
|
||||
empty: { noMatches: "Нет подходящих плагинов" },
|
||||
@@ -1004,78 +492,9 @@ export const pluginGallery = {
|
||||
warningTitle: "Работает с вашим доступом на {{host}}",
|
||||
warningDescription: "Плагины не изолированы. Устанавливайте только код, которому доверяете.",
|
||||
turnsOn: "Плагины не изолированы. Установка также включит плагины.",
|
||||
reviewNotesWarning:
|
||||
"У этой версии есть замечания проверки ({{count}}). Проверьте карточку перед установкой.",
|
||||
},
|
||||
update: { updated: "{{name}} обновлён", updatedMany: "Обновлено плагинов: {{count}}" },
|
||||
details: {
|
||||
license: "Лицензия",
|
||||
updated: "Обновлён",
|
||||
published: "Опубликован",
|
||||
compatibility: "Совместимость",
|
||||
platforms: "Платформы",
|
||||
platformNames: {
|
||||
desktop: "Десктоп",
|
||||
web: "Веб",
|
||||
mobile: "Мобильные",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "Открыть изображение",
|
||||
author: "Автор",
|
||||
morePlugins: "Плагинов: {{count}}",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "Настройки",
|
||||
overview: "Обзор",
|
||||
scorecard: "Оценка",
|
||||
updates: "Версии",
|
||||
updatesCount: "Версии · {{count}}",
|
||||
details: "Подробности",
|
||||
},
|
||||
updateHostRequired:
|
||||
"Обновите хост Paseo, чтобы просматривать карточки оценки и историю версий.",
|
||||
scorecard: {
|
||||
notice:
|
||||
"Автоматическая и ИИ-проверка версии {{version}}. Прохождение проверки не является гарантией безопасности.",
|
||||
reviewPolicy: "Политика проверки",
|
||||
health: "Состояние",
|
||||
review: "Проверка",
|
||||
healthGrades: { excellent: "Отличное", good: "Хорошее", fair: "Среднее", low: "Низкое" },
|
||||
reviewStatuses: {
|
||||
passed: "Пройдена",
|
||||
passed_with_notes: "Пройдена с замечаниями",
|
||||
unreviewed: "Не проверена",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "Оформление",
|
||||
maintenance: "Поддержка",
|
||||
responsiveness: "Отзывчивость",
|
||||
adoption: "Популярность",
|
||||
},
|
||||
groups: {
|
||||
notes: "Замечания проверки",
|
||||
passed: "Пройденные проверки",
|
||||
capabilities: "Возможности и доступ",
|
||||
},
|
||||
noIssues: "При проверке версии {{version}} проблем не найдено.",
|
||||
notesCount: "При проверке версии {{version}} найдено замечаний: {{count}}.",
|
||||
unreviewedSummary: "Полная структурированная проверка этой версии ещё не завершена.",
|
||||
reviewPr: "PR проверки",
|
||||
baselineTitle: "Проверено {{date}}",
|
||||
baselineBody: "Плагин прошёл проверку реестра до включения подробных карточек оценки.",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "Текущая версия",
|
||||
githubRelease: "Релиз GitHub",
|
||||
commitSnapshot: "Снимок коммита",
|
||||
npmPackage: "Пакет npm",
|
||||
viewAllReleases: "Все релизы на GitHub",
|
||||
viewRepository: "Открыть репозиторий",
|
||||
},
|
||||
related: { title: "Похожие плагины" },
|
||||
},
|
||||
details: { license: "Лицензия", updated: "Обновлён", openImage: "Открыть изображение" },
|
||||
missing: "Этот плагин не установлен и не опубликован",
|
||||
},
|
||||
"zh-CN": {
|
||||
@@ -1116,9 +535,6 @@ export const pluginGallery = {
|
||||
repository: "仓库",
|
||||
showMore: "显示更多",
|
||||
browse: "浏览插件",
|
||||
reportBug: "报告问题",
|
||||
viewOnNpm: "在 npm 查看",
|
||||
sponsor: "赞助作者",
|
||||
},
|
||||
off: { title: "{{host}} 上的插件已关闭" },
|
||||
empty: { noMatches: "没有匹配的插件" },
|
||||
@@ -1135,75 +551,9 @@ export const pluginGallery = {
|
||||
warningTitle: "以你在 {{host}} 上的权限运行",
|
||||
warningDescription: "插件没有沙箱隔离。只安装你信任的代码。",
|
||||
turnsOn: "插件没有沙箱隔离。安装后也会开启插件。",
|
||||
reviewNotesWarning: "此版本包含 {{count}} 条审核提示,建议安装前查看评分卡。",
|
||||
},
|
||||
update: { updated: "已更新 {{name}}", updatedMany: "已更新 {{count}} 个插件" },
|
||||
details: {
|
||||
license: "许可证",
|
||||
updated: "更新于",
|
||||
published: "首次上架",
|
||||
compatibility: "兼容性",
|
||||
platforms: "平台",
|
||||
platformNames: {
|
||||
desktop: "桌面端",
|
||||
web: "网页端",
|
||||
mobile: "移动端",
|
||||
ios: "iOS",
|
||||
android: "Android",
|
||||
},
|
||||
openImage: "打开图片",
|
||||
author: "作者",
|
||||
morePlugins: "{{count}} 个插件",
|
||||
},
|
||||
page: {
|
||||
tabs: {
|
||||
settings: "设置",
|
||||
overview: "概览",
|
||||
scorecard: "评分卡",
|
||||
updates: "更新记录",
|
||||
updatesCount: "更新记录 · {{count}}",
|
||||
details: "详情",
|
||||
},
|
||||
updateHostRequired: "更新 Paseo 主机以查看插件评分卡和更新记录。",
|
||||
scorecard: {
|
||||
notice: "版本 {{version}} 经过自动化与 AI 辅助审核。通过审核不代表安全担保。",
|
||||
reviewPolicy: "审核政策",
|
||||
health: "健康度",
|
||||
review: "审核结果",
|
||||
healthGrades: { excellent: "优秀", good: "良好", fair: "一般", low: "偏低" },
|
||||
reviewStatuses: {
|
||||
passed: "已通过",
|
||||
passed_with_notes: "附注通过",
|
||||
unreviewed: "未审核",
|
||||
},
|
||||
signals: {
|
||||
hygiene: "规范度",
|
||||
maintenance: "维护情况",
|
||||
responsiveness: "响应速度",
|
||||
adoption: "使用情况",
|
||||
},
|
||||
groups: {
|
||||
notes: "审核提示",
|
||||
passed: "已通过检查",
|
||||
capabilities: "能力与访问范围",
|
||||
},
|
||||
noIssues: "版本 {{version}} 的审核未发现问题。",
|
||||
notesCount: "版本 {{version}} 的审核包含 {{count}} 条提示。",
|
||||
unreviewedSummary: "此版本尚未完成完整的结构化审核。",
|
||||
reviewPr: "审核 PR",
|
||||
baselineTitle: "审核于 {{date}}",
|
||||
baselineBody: "该插件在启用结构化评分卡之前已通过注册表审核。",
|
||||
},
|
||||
updates: {
|
||||
currentPin: "当前固定版本",
|
||||
githubRelease: "GitHub 发布页",
|
||||
commitSnapshot: "提交快照",
|
||||
npmPackage: "npm 包",
|
||||
viewAllReleases: "在 GitHub 查看全部发布",
|
||||
viewRepository: "查看仓库",
|
||||
},
|
||||
related: { title: "相关插件" },
|
||||
},
|
||||
details: { license: "许可证", updated: "更新于", openImage: "打开图片" },
|
||||
missing: "此插件既未安装也未上架",
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -742,6 +742,8 @@ export const ptBR: TranslationResources = {
|
||||
reconnecting: "Reconectando a {{hostName}}...",
|
||||
updateTitle: "Atualize {{hostName}} para navegar por este host",
|
||||
updateDescription: "Este host ainda não oferece suporte ao proxy do navegador.",
|
||||
routedTitle: "O proxy do navegador não está disponível para hosts roteados",
|
||||
routedDescription: "Conecte-se diretamente a este host ou navegue localmente.",
|
||||
offlineTitle: "{{hostName}} está offline",
|
||||
offlineDescription: "Aguarde o host reconectar ou navegue localmente.",
|
||||
errorTitle: "Não foi possível conectar o proxy do navegador",
|
||||
@@ -2057,71 +2059,6 @@ 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: {
|
||||
@@ -2526,7 +2463,6 @@ 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",
|
||||
|
||||
@@ -745,6 +745,8 @@ export const ru: TranslationResources = {
|
||||
reconnecting: "Повторное подключение к {{hostName}}...",
|
||||
updateTitle: "Обновите {{hostName}}, чтобы просматривать через этот хост",
|
||||
updateDescription: "Этот хост пока не поддерживает проксирование браузера.",
|
||||
routedTitle: "Прокси браузера недоступен для маршрутизируемых хостов",
|
||||
routedDescription: "Подключитесь к хосту напрямую или просматривайте локально.",
|
||||
offlineTitle: "{{hostName}} не в сети",
|
||||
offlineDescription: "Дождитесь повторного подключения хоста или просматривайте локально.",
|
||||
errorTitle: "Не удалось подключить прокси браузера",
|
||||
@@ -2056,71 +2058,6 @@ 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: {
|
||||
@@ -2527,8 +2464,6 @@ export const ru: TranslationResources = {
|
||||
options: "Настройки",
|
||||
host: "Хост",
|
||||
refreshFailed: "Не удалось обновить использование",
|
||||
notFetched:
|
||||
"Ещё не проверено. Использование {{source}} обновляется, только когда вы его обновляете.",
|
||||
noHosts: "Нет подключённых хостов",
|
||||
agentError: "Не удалось загрузить использование: {{reason}}",
|
||||
pin: "Закрепить",
|
||||
|
||||
@@ -737,6 +737,8 @@ export const zhCN: TranslationResources = {
|
||||
reconnecting: "正在重新连接到 {{hostName}}...",
|
||||
updateTitle: "请更新 {{hostName}} 以通过此主机浏览",
|
||||
updateDescription: "此主机尚不支持浏览器代理。",
|
||||
routedTitle: "路由主机不支持浏览器代理",
|
||||
routedDescription: "请直接连接到此主机,或改为本地浏览。",
|
||||
offlineTitle: "{{hostName}} 已离线",
|
||||
offlineDescription: "请等待主机重新连接,或改为本地浏览。",
|
||||
errorTitle: "无法连接浏览器代理",
|
||||
@@ -2001,71 +2003,6 @@ 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: {
|
||||
@@ -2462,7 +2399,6 @@ 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 the minimal spinner stays in place.
|
||||
* splash up while the cache can still answer; after that it says what the host has yet to send.
|
||||
*/
|
||||
function AgentLoadingState({
|
||||
serverId,
|
||||
@@ -686,7 +686,7 @@ function AgentLoadingState({
|
||||
return (
|
||||
<LoadingState
|
||||
testID={testID}
|
||||
accessibilityLabel={
|
||||
title={
|
||||
wait.waitingFor === "agent"
|
||||
? t("agentPanel.states.loadingAgent")
|
||||
: t("agentPanel.states.loadingHistory")
|
||||
@@ -1258,14 +1258,6 @@ 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;
|
||||
@@ -1285,9 +1277,12 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
draft={draft}
|
||||
routeBottomAnchorRequest={routeBottomAnchorRequest}
|
||||
hasAppliedAuthoritativeHistory={hasAppliedAuthoritativeHistory}
|
||||
isInitialHistoryLoading={isInitialHistoryLoading}
|
||||
isInitialHistoryLoading={
|
||||
routeBottomAnchorRequest?.reason === "initial-entry" &&
|
||||
!hasCachedHistory &&
|
||||
!showHistorySyncError
|
||||
}
|
||||
revealInitialHistory={hasCachedHistory || showHistorySyncError}
|
||||
onInitialHistoryVisibilityChange={handleInitialHistoryVisibilityChange}
|
||||
hasActiveComposer={hasActiveComposer}
|
||||
toast={toastApi}
|
||||
onOpenWorkspaceFile={onOpenWorkspaceFile}
|
||||
@@ -1316,12 +1311,11 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
|
||||
const dockOverlay = (
|
||||
<>
|
||||
<ChatHistoryLoadingOverlay
|
||||
serverId={serverId}
|
||||
agentId={agentId}
|
||||
showHistorySyncOverlay={showHistorySyncOverlay}
|
||||
showInitialHistoryOverlay={isInitialHistoryHidden}
|
||||
/>
|
||||
{showHistorySyncOverlay ? (
|
||||
<View style={styles.historySyncOverlay}>
|
||||
<AgentLoadingState serverId={serverId} agentId={agentId} testID="agent-history-overlay" />
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
<TimelineSyncStatus sync={timelineSync} toast={toast} onDismiss={dismiss} />
|
||||
</>
|
||||
@@ -1376,55 +1370,6 @@ 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,
|
||||
@@ -1522,7 +1467,6 @@ const AgentStreamSection = memo(function AgentStreamSection({
|
||||
hasAppliedAuthoritativeHistory,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
onInitialHistoryVisibilityChange,
|
||||
hasActiveComposer,
|
||||
toast,
|
||||
onOpenWorkspaceFile,
|
||||
@@ -1536,7 +1480,6 @@ 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;
|
||||
@@ -1629,7 +1572,6 @@ const AgentStreamSection = memo(function AgentStreamSection({
|
||||
isAuthoritativeHistoryReady={hasAppliedAuthoritativeHistory}
|
||||
isInitialHistoryLoading={isInitialHistoryLoading}
|
||||
revealInitialHistory={revealInitialHistory}
|
||||
onInitialHistoryVisibilityChange={onInitialHistoryVisibilityChange}
|
||||
bottomOverlayTailClearance={bottomOverlayTailClearance}
|
||||
bottomOverlayControlClearance={bottomOverlayControlClearance}
|
||||
toast={toast}
|
||||
@@ -2006,9 +1948,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
justifyContent: "center",
|
||||
zIndex: 40,
|
||||
},
|
||||
initialHistoryOverlay: {
|
||||
pointerEvents: "none",
|
||||
},
|
||||
archivingOverlay: {
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
|
||||
@@ -4,11 +4,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { PluginListItem } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
pluginReviewNoteCount,
|
||||
type PluginListing,
|
||||
type PluginListingDetail,
|
||||
} from "@getpaseo/protocol/plugin-registry";
|
||||
import type { PluginListing } from "@getpaseo/protocol/plugin-registry";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
import { SettingsCard, SettingsRow } from "@/components/settings";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
@@ -26,9 +22,7 @@ const PLUGIN_SOURCE_DOCS_URL = "https://paseo.sh/docs/plugins/reference#plugin-s
|
||||
const SOURCE_SUBJECT = "source";
|
||||
|
||||
/** What the sheet installs: a directory listing, or a source the user types. */
|
||||
export type InstallTarget =
|
||||
| { kind: "listing"; listing: PluginListing; detail?: PluginListingDetail }
|
||||
| { kind: "source" };
|
||||
export type InstallTarget = { kind: "listing"; listing: PluginListing } | { kind: "source" };
|
||||
|
||||
export function useHostLabel(serverId: string): string {
|
||||
const hosts = useHosts();
|
||||
@@ -40,11 +34,6 @@ export function useHostLabel(serverId: string): string {
|
||||
* unsandboxed on the host. A listing install closes the sheet and reports on the listing's row; an
|
||||
* install from source has no row, so the sheet stays open until it finishes.
|
||||
*/
|
||||
function listingReviewNoteCount(target: InstallTarget): number {
|
||||
if (target.kind !== "listing") return 0;
|
||||
return pluginReviewNoteCount(target.listing, target.detail);
|
||||
}
|
||||
|
||||
export function InstallPluginSheet({
|
||||
serverId,
|
||||
target,
|
||||
@@ -177,15 +166,6 @@ export function InstallPluginSheet({
|
||||
/>
|
||||
</Field>
|
||||
)}
|
||||
{listingReviewNoteCount(target) > 0 ? (
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
title={t("settings.plugins.gallery.install.reviewNotesWarning", {
|
||||
count: listingReviewNoteCount(target),
|
||||
})}
|
||||
/>
|
||||
) : null}
|
||||
<Alert
|
||||
size="sm"
|
||||
variant="warning"
|
||||
|
||||
@@ -58,18 +58,6 @@ export function formatInstallCount(count: number): string {
|
||||
return `${Math.round(count / 1000)}k`;
|
||||
}
|
||||
|
||||
/** Formats an ISO timestamp like "Sep 26, 2026" in UTC, falling back to YYYY-MM-DD. */
|
||||
export function formatPluginDate(iso: string): string {
|
||||
const timestamp = Date.parse(iso);
|
||||
if (Number.isNaN(timestamp)) return iso.slice(0, 10);
|
||||
return new Date(timestamp).toLocaleDateString(undefined, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
year: "numeric",
|
||||
timeZone: "UTC",
|
||||
});
|
||||
}
|
||||
|
||||
/** The registry listing an installed plugin came from, if it came from one. */
|
||||
export function installedListingId(plugin: PluginListItem): string | undefined {
|
||||
const identity = plugin.installation?.identity;
|
||||
|
||||
@@ -4,28 +4,14 @@ import { Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
ArrowUpRight,
|
||||
BookOpen,
|
||||
Bug,
|
||||
Code2,
|
||||
FileText,
|
||||
Globe,
|
||||
Heart,
|
||||
History,
|
||||
MessageSquare,
|
||||
MoreHorizontal,
|
||||
Package,
|
||||
PackagePlus,
|
||||
Power,
|
||||
RotateCw,
|
||||
Trash2,
|
||||
} from "lucide-react-native";
|
||||
import type { PluginListItem, PluginLogEntry } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
pluginReportBugUrl,
|
||||
pluginSafeHttpsUrl,
|
||||
pluginSafeLinks,
|
||||
type PluginListing,
|
||||
} from "@getpaseo/protocol/plugin-registry";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
SheetHeaderIconButton,
|
||||
@@ -37,7 +23,6 @@ import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import {
|
||||
@@ -69,53 +54,12 @@ const ThemedArrow = withUnistyles(ArrowUpRight);
|
||||
const ThemedRotate = withUnistyles(RotateCw);
|
||||
const ThemedLogs = withUnistyles(FileText);
|
||||
const ThemedTrash = withUnistyles(Trash2);
|
||||
const ThemedBug = withUnistyles(Bug);
|
||||
const ThemedPackage = withUnistyles(Package);
|
||||
const ThemedGlobe = withUnistyles(Globe);
|
||||
const ThemedBook = withUnistyles(BookOpen);
|
||||
const ThemedMessage = withUnistyles(MessageSquare);
|
||||
const ThemedCode = withUnistyles(Code2);
|
||||
const ThemedHeart = withUnistyles(Heart);
|
||||
const ThemedHistory = withUnistyles(History);
|
||||
const installIcon = <ThemedPackagePlus size={14} uniProps={mutedIconColorMapping} />;
|
||||
const powerIcon = <ThemedPower size={14} uniProps={mutedIconColorMapping} />;
|
||||
const linkIcon = <ThemedArrow size={14} uniProps={mutedIconColorMapping} />;
|
||||
const reloadIcon = <ThemedRotate size={14} uniProps={mutedIconColorMapping} />;
|
||||
const logsIcon = <ThemedLogs size={14} uniProps={mutedIconColorMapping} />;
|
||||
const removeIcon = <ThemedTrash size={14} uniProps={dangerIconMapping} />;
|
||||
const bugIcon = <ThemedBug size={14} uniProps={mutedIconColorMapping} />;
|
||||
const packageIcon = <ThemedPackage size={14} uniProps={mutedIconColorMapping} />;
|
||||
const globeIcon = <ThemedGlobe size={14} uniProps={mutedIconColorMapping} />;
|
||||
const bookIcon = <ThemedBook size={14} uniProps={mutedIconColorMapping} />;
|
||||
const messageIcon = <ThemedMessage size={14} uniProps={mutedIconColorMapping} />;
|
||||
const codeIcon = <ThemedCode size={14} uniProps={mutedIconColorMapping} />;
|
||||
const heartIcon = <ThemedHeart size={14} uniProps={mutedIconColorMapping} />;
|
||||
const historyIcon = <ThemedHistory size={14} uniProps={mutedIconColorMapping} />;
|
||||
|
||||
function actionLinkIcon(icon?: string) {
|
||||
switch (icon) {
|
||||
case "globe":
|
||||
return globeIcon;
|
||||
case "book":
|
||||
return bookIcon;
|
||||
case "bug":
|
||||
return bugIcon;
|
||||
case "message":
|
||||
return messageIcon;
|
||||
case "code":
|
||||
return codeIcon;
|
||||
case "heart":
|
||||
return heartIcon;
|
||||
case "changelog":
|
||||
return historyIcon;
|
||||
default:
|
||||
return linkIcon;
|
||||
}
|
||||
}
|
||||
|
||||
function reportBugUrl(repositoryUrl?: string): string | undefined {
|
||||
return repositoryUrl ? pluginReportBugUrl(repositoryUrl) : undefined;
|
||||
}
|
||||
|
||||
type TriggerState = PressableStateCallbackType & { hovered?: boolean; open?: boolean };
|
||||
// The trigger hangs by how far its frame reaches past the glyph, so the glyph sits on the trailing
|
||||
@@ -197,207 +141,69 @@ export function PluginGalleryMenu({ serverId }: { serverId: string }) {
|
||||
}
|
||||
const SOURCE_TARGET = { kind: "source" } as const;
|
||||
|
||||
interface SafeActionLink {
|
||||
label: string;
|
||||
url: string;
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
function collectSafeLinks(listing?: PluginListing): SafeActionLink[] {
|
||||
return listing ? pluginSafeLinks(listing) : [];
|
||||
}
|
||||
|
||||
function CustomLinkMenuItem({ entry }: { entry: SafeActionLink }) {
|
||||
const onSelect = useCallback(() => {
|
||||
void openExternalUrl(entry.url);
|
||||
}, [entry.url]);
|
||||
return (
|
||||
<DropdownMenuItem leading={actionLinkIcon(entry.icon)} onSelect={onSelect}>
|
||||
{entry.label}
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
|
||||
function ListingMenuItems({
|
||||
repoHref,
|
||||
bugHref,
|
||||
npmHref,
|
||||
customLinks,
|
||||
}: {
|
||||
repoHref?: string;
|
||||
bugHref?: string;
|
||||
npmHref?: string;
|
||||
customLinks: readonly SafeActionLink[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const openRepository = useCallback(() => {
|
||||
if (repoHref) void openExternalUrl(repoHref);
|
||||
}, [repoHref]);
|
||||
const openBug = useCallback(() => {
|
||||
if (bugHref) void openExternalUrl(bugHref);
|
||||
}, [bugHref]);
|
||||
const openNpm = useCallback(() => {
|
||||
if (npmHref) void openExternalUrl(npmHref);
|
||||
}, [npmHref]);
|
||||
const hasBuiltIn = Boolean(repoHref || bugHref || npmHref);
|
||||
return (
|
||||
<>
|
||||
{repoHref ? (
|
||||
<DropdownMenuItem leading={linkIcon} onSelect={openRepository}>
|
||||
{t("settings.plugins.gallery.actions.repository")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{bugHref ? (
|
||||
<DropdownMenuItem leading={bugIcon} onSelect={openBug}>
|
||||
{t("settings.plugins.gallery.actions.reportBug")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{npmHref ? (
|
||||
<DropdownMenuItem leading={packageIcon} onSelect={openNpm}>
|
||||
{t("settings.plugins.gallery.actions.viewOnNpm")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{customLinks.length > 0 && hasBuiltIn ? <DropdownMenuSeparator /> : null}
|
||||
{customLinks.map((entry) => (
|
||||
<CustomLinkMenuItem key={`${entry.label}-${entry.url}`} entry={entry} />
|
||||
))}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function InstalledMenuHeader({
|
||||
plugin,
|
||||
logsSupported,
|
||||
pendingAction,
|
||||
hasListingLinks,
|
||||
onReload,
|
||||
onOpenLogs,
|
||||
}: {
|
||||
plugin: PluginListItem;
|
||||
logsSupported: boolean;
|
||||
pendingAction?: PluginAction;
|
||||
hasListingLinks: boolean;
|
||||
onReload(): void;
|
||||
onOpenLogs(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuItem
|
||||
leading={reloadIcon}
|
||||
onSelect={onReload}
|
||||
disabled={!plugin.enabled || pendingAction !== undefined}
|
||||
status={pendingAction === "reload" ? "pending" : "idle"}
|
||||
pendingLabel={t("settings.plugins.actions.reloading")}
|
||||
>
|
||||
{t("settings.plugins.actions.reload")}
|
||||
</DropdownMenuItem>
|
||||
{logsSupported ? (
|
||||
<DropdownMenuItem leading={logsIcon} onSelect={onOpenLogs}>
|
||||
{t("settings.plugins.logs.action")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
{hasListingLinks ? <DropdownMenuSeparator /> : null}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function InstalledMenuRemove({
|
||||
pendingAction,
|
||||
onRemove,
|
||||
}: {
|
||||
pendingAction?: PluginAction;
|
||||
onRemove(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem
|
||||
destructive
|
||||
leading={removeIcon}
|
||||
onSelect={onRemove}
|
||||
disabled={pendingAction !== undefined}
|
||||
status={pendingAction === "remove" ? "pending" : "idle"}
|
||||
pendingLabel={t("settings.plugins.actions.removing")}
|
||||
>
|
||||
{t("settings.plugins.actions.remove")}
|
||||
</DropdownMenuItem>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function listingNpmUrl(listing?: PluginListing): string | undefined {
|
||||
if (listing?.artifact.kind === "npm" && listing.artifact.package) {
|
||||
return `https://www.npmjs.com/package/${listing.artifact.package}`;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** One plugin's actions menu on its page (works for both installed plugins and directory listings). */
|
||||
/** One installed plugin's occasional actions, on its page. */
|
||||
export function PluginActionsMenu({
|
||||
serverId,
|
||||
plugin,
|
||||
listing,
|
||||
displayName,
|
||||
repositoryUrl,
|
||||
pendingAction,
|
||||
onAction,
|
||||
}: {
|
||||
serverId: string;
|
||||
plugin?: PluginListItem;
|
||||
listing?: PluginListing;
|
||||
displayName?: string;
|
||||
plugin: PluginListItem;
|
||||
repositoryUrl?: string;
|
||||
pendingAction?: PluginAction;
|
||||
onAction?(action: PluginAction): void;
|
||||
onAction(action: PluginAction): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// COMPAT(pluginLogs): added in v0.4.0, remove gate after 2027-08-16.
|
||||
const logsSupported = useHostFeature(serverId, "pluginLogs");
|
||||
const [logsOpen, setLogsOpen] = useState(false);
|
||||
const reload = useCallback(() => onAction?.("reload"), [onAction]);
|
||||
const remove = useCallback(() => onAction?.("remove"), [onAction]);
|
||||
const reload = useCallback(() => onAction("reload"), [onAction]);
|
||||
const remove = useCallback(() => onAction("remove"), [onAction]);
|
||||
const openLogs = useCallback(() => setLogsOpen(true), []);
|
||||
const closeLogs = useCallback(() => setLogsOpen(false), []);
|
||||
const repoHref = pluginSafeHttpsUrl(repositoryUrl ?? listing?.repository.url);
|
||||
const bugHref = reportBugUrl(repoHref);
|
||||
const npmHref = listingNpmUrl(listing);
|
||||
const customLinks = useMemo(() => collectSafeLinks(listing), [listing]);
|
||||
const hasListingLinks = Boolean(repoHref || bugHref || npmHref || customLinks.length > 0);
|
||||
if (!plugin && !hasListingLinks) return null;
|
||||
|
||||
const fallbackName = plugin ? pluginDisplayName(plugin) : (listing?.name ?? "");
|
||||
const label = t("settings.plugins.actions.menu", { name: displayName ?? fallbackName });
|
||||
const testId = plugin
|
||||
? `plugin-actions-${plugin.id}`
|
||||
: `plugin-actions-${listing?.id ?? "listing"}`;
|
||||
|
||||
const openRepository = useCallback(() => {
|
||||
if (repositoryUrl) void openExternalUrl(repositoryUrl);
|
||||
}, [repositoryUrl]);
|
||||
const label = t("settings.plugins.actions.menu", { name: pluginDisplayName(plugin) });
|
||||
return (
|
||||
<>
|
||||
<DropdownMenu>
|
||||
<MenuTrigger label={label} testID={testId} />
|
||||
<DropdownMenuContent align="end" width={230} sheetTitle={label}>
|
||||
{plugin ? (
|
||||
<InstalledMenuHeader
|
||||
plugin={plugin}
|
||||
logsSupported={logsSupported}
|
||||
pendingAction={pendingAction}
|
||||
hasListingLinks={hasListingLinks}
|
||||
onReload={reload}
|
||||
onOpenLogs={openLogs}
|
||||
/>
|
||||
<MenuTrigger label={label} testID={`plugin-actions-${plugin.id}`} />
|
||||
<DropdownMenuContent align="end" width={220} sheetTitle={label}>
|
||||
<DropdownMenuItem
|
||||
leading={reloadIcon}
|
||||
onSelect={reload}
|
||||
disabled={!plugin.enabled || pendingAction !== undefined}
|
||||
status={pendingAction === "reload" ? "pending" : "idle"}
|
||||
pendingLabel={t("settings.plugins.actions.reloading")}
|
||||
>
|
||||
{t("settings.plugins.actions.reload")}
|
||||
</DropdownMenuItem>
|
||||
{logsSupported ? (
|
||||
<DropdownMenuItem leading={logsIcon} onSelect={openLogs}>
|
||||
{t("settings.plugins.logs.action")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
<ListingMenuItems
|
||||
repoHref={repoHref}
|
||||
bugHref={bugHref}
|
||||
npmHref={npmHref}
|
||||
customLinks={customLinks}
|
||||
/>
|
||||
{plugin ? <InstalledMenuRemove pendingAction={pendingAction} onRemove={remove} /> : null}
|
||||
{repositoryUrl ? (
|
||||
<DropdownMenuItem leading={linkIcon} onSelect={openRepository}>
|
||||
{t("settings.plugins.gallery.actions.repository")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
<DropdownMenuItem
|
||||
destructive
|
||||
leading={removeIcon}
|
||||
onSelect={remove}
|
||||
disabled={pendingAction !== undefined}
|
||||
status={pendingAction === "remove" ? "pending" : "idle"}
|
||||
pendingLabel={t("settings.plugins.actions.removing")}
|
||||
>
|
||||
{t("settings.plugins.actions.remove")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{plugin && logsOpen ? (
|
||||
{logsOpen ? (
|
||||
<PluginLogsSheet serverId={serverId} plugin={plugin} onClose={closeLogs} />
|
||||
) : null}
|
||||
</>
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,579 +0,0 @@
|
||||
import { AlertTriangle, CheckCircle2, ChevronDown, ChevronRight, Info } from "lucide-react-native";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useCallback, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
pluginHealthScore,
|
||||
pluginHealthTone,
|
||||
pluginKnownHealthGrade,
|
||||
pluginKnownReviewStatus,
|
||||
pluginReviewTone,
|
||||
pluginSafeHttpsUrl,
|
||||
pluginScorecardGlance,
|
||||
type PluginHealthSignal,
|
||||
type PluginListing,
|
||||
type PluginListingDetail,
|
||||
type PluginMeterTone,
|
||||
type PluginReviewItem,
|
||||
} from "@getpaseo/protocol/plugin-registry";
|
||||
import { SettingsCard } from "@/components/settings";
|
||||
import { ExternalLink } from "@/components/ui/external-link";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { formatPluginDate, listingVersion } from "./listing";
|
||||
|
||||
const ThemedCheck = withUnistyles(CheckCircle2);
|
||||
const ThemedInfo = withUnistyles(Info);
|
||||
const ThemedWarn = withUnistyles(AlertTriangle);
|
||||
const ThemedChevronRight = withUnistyles(ChevronRight);
|
||||
const ThemedChevronDown = withUnistyles(ChevronDown);
|
||||
|
||||
const successIconMapping = (theme: Theme) => ({ color: theme.colors.statusSuccess });
|
||||
const warningIconMapping = (theme: Theme) => ({ color: theme.colors.statusWarning });
|
||||
const mutedIconMapping = (theme: Theme) => ({ color: theme.colors.foregroundExtraMuted });
|
||||
|
||||
function segmentFillStyle(tone: PluginMeterTone) {
|
||||
if (tone === "success") return styles.segSuccess;
|
||||
if (tone === "warning") return styles.segWarning;
|
||||
return styles.segDanger;
|
||||
}
|
||||
|
||||
export function SemaphoreBar({ score, tone }: { score: number; tone: PluginMeterTone }) {
|
||||
const clamped = Math.max(0, Math.min(4, Math.round(score)));
|
||||
const fillStyle = segmentFillStyle(tone);
|
||||
return (
|
||||
<View style={styles.meter} accessible={false}>
|
||||
{[1, 2, 3, 4].map((index) => (
|
||||
<View key={index} style={[styles.seg, index <= clamped ? fillStyle : styles.segEmpty]} />
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function toneTextStyle(tone: PluginMeterTone) {
|
||||
if (tone === "success") return styles.textSuccess;
|
||||
if (tone === "warning") return styles.textWarning;
|
||||
return styles.textDanger;
|
||||
}
|
||||
|
||||
function healthGradeLabel(grade: string, t: TFunction): string {
|
||||
const known = pluginKnownHealthGrade(grade);
|
||||
return known ? t(`settings.plugins.gallery.page.scorecard.healthGrades.${known}`) : grade;
|
||||
}
|
||||
|
||||
function reviewStatusLabel(status: string, t: TFunction): string {
|
||||
const known = pluginKnownReviewStatus(status);
|
||||
return known ? t(`settings.plugins.gallery.page.scorecard.reviewStatuses.${known}`) : status;
|
||||
}
|
||||
|
||||
function signalLabel(signal: PluginHealthSignal, t: TFunction): string {
|
||||
switch (signal.id) {
|
||||
case "hygiene":
|
||||
return t("settings.plugins.gallery.page.scorecard.signals.hygiene");
|
||||
case "maintenance":
|
||||
return t("settings.plugins.gallery.page.scorecard.signals.maintenance");
|
||||
case "responsiveness":
|
||||
return t("settings.plugins.gallery.page.scorecard.signals.responsiveness");
|
||||
case "adoption":
|
||||
return t("settings.plugins.gallery.page.scorecard.signals.adoption");
|
||||
default:
|
||||
return signal.label ?? signal.id;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Compact clickable Health & Review glance card in the sidebar (stacked) or mobile header (inline).
|
||||
* Returns null when a listing has neither health nor review scorecard data.
|
||||
*/
|
||||
export function ScorecardGlanceCard({
|
||||
listing,
|
||||
detail,
|
||||
active,
|
||||
inline = false,
|
||||
onPress,
|
||||
}: {
|
||||
listing: PluginListing;
|
||||
detail?: PluginListingDetail;
|
||||
active: boolean;
|
||||
inline?: boolean;
|
||||
onPress(): void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const glance = pluginScorecardGlance(listing, detail);
|
||||
if (!glance.health && !glance.review) return null;
|
||||
|
||||
if (inline) {
|
||||
return (
|
||||
<View style={styles.inlineGlanceRow}>
|
||||
{glance.health ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
onPress={onPress}
|
||||
style={[styles.inlineGlanceCard, active && styles.glanceActive]}
|
||||
highlightStyle={styles.pressed}
|
||||
testID="plugin-glance-health"
|
||||
>
|
||||
<View style={styles.glanceTop}>
|
||||
<Text style={styles.glanceLabel}>
|
||||
{t("settings.plugins.gallery.page.scorecard.health")}
|
||||
</Text>
|
||||
<Text style={[styles.glanceGrade, toneTextStyle(glance.health.tone)]}>
|
||||
{healthGradeLabel(glance.health.grade, t)}
|
||||
</Text>
|
||||
</View>
|
||||
<SemaphoreBar score={glance.health.score} tone={glance.health.tone} />
|
||||
</PressHighlight>
|
||||
) : null}
|
||||
{glance.review ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
onPress={onPress}
|
||||
style={[styles.inlineGlanceCard, active && styles.glanceActive]}
|
||||
highlightStyle={styles.pressed}
|
||||
testID="plugin-glance-review"
|
||||
>
|
||||
<View style={styles.glanceTop}>
|
||||
<Text style={styles.glanceLabel}>
|
||||
{t("settings.plugins.gallery.page.scorecard.review")}
|
||||
</Text>
|
||||
<Text style={[styles.glanceGrade, toneTextStyle(glance.review.tone)]}>
|
||||
{reviewStatusLabel(glance.review.status, t)}
|
||||
</Text>
|
||||
</View>
|
||||
<SemaphoreBar score={glance.review.score} tone={glance.review.tone} />
|
||||
</PressHighlight>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
onPress={onPress}
|
||||
style={[styles.glanceCard, active && styles.glanceActive]}
|
||||
highlightStyle={styles.pressed}
|
||||
testID="plugin-glance-card"
|
||||
>
|
||||
{glance.health ? (
|
||||
<View style={styles.glanceBlock}>
|
||||
<View style={styles.glanceTop}>
|
||||
<Text style={styles.glanceLabel}>
|
||||
{t("settings.plugins.gallery.page.scorecard.health")}
|
||||
</Text>
|
||||
<Text style={[styles.glanceGrade, toneTextStyle(glance.health.tone)]}>
|
||||
{healthGradeLabel(glance.health.grade, t)}
|
||||
</Text>
|
||||
</View>
|
||||
<SemaphoreBar score={glance.health.score} tone={glance.health.tone} />
|
||||
</View>
|
||||
) : null}
|
||||
{glance.review ? (
|
||||
<View style={styles.glanceBlock}>
|
||||
<View style={styles.glanceTop}>
|
||||
<Text style={styles.glanceLabel}>
|
||||
{t("settings.plugins.gallery.page.scorecard.review")}
|
||||
</Text>
|
||||
<Text style={[styles.glanceGrade, toneTextStyle(glance.review.tone)]}>
|
||||
{reviewStatusLabel(glance.review.status, t)}
|
||||
</Text>
|
||||
</View>
|
||||
<SemaphoreBar score={glance.review.score} tone={glance.review.tone} />
|
||||
</View>
|
||||
) : null}
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
const EXPANDED_STATE = { expanded: true } as const;
|
||||
const COLLAPSED_STATE = { expanded: false } as const;
|
||||
|
||||
function FindingGlyph({ kind }: { kind: "note" | "passed" | "capability" }) {
|
||||
if (kind === "passed") return <ThemedCheck size={15} uniProps={successIconMapping} />;
|
||||
if (kind === "note") return <ThemedWarn size={15} uniProps={warningIconMapping} />;
|
||||
return <ThemedInfo size={15} uniProps={mutedIconMapping} />;
|
||||
}
|
||||
|
||||
function ReviewItemRow({
|
||||
item,
|
||||
kind,
|
||||
first,
|
||||
}: {
|
||||
item: PluginReviewItem;
|
||||
kind: "note" | "passed" | "capability";
|
||||
first: boolean;
|
||||
}) {
|
||||
const [expanded, setExpanded] = useState(false);
|
||||
const toggle = useCallback(() => setExpanded((current) => !current), []);
|
||||
const expandable = Boolean(item.details);
|
||||
|
||||
const rowInner = (
|
||||
<View style={styles.findingLine}>
|
||||
<View style={styles.findingIcon}>
|
||||
<FindingGlyph kind={kind} />
|
||||
</View>
|
||||
<View style={styles.findingBody}>
|
||||
<Text style={styles.findingText}>
|
||||
{item.label ? <Text style={styles.findingLabel}>{item.label}: </Text> : null}
|
||||
{item.summary}
|
||||
</Text>
|
||||
{expandable && expanded ? (
|
||||
<View style={styles.findingDrawer}>
|
||||
<Text style={styles.findingDrawerText}>{item.details}</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{expandable ? (
|
||||
<View style={styles.findingChevron}>
|
||||
{expanded ? (
|
||||
<ThemedChevronDown size={15} uniProps={mutedIconMapping} />
|
||||
) : (
|
||||
<ThemedChevronRight size={15} uniProps={mutedIconMapping} />
|
||||
)}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={[!first && settingsStyles.rowBorder]}>
|
||||
{expandable ? (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
accessibilityState={expanded ? EXPANDED_STATE : COLLAPSED_STATE}
|
||||
onPress={toggle}
|
||||
style={styles.findingRow}
|
||||
highlightStyle={styles.pressed}
|
||||
>
|
||||
{rowInner}
|
||||
</PressHighlight>
|
||||
) : (
|
||||
<View style={styles.findingRow}>{rowInner}</View>
|
||||
)}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function FindingGroup({
|
||||
title,
|
||||
items,
|
||||
kind,
|
||||
}: {
|
||||
title: string;
|
||||
items: readonly PluginReviewItem[];
|
||||
kind: "note" | "passed" | "capability";
|
||||
}) {
|
||||
if (items.length === 0) return null;
|
||||
return (
|
||||
<View style={styles.group}>
|
||||
<View style={styles.groupHeader}>
|
||||
<Text style={styles.groupTitle}>{title}</Text>
|
||||
<View style={[styles.groupPill, kind === "note" && styles.groupPillWarning]}>
|
||||
<Text style={[styles.groupCount, kind === "note" && styles.textWarning]}>
|
||||
{items.length}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<View>
|
||||
{items.map((item, index) => (
|
||||
<ReviewItemRow key={item.id} item={item} kind={kind} first={index === 0} />
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function PluginScorecardTab({
|
||||
listing,
|
||||
detail,
|
||||
reviewPolicyUrl,
|
||||
}: {
|
||||
listing: PluginListing;
|
||||
detail?: PluginListingDetail;
|
||||
reviewPolicyUrl?: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const version = listingVersion(listing) ?? "";
|
||||
const health = detail?.health;
|
||||
const review = detail?.review;
|
||||
const reviewPrUrl = pluginSafeHttpsUrl(review?.reviewUrl);
|
||||
const policyHref = pluginSafeHttpsUrl(review?.policyUrl ?? reviewPolicyUrl);
|
||||
|
||||
let reviewSummary: string | undefined;
|
||||
if (review) {
|
||||
if (review.status === "unreviewed") {
|
||||
reviewSummary = t("settings.plugins.gallery.page.scorecard.unreviewedSummary");
|
||||
} else if (review.notes.length > 0) {
|
||||
reviewSummary = t("settings.plugins.gallery.page.scorecard.notesCount", {
|
||||
count: review.notes.length,
|
||||
version,
|
||||
});
|
||||
} else {
|
||||
reviewSummary = t("settings.plugins.gallery.page.scorecard.noIssues", { version });
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.stack}>
|
||||
<SettingsCard>
|
||||
<View style={styles.noticeRow}>
|
||||
<Text style={styles.noticeText}>
|
||||
{t("settings.plugins.gallery.page.scorecard.notice", { version })}
|
||||
</Text>
|
||||
{policyHref ? (
|
||||
<ExternalLink
|
||||
href={policyHref}
|
||||
label={t("settings.plugins.gallery.page.scorecard.reviewPolicy")}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</SettingsCard>
|
||||
|
||||
{health ? (
|
||||
<SettingsCard>
|
||||
<View style={styles.cardBody}>
|
||||
<View style={styles.sectionHeader}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
{t("settings.plugins.gallery.page.scorecard.health")}
|
||||
</Text>
|
||||
<Text style={[styles.sectionGrade, toneTextStyle(pluginHealthTone(health.grade))]}>
|
||||
{healthGradeLabel(health.grade, t)}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={styles.sectionSub}>{health.summary}</Text>
|
||||
<View style={styles.meterWrap}>
|
||||
<SemaphoreBar
|
||||
score={pluginHealthScore(health.grade)}
|
||||
tone={pluginHealthTone(health.grade)}
|
||||
/>
|
||||
</View>
|
||||
<View style={styles.signals}>
|
||||
{health.signals.map((signal, index) => (
|
||||
<View
|
||||
key={signal.id}
|
||||
style={[styles.signalRow, index > 0 && settingsStyles.rowBorder]}
|
||||
>
|
||||
<Text style={styles.signalKey}>{signalLabel(signal, t)}</Text>
|
||||
<Text style={styles.signalValue}>{signal.summary}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
</SettingsCard>
|
||||
) : null}
|
||||
|
||||
<SettingsCard>
|
||||
<View style={styles.cardBody}>
|
||||
{review ? (
|
||||
<>
|
||||
<View style={styles.sectionHeaderRow}>
|
||||
<View style={styles.sectionHeader}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
{t("settings.plugins.gallery.page.scorecard.review")}
|
||||
</Text>
|
||||
<Text
|
||||
style={[styles.sectionGrade, toneTextStyle(pluginReviewTone(review.status))]}
|
||||
>
|
||||
{reviewStatusLabel(review.status, t)}
|
||||
</Text>
|
||||
</View>
|
||||
<View style={styles.reviewMeta}>
|
||||
<Text style={styles.reviewMetaText}>
|
||||
{formatPluginDate(review.reviewedAt ?? listing.reviewedAt)}
|
||||
</Text>
|
||||
{reviewPrUrl ? (
|
||||
<ExternalLink
|
||||
href={reviewPrUrl}
|
||||
label={t("settings.plugins.gallery.page.scorecard.reviewPr")}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
</View>
|
||||
{reviewSummary ? <Text style={styles.sectionSub}>{reviewSummary}</Text> : null}
|
||||
<View style={styles.meterWrap}>
|
||||
<SemaphoreBar score={review.score} tone={pluginReviewTone(review.status)} />
|
||||
</View>
|
||||
|
||||
<FindingGroup
|
||||
title={t("settings.plugins.gallery.page.scorecard.groups.notes")}
|
||||
items={review.notes}
|
||||
kind="note"
|
||||
/>
|
||||
<FindingGroup
|
||||
title={t("settings.plugins.gallery.page.scorecard.groups.passed")}
|
||||
items={review.passed}
|
||||
kind="passed"
|
||||
/>
|
||||
<FindingGroup
|
||||
title={t("settings.plugins.gallery.page.scorecard.groups.capabilities")}
|
||||
items={review.capabilities}
|
||||
kind="capability"
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<View style={styles.sectionHeader}>
|
||||
<Text style={styles.sectionTitle}>
|
||||
{t("settings.plugins.gallery.page.scorecard.review")}
|
||||
</Text>
|
||||
</View>
|
||||
<Text style={styles.baselineTitle}>
|
||||
{t("settings.plugins.gallery.page.scorecard.baselineTitle", {
|
||||
date: formatPluginDate(listing.reviewedAt),
|
||||
})}
|
||||
</Text>
|
||||
<Text style={styles.sectionSub}>
|
||||
{t("settings.plugins.gallery.page.scorecard.baselineBody")}
|
||||
</Text>
|
||||
</>
|
||||
)}
|
||||
</View>
|
||||
</SettingsCard>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
stack: { gap: theme.spacing[4] },
|
||||
noticeRow: {
|
||||
padding: theme.spacing[4],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
noticeText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 18,
|
||||
},
|
||||
cardBody: { padding: theme.spacing[4] },
|
||||
sectionHeaderRow: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
sectionHeader: { flexDirection: "row", alignItems: "baseline", gap: theme.spacing[2] },
|
||||
sectionTitle: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.lg,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
sectionGrade: { fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium },
|
||||
reviewMeta: { flexDirection: "row", alignItems: "center", gap: theme.spacing[2] },
|
||||
reviewMetaText: { color: theme.colors.foregroundExtraMuted, fontSize: theme.fontSize.sm },
|
||||
sectionSub: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
baselineTitle: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
marginTop: theme.spacing[2],
|
||||
},
|
||||
meterWrap: { marginTop: theme.spacing[3] },
|
||||
meter: { flexDirection: "row", gap: theme.spacing[1] },
|
||||
seg: { flex: 1, height: 4, borderRadius: theme.borderRadius.full },
|
||||
segEmpty: { backgroundColor: theme.colors.surface3 },
|
||||
segSuccess: { backgroundColor: theme.colors.statusSuccess },
|
||||
segWarning: { backgroundColor: theme.colors.statusWarning },
|
||||
segDanger: { backgroundColor: theme.colors.statusDanger },
|
||||
textSuccess: { color: theme.colors.statusSuccess },
|
||||
textWarning: { color: theme.colors.statusWarning },
|
||||
textDanger: { color: theme.colors.statusDanger },
|
||||
signals: { marginTop: theme.spacing[4] },
|
||||
signalRow: {
|
||||
paddingVertical: theme.spacing[3],
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
signalKey: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
signalValue: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 19,
|
||||
},
|
||||
group: { marginTop: theme.spacing[6] },
|
||||
groupHeader: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
marginBottom: theme.spacing[1.5],
|
||||
},
|
||||
groupTitle: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
groupPill: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderRadius: theme.borderRadius.full,
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
paddingVertical: 1,
|
||||
},
|
||||
groupPillWarning: { backgroundColor: theme.colors.surface2 },
|
||||
groupCount: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
findingRow: { paddingVertical: theme.spacing[3] },
|
||||
findingLine: { flexDirection: "row", alignItems: "flex-start", gap: theme.spacing[3] },
|
||||
findingIcon: { marginTop: 2 },
|
||||
findingBody: { flex: 1, minWidth: 0 },
|
||||
findingText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 19,
|
||||
},
|
||||
findingLabel: { color: theme.colors.foreground, fontWeight: theme.fontWeight.medium },
|
||||
findingChevron: { marginTop: 2 },
|
||||
findingDrawer: {
|
||||
marginTop: theme.spacing[2],
|
||||
padding: theme.spacing[3],
|
||||
borderRadius: theme.borderRadius.md,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
},
|
||||
findingDrawerText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 18,
|
||||
},
|
||||
glanceCard: {
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
padding: theme.spacing[3.5],
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
glanceActive: { borderColor: theme.colors.accent },
|
||||
glanceBlock: { gap: theme.spacing[1.5] },
|
||||
glanceTop: { flexDirection: "row", justifyContent: "space-between", alignItems: "center" },
|
||||
glanceLabel: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
glanceGrade: { fontSize: theme.fontSize.sm, fontWeight: theme.fontWeight.medium },
|
||||
inlineGlanceRow: { flexDirection: "row", gap: theme.spacing[3] },
|
||||
inlineGlanceCard: {
|
||||
flex: 1,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
padding: theme.spacing[3],
|
||||
gap: theme.spacing[1.5],
|
||||
},
|
||||
pressed: { backgroundColor: theme.colors.surface2 },
|
||||
}));
|
||||
@@ -1,289 +0,0 @@
|
||||
import { Heart } from "lucide-react-native";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useCallback, type ReactNode } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { PluginListItem } from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
pluginFundingLinks,
|
||||
pluginSafeHttpsUrl,
|
||||
type PluginListing,
|
||||
type PluginListingDetail,
|
||||
} from "@getpaseo/protocol/plugin-registry";
|
||||
import { formatPluginInstallation } from "@getpaseo/protocol/plugin-source-reference";
|
||||
import { SettingsCard } from "@/components/settings";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ExternalLink } from "@/components/ui/external-link";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import {
|
||||
formatPluginDate,
|
||||
listingAuthor,
|
||||
listingAuthorAvatar,
|
||||
listingSource,
|
||||
listingVersion,
|
||||
} from "./listing";
|
||||
import { AuthorAvatar } from "./plugin-row";
|
||||
|
||||
const ThemedHeart = withUnistyles(Heart);
|
||||
const sponsorHeartIcon = <ThemedHeart size={14} uniProps={mutedIconColorMapping} />;
|
||||
|
||||
function DetailValue({ children, mono = false }: { children: ReactNode; mono?: boolean }) {
|
||||
return (
|
||||
<Text style={[styles.detailValue, mono && styles.detailValueMono]} numberOfLines={1}>
|
||||
{children}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
function detailSource(plugin: PluginListItem | undefined, listing: PluginListing | undefined) {
|
||||
if (plugin?.installation) return formatPluginInstallation(plugin.installation);
|
||||
if (plugin) return plugin.path;
|
||||
if (!listing) return undefined;
|
||||
return listingSource(listing);
|
||||
}
|
||||
|
||||
function formatPlatforms(
|
||||
platforms: readonly string[] | undefined,
|
||||
t: TFunction,
|
||||
): string | undefined {
|
||||
if (!platforms || platforms.length === 0) return undefined;
|
||||
const normalized = new Set(platforms.map((entry) => entry.toLowerCase()));
|
||||
const hasBothMobile = normalized.has("ios") && normalized.has("android");
|
||||
const labels: string[] = [];
|
||||
let mobileAdded = false;
|
||||
for (const raw of platforms) {
|
||||
const key = raw.toLowerCase();
|
||||
if (key === "desktop") {
|
||||
labels.push(t("settings.plugins.gallery.details.platformNames.desktop"));
|
||||
} else if (key === "web") {
|
||||
labels.push(t("settings.plugins.gallery.details.platformNames.web"));
|
||||
} else if ((key === "ios" || key === "android") && hasBothMobile) {
|
||||
if (!mobileAdded) {
|
||||
labels.push(t("settings.plugins.gallery.details.platformNames.mobile"));
|
||||
mobileAdded = true;
|
||||
}
|
||||
} else if (key === "ios") {
|
||||
labels.push(t("settings.plugins.gallery.details.platformNames.ios"));
|
||||
} else if (key === "android") {
|
||||
labels.push(t("settings.plugins.gallery.details.platformNames.android"));
|
||||
} else {
|
||||
labels.push(raw);
|
||||
}
|
||||
}
|
||||
return labels.length > 0 ? labels.join(" · ") : undefined;
|
||||
}
|
||||
|
||||
export function DetailsCard({
|
||||
plugin,
|
||||
listing,
|
||||
detail,
|
||||
categories,
|
||||
}: {
|
||||
plugin?: PluginListItem;
|
||||
listing?: PluginListing;
|
||||
detail?: PluginListingDetail;
|
||||
categories?: readonly string[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const version = plugin?.installation?.currentRevision ?? (listing && listingVersion(listing));
|
||||
const source = listing ? undefined : detailSource(plugin, listing);
|
||||
const compatibility = listing?.requirements?.paseo;
|
||||
const platforms = formatPlatforms(detail?.review?.platforms, t);
|
||||
const rows: Array<{ key: string; label: string; value: string; mono?: boolean }> = [];
|
||||
if (version)
|
||||
rows.push({
|
||||
key: "version",
|
||||
label: t("settings.plugins.gallery.install.version"),
|
||||
value: version,
|
||||
mono: true,
|
||||
});
|
||||
if (compatibility)
|
||||
rows.push({
|
||||
key: "compat",
|
||||
label: t("settings.plugins.gallery.details.compatibility"),
|
||||
value: `Paseo ${compatibility}`,
|
||||
mono: true,
|
||||
});
|
||||
if (platforms)
|
||||
rows.push({
|
||||
key: "platforms",
|
||||
label: t("settings.plugins.gallery.details.platforms"),
|
||||
value: platforms,
|
||||
});
|
||||
if (listing?.license)
|
||||
rows.push({
|
||||
key: "license",
|
||||
label: t("settings.plugins.gallery.details.license"),
|
||||
value: listing.license,
|
||||
});
|
||||
if (listing) {
|
||||
rows.push({
|
||||
key: "published",
|
||||
label: t("settings.plugins.gallery.details.published"),
|
||||
value: formatPluginDate(listing.publishedAt),
|
||||
});
|
||||
rows.push({
|
||||
key: "updated",
|
||||
label: t("settings.plugins.gallery.details.updated"),
|
||||
value: formatPluginDate(listing.updatedAt),
|
||||
});
|
||||
}
|
||||
if (source)
|
||||
rows.push({
|
||||
key: "source",
|
||||
label: t("settings.plugins.gallery.install.source"),
|
||||
value: source,
|
||||
});
|
||||
|
||||
return (
|
||||
<SettingsCard>
|
||||
<View style={styles.kvCard}>
|
||||
{rows.map((row) => (
|
||||
<View key={row.key} style={styles.kvRow}>
|
||||
<Text style={styles.kvLabel}>{row.label}</Text>
|
||||
<DetailValue mono={row.mono}>{row.value}</DetailValue>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
{categories && categories.length > 0 ? (
|
||||
<View style={styles.categoryWrap}>
|
||||
{categories.map((label) => (
|
||||
<View key={label} style={styles.categoryPill}>
|
||||
<Text style={styles.categoryText}>{label}</Text>
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
function SponsorButton({ label, url }: { label: string; url: string }) {
|
||||
const open = useCallback(() => {
|
||||
void openExternalUrl(url);
|
||||
}, [url]);
|
||||
return (
|
||||
<Button variant="outline" onPress={open} leftIcon={sponsorHeartIcon}>
|
||||
{label}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
export function AuthorCard({
|
||||
listing,
|
||||
authorPluginCount,
|
||||
}: {
|
||||
listing: PluginListing;
|
||||
authorPluginCount: number;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const authorName = listingAuthor(listing);
|
||||
const avatar = listingAuthorAvatar(listing);
|
||||
const githubUrl = `https://github.com/${encodeURIComponent(listing.author.github)}`;
|
||||
const npmUrl = listing.author.npm
|
||||
? `https://www.npmjs.com/~${encodeURIComponent(listing.author.npm)}`
|
||||
: undefined;
|
||||
const websiteUrl = pluginSafeHttpsUrl(listing.author.website);
|
||||
const fundingLinks = pluginFundingLinks(listing);
|
||||
|
||||
return (
|
||||
<SettingsCard>
|
||||
<View style={styles.authorCard}>
|
||||
<View style={styles.authorHead}>
|
||||
<AuthorAvatar url={avatar} />
|
||||
<View style={styles.authorIdentity}>
|
||||
<Text style={styles.authorName} numberOfLines={1}>
|
||||
{authorName}
|
||||
</Text>
|
||||
<Text style={styles.authorHandle} numberOfLines={1}>
|
||||
@{listing.author.github}
|
||||
{authorPluginCount > 1
|
||||
? ` · ${t("settings.plugins.gallery.details.morePlugins", { count: authorPluginCount })}`
|
||||
: ""}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
{listing.author.bio ? <Text style={styles.authorBio}>{listing.author.bio}</Text> : null}
|
||||
<View style={styles.authorLinks}>
|
||||
<ExternalLink href={githubUrl} label="GitHub" />
|
||||
{npmUrl ? <ExternalLink href={npmUrl} label="npm" /> : null}
|
||||
{websiteUrl ? (
|
||||
<ExternalLink
|
||||
href={websiteUrl}
|
||||
label={websiteUrl.replace(/^https:\/\/(?:www\.)?/, "").replace(/\/$/, "")}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
{fundingLinks.length > 0 ? (
|
||||
<View style={styles.fundingStack}>
|
||||
{fundingLinks.map((entry) => (
|
||||
<SponsorButton
|
||||
key={entry.url}
|
||||
url={entry.url}
|
||||
label={entry.label ?? t("settings.plugins.gallery.actions.sponsor")}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
</SettingsCard>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
kvCard: { padding: theme.spacing[4], gap: theme.spacing[3] },
|
||||
kvRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "baseline",
|
||||
justifyContent: "space-between",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
kvLabel: {
|
||||
color: theme.colors.foregroundExtraMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
flexShrink: 0,
|
||||
},
|
||||
detailValue: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
textAlign: "right",
|
||||
flexShrink: 1,
|
||||
},
|
||||
detailValueMono: { fontFamily: theme.fontFamily.mono },
|
||||
categoryWrap: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
gap: theme.spacing[1.5],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
paddingVertical: theme.spacing[3],
|
||||
borderTopWidth: 1,
|
||||
borderTopColor: theme.colors.border,
|
||||
},
|
||||
categoryPill: {
|
||||
borderRadius: theme.borderRadius.full,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingVertical: 2,
|
||||
},
|
||||
categoryText: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
|
||||
authorCard: { padding: theme.spacing[4], gap: theme.spacing[3] },
|
||||
authorHead: { flexDirection: "row", alignItems: "center", gap: theme.spacing[3] },
|
||||
authorIdentity: { flex: 1, minWidth: 0 },
|
||||
authorName: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
authorHandle: { color: theme.colors.foregroundExtraMuted, fontSize: theme.fontSize.sm },
|
||||
authorBio: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 19,
|
||||
},
|
||||
authorLinks: { flexDirection: "row", flexWrap: "wrap", gap: theme.spacing[3] },
|
||||
fundingStack: { gap: theme.spacing[2] },
|
||||
}));
|
||||
@@ -1,203 +0,0 @@
|
||||
import { ChevronRight } from "lucide-react-native";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
pluginReleasesUrl,
|
||||
pluginRevisionBadge,
|
||||
pluginRevisionDestinationKind,
|
||||
pluginRevisions,
|
||||
pluginSafeHttpsUrl,
|
||||
type PluginListing,
|
||||
type PluginListingDetail,
|
||||
type PluginRevision,
|
||||
} from "@getpaseo/protocol/plugin-registry";
|
||||
import { SettingsCard } from "@/components/settings";
|
||||
import { ExternalLink } from "@/components/ui/external-link";
|
||||
import { mutedIconColorMapping } from "@/components/ui/icon-color";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { settingsStyles } from "@/styles/settings";
|
||||
import { openExternalUrl } from "@/utils/open-external-url";
|
||||
import { formatPluginDate } from "./listing";
|
||||
|
||||
const ThemedChevron = withUnistyles(ChevronRight);
|
||||
|
||||
function destinationLabel(revision: PluginRevision, t: TFunction): string {
|
||||
switch (pluginRevisionDestinationKind(revision)) {
|
||||
case "release":
|
||||
return t("settings.plugins.gallery.page.updates.githubRelease");
|
||||
case "commit":
|
||||
return t("settings.plugins.gallery.page.updates.commitSnapshot");
|
||||
case "npm":
|
||||
return t("settings.plugins.gallery.page.updates.npmPackage");
|
||||
default:
|
||||
return t("settings.plugins.gallery.actions.repository");
|
||||
}
|
||||
}
|
||||
|
||||
function reviewPrSuffix(url: string): string {
|
||||
const match = /\/pull\/(\d+)/.exec(url);
|
||||
return match ? ` #${match[1]}` : "";
|
||||
}
|
||||
|
||||
function RevisionRow({
|
||||
revision,
|
||||
current,
|
||||
first,
|
||||
}: {
|
||||
revision: PluginRevision;
|
||||
current: boolean;
|
||||
first: boolean;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const href = pluginSafeHttpsUrl(revision.url);
|
||||
const reviewHref = pluginSafeHttpsUrl(revision.reviewUrl);
|
||||
const open = useCallback(() => {
|
||||
if (href) void openExternalUrl(href);
|
||||
}, [href]);
|
||||
|
||||
const kindText = pluginRevisionBadge(revision);
|
||||
const dest = destinationLabel(revision, t);
|
||||
|
||||
const metaLine = (
|
||||
<View style={styles.metaRow}>
|
||||
<Text style={styles.date}>{formatPluginDate(revision.publishedAt)}</Text>
|
||||
{reviewHref ? (
|
||||
<ExternalLink
|
||||
href={reviewHref}
|
||||
label={`${t("settings.plugins.gallery.page.scorecard.reviewPr")}${reviewPrSuffix(reviewHref)}`}
|
||||
/>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
|
||||
const content = (
|
||||
<>
|
||||
<View style={styles.left}>
|
||||
<View style={styles.topLine}>
|
||||
<Text style={styles.label}>{revision.label}</Text>
|
||||
<View style={styles.kindBadge}>
|
||||
<Text style={styles.kindText}>{kindText}</Text>
|
||||
</View>
|
||||
{current ? (
|
||||
<View style={styles.currentBadge}>
|
||||
<Text style={styles.currentText}>
|
||||
{t("settings.plugins.gallery.page.updates.currentPin")}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{metaLine}
|
||||
</View>
|
||||
{href ? (
|
||||
<View style={styles.right}>
|
||||
<Text style={styles.dest}>{dest}</Text>
|
||||
<ThemedChevron size={14} uniProps={mutedIconColorMapping} />
|
||||
</View>
|
||||
) : null}
|
||||
</>
|
||||
);
|
||||
|
||||
if (href) {
|
||||
return (
|
||||
<PressHighlight
|
||||
accessibilityRole="link"
|
||||
onPress={open}
|
||||
style={[settingsStyles.row, styles.row, !first && settingsStyles.rowBorder]}
|
||||
highlightStyle={styles.pressed}
|
||||
>
|
||||
{content}
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<View style={[settingsStyles.row, styles.row, !first && settingsStyles.rowBorder]}>
|
||||
{content}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
export function PluginUpdatesTab({
|
||||
listing,
|
||||
detail,
|
||||
}: {
|
||||
listing: PluginListing;
|
||||
detail?: PluginListingDetail;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const revisions = pluginRevisions(detail ?? listing);
|
||||
const releases = pluginReleasesUrl(listing.repository.url);
|
||||
const footerHref = releases ?? pluginSafeHttpsUrl(listing.repository.url);
|
||||
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<SettingsCard>
|
||||
{revisions.map((revision, index) => (
|
||||
<RevisionRow
|
||||
key={`${revision.kind}-${revision.label}-${revision.publishedAt}`}
|
||||
revision={revision}
|
||||
current={index === 0}
|
||||
first={index === 0}
|
||||
/>
|
||||
))}
|
||||
{footerHref ? (
|
||||
<View style={[styles.footer, settingsStyles.rowBorder]}>
|
||||
<ExternalLink
|
||||
href={footerHref}
|
||||
label={
|
||||
releases
|
||||
? t("settings.plugins.gallery.page.updates.viewAllReleases")
|
||||
: t("settings.plugins.gallery.page.updates.viewRepository")
|
||||
}
|
||||
/>
|
||||
</View>
|
||||
) : null}
|
||||
</SettingsCard>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
container: { gap: theme.spacing[4] },
|
||||
row: { justifyContent: "space-between", gap: theme.spacing[3] },
|
||||
pressed: { backgroundColor: theme.colors.surface2 },
|
||||
left: { flex: 1, minWidth: 0, gap: theme.spacing[1] },
|
||||
topLine: { flexDirection: "row", flexWrap: "wrap", alignItems: "center", gap: theme.spacing[2] },
|
||||
metaRow: { flexDirection: "row", flexWrap: "wrap", alignItems: "center", gap: theme.spacing[3] },
|
||||
label: {
|
||||
color: theme.colors.foreground,
|
||||
fontFamily: theme.fontFamily.mono,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
date: { color: theme.colors.foregroundMuted, fontSize: theme.fontSize.sm },
|
||||
kindBadge: {
|
||||
borderRadius: theme.borderRadius.sm,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
paddingHorizontal: theme.spacing[1.5],
|
||||
paddingVertical: 1,
|
||||
},
|
||||
kindText: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontFamily: theme.fontFamily.mono,
|
||||
fontSize: theme.fontSize.sm,
|
||||
},
|
||||
currentBadge: {
|
||||
borderRadius: theme.borderRadius.full,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
paddingHorizontal: theme.spacing[2],
|
||||
paddingVertical: 1,
|
||||
},
|
||||
currentText: {
|
||||
color: theme.colors.statusSuccess,
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
right: { flexDirection: "row", alignItems: "center", gap: theme.spacing[1] },
|
||||
dest: { color: theme.colors.foregroundExtraMuted, fontSize: theme.fontSize.sm },
|
||||
footer: { paddingHorizontal: theme.spacing[4], paddingVertical: theme.spacing[3] },
|
||||
}));
|
||||
@@ -1,162 +0,0 @@
|
||||
import { router } from "expo-router";
|
||||
import { useCallback } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import {
|
||||
pluginKnownReviewStatus,
|
||||
pluginReviewTone,
|
||||
type PluginListing,
|
||||
type PluginMeterTone,
|
||||
} from "@getpaseo/protocol/plugin-registry";
|
||||
import { SettingsSection } from "@/components/settings";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { formatInstallCount, listingAuthor, listingText } from "./listing";
|
||||
import { PluginTile } from "./plugin-row";
|
||||
import { buildPluginListingRoute } from "./routes";
|
||||
|
||||
function toneDotStyle(tone: PluginMeterTone) {
|
||||
if (tone === "warning") return styles.dotWarning;
|
||||
if (tone === "danger") return styles.dotDanger;
|
||||
return styles.dotSuccess;
|
||||
}
|
||||
|
||||
function RelatedPluginCard({
|
||||
serverId,
|
||||
listing,
|
||||
wide,
|
||||
}: {
|
||||
serverId: string;
|
||||
listing: PluginListing;
|
||||
wide: boolean;
|
||||
}) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const text = listingText(listing, i18n.language);
|
||||
const author = listingAuthor(listing);
|
||||
const reviewStatus = listing.scorecardSummary?.review?.status;
|
||||
const knownStatus = reviewStatus ? pluginKnownReviewStatus(reviewStatus) : undefined;
|
||||
const open = useCallback(
|
||||
() => router.push(buildPluginListingRoute(serverId, listing.id)),
|
||||
[listing.id, serverId],
|
||||
);
|
||||
|
||||
return (
|
||||
<PressHighlight
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={text.name}
|
||||
onPress={open}
|
||||
style={[styles.card, wide && styles.cardWide]}
|
||||
highlightStyle={styles.pressed}
|
||||
testID={`plugin-related-${listing.id}`}
|
||||
>
|
||||
<View style={styles.top}>
|
||||
<PluginTile name={text.name} icon={listing.icon} />
|
||||
<View style={styles.identity}>
|
||||
<Text style={styles.name} numberOfLines={1}>
|
||||
{text.name}
|
||||
</Text>
|
||||
<Text style={styles.author} numberOfLines={1}>
|
||||
@{author}
|
||||
</Text>
|
||||
</View>
|
||||
</View>
|
||||
<Text style={styles.description} numberOfLines={2}>
|
||||
{text.description}
|
||||
</Text>
|
||||
<View style={styles.footer}>
|
||||
{reviewStatus ? (
|
||||
<View style={styles.status}>
|
||||
<View style={[styles.dot, toneDotStyle(pluginReviewTone(reviewStatus))]} />
|
||||
<Text style={styles.statusText}>
|
||||
{knownStatus
|
||||
? t(`settings.plugins.gallery.page.scorecard.reviewStatuses.${knownStatus}`)
|
||||
: reviewStatus}
|
||||
</Text>
|
||||
</View>
|
||||
) : (
|
||||
<View />
|
||||
)}
|
||||
{listing.installs !== undefined ? (
|
||||
<Text style={styles.installs}>
|
||||
{t("settings.plugins.gallery.installs", {
|
||||
count: listing.installs,
|
||||
installs: formatInstallCount(listing.installs),
|
||||
})}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
</PressHighlight>
|
||||
);
|
||||
}
|
||||
|
||||
export function RelatedPluginsSection({
|
||||
serverId,
|
||||
plugins,
|
||||
}: {
|
||||
serverId: string;
|
||||
plugins: readonly PluginListing[];
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const compact = useIsCompactFormFactor();
|
||||
if (plugins.length === 0) return null;
|
||||
|
||||
return (
|
||||
<View style={styles.wrap}>
|
||||
<SettingsSection title={t("settings.plugins.gallery.page.related.title")}>
|
||||
<View style={[styles.grid, !compact && styles.gridWide]}>
|
||||
{plugins.map((listing) => (
|
||||
<RelatedPluginCard
|
||||
key={listing.id}
|
||||
serverId={serverId}
|
||||
listing={listing}
|
||||
wide={!compact}
|
||||
/>
|
||||
))}
|
||||
</View>
|
||||
</SettingsSection>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
wrap: { marginTop: theme.spacing[8] },
|
||||
grid: { gap: theme.spacing[3] },
|
||||
gridWide: { flexDirection: "row", flexWrap: "wrap" },
|
||||
card: {
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
backgroundColor: theme.colors.surface1,
|
||||
padding: theme.spacing[3.5],
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
cardWide: { width: "48.5%", flexGrow: 1, minWidth: 220 },
|
||||
pressed: { backgroundColor: theme.colors.surface2 },
|
||||
top: { flexDirection: "row", alignItems: "center", gap: theme.spacing[3] },
|
||||
identity: { flex: 1, minWidth: 0 },
|
||||
name: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.medium,
|
||||
},
|
||||
author: { color: theme.colors.foregroundExtraMuted, fontSize: theme.fontSize.sm },
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: 18,
|
||||
},
|
||||
footer: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
justifyContent: "space-between",
|
||||
marginTop: theme.spacing[1],
|
||||
},
|
||||
status: { flexDirection: "row", alignItems: "center", gap: theme.spacing[1.5] },
|
||||
dot: { width: 6, height: 6, borderRadius: theme.borderRadius.full },
|
||||
dotSuccess: { backgroundColor: theme.colors.statusSuccess },
|
||||
dotWarning: { backgroundColor: theme.colors.statusWarning },
|
||||
dotDanger: { backgroundColor: theme.colors.statusDanger },
|
||||
statusText: { color: theme.colors.foregroundExtraMuted, fontSize: theme.fontSize.sm },
|
||||
installs: { color: theme.colors.foregroundExtraMuted, fontSize: theme.fontSize.sm },
|
||||
}));
|
||||
@@ -48,13 +48,9 @@ it("requests the managed connection credential through desktop main without a we
|
||||
requests.push(listen);
|
||||
return token;
|
||||
};
|
||||
expect(
|
||||
await readDesktopManagedLocalCredential({ serverId: "srv-local", connection }, invoke),
|
||||
).toBe("local-token");
|
||||
expect(await readDesktopManagedLocalCredential(connection, invoke)).toBe("local-token");
|
||||
token = "rotated-token";
|
||||
expect(
|
||||
await readDesktopManagedLocalCredential({ serverId: "srv-local", connection }, invoke),
|
||||
).toBe("rotated-token");
|
||||
expect(await readDesktopManagedLocalCredential(connection, invoke)).toBe("rotated-token");
|
||||
expect(requests).toEqual(["localhost:6767", "localhost:6767"]);
|
||||
});
|
||||
|
||||
@@ -5545,13 +5541,10 @@ 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(
|
||||
{ serverId: probeHost.serverId, connection },
|
||||
async (listen) => {
|
||||
credentialRequests.push(listen);
|
||||
return listen === "localhost:6799" ? "local-token" : null;
|
||||
},
|
||||
);
|
||||
const credential = await readDesktopManagedLocalCredential(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,7 +43,6 @@ 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";
|
||||
@@ -587,12 +586,10 @@ function createDefaultDeps(
|
||||
createClient: ({ host, connection, clientId, runtimeGeneration }) => {
|
||||
const desktopTransportFactory = createDesktopDaemonTransportFactory();
|
||||
const webSocketConfig = { webSocketFactory: createAppWebSocketFactory() };
|
||||
const appIdentity = resolveAppClientIdentity();
|
||||
const base = {
|
||||
suppressSendErrors: true,
|
||||
clientId,
|
||||
clientType: appIdentity.clientType,
|
||||
clientInfo: appIdentity.clientInfo,
|
||||
clientType: "mobile",
|
||||
appVersion: resolveAppVersion() ?? undefined,
|
||||
runtimeGeneration,
|
||||
capabilities: appCapabilities,
|
||||
@@ -601,8 +598,7 @@ function createDefaultDeps(
|
||||
providerSnapshots: "wire",
|
||||
createPluginClientBundleStore: createHostPluginClientBundleStore,
|
||||
...(host.password ? { password: host.password } : {}),
|
||||
localCredential: () =>
|
||||
readDesktopManagedLocalCredential({ serverId: host.serverId, connection }),
|
||||
localCredential: () => readDesktopManagedLocalCredential(connection),
|
||||
} satisfies Omit<DaemonClientConfig, "url">;
|
||||
if (connection.type === "routed") {
|
||||
const origin = resolveOrigin(connection.originServerId);
|
||||
@@ -694,8 +690,7 @@ function createDefaultDeps(
|
||||
return connectToDaemon(connection, {
|
||||
...(host.serverId ? { serverId: host.serverId } : {}),
|
||||
...(host.password ? { password: host.password } : {}),
|
||||
localCredential: () =>
|
||||
readDesktopManagedLocalCredential({ serverId: host.serverId, connection }),
|
||||
localCredential: () => readDesktopManagedLocalCredential(connection),
|
||||
...(timeoutMs !== undefined ? { timeoutMs } : {}),
|
||||
capabilities: appCapabilities,
|
||||
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
|
||||
|
||||
@@ -2,11 +2,10 @@ import { forwardRef, useCallback, useMemo, type ReactElement, type ReactNode } f
|
||||
import { Text, View, type PressableStateCallbackType } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { ChevronDown } from "lucide-react-native";
|
||||
import { ComboboxTrigger, type ComboboxTriggerState } from "@/components/ui/combobox-trigger";
|
||||
import { ComboboxTrigger } from "@/components/ui/combobox-trigger";
|
||||
import { CONTROL_HEIGHTS } from "@/components/ui/control-geometry";
|
||||
import { Shortcut } from "@/components/ui/shortcut";
|
||||
import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import type { SurfaceBackdrop } from "@/styles/surface-backdrop";
|
||||
import { ICON_SIZE, type Theme } from "@/styles/theme";
|
||||
|
||||
/**
|
||||
@@ -96,25 +95,7 @@ export function useFieldTriggerStyle(variant: FieldTriggerVariant, disabled: boo
|
||||
);
|
||||
}
|
||||
|
||||
function resolveFieldTriggerBackdrop(
|
||||
variant: FieldTriggerVariant,
|
||||
hovered: boolean,
|
||||
pressed: boolean,
|
||||
): SurfaceBackdrop {
|
||||
if (variant === "field") {
|
||||
return hovered || pressed ? "surface2" : "surface1";
|
||||
}
|
||||
return hovered && !pressed ? "surface2" : "surface0";
|
||||
}
|
||||
|
||||
export interface FieldTriggerInteractionState {
|
||||
hovered: boolean;
|
||||
pressed: boolean;
|
||||
backdrop: SurfaceBackdrop;
|
||||
}
|
||||
|
||||
export interface FieldTriggerProps extends Omit<FieldTriggerContentProps, "icon"> {
|
||||
icon: ReactNode | ((state: FieldTriggerInteractionState) => ReactNode);
|
||||
export interface FieldTriggerProps extends FieldTriggerContentProps {
|
||||
/** What a screen reader announces; defaults to `label`. */
|
||||
accessibilityLabel?: string;
|
||||
onPress: () => void;
|
||||
@@ -127,16 +108,7 @@ export interface FieldTriggerProps extends Omit<FieldTriggerContentProps, "icon"
|
||||
|
||||
/** A field trigger that anchors a Combobox. */
|
||||
export const FieldTrigger = forwardRef<View, FieldTriggerProps>(function FieldTrigger(
|
||||
{
|
||||
accessibilityLabel,
|
||||
onPress,
|
||||
disabled = false,
|
||||
tooltip,
|
||||
shortcutAction,
|
||||
testID,
|
||||
icon,
|
||||
...content
|
||||
},
|
||||
{ accessibilityLabel, onPress, disabled = false, tooltip, shortcutAction, testID, ...content },
|
||||
ref,
|
||||
): ReactElement {
|
||||
const style = useFieldTriggerStyle(content.variant, disabled);
|
||||
@@ -151,31 +123,6 @@ export const FieldTrigger = forwardRef<View, FieldTriggerProps>(function FieldTr
|
||||
) : undefined,
|
||||
[content.variant, tooltip, shortcutKeys],
|
||||
);
|
||||
const renderDynamicContent = useCallback(
|
||||
({ hovered, pressed }: ComboboxTriggerState) => {
|
||||
const effectiveHovered = !disabled && hovered;
|
||||
const effectivePressed = !disabled && pressed;
|
||||
return (
|
||||
<FieldTriggerContent
|
||||
{...content}
|
||||
icon={
|
||||
typeof icon === "function"
|
||||
? icon({
|
||||
hovered: effectiveHovered,
|
||||
pressed: effectivePressed,
|
||||
backdrop: resolveFieldTriggerBackdrop(
|
||||
content.variant,
|
||||
effectiveHovered,
|
||||
effectivePressed,
|
||||
),
|
||||
})
|
||||
: icon
|
||||
}
|
||||
/>
|
||||
);
|
||||
},
|
||||
[content, disabled, icon],
|
||||
);
|
||||
return (
|
||||
<ComboboxTrigger
|
||||
ref={ref}
|
||||
@@ -189,11 +136,7 @@ export const FieldTrigger = forwardRef<View, FieldTriggerProps>(function FieldTr
|
||||
accessibilityLabel={accessibilityLabel ?? content.label}
|
||||
tooltip={tooltipContent}
|
||||
>
|
||||
{typeof icon === "function" ? (
|
||||
renderDynamicContent
|
||||
) : (
|
||||
<FieldTriggerContent {...content} icon={icon} />
|
||||
)}
|
||||
<FieldTriggerContent {...content} />
|
||||
</ComboboxTrigger>
|
||||
);
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user