Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andClaude Opus 5.5 f6dd5fdb1a fix(app): keep the context meter's details open after a tap
Ignoring the focus that follows a touch press applied to every hover card,
so on a wide touch screen the context window meter's details opened on the
tap and closed again after the close grace. Whether a card ignores touch is
now one decision on HoverCard, used for both the touch's pointerenter and the
focus after it. The workspace row opts in; the meter keeps opening on a tap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:41:25 +00:00
d4d692260a test(app): fail when a tap opens the workspace hover card at all
The touch-tap test only checked that no card was left open after the tap,
which still passes when the touch's pointerenter opens the card during the
tap. That card is what makes iPad Safari drop the tap, so the test now records
whether the card mounted at any point. The trigger also reads the pointer
type from React Native's typed pointer event.

Co-authored-by: Zen <zoho.cn@gmail.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:41:24 +00:00
ZenandClaude Opus 5.5 d741af03cd fix(app): a tap on a touch screen opens a workspace row instead of its hover card
On a wide touch screen the workspace hover card opened on the tap's
pointerenter and on the focus the tap left behind. On iPad Safari that
changed the page under the finger, so the tap showed the card and never
opened the workspace. The workspace row's trigger now ignores touch, and
focus that follows a touch press no longer opens a hover card. Mouse hover
and keyboard focus open cards as before. Other triggers, such as the
context meter, which has no press of its own on wide screens, keep opening
on a touch's pointerenter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 06:41:15 +00:00
1ff119dc2a feat(app): copy a quote's body with one tap (#10608)
Agents often write drafts as quotes meant to be pasted elsewhere. A plain
quote now has a copy control on web, desktop, Android and iOS. It copies
the quote's body without the `>` markers and with its nested Markdown. A
nested quote, a code block or a Mermaid diagram inside it keeps its own
control. Admonitions get no control.

Web reads the rendered quote at press time, so a streaming quote copies
what it shows, and writes the same two clipboard flavors as selection
copy. A rendered Mermaid diagram copies as the fence it shows, and an
admonition inside a copied quote copies as its `> [!TYPE]` source. Code
blocks and quotes share one copy button with a Copied state and an error
toast when the clipboard refuses the write. On compact layouts the
control is always visible in a band above the quote body. On wide
layouts it shows on hover or focus and the quote keeps a right gutter.

Native code blocks and quotes share one header copy control with the
Lucide Copy glyph. A quote reserves the code block's header band above
its body, so the control never covers text at any font size. Native copy
emits the quote body as written, and a copied fence grows longer than
any fence inside its code.

Supersedes #9429 and #9319. Refs discussion #9303.

Co-authored-by: Pedro Vieira <pedro.vieira@dremio.com>
Co-authored-by: Phieu Dinh <phieu@fiu.one>
2026-11-25 13:36:01 +07:00
Mohamed Boudra 6e6f224e44 Hub login prints a one-click URL, and an uninstalled Muse Code shows as unavailable (#10751)
* fix(cli): print the one-click Hub login URL

`paseo hub login` opened verificationUriComplete in a browser but printed
the bare verificationUri. Over SSH or on a remote host the browser launch
does nothing, so users had to open the bare page and type the code by hand.
Print the URL that carries ?code= and keep the code next to it so the user
can check it matches the Hub approval page.

* fix(providers): report uninstalled plugin providers as unavailable

A fresh host with only Claude Code installed listed Muse Code as an
error ("muse not found on PATH"). The snapshot manager resolves a
provider's catalogue key before it checks availability, and treats any
failure there as an error. For a plugin provider with a command, the key
lookup required a resolved executable and threw when it was missing.

A command that does not resolve has no catalogue identity. Fall back to
the target key so the availability check runs and reports unavailable.

* fix(providers): keep a removed plugin executable off its cached catalogue

The previous fix returned no catalogue key for a missing executable. A
plugin that returns no key asks for a per-workspace catalogue, so after
its executable was removed the next read bound to the catalogue cached
while it was installed and kept reporting ready.

Give a missing executable its own key. Removal now moves the provider to
a fresh catalogue, and its refresh reports unavailable.
2026-11-25 13:30:37 +07:00
Mohamed Boudra 395a5a5f80 Run OpenCode v2 agents with their own MCP servers and env on a shared OpenCode server (#10752)
* refactor(server): share the MCP client connection that providers host

OMP connected MCP servers itself; OpenCode v2 now needs the same client to
host per-session servers. The shared connection also ends Streamable HTTP
sessions explicitly on close, because a stateful server keeps them otherwise.

* fix(opencode): run agent MCP servers and env on shared v2 servers

Agents with MCP servers or a launch environment failed on any OpenCode v2
server Paseo did not start, with "require an isolated server". OpenCode's MCP
configuration is shared by every session in a location, so Paseo answered by
starting a dedicated server, which a reused server cannot do.

Paseo now hosts each session's MCP servers itself and the v2 plugin exposes
their tools only to that session and its descendants, under OpenCode's
`<server>_<tool>` names. The plugin runs OpenCode's permission check before
each call, so preapproved grants still apply; that API exists from OpenCode
2.0.29, and older servers or stale plugins fail at session creation. Launch
env reaches shells through session.environment, which children do not
inherit, so the plugin asks Paseo to adopt each child before its first model
request. No agent gets a dedicated server any more, including on Paseo's own
helper.

A registered service is skipped when the provider env configures the OpenCode
process, so a service.json no longer breaks catalogs and launches for those
setups. An explicit server URL still reports those variables.

Fixes #9669

* fix(opencode): keep user tools, child instructions, and MCP call cleanup on shared servers

- A Paseo MCP tool replaced a same-named tool from the user's own OpenCode
  configuration, and the context hook then removed it from unrelated sessions.
  The plugin now captures that tool when it registers, keeps it for sessions
  without their own Paseo tool, and runs it for them.
- MCP instructions were an instruction entry written when a child was adopted.
  OpenCode loads entries before the context hook runs, so the child's first
  request missed them. The context hook now adds them to every request.
- Structured-only MCP results reached OpenCode with empty content. The bridge
  now adds them as text, as it already does for Paseo tools.
- The bridge listened for the request's `aborted` event, which never fires
  once the body is read, so Stop left the MCP call running. It now aborts when
  the response closes before it finishes.
- Closing an HTTP MCP connection waited on a session DELETE with no deadline.
  It now waits at most two seconds before closing the transport, which aborts
  the DELETE.

* test(server): run daemon OpenCode tests with the bridge the daemon always starts

These tests built the OpenCode v2 client without a bridge, so the client
reported no native Paseo tools and the daemon injected its internal MCP
server instead. OpenCode v2 now hosts agent MCP servers through the bridge
and rejects them without one. The daemon always starts the bridge, so the
tests now do too.

* fix(server): reconnect expired MCP sessions and bound the MCP handshake

- The OpenCode plugin copied a same-named user tool's input schema into the
  shared registration. OpenCode validates arguments against the registration,
  so the agent's own calls failed the user's schema. The registration keeps a
  permissive schema, and the context hook gives each session its own.
- A stateful HTTP MCP server answers 404 after it restarts or expires a
  session, and the SDK kept sending the old session ID. A call that gets 404
  now opens a new session once and retries.
- The SDK times out only the `initialize` request, so a server that never
  answered the `initialized` notification stalled agent creation. The whole
  handshake now has a 10-second deadline.
2026-11-25 13:30:13 +07:00
Mohamed Boudra 12bc84046c Keep iOS chat visible with tall pending cards (#10759)
* fix(app): reveal chat with tall pending cards

The initial scroll can settle inside the footer, where no rows need to be measured. Run the layout readiness check before allowing cached ranges to skip it.

* test(app): cover cached range during initial list placement

Exercise an observed end offset with measured rows in the buffer. Canceling the initial scroll must complete readiness even when the render range is already cached.
2026-11-25 13:24:09 +07:00
87 changed files with 3921 additions and 855 deletions
-1
View File
@@ -551,7 +551,6 @@
"packages/app/src/components/download-toast.tsx",
"packages/app/src/components/file-explorer-pane.tsx",
"packages/app/src/components/headers/back-header.tsx",
"packages/app/src/components/highlighted-code-block.tsx",
"packages/app/src/components/hosts/host-filter.tsx",
"packages/app/src/components/import-session-sheet.tsx",
"packages/app/src/components/left-sidebar.tsx",
+3 -1
View File
@@ -133,7 +133,9 @@ A configured URL takes precedence even when unreachable; Paseo reports the conne
An explicitly configured server needs the bridge installed separately. Connect once and start a session: the setup error gives the local package directory. Copy that directory to the server's OpenCode global `plugins` directory, then retry. For a server on another machine, set `PASEO_OPENCODE_BRIDGE_PORT` in the Paseo OpenCode provider environment before starting Paseo, and set `PASEO_OPENCODE_BRIDGE_URL` to the URL the OpenCode server can use to reach that port. For example, an SSH reverse tunnel can expose the Paseo loopback port on the OpenCode host. The bridge token is exchanged through the OpenCode connection and is not written into the plugin package.
OpenCode's custom MCP registrations are shared by all sessions in a location. Paseo rejects custom MCP servers and per-agent process environment overrides on a reused server rather than applying them to other sessions or ignoring them. Session identity is applied to each session's shell environment. A Paseo-owned helper supports custom process and MCP settings; it is selected when there is no explicit URL or healthy registered service.
Agent MCP servers and per-agent environment work on a reused server with OpenCode 2.0.29 or newer. Paseo connects each agent's MCP servers itself and shows their tools only to that agent and its subagents. Other agents in the same directory and your own OpenCode sessions do not see them. The agent's environment applies to its shell commands, its subagents, and its stdio MCP servers.
The provider `env` configures the OpenCode process. When it sets variables other than the connection variables above and `XDG_CONFIG_HOME`, `XDG_STATE_HOME`, or `OPENCODE_CONFIG_DIR`, Paseo ignores a registered service and starts its own helper. With an explicit URL, Paseo reports those variables as an error.
---
+6 -2
View File
@@ -43,7 +43,11 @@ Math and video are disabled. Task lists and admonitions are enabled; task checkb
Mermaid fences use the existing isolated diagram runtime and fullscreen viewer. Web dispatches them through the library’s code-block override. Native has no block-renderer hook, so the renderer extracts only Mermaid fences and places the existing WebView host between library-rendered segments. This is the only block exception; see [native selection limitations](native-text-selection.md) for diagram grouping and leading inline images. Streaming keeps the last valid diagram visible while the next revision renders.
Native code blocks use the library's copy control and compiled grammars. Web code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override. Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
Code blocks and plain quotes have a copy control in their top trailing corner. Native code blocks use the library's compiled grammars. On native, the code block and quote container views share one control (`HeaderCopyButton` on Android, `ENRMHeaderCopyButton` on iOS). A quote reserves the code block's header band above its body, so the control never covers quote text at any font size. On web, code blocks use `HighlightedCodeBlock` through the library's `renderers.codeBlock` override, and quotes use `WebBlockquote` through `renderers.blockquote`. Both use `BlockCopyButton`. On compact layouts the control is always visible, so the web quote reserves a band above its body, as native does. On wide layouts the control appears on hover or focus, so the quote keeps a right gutter instead; a band there would leave an empty strip above every quote.
A quote copies its body without the `>` markers, with its nested Markdown, and reads the content at the time of the press, so a streaming quote copies what it shows. A nested quote or code block keeps its own control. Web quote copy uses the same two clipboard flavors as selection copy: `text/plain` is unescaped Markdown and `text/html` is rendered from escaped Markdown. A rendered Mermaid diagram copies as its fence because its wrapper carries the fence source. Native quote copy serializes the quote's parsed Markdown, so a workspace image copies as its cached file URL, as native selection copy does; native has no map back to the workspace path. A native Mermaid diagram in a quote renders outside it (see [native selection limitations](native-text-selection.md)), so each quote fragment copies only its own text. Admonitions get no control: web renders them with a separate library renderer. On web an admonition inside a copied quote copies as its `> [!TYPE]` source; the fork marks the box and its generated title for this. Selection copy keeps the text it shows, because the cloned range cannot tell a whole callout from part of one. On native, quotes inside list items get no control, because they render as text spans in the item. Web renders them as blocks, so they get one.
Selection copy has to tell links Paseo recognized in the text (paths, forge references, code spans) from links in the Markdown, so the web link renderer marks the recognized ones. Plain-text paste carries them as the text the reply showed, and rich paste keeps them as links only when they point to an `http` or `https` URL. Authored links and parser autolinks such as a bare `www.example.com` copy as links. The fork also keeps the library's block spacing around the web code block override, preserves web list numbering and link titles, marks pending parses with `aria-busy` so Find waits for rendered text, and carries link syntax through native and web tap events. Web inline code inside a link inherits only the link colour; its code font, size and background stay intact. Keep link variants colour-only: native pills replace text runs and prevent paths from wrapping; Android pills also use the surrounding block’s font size. [Upstream PR #997](https://github.com/software-mansion/enriched-markdown/pull/997) tracks these changes.
The fork also keeps overflowing native horizontal blocks in control of their drags: Android claims parent interception at touch-down and releases it for vertical drags so the chat list can scroll; iOS keeps its scroll recognizer active for outward drags at the leading edge. This prevents compact sidebar pans from taking block scrolling without changing sidebar swipes on prose or non-overflowing blocks. Native changes require a client rebuild.
@@ -55,4 +59,4 @@ The library determines how incomplete Markdown appears during streaming. Complet
## Verification
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
Follow [QA](qa.md) and [mobile testing](mobile-testing.md). Exercise chat, file preview, plan and PR content on all three platforms. Include cross-paragraph selection, progressive streaming, a file-link tap, code copy/highlighting, quote copy (nested quote, code block in a quote, admonition, large font on native), a table and a workspace image. On iPad, repeat preview selection after opening and closing Explorer and after rotation. Check web find, selection-copy and source-message navigation after DOM changes.
+1 -1
View File
@@ -171,7 +171,7 @@ V2.0.4 also removed the activation endpoint that gated a cold location, and a co
Paseo installs its OpenCode tool bridge through `OPENCODE_CONFIG_CONTENT`. V1 accepts a plugin file; v2 silently skips configured files and requires a package directory with a server entry point. Both versions use the daemon's private loopback bridge for caller-scoped tools. The global manifest must use agent-scoped schemas before a session is bound, because every bridge call executes in an agent session. V2 discovers definitions from each bound session's catalog: plugin-contributed tools can be absent from the global manifest, and an allowlist cannot register a missing definition. Registration is location-wide, so session filtering and caller-scoped execution must remain in place. Bridge context lives only in daemon memory and is removed when the Paseo session closes. The content-addressed plugin artifacts contain no session data or secrets. V2 also needs this plugin when native Paseo tools are disabled: its prompt API has no structured-output format, so the plugin supplies a schema-validated final-answer tool.
An agent with custom environment variables or user-configured MCP servers gets a dedicated OpenCode server. V2 supports session environment, but its MCP configuration remains location-scoped, so separate servers still prevent one agent from changing another agent's MCP setup. Configure custom MCP with `mcp.add`; do not follow it with `mcp.connect`, which only toggles config-backed servers.
No v2 agent gets a dedicated OpenCode server, because a reused server cannot provide one. OpenCode's MCP configuration is location-scoped, so Paseo never calls `mcp.add` for an agent. The daemon connects the agent's MCP servers itself (`v2/session-mcp.ts`), and the v2 plugin exposes their tools under OpenCode's native `<server>_<tool>` names. Each name registers once per location. The plugin's `context` hook gives each session its own definition and removes the tool from other sessions. If the user's own OpenCode configuration registered a tool with the same name first, other sessions keep that tool and its execution. Execution routes to the calling session's root binding. The hook also adds the servers' instructions to each request. OpenCode loads instruction entries before the hook runs, so an entry written when a child is adopted would miss the child's first request. The plugin calls OpenCode's `permission.assert` before each call, so `toolPolicy.preapproved` grants still apply. That API exists from OpenCode 2.0.29. Bind reports `features.mcpTools`, so an older server or a stale plugin fails the session at creation instead of hiding its tools. Per-agent `launch.env` reaches shells through `session.environment`, which child sessions do not inherit. The plugin asks the daemon to adopt each descendant in its first `context` hook, before its first model request.
OpenCode owns user message IDs. Do not pass Paseo-generated IDs to OpenCode prompt APIs; let OpenCode create `msg*` IDs and record the user timeline item from the `message.updated` event.
@@ -757,6 +757,161 @@ test("pasting an assistant selection preserves literal underscores and authored
}
});
const QUOTE_BODY = [
"Draft for the team: **ship it** with [the notes](https://example.com/notes).",
"",
"> Nested reply.",
"",
"```ts",
"const quoted = 1;",
"```",
"",
"```mermaid",
"flowchart LR",
" Start --> Done",
"```",
"",
"Thanks!",
].join("\n");
const QUOTE_MARKDOWN = [
"Text before the quote.",
"",
...QUOTE_BODY.split("\n").map((line) => (line ? `> ${line}` : ">")),
"",
"> [!NOTE]",
"> Heads up before you paste.",
"",
"Text after the quote.",
].join("\n");
function assistantQuote(page: Page, index: number): Locator {
return assistantMessageBlocks(page).getByRole("blockquote").nth(index);
}
/** A quote's own control is its first, ahead of any nested quote's. */
function quoteCopyControl(quote: Locator): Locator {
return quote.getByRole("button", { name: "Copy quote" }).first();
}
async function copyQuote(quote: Locator): Promise<void> {
await quote.hover();
await quoteCopyControl(quote).click();
await expect(quote.getByRole("button", { name: "Copied" })).toBeVisible();
}
async function pasteIntoPlainAndRichFields(page: Page): Promise<{ plain: Locator; rich: Locator }> {
await page.evaluate(() => {
const fields = document.createElement("div");
fields.style.cssText = "position: fixed; bottom: 0; left: 0; z-index: 10000; background: white";
const plainText = document.createElement("textarea");
plainText.setAttribute("aria-label", "Plain text paste");
const richText = document.createElement("div");
richText.contentEditable = "true";
richText.setAttribute("role", "textbox");
richText.setAttribute("aria-label", "Rich text paste");
fields.append(plainText, richText);
document.body.append(fields);
});
const plain = page.getByRole("textbox", { name: "Plain text paste" });
await plain.focus();
await page.keyboard.press("ControlOrMeta+v");
const rich = page.getByRole("textbox", { name: "Rich text paste" });
await rich.focus();
await page.keyboard.press("ControlOrMeta+v");
return { plain, rich };
}
test("a quote's copy control copies only that quote's body", async ({ context, page }) => {
const agent = await seedMockAgentWorkspace({
repoPrefix: "assistant-quote-copy-",
title: "Assistant quote copy",
initialPrompt: "Render the quote fixture.",
featureValues: { mockAssistantResponse: QUOTE_MARKDOWN },
});
try {
await allowRichClipboard(context);
await agent.client.waitForAgentUpsert(
agent.agentId,
(snapshot) => snapshot.status === "idle",
30_000,
);
await openAgentRoute(page, agent);
const quote = assistantQuote(page, 0);
const nested = assistantQuote(page, 1);
await expect(quote).toContainText("Thanks!");
await test.step("an admonition has no copy control", async () => {
await expect(assistantMessageBlocks(page)).toContainText("Heads up before you paste.");
await expect(
assistantMessageBlocks(page).getByRole("button", { name: "Copy quote" }),
).toHaveCount(2);
});
await test.step("the control appears on hover or keyboard focus", async () => {
const control = quoteCopyControl(quote);
await expect(control).toHaveCSS("opacity", "0");
await quote.hover();
await expect(control).toHaveCSS("opacity", "1");
await page.mouse.move(0, 0);
await expect(control).toHaveCSS("opacity", "0");
await control.focus();
await expect(control).toHaveCSS("opacity", "1");
await control.blur();
});
await test.step("copying the quote takes its body, with a diagram as its fence", async () => {
await expect(quote.getByRole("img", { name: "Diagram" })).toBeVisible({ timeout: 30_000 });
await copyQuote(quote);
const copied = await readRichClipboard(page);
expect(copied.plainText).toBe(QUOTE_BODY);
expect(copied.html).toContain("<strong>ship it</strong>");
expect(copied.html).toContain("<blockquote>");
});
await test.step("the copy pastes as Markdown and as rich text", async () => {
const { plain, rich } = await pasteIntoPlainAndRichFields(page);
await expect(plain).toHaveValue(QUOTE_BODY);
await expect(rich.locator("strong")).toHaveText("ship it");
await expect(rich.getByRole("link", { name: "the notes" })).toHaveAttribute(
"href",
"https://example.com/notes",
);
await expect(rich).not.toContainText("Text before the quote.");
});
await test.step("a nested quote copies only itself", async () => {
await copyQuote(nested);
await expect
.poll(async () => (await readRichClipboard(page)).plainText)
.toBe("Nested reply.");
});
await test.step("a code block in the quote keeps its own copy", async () => {
const code = quote.getByText("const quoted = 1;", { exact: true });
await code.hover();
await quote.getByRole("button", { name: "Copy code" }).first().click();
await expect.poll(() => readPlainClipboard(page)).toBe("const quoted = 1;");
});
await test.step("a phone-sized layout shows the control above the full-width text", async () => {
await page.mouse.move(0, 0);
await page.setViewportSize({ width: 390, height: 844 });
const control = quoteCopyControl(quote);
await expect(control).toHaveCSS("opacity", "1");
const controlBox = await control.boundingBox();
const firstLine = await quote.getByText(/^Draft for the team/).boundingBox();
expect(controlBox && firstLine).toBeTruthy();
// The text starts below the control instead of wrapping short of it.
expect(firstLine!.y).toBeGreaterThanOrEqual(controlBox!.y + controlBox!.height);
expect(firstLine!.x + firstLine!.width).toBeGreaterThan(controlBox!.x);
});
} finally {
await agent.cleanup();
}
});
test("copying a selection across an assistant image keeps its Markdown source and alt text", async ({
context,
page,
@@ -26,6 +26,7 @@ import {
reloadAgent,
scriptAgentUsage,
seedAgentWithContextWindow,
tapContextWindowMeter,
usageCard,
} from "../support/helpers/context-window";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
@@ -509,6 +510,24 @@ test("context details stay open while the chat streams", async ({ page }) => {
}
});
test.describe("on a wide touch screen", () => {
test.use({ hasTouch: true });
test("tapping the meter opens context details that stay open", async ({ page, agent }) => {
const usage = await scriptAgentUsage(page);
await page.setViewportSize(DESKTOP);
await openAgent(page, agent);
const [claude] = claudeAndCodexReports();
// A tap can request the agent's usage more than once.
usage.answerNext([onPersonalLogin(claude!)]);
usage.answerNext([onPersonalLogin(claude!)]);
const details = await tapContextWindowMeter(page);
// Past the card's close grace. A touch sends no pointer movement after the tap.
await page.waitForTimeout(500);
await expect(details).toBeVisible();
});
});
test("pointer hovering context details preserves composer focus", async ({ page, agent }) => {
const usage = await scriptAgentUsage(page);
await page.setViewportSize(DESKTOP);
@@ -16,6 +16,7 @@ import {
pinWorkspaceFromSidebar,
scrollWorkspaceList,
sweepPointerAcrossWorkspaceRows,
watchWorkspaceHoverCard,
} from "../support/helpers/sidebar";
import { seedWorkspace } from "../support/helpers/seed-client";
import { expectWorkspaceHeader } from "../support/helpers/workspace-ui";
@@ -544,6 +545,29 @@ test.describe("Sidebar workspace list", () => {
});
});
// On a wide touch screen (iPad) a tap is not a hover. Opening the card on the tap changes the page
// under the finger, and iPad Safari then drops the tap instead of opening the workspace.
test.describe("Sidebar workspace rows on a touch screen", () => {
test.use({ hasTouch: true, viewport: { width: 1180, height: 820 } });
test("tapping a workspace row opens it without the hover card", async ({ page }) => {
const workspace = await seedWorkspace({ repoPrefix: "sidebar-touch-tap-" });
try {
await gotoAppShell(page);
await waitForSidebarProject(page, path.basename(workspace.repoPath));
const row = await waitForSidebarWorkspace(page, workspace.workspaceId);
const hoverCard = await watchWorkspaceHoverCard(page);
await row.tap();
await expect(page).toHaveURL(/\/workspace\//, { timeout: 30_000 });
await expectWorkspaceHoverCardClosed(page);
// A card that opens during the tap is what makes iPad Safari drop the tap.
expect(await hoverCard.hasOpened()).toBe(false);
} finally {
await workspace.cleanup();
}
});
});
test.describe("Mobile sidebar panelState transition", () => {
test.use({ viewport: { width: 390, height: 844 } });
@@ -41,6 +41,14 @@ export async function hoverContextWindowMeter(page: Page, name = METER_NAME): Pr
return card;
}
/** Taps the meter on a touch screen and returns its details once they are on screen. */
export async function tapContextWindowMeter(page: Page, name = METER_NAME): Promise<Locator> {
await page.getByRole("img", { name, exact: true }).tap({ timeout: 30_000 });
const card = contextWindowDetails(page);
await expect(card).toBeVisible();
return card;
}
/** Walks the pointer from the meter up onto its hover card, across the gap between them. */
export async function moveOntoContextWindowDetails(page: Page, card: Locator): Promise<void> {
const meter = await page.getByRole("img", { name: METER_NAME }).boundingBox();
@@ -132,6 +132,31 @@ export async function expectWorkspaceHoverCardClosed(page: Page): Promise<void>
await expect(page.getByTestId("workspace-hover-card")).toHaveCount(0);
}
/**
* Records whether a workspace hover card mounts at any point from now on, including one that
* closes again before an assertion could see it.
*/
export async function watchWorkspaceHoverCard(
page: Page,
): Promise<{ hasOpened: () => Promise<boolean> }> {
await page.evaluate(() => {
const target = window as unknown as { __workspaceHoverCardOpened?: boolean };
const isOpen = () => document.querySelector('[data-testid="workspace-hover-card"]') !== null;
target.__workspaceHoverCardOpened = isOpen();
new MutationObserver(() => {
if (isOpen()) target.__workspaceHoverCardOpened = true;
}).observe(document.body, { childList: true, subtree: true });
});
return {
hasOpened: () =>
page.evaluate(
() =>
(window as unknown as { __workspaceHoverCardOpened?: boolean })
.__workspaceHoverCardOpened === true,
),
};
}
export async function closeWorkspaceContextMenu(page: Page, workspaceId: string): Promise<void> {
const workspaceKey = `${getServerId()}:${workspaceId}`;
await page.getByTestId(`sidebar-workspace-context-menu-${workspaceKey}-backdrop`).click();
+1 -1
View File
@@ -40,7 +40,7 @@
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
"build:apk": "npm --prefix ../.. run build:apk",
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
},
"dependencies": {
"@codemirror/commands": "6.10.4",
@@ -2,7 +2,7 @@ import { LegendList, type LegendListRef } from "@legendapp/list/react-native";
import React, { act, useSyncExternalStore } from "react";
import { createRoot, type Root } from "react-dom/client";
import { View } from "react-native";
import { afterEach, beforeEach, expect, it } from "vitest";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { disclosureAnchor } from "./native-disclosure-hold";
// The native chat timeline runs on the patched LegendList (patches/@legendapp+list+3.7.1.patch).
@@ -90,7 +90,7 @@ function keyExtractor(item: Row) {
return item.id;
}
function estimateRowSize(item: Row) {
function rowHeight(item: Row) {
return item.height;
}
@@ -289,7 +289,7 @@ it("expands the draw distance of a placed end-anchored list without moving its b
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
recycleItems={false}
getEstimatedItemSize={estimateRowSize}
getEstimatedItemSize={rowHeight}
drawDistance={drawDistance}
alignItemsAtEnd
initialScrollAtEnd
@@ -315,3 +315,96 @@ it("expands the draw distance of a placed end-anchored list without moving its b
expect(expanded?.scroll).toBe(initial?.scroll);
expect(expanded?.positionByKey(lastRow.id)).toBe(lastRowTop);
});
it.each([2, 4])("reveals an end-anchored list with a footer %sx the viewport", async (scale) => {
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
id: `row-${index}`,
height: 40,
}));
const footerHeight = VIEWPORT_HEIGHT * scale;
const listRef = React.createRef<LegendListRef>();
const footer = React.createElement(View, { style: rowStyle(footerHeight) });
const onReady = vi.fn();
act(() => {
root.render(
<LegendList
ref={listRef}
data={rows}
renderItem={renderRow}
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
getEstimatedItemSize={rowHeight}
drawDistance={50}
recycleItems={false}
alignItemsAtEnd
initialScrollAtEnd
ListFooterComponent={footer}
onReady={onReady}
style={LIST_STYLE}
/>,
);
});
await expect
.poll(async () => {
await wait(16);
return onReady.mock.calls.length;
})
.toBe(1);
expect(listRef.current?.getState().scroll).toBe(
rows.length * 40 + footerHeight - VIEWPORT_HEIGHT,
);
});
const END_PADDED_CONTENT_STYLE = { paddingBottom: 125 };
it("reveals buffered rows when the scroll view takes over initial end positioning", () => {
const rowSize = 40;
const rows: Row[] = Array.from({ length: 10 }, (_, index) => ({
id: `row-${index}`,
height: rowSize,
}));
const listRef = React.createRef<LegendListRef>();
const onReady = vi.fn();
act(() => {
root.render(
<LegendList
ref={listRef}
data={rows}
renderItem={renderRow}
keyExtractor={keyExtractor}
estimatedListSize={ESTIMATED_LIST_SIZE}
getFixedItemSize={rowHeight}
drawDistance={120}
recycleItems={false}
alignItemsAtEnd
initialScrollAtEnd
contentContainerStyle={END_PADDED_CONTENT_STYLE}
onReady={onReady}
style={LIST_STYLE}
/>,
);
});
const list = listRef.current;
if (!list) throw new Error("The list did not mount");
const scroller: unknown = list.getScrollableNode();
if (!(scroller instanceof HTMLElement)) throw new Error("The list has no scroll element");
const endOffset =
rows.length * rowSize + END_PADDED_CONTENT_STYLE.paddingBottom - VIEWPORT_HEIGHT;
act(() => {
// Deliver the scroll view's observed end offset before canceling the list's initial scroll.
// Keep both calls in one task so a later layout pass cannot complete the reveal for them.
scroller.scrollTop = endOffset;
scroller.dispatchEvent(new Event("scroll"));
expect(onReady).not.toHaveBeenCalled();
list.cancelScroll();
});
const state = list.getState();
expect(state.scroll).toBe(endOffset);
expect(state.start).toBeNull();
expect(state.endBuffered).toBe(rows.length - 1);
expect(state.sizeAtIndex(rows.length - 1)).toBe(rowSize);
expect(onReady).toHaveBeenCalledTimes(1);
});
@@ -1,5 +1,20 @@
import { afterEach, describe, expect, it } from "vitest";
import { createAssistantSelectionClipboardContent } from "./content.web";
import { createElement as h } from "react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { within } from "@testing-library/dom";
import { EnrichedMarkdownText } from "react-native-enriched-markdown";
import { I18nextProvider } from "react-i18next";
import { afterEach, describe, expect, it, vi } from "vitest";
import { WEB_RENDERERS } from "@/components/markdown/renderers.web";
import type { ToastApi } from "@/components/toast-host";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { i18n } from "@/i18n/i18next";
import {
createAssistantSelectionClipboardContent,
createElementClipboardContent,
} from "./content.web";
import { MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE } from "./markup";
const fixture = `
<div data-testid="assistant-message">
@@ -953,3 +968,158 @@ it("copies a workspace image path instead of its temporary display URL", () => {
"![chart](assets/chart.png)",
);
});
describe("quote copy", () => {
let root: Root | undefined;
let host: HTMLDivElement | undefined;
const toast: ToastApi = { show: () => () => {}, copied: () => {}, error: () => {} };
const queryClient = new QueryClient();
afterEach(() => {
const mounted = root;
if (mounted) flushSync(() => mounted.unmount());
root = undefined;
host?.remove();
host = undefined;
});
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
if (!host || !root) {
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
}
const mounted = root;
flushSync(() =>
mounted.render(
h(
QueryClientProvider,
{ client: queryClient },
h(
I18nextProvider,
{ i18n },
h(ToastApiProvider, {
api: toast,
children: h(EnrichedMarkdownText, {
markdown,
flavor: "github",
md4cFlags: { latexMath: false, admonitions: true },
renderers: WEB_RENDERERS,
}),
}),
),
),
),
);
const rendered = host;
await vi.waitFor(() => expect(rendered.textContent).toContain(lastText));
return rendered;
}
it("copies a quote's body with its formatting and without the quote marker", async () => {
const rendered = await renderMarkdown(
"> Hello **team**, see [the PR](https://example.test/pr).\n>\n> - Review\n>\n> > Nested reply",
"Nested reply",
);
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe(
"Hello **team**, see [the PR](https://example.test/pr).\n\n- Review\n\n> Nested reply",
);
expect(content?.html).toContain("<strong>team</strong>");
expect(content?.html).toContain("<blockquote>");
expect(content?.html).not.toContain("Copy quote");
});
it("gives a nested quote its own control that copies only the nested quote", async () => {
const rendered = await renderMarkdown("> Outer\n>\n> > Nested reply", "Nested reply");
const nested = fixtureElement(rendered, "blockquote", 1);
expect(within(rendered).getAllByRole("button", { name: "Copy quote" })).toHaveLength(2);
expect(within(nested).getAllByRole("button", { name: "Copy quote" })).toHaveLength(1);
expect(createElementClipboardContent(nested)?.plainText).toBe("Nested reply");
});
it("copies a code block inside a quote as its fence and keeps the code's own control", async () => {
const rendered = await renderMarkdown("> Run:\n>\n> ```sh\n> npm test\n> ```", "npm test");
const quote = fixtureElement(rendered, "blockquote");
expect(within(quote).getByRole("button", { name: "Copy code" })).toBeTruthy();
expect(createElementClipboardContent(quote)?.plainText).toBe("Run:\n\n```sh\nnpm test\n```");
});
it("copies what a streaming quote shows at the time of the copy", async () => {
const first = await renderMarkdown("> First draft", "First draft");
const quote = fixtureElement(first, "blockquote");
const revised = await renderMarkdown("> First draft, revised", "revised");
expect(fixtureElement(revised, "blockquote")).toBe(quote);
expect(createElementClipboardContent(quote)?.plainText).toBe("First draft, revised");
});
it("copies literal Markdown characters raw in text/plain and escaped in text/html", async () => {
const rendered = await renderMarkdown("> literal \\_word\\_ stays literal", "stays literal");
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe("literal _word_ stays literal");
expect(content?.html).toContain("literal _word_ stays literal");
expect(content?.html).not.toContain("<em>");
});
it("gives an admonition no copy control", async () => {
const rendered = await renderMarkdown("> [!NOTE]\n> Heads up", "Heads up");
expect(within(rendered).queryByRole("button", { name: "Copy quote" })).toBeNull();
});
it("copies a nested admonition as its callout source", async () => {
const rendered = await renderMarkdown(
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
"After",
);
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
expect(content?.plainText).toBe("Before\n\n> [!WARNING]\n> Do not deploy.\n\nAfter");
});
it("copies a selection across an admonition as the text it shows, without a callout marker", async () => {
const rendered = await renderMarkdown(
"> Before\n>\n> > [!WARNING]\n> > Do not deploy.\n>\n> After",
"After",
);
rendered.setAttribute("data-testid", "assistant-message");
const body = tokenText(rendered, "Do not deploy.");
expect(
copyBetween([body, "Do not ".length], [tokenText(rendered, "After"), 5])?.plainText,
).toBe("deploy.\n\nAfter");
expect(
copyBetween([tokenText(rendered, "Before"), 0], [tokenText(rendered, "Warning"), 4])
?.plainText,
).toBe("Before\n\nWarn");
expect(
copyBetween([tokenText(rendered, "Before"), 0], [body, "Do not".length])?.plainText,
).not.toContain("[!WARNING]");
});
it("copies a rendered Mermaid diagram as its fence", () => {
const quote = document.createElement("blockquote");
quote.innerHTML = `<p>Before</p><div ${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}="graph TD; A-->B" data-paseo-markdown-language="mermaid"><svg aria-label="diagram"></svg></div><p>After</p>`;
expect(createElementClipboardContent(quote)?.plainText).toBe(
"Before\n\n```mermaid\ngraph TD; A-->B\n```\n\nAfter",
);
});
it("copies nothing from a quote that holds only its control", () => {
const quote = document.createElement("blockquote");
quote.innerHTML = '<button data-paseo-markdown-ignore="true">Copy quote</button>';
expect(createElementClipboardContent(quote)).toBeNull();
});
});
@@ -6,9 +6,12 @@ import {
type MarkdownClipboardContent,
} from "@/utils/rich-clipboard";
import {
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
MARKDOWN_COPY_ALIGN_ATTRIBUTE,
MARKDOWN_COPY_ALT_ATTRIBUTE,
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
MARKDOWN_COPY_IGNORE_ATTRIBUTE,
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
MARKDOWN_COPY_LIST_MARKER_ATTRIBUTE,
@@ -91,6 +94,17 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
} else {
turndown.escape = (text) => text;
}
// An admonition copies as its `> [!TYPE]` source.
turndown.addRule("admonition", {
filter: (node) => node.hasAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE),
replacement: (content, node) => {
const type = (node as Element)
.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE)!
.toUpperCase();
const body = content.replace(/^\n+|\n+$/g, "");
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
},
});
turndown.addRule("gfmStrikethrough", {
filter: ["del", "s"],
replacement: (content) => `~~${content}~~`,
@@ -120,6 +134,53 @@ function isWebUrl(href: string): boolean {
const markdownTurndown = createTurndown("markdown");
const plainTurndown = createTurndown("plain");
/**
* A fence rendered as something other than its code, such as a Mermaid diagram, carries
* its source in an attribute. Put the code block back so the fence is what gets copied.
*/
function restoreFenceSources(container: Element): void {
for (const region of container.querySelectorAll(`[${MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE}]`)) {
const source = region.getAttribute(MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE);
if (source === null) continue;
const pre = document.createElement("pre");
const code = document.createElement("code");
const language = region.getAttribute(MARKDOWN_COPY_LANGUAGE_ATTRIBUTE);
if (language) code.className = `language-${language}`;
code.textContent = source;
pre.append(code);
region.replaceWith(pre);
}
}
/**
* Clipboard payload for everything inside `element`, without the element's own syntax:
* a quote's body carries no `>` prefix. Null when there is nothing to copy.
*/
export function createElementClipboardContent(element: Element): MarkdownClipboardContent | null {
const container = document.createElement("div");
container.append(...Array.from(element.childNodes, (child) => child.cloneNode(true)));
const originals = element.querySelectorAll("*");
const copies = container.querySelectorAll("*");
originals.forEach((original, index) => copySemanticAttributes(original, copies[index]!));
restoreFenceSources(container);
restoreAdmonitions(container);
restoreMarkdownElements(container);
return clipboardContentFromMarkup(container);
}
function clipboardContentFromMarkup(container: HTMLElement): MarkdownClipboardContent | null {
const markdown = markdownTurndown.turndown(container).trim();
if (!markdown) {
return null;
}
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
// literal in a rich target.
const plainText = plainTurndown.turndown(container).trim();
const content = createSelectionClipboardContent(markdown, plainText);
return { ...content, html: flattenClipboardListMarkup(content.html) };
}
export function createAssistantSelectionClipboardContent(
selection: Selection | null,
): MarkdownClipboardContent | null {
@@ -145,17 +206,7 @@ export function createAssistantSelectionClipboardContent(
container.append(cloneMarkdownSelection(part.range, part.message));
}
restoreMarkdownElements(container);
const markdown = markdownTurndown.turndown(container).trim();
if (!markdown) {
return null;
}
// text/plain carries unescaped Markdown: a plain target shows backslashes literally.
// text/html is rendered from escaped Markdown, so literal Markdown characters stay
// literal in a rich target.
const plainText = plainTurndown.turndown(container).trim();
const content = createSelectionClipboardContent(markdown, plainText);
return { ...content, html: flattenClipboardListMarkup(content.html) };
return clipboardContentFromMarkup(container);
}
/**
@@ -702,6 +753,28 @@ function numberOrderedListItems(list: Element, start: number): void {
});
}
/**
* The library renders an admonition as a box with a generated title. Keep it a quote
* with its type, so it copies as its callout source rather than as the title's prose.
* Only a whole-element copy does this: a selection cannot tell from its cloned markup
* whether it holds the whole callout, so it copies the text it shows.
*/
function restoreAdmonitions(container: Element): void {
const admonitions = Array.from(
container.querySelectorAll(`[${MARKDOWN_ADMONITION_TYPE_ATTRIBUTE}]`),
);
for (const admonition of admonitions.toReversed()) {
admonition.querySelector(`:scope > [${MARKDOWN_ADMONITION_TITLE_ATTRIBUTE}]`)?.remove();
const quote = document.createElement("blockquote");
quote.setAttribute(
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
admonition.getAttribute(MARKDOWN_ADMONITION_TYPE_ATTRIBUTE) ?? "note",
);
quote.append(...admonition.childNodes);
admonition.replaceWith(quote);
}
}
function unwrapIncompleteTables(container: HTMLElement): void {
for (const table of container.querySelectorAll("table")) {
if (hasUsableTableColumnContract(table)) {
@@ -6,9 +6,13 @@ export const MARKDOWN_COPY_UNWRAP_ATTRIBUTE = "data-paseo-markdown-unwrap";
export const MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE = "data-paseo-markdown-recognized-link";
export const MARKDOWN_COPY_LIST_START_ATTRIBUTE = "data-paseo-markdown-list-start";
export const MARKDOWN_COPY_LANGUAGE_ATTRIBUTE = "data-paseo-markdown-language";
export const MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE = "data-paseo-markdown-fence-source";
export const MARKDOWN_COPY_ALIGN_ATTRIBUTE = "data-paseo-markdown-align";
export const MARKDOWN_COPY_SRC_ATTRIBUTE = "data-paseo-markdown-src";
export const MARKDOWN_COPY_ALT_ATTRIBUTE = "data-paseo-markdown-alt";
/** Set by the Markdown library's web admonition renderer on the box and on its generated title. */
export const MARKDOWN_ADMONITION_TYPE_ATTRIBUTE = "data-enrm-admonition-type";
export const MARKDOWN_ADMONITION_TITLE_ATTRIBUTE = "data-enrm-admonition-title";
/**
* Trailing line breaks, with any indentation that followed the last one.
@@ -1,17 +1,9 @@
import React, { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
Pressable,
View,
Text,
type StyleProp,
type TextStyle,
type ViewStyle,
} from "react-native";
import { StyleSheet } from "react-native-unistyles";
import React, { useCallback, useMemo, useState } from "react";
import { View, Text, type StyleProp, type TextStyle, type ViewStyle } from "react-native";
import * as Clipboard from "expo-clipboard";
import { Check, Copy } from "lucide-react-native";
import { useTranslation } from "react-i18next";
import type { HighlightToken } from "@getpaseo/highlight";
import { BlockCopyButton } from "@/components/markdown/block-copy-button";
import { isNative, isWeb } from "@/constants/platform";
import { useIsCompactFormFactor } from "@/constants/layout";
import { syntaxTokenStyleFor } from "@/styles/syntax-token-styles";
@@ -85,6 +77,7 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
[renderedCode, language],
);
const { t } = useTranslation();
const isCompact = useIsCompactFormFactor();
const [isHovered, setIsHovered] = useState(false);
const handlePointerEnter = useCallback(() => setIsHovered(true), []);
@@ -93,7 +86,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
// Copy the code without its trailing blank lines. A fence body ends in a newline,
// and ends in more than one when the author left a blank line before the closing
// fence; pasting any of them into a terminal runs the last line.
const getCode = useCallback(() => code.replace(TRAILING_CODE_LINE_BREAKS, ""), [code]);
const copyCode = useCallback(async () => {
const content = code.replace(TRAILING_CODE_LINE_BREAKS, "");
if (!content) return false;
return Clipboard.setStringAsync(content);
}, [code]);
return (
<View
@@ -111,7 +108,11 @@ export const HighlightedCodeBlock = React.memo(function HighlightedCodeBlock({
{renderedCode}
</Text>
)}
<CopyButton getCode={getCode} visible={controlsVisible} />
<BlockCopyButton
onCopy={copyCode}
visible={controlsVisible}
label={t("message.actions.copyCode")}
/>
</View>
);
});
@@ -168,87 +169,3 @@ function splitFenceStyle(inheritedStyles: TextStyle, textStyle: TextStyle): Spli
innerTextStyle: [inheritedStyles, textOnly],
};
}
interface CopyButtonProps {
getCode: () => string;
visible: boolean;
}
const COPIED_RESET_MS = 1500;
const CopyButton = React.memo(function CopyButton({ getCode, visible }: CopyButtonProps) {
const { t } = useTranslation();
const [copied, setCopied] = useState(false);
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
useEffect(
() => () => {
if (resetRef.current) clearTimeout(resetRef.current);
},
[],
);
const handlePress = useCallback(async () => {
const content = getCode();
if (!content) return;
await Clipboard.setStringAsync(content);
setCopied(true);
if (resetRef.current) clearTimeout(resetRef.current);
resetRef.current = setTimeout(() => {
setCopied(false);
resetRef.current = null;
}, COPIED_RESET_MS);
}, [getCode]);
const visibilityStyle = visible
? copyButtonStyles.containerVisible
: copyButtonStyles.containerHidden;
const wrapperStyle = useMemo(
() => [copyButtonStyles.container, visibilityStyle],
[visibilityStyle],
);
return (
<Pressable
onPress={handlePress}
style={wrapperStyle}
pointerEvents={visible ? "auto" : "none"}
accessibilityRole="button"
accessibilityLabel={copied ? t("message.actions.copied") : t("message.actions.copyCode")}
hitSlop={8}
dataSet={markdownCopyDataSet.ignore}
>
{({ hovered }) => {
const iconColor = hovered
? copyButtonStyles.iconHoveredColor.color
: copyButtonStyles.iconColor.color;
return copied ? (
<Check size={14} color={iconColor} />
) : (
<Copy size={14} color={iconColor} />
);
}}
</Pressable>
);
});
const copyButtonStyles = StyleSheet.create((theme) => ({
container: {
position: "absolute",
top: theme.spacing[2],
right: theme.spacing[2],
padding: theme.spacing[1],
},
containerVisible: {
opacity: 1,
},
containerHidden: {
opacity: 0,
},
iconColor: {
color: theme.colors.foregroundMuted,
},
iconHoveredColor: {
color: theme.colors.foreground,
},
}));
@@ -0,0 +1,119 @@
import { flushSync } from "react-dom";
import { createRoot, type Root } from "react-dom/client";
import { within } from "@testing-library/dom";
import { userEvent } from "vitest/browser";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { I18nextProvider } from "react-i18next";
import type { ToastApi } from "@/components/toast-host";
import { ToastApiProvider } from "@/contexts/toast-api-context";
import { i18n } from "@/i18n/i18next";
import { BlockCopyButton } from "./block-copy-button";
const LABEL = "Copy quote";
let errors: string[] = [];
const toast: ToastApi = {
show: () => () => {},
copied: () => {},
error: (message) => errors.push(message),
};
describe("BlockCopyButton", () => {
let root: Root;
let host: HTMLDivElement;
beforeEach(async () => {
await i18n.changeLanguage("en");
errors = [];
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
});
afterEach(() => {
flushSync(() => root.unmount());
host.remove();
});
function render(onCopy: () => Promise<boolean>, visible = true) {
flushSync(() =>
root.render(
<I18nextProvider i18n={i18n}>
<ToastApiProvider api={toast}>
<BlockCopyButton onCopy={onCopy} visible={visible} label={LABEL} />
</ToastApiProvider>
</I18nextProvider>,
),
);
}
function button(name = LABEL): HTMLElement {
return within(host).getByRole("button", { name });
}
it("shows Copied after a write and returns to its label", async () => {
let calls = 0;
render(async () => {
calls += 1;
return true;
});
await userEvent.click(button());
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
await vi.waitFor(() => expect(button()).toBeTruthy(), { timeout: 2500 });
expect(calls).toBe(1);
expect(errors).toEqual([]);
});
it.each([
["resolves false", async () => false],
[
"rejects",
async (): Promise<boolean> => {
throw new Error("Clipboard denied");
},
],
])("tells the user and never shows Copied when the write %s", async (_case, failure) => {
let calls = 0;
render(() => {
calls += 1;
return calls === 1 ? failure() : Promise.resolve(true);
});
await userEvent.click(button());
await vi.waitFor(() => expect(errors).toEqual(["Unable to copy"]));
expect(within(host).queryByRole("button", { name: "Copied" })).toBeNull();
await userEvent.click(button());
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
expect(calls).toBe(2);
});
it("does not write twice while a write is pending", async () => {
let finish!: (written: boolean) => void;
let calls = 0;
render(() => {
calls += 1;
return new Promise<boolean>((resolve) => {
finish = resolve;
});
});
await userEvent.click(button());
await userEvent.click(button());
expect(calls).toBe(1);
finish(true);
await vi.waitFor(() => expect(button("Copied")).toBeTruthy());
expect(calls).toBe(1);
});
it("stays hidden until its block reveals it or it takes keyboard focus", async () => {
render(async () => true, false);
expect(getComputedStyle(button()).opacity).toBe("0");
await userEvent.tab();
expect(document.activeElement).toBe(button());
await vi.waitFor(() => expect(getComputedStyle(button()).opacity).toBe("1"));
});
});
@@ -0,0 +1,109 @@
import { memo, useCallback, useEffect, useRef, useState } from "react";
import { View } from "react-native";
import { Check, Copy } from "lucide-react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { useTranslation } from "react-i18next";
import { markdownCopyDataSet } from "@/assistant-selection-copy/markup";
import { mutedIconColorMapping } from "@/components/ui/icon-color";
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
import { paneContentToolbarIconSize, ToolbarButton } from "@/components/ui/pane-content-toolbar";
import { useIsCompactFormFactor } from "@/constants/layout";
import { useToast } from "@/contexts/toast-api-context";
import type { Theme } from "@/styles/theme";
const ThemedCopy = withUnistyles(Copy, mutedIconColorMapping);
const ThemedCheck = withUnistyles(Check, mutedIconColorMapping);
const COPIED_RESET_MS = 1500;
/** How far the copy glyph sits from the top and trailing edges of its block. */
export function blockCopyGlyphInset(theme: Theme): number {
return theme.spacing[2] + theme.spacing[1];
}
interface BlockCopyButtonProps {
/** Writes the block to the clipboard. Resolves false, or rejects, when nothing was written. */
onCopy: () => Promise<boolean>;
/** The block's own reveal state. Keyboard focus shows the button regardless. */
visible: boolean;
label: string;
}
/**
* The copy control in the top trailing corner of a Markdown block. The block is its
* positioned ancestor.
*/
export const BlockCopyButton = memo(function BlockCopyButton({
onCopy,
visible,
label,
}: BlockCopyButtonProps) {
const { t } = useTranslation();
const toast = useToast();
const compact = useIsCompactFormFactor();
const [copied, setCopied] = useState(false);
const [focused, setFocused] = useState(false);
const writing = useRef(false);
const resetRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const focus = useCallback(() => setFocused(true), []);
const blur = useCallback(() => setFocused(false), []);
useEffect(
() => () => {
if (resetRef.current) clearTimeout(resetRef.current);
},
[],
);
const handlePress = useCallback(async () => {
// A slow clipboard must not queue a second write behind the first.
if (writing.current) return;
writing.current = true;
const written = await onCopy()
.catch(() => false)
.finally(() => {
writing.current = false;
});
if (!written) {
toast.error(t("common.errors.unableToCopy"));
return;
}
setCopied(true);
if (resetRef.current) clearTimeout(resetRef.current);
resetRef.current = setTimeout(() => setCopied(false), COPIED_RESET_MS);
}, [onCopy, t, toast]);
const shown = visible || focused;
const Glyph = copied ? ThemedCheck : ThemedCopy;
return (
<View style={styles.corner(compact)} dataSet={markdownCopyDataSet.ignore}>
<ToolbarButton
compact={compact}
label={copied ? t("message.actions.copied") : label}
onPress={handlePress}
onFocus={focus}
onBlur={blur}
style={shown ? styles.shown : styles.hidden}
>
<Glyph size={paneContentToolbarIconSize(compact)} />
</ToolbarButton>
</View>
);
});
const styles = StyleSheet.create((theme) => ({
// The glyph, not the button frame, sits on the inset; the frame overhangs it.
corner: (compact: boolean) => {
const frameOverhang =
(smallIconButtonChromeFrameSize(compact) - paneContentToolbarIconSize(compact)) / 2;
const inset = blockCopyGlyphInset(theme) - frameOverhang;
return {
position: "absolute" as const,
top: inset,
right: inset,
pointerEvents: "box-none" as const,
};
},
shown: { opacity: 1, pointerEvents: "auto" },
hidden: { opacity: 0, pointerEvents: "none" },
}));
@@ -5,6 +5,10 @@ import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import { ZoomableViewport } from "@/components/zoomable-viewport";
import {
MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE,
MARKDOWN_COPY_LANGUAGE_ATTRIBUTE,
} from "@/assistant-selection-copy/markup";
import type { Theme } from "@/styles/theme";
import type { MarkdownFenceRendererProps } from "./types";
import { MermaidFullscreenViewer } from "./fullscreen-viewer.web";
@@ -81,6 +85,16 @@ function MermaidFenceHostImpl({
[visible],
);
const sourceVisible = !diagramVisible;
// A visible diagram stands in for its fence, so copying the surrounding block takes
// the source from here: the revision on screen, which lags `code` while a streamed
// revision renders. The source view copies as its own code block.
const diagramCopyAttributes =
diagramVisible && visible
? {
[MARKDOWN_COPY_FENCE_SOURCE_ATTRIBUTE]: visible.source,
[MARKDOWN_COPY_LANGUAGE_ATTRIBUTE]: "mermaid",
}
: null;
const viewportStyle = diagramVisible ? diagramStyle : measuringStyle;
return (
@@ -111,7 +125,7 @@ function MermaidFenceHostImpl({
) : null}
</View>
) : null}
<div inert={!diagramVisible} style={boundaryStyle}>
<div inert={!diagramVisible} style={boundaryStyle} {...diagramCopyAttributes}>
<ZoomableViewport
accessibilityLabel={t("message.diagram.diagram")}
actions={actions}
@@ -0,0 +1,71 @@
import { useCallback, useMemo, useRef, useState } from "react";
import { withUnistyles } from "react-native-unistyles";
import type { BlockquoteRendererProps } from "react-native-enriched-markdown";
import { useTranslation } from "react-i18next";
import { createElementClipboardContent } from "@/assistant-selection-copy/content.web";
import { smallIconButtonChromeFrameSize } from "@/components/ui/icon-button-chrome";
import { paneContentToolbarIconSize } from "@/components/ui/pane-content-toolbar";
import { useIsCompactFormFactor } from "@/constants/layout";
import { writeClipboardContent } from "@/utils/rich-clipboard";
import { getDefaultMarkdownClipboardEnvironment } from "@/utils/rich-clipboard-default-environment";
import { BlockCopyButton, blockCopyGlyphInset } from "./block-copy-button";
interface WebBlockquoteProps extends BlockquoteRendererProps {
copyGlyphInset: number;
}
/**
* Room the quote reserves so the control never covers its text. Compact layouts always
* show the control, so it gets a band above the body and the text keeps the full width.
* Wide layouts reveal it on hover, where a band would leave an empty strip above every
* quote, so the text wraps short of it instead.
*/
function copyRoom(compact: boolean, glyphInset: number) {
if (compact) {
return { paddingTop: glyphInset + paneContentToolbarIconSize(compact) + glyphInset };
}
return { paddingRight: smallIconButtonChromeFrameSize(compact) + glyphInset };
}
/** A quote with a control that copies its body, for drafts an agent wrote to be pasted elsewhere. */
export const WebBlockquote = withUnistyles(
function WebBlockquote({ blockquoteProps, children, copyGlyphInset }: WebBlockquoteProps) {
const { t } = useTranslation();
const quote = useRef<HTMLQuoteElement>(null);
const [hovered, setHovered] = useState(false);
const compact = useIsCompactFormFactor();
const enter = useCallback(() => setHovered(true), []);
const leave = useCallback(() => setHovered(false), []);
const style = useMemo(
() => ({
...blockquoteProps.style,
position: "relative" as const,
...copyRoom(compact, copyGlyphInset),
}),
[blockquoteProps.style, compact, copyGlyphInset],
);
const copy = useCallback(async () => {
// Read the rendered body at press time: a streaming quote copies what it shows now.
const content = quote.current && createElementClipboardContent(quote.current);
if (!content) return false;
return writeClipboardContent(content, getDefaultMarkdownClipboardEnvironment());
}, []);
return (
<blockquote
{...blockquoteProps}
ref={quote}
style={style}
onPointerEnter={enter}
onPointerLeave={leave}
>
<BlockCopyButton
onCopy={copy}
visible={hovered || compact}
label={t("message.actions.copyQuote")}
/>
{children}
</blockquote>
);
},
(theme) => ({ copyGlyphInset: blockCopyGlyphInset(theme) }),
);
@@ -14,6 +14,7 @@ import { HighlightedCodeBlock } from "@/components/highlighted-code-block";
import type { Theme } from "@/styles/theme";
import { MermaidFence } from "./fence/mermaid";
import { isRecognizedLink, markdownLinkSource } from "./source";
import { WebBlockquote } from "./quote-block.web";
const ThemedCodeBlock = withUnistyles(HighlightedCodeBlock);
const codeStyle = (theme: Theme) => ({
@@ -111,4 +112,8 @@ const styles = StyleSheet.create((theme) => ({
},
}));
export const WEB_RENDERERS: MarkdownRenderers = { codeBlock: WebCodeBlock, link: WebLink };
export const WEB_RENDERERS: MarkdownRenderers = {
codeBlock: WebCodeBlock,
link: WebLink,
blockquote: WebBlockquote,
};
+55 -8
View File
@@ -12,7 +12,14 @@ import {
type ReactNode,
type RefObject,
} from "react";
import { Dimensions, View, type Role, type StyleProp, type ViewStyle } from "react-native";
import {
Dimensions,
View,
type PointerEvent as ViewPointerEvent,
type Role,
type StyleProp,
type ViewStyle,
} from "react-native";
import { FadeIn, FadeOut } from "react-native-reanimated";
import { StyleSheet } from "react-native-unistyles";
import { Portal } from "@gorhom/portal";
@@ -35,7 +42,7 @@ interface HoverCardContextValue {
setTriggerRef: (node: View | null) => void;
triggerRef: RefObject<View | null>;
contentRef: RefObject<View | null>;
openNow: () => void;
pointerEntered: (event: ViewPointerEvent) => void;
scheduleClose: () => void;
}
@@ -55,21 +62,34 @@ const HoverCardContext = createContext<HoverCardContextValue | null>(null);
*/
export function HoverCard({
disabled = false,
ignoreTouch = false,
children,
}: {
/** Closes the card and keeps it closed, e.g. while its trigger is dragged. */
disabled?: boolean;
/**
* The trigger handles a tap itself, so a touch does not open the card: neither the touch's
* pointerenter nor the focus the tap leaves on the trigger. Opening during a tap changes the
* page under the finger, and iPad Safari then drops the tap.
*/
ignoreTouch?: boolean;
children: ReactNode;
}): ReactNode {
if (!isWeb) return children;
return <WebHoverCard disabled={disabled}>{children}</WebHoverCard>;
return (
<WebHoverCard disabled={disabled} ignoreTouch={ignoreTouch}>
{children}
</WebHoverCard>
);
}
function WebHoverCard({
disabled,
ignoreTouch,
children,
}: {
disabled: boolean;
ignoreTouch: boolean;
children: ReactNode;
}): ReactElement {
const layer = useOverlayLayer("floating");
@@ -79,6 +99,8 @@ function WebHoverCard({
const graceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
// Read when focus arrives: by focusout the element losing focus no longer matches :focus-visible.
const keyboardFocusedRef = useRef(false);
// Whether the latest press was a touch, so with ignoreTouch the focus that tap leaves is ignored.
const touchPressedRef = useRef(false);
const clearGraceTimer = useCallback(() => {
if (graceTimerRef.current) {
@@ -125,6 +147,13 @@ function WebHoverCard({
setOpen(true);
}, [clearGraceTimer, closeNow, disabled, layer]);
const pointerEntered = useCallback(
(event: ViewPointerEvent) => {
if (!(ignoreTouch && event.nativeEvent.pointerType === "touch")) openNow();
},
[ignoreTouch, openNow],
);
useEffect(() => {
if (!open) return;
return () => {
@@ -191,7 +220,7 @@ function WebHoverCard({
const target = event.target as Element;
keyboardFocusedRef.current = target.matches(":focus-visible");
if (trigger.contains(target)) {
openNow();
if (!(ignoreTouch && touchPressedRef.current)) openNow();
} else if ((contentRef.current as unknown as HTMLElement | null)?.contains(target)) {
clearGraceTimer();
}
@@ -208,6 +237,12 @@ function WebHoverCard({
scheduleClose();
}
};
const pointerPressed = (event: PointerEvent) => {
touchPressedRef.current = event.pointerType === "touch";
};
const keyPressedAnywhere = () => {
touchPressedRef.current = false;
};
const activateClosedTrigger = (event: KeyboardEvent) => {
if (
!open &&
@@ -221,19 +256,23 @@ function WebHoverCard({
const scrolled = (event: Event) => {
if ((event.target as Node).contains(trigger)) close();
};
document.addEventListener("pointerdown", pointerPressed, true);
document.addEventListener("keydown", keyPressedAnywhere, true);
document.addEventListener("focusin", focusEntered);
document.addEventListener("focusout", focusLeft);
trigger.addEventListener("keydown", activateClosedTrigger);
document.addEventListener("scroll", scrolled, true);
window.addEventListener("resize", close);
return () => {
document.removeEventListener("pointerdown", pointerPressed, true);
document.removeEventListener("keydown", keyPressedAnywhere, true);
document.removeEventListener("focusin", focusEntered);
document.removeEventListener("focusout", focusLeft);
trigger.removeEventListener("keydown", activateClosedTrigger);
document.removeEventListener("scroll", scrolled, true);
window.removeEventListener("resize", close);
};
}, [clearGraceTimer, keyPressed, open, openNow, scheduleClose]);
}, [clearGraceTimer, ignoreTouch, keyPressed, open, openNow, scheduleClose]);
// While open, the safe zone covers trigger + content + the bridge between
// them. Close only fires when the pointer leaves the safe zone; re-entering
@@ -256,8 +295,16 @@ function WebHoverCard({
useEffect(() => clearGraceTimer, [clearGraceTimer]);
const value = useMemo<HoverCardContextValue>(
() => ({ open, layer, setTriggerRef, triggerRef, contentRef, openNow, scheduleClose }),
[open, layer, setTriggerRef, openNow, scheduleClose],
() => ({
open,
layer,
setTriggerRef,
triggerRef,
contentRef,
pointerEntered,
scheduleClose,
}),
[open, layer, setTriggerRef, pointerEntered, scheduleClose],
);
return (
@@ -290,7 +337,7 @@ export function HoverCardTrigger({
accessibilityRole={focusable ? "button" : undefined}
accessibilityLabel={accessibilityLabel}
collapsable={false}
onPointerEnter={ctx.openNow}
onPointerEnter={ctx.pointerEntered}
onPointerLeave={ctx.scheduleClose}
>
{children}
@@ -64,7 +64,7 @@ export function WorkspaceHoverCard({
}
return (
<HoverCard disabled={isDragging || disabled}>
<HoverCard disabled={isDragging || disabled} ignoreTouch>
<HoverCardTrigger>{children}</HoverCardTrigger>
<HoverCardContent
placement="right"
+1
View File
@@ -345,6 +345,7 @@ export const ar: TranslationResources = {
viewDiagram: "عرض المخطط",
},
actions: {
copyQuote: "نسخ الاقتباس",
copyCode: "نسخ الرمز",
copyTurn: "نسخ بدوره",
copyMessage: "انسخ الرسالة",
+1
View File
@@ -344,6 +344,7 @@ export const en = {
viewDiagram: "View diagram",
},
actions: {
copyQuote: "Copy quote",
copyCode: "Copy code",
copyTurn: "Copy turn",
copyMessage: "Copy message",
+1
View File
@@ -350,6 +350,7 @@ export const es: TranslationResources = {
viewDiagram: "Ver diagrama",
},
actions: {
copyQuote: "Copiar cita",
copyCode: "Copiar código",
copyTurn: "Copiar turno",
copyMessage: "Copiar mensaje",
+1
View File
@@ -350,6 +350,7 @@ export const fr: TranslationResources = {
viewDiagram: "Afficher le diagramme",
},
actions: {
copyQuote: "Copier la citation",
copyCode: "Copier le code",
copyTurn: "Copier l’échange",
copyMessage: "Copier le message",
+1
View File
@@ -350,6 +350,7 @@ export const ja: TranslationResources = {
viewDiagram: "図を表示",
},
actions: {
copyQuote: "引用をコピー",
copyCode: "コードをコピー",
copyTurn: "ターンをコピー",
copyMessage: "メッセージをコピー",
+1
View File
@@ -346,6 +346,7 @@ export const ko: TranslationResources = {
viewDiagram: "다이어그램 보기",
},
actions: {
copyQuote: "인용문 복사",
copyCode: "코드 복사",
copyTurn: "턴 복사",
copyMessage: "메시지 복사",
+1
View File
@@ -349,6 +349,7 @@ export const ptBR: TranslationResources = {
viewDiagram: "Ver diagrama",
},
actions: {
copyQuote: "Copiar citação",
copyCode: "Copiar código",
copyTurn: "Copiar turno",
copyMessage: "Copiar mensagem",
+1
View File
@@ -349,6 +349,7 @@ export const ru: TranslationResources = {
viewDiagram: "Показать диаграмму",
},
actions: {
copyQuote: "Копировать цитату",
copyCode: "Скопировать код",
copyTurn: "Скопировать ответ",
copyMessage: "Копировать сообщение",
+1
View File
@@ -345,6 +345,7 @@ export const zhCN: TranslationResources = {
viewDiagram: "查看图表",
},
actions: {
copyQuote: "复制引用",
copyCode: "复制代码",
copyTurn: "复制回合",
copyMessage: "复制消息",
+45 -2
View File
@@ -5,6 +5,7 @@ import {
createSelectionClipboardContent,
type MarkdownClipboardEnvironment,
type RichClipboardWriter,
writeClipboardContent,
writeMarkdownToRichClipboard,
} from "./rich-clipboard";
@@ -15,9 +16,9 @@ interface RecordingClipboard {
}
function createRecordingClipboard(
options: { supportsHtml?: boolean; richWriteFails?: boolean } = {},
options: { supportsHtml?: boolean; richWriteFails?: boolean; plainWriteResult?: unknown } = {},
): RecordingClipboard {
const { supportsHtml = true, richWriteFails = false } = options;
const { supportsHtml = true, richWriteFails = false, plainWriteResult } = options;
const richWrites: Array<Record<"text/plain" | "text/html", Blob>> = [];
const plainTexts: string[] = [];
@@ -35,6 +36,7 @@ function createRecordingClipboard(
richWriter,
writePlainText: async (text) => {
plainTexts.push(text);
return plainWriteResult;
},
};
@@ -185,3 +187,44 @@ describe("writeMarkdownToRichClipboard", () => {
expect(clipboard.richWrites).toEqual([]);
});
});
describe("writeClipboardContent", () => {
const content = { plainText: "_raw_ draft", html: "<p>\\_raw\\_ draft</p>" };
it("writes both flavors and reports the write", async () => {
const clipboard = createRecordingClipboard();
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
const written = clipboard.richWrites[0];
if (!written) {
throw new Error("Expected rich clipboard data to be written");
}
await expect(written["text/plain"].text()).resolves.toBe(content.plainText);
await expect(written["text/html"].text()).resolves.toBe(content.html);
});
it("falls back to the plain flavor when the rich write fails", async () => {
const clipboard = createRecordingClipboard({ richWriteFails: true });
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(true);
expect(clipboard.plainTexts).toEqual([content.plainText]);
});
it("reports a plain write the host refused", async () => {
const clipboard = createRecordingClipboard({ supportsHtml: false, plainWriteResult: false });
await expect(writeClipboardContent(content, clipboard.environment)).resolves.toBe(false);
});
it("propagates a plain write that throws", async () => {
const environment: MarkdownClipboardEnvironment = {
writePlainText: async () => {
throw new Error("clipboard denied");
},
};
await expect(writeClipboardContent(content, environment)).rejects.toThrow("clipboard denied");
});
});
+14 -3
View File
@@ -86,19 +86,30 @@ export async function writeMarkdownToRichClipboard(
markdown: string,
environment: MarkdownClipboardEnvironment,
): Promise<void> {
await writeClipboardContent(createMarkdownClipboardContent(markdown), environment);
}
/**
* Writes both flavors, or `plainText` alone where the host has no rich clipboard.
* Resolves false when the host refused the write.
*/
export async function writeClipboardContent(
content: MarkdownClipboardContent,
environment: MarkdownClipboardEnvironment,
): Promise<boolean> {
if (environment.richWriter?.supportsHtml()) {
const content = createMarkdownClipboardContent(markdown);
try {
await environment.richWriter.write({
"text/plain": new Blob([content.plainText], { type: "text/plain" }),
"text/html": new Blob([content.html], { type: "text/html" }),
});
return;
return true;
} catch {
// Fall through to the plain-text path. Some webviews expose rich clipboard
// APIs but deny writes depending on focus, permissions, or browser policy.
}
}
await environment.writePlainText(markdown);
// Expo resolves false for a write the host refused, instead of rejecting.
return (await environment.writePlainText(content.plainText)) !== false;
}
@@ -38,7 +38,9 @@ describe("Hub CLI login browser flow", () => {
assert.equal(credential, "paseo_cli_prefix_durable-secret-value");
assert.deepEqual(journey.waits, [5_000, 5_000, 10_000]);
assert.deepEqual(journey.opened, ["https://hub.test/cli-login?code=ABCD-EFGH"]);
assert.deepEqual(journey.instructions, ["https://hub.test/cli-login ABCD-EFGH"]);
assert.deepEqual(journey.instructions, [
"Open https://hub.test/cli-login?code=ABCD-EFGH to approve CLI login (code: ABCD-EFGH)",
]);
});
it("does not open a browser in noninteractive mode", async () => {
@@ -57,7 +59,9 @@ describe("Hub CLI login browser flow", () => {
await journey.authorize();
assert.deepEqual(journey.opened, []);
assert.equal(journey.instructions.length, 1);
assert.deepEqual(journey.instructions, [
"Open https://hub.test/cli-login?code=ABCD-EFGH to approve CLI login (code: ABCD-EFGH)",
]);
});
});
@@ -95,7 +99,7 @@ class LoginJourney {
now: () => this.now,
},
browser: { open: async (url) => void this.opened.push(url) },
instructions: (url, code) => void this.instructions.push(`${url} ${code}`),
instructions: (message) => void this.instructions.push(message),
openBrowser,
});
}
+6 -4
View File
@@ -40,7 +40,7 @@ interface CliLoginFlowOptions {
hub: Pick<HubHttpClient, "startCliAuthorization" | "pollCliAuthorization">;
waiter: LoginWaiter;
browser: BrowserOpener;
instructions(verificationUri: string, userCode: string): void;
instructions(message: string): void;
openBrowser: boolean;
}
@@ -49,7 +49,9 @@ export class CliLoginFlow {
async authorize(origin: string): Promise<string> {
const authorization = await this.options.hub.startCliAuthorization(origin);
this.options.instructions(authorization.verificationUri, authorization.userCode);
this.options.instructions(
`Open ${authorization.verificationUriComplete} to approve CLI login (code: ${authorization.userCode})`,
);
if (this.options.openBrowser) {
await this.options.browser.open(authorization.verificationUriComplete).catch(() => undefined);
}
@@ -84,8 +86,8 @@ export function createCliLoginFlow(hub: HubHttpClient): CliLoginFlow {
now: Date.now,
},
browser: new SystemBrowser(),
instructions(verificationUri, userCode) {
process.stderr.write(`Open ${verificationUri} and enter code ${userCode}\n`);
instructions(message) {
process.stderr.write(`${message}\n`);
},
openBrowser: process.stderr.isTTY === true,
});
@@ -0,0 +1,43 @@
ISC License
Copyright (c) 2026 Lucide Icons and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
---
The following Lucide icons are derived from the Feather project:
airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out
The MIT License (MIT) (for the icons listed above)
Copyright (c) 2013-present Cole Bemis
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -62,6 +62,9 @@ class BlockquoteContainerView(
// Cached markdown source for the "Copy as Markdown" action.
private var cachedMarkdown: String = ""
// Cached markdown of the quote's body, without its own `> ` prefix, for the copy button.
private var cachedBodyMarkdown: String = ""
// Cached plain text for the "Copy" action.
private var cachedPlainText: String = ""
@@ -85,7 +88,15 @@ class BlockquoteContainerView(
private val iconPaint =
Paint(Paint.ANTI_ALIAS_FLAG).apply { style = Paint.Style.FILL }
private fun reservedHeaderHeight(): Int = if (admonitionType != null) ceil(admonitionHeaderReservedHeight(blockquoteStyle)).toInt() else 0
// A plain quote shows the code block's copy control in a header band of the
// same height; an admonition keeps its title band and has no copy control.
private val copyButton =
HeaderCopyButton(context, parentConfig.style.codeBlockStyle) { parentConfig.dynamicProps.copyLabel }.apply {
setOnClickListener { copyBody() }
}
private fun reservedHeaderHeight(): Int =
if (admonitionType != null) ceil(admonitionHeaderReservedHeight(blockquoteStyle)).toInt() else copyButton.bandHeight
// Only the outermost quote carries vertical margins; a quote nested directly
// inside another quote is separated by the parent's padding alone (matches the
@@ -108,7 +119,12 @@ class BlockquoteContainerView(
init {
setWillNotDraw(false)
setPadding(leftInset, verticalInset, rightInset, verticalInset)
// The copy control sits in the header band, which top padding reserves.
clipToPadding = false
setPadding(leftInset, verticalInset + reservedHeaderHeight(), rightInset, verticalInset)
// applySegments keeps segment views at the front of the child array, so the
// control stays the last child, drawn and hit-tested above the body.
addView(copyButton)
segmentViewFactory = ChildFactory()
trailingMarginEnabled = false
isLongClickable = true
@@ -125,6 +141,9 @@ class BlockquoteContainerView(
// Reserve the header band above the body by enlarging the top padding.
setPadding(leftInset, verticalInset + reservedHeaderHeight(), rightInset, verticalInset)
copyButton.visibility = if (admonitionType == null) View.VISIBLE else View.GONE
cachedBodyMarkdown = MarkdownASTSerializer.serializeBlockquoteBody(node)
copyButton.isEnabled = cachedBodyMarkdown.isNotEmpty()
cachedMarkdown = MarkdownASTSerializer.serializeBlockquote(node)
cachedPlainText = MarkdownASTSerializer.plainText(node)
@@ -143,6 +162,12 @@ class BlockquoteContainerView(
requestLayout()
}
private fun copyBody() {
if (cachedBodyMarkdown.isEmpty()) return
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
clipboard.setPrimaryClip(ClipData.newPlainText("Blockquote", cachedBodyMarkdown))
}
private fun showContextMenu(anchor: View): Boolean {
if (!parentConfig.dynamicProps.enableBlockContextMenu) return false
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
@@ -167,6 +192,7 @@ class BlockquoteContainerView(
) {
val measuredWidth = MeasureSpec.getSize(widthSpec)
measureSegmentChildren(measuredWidth)
if (copyButton.visibility != View.GONE) copyButton.measureInBand()
setMeasuredDimension(measuredWidth, computeSegmentsTotalHeight())
}
@@ -178,6 +204,7 @@ class BlockquoteContainerView(
b: Int,
) {
layoutSegments()
if (copyButton.visibility != View.GONE) copyButton.layoutInBand(width)
}
override fun onDraw(canvas: Canvas) {
@@ -368,7 +395,7 @@ class BlockquoteContainerView(
if (node.type == MarkdownASTNode.NodeType.Admonition) {
ceil(admonitionHeaderReservedHeight(style))
} else {
0f
CodeBlockContainerView.headerHeight(config.codeBlockStyle).toFloat()
}
val innerWidth = (width - leftInset - rightInset).coerceAtLeast(1f)
@@ -4,11 +4,8 @@ import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.graphics.drawable.GradientDrawable
import android.os.Build
import android.text.Layout
@@ -21,8 +18,6 @@ import android.view.GestureDetector
import android.view.MotionEvent
import android.view.View
import android.widget.FrameLayout
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatTextView
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
import com.swmansion.enriched.markdown.spans.LineHeightSpan
@@ -34,7 +29,6 @@ import com.swmansion.enriched.markdown.utils.text.extensions.applyCodeBlockTextS
import com.swmansion.enriched.markdown.utils.text.span.SPAN_FLAGS_EXCLUSIVE_EXCLUSIVE
import com.swmansion.enriched.markdown.views.ClaimingHorizontalScrollView
import com.swmansion.enriched.markdown.views.ContextMenuPopup
import com.swmansion.enriched.markdown.views.CopyGlyph
import kotlin.math.ceil
import kotlin.math.roundToInt
@@ -125,20 +119,8 @@ class CodeBlockContainerView(
setTextColor(secondaryColor(codeBlockStyle.color))
}
// contentDescription reads the shared label live so a runtime label change is
// reflected for TalkBack without a push (mirrors the live block-menu reads).
private val copyButton =
object : AppCompatImageButton(context) {
override fun getContentDescription(): CharSequence = dynamicProps.copyLabel
}.apply {
background = null
scaleType = ImageView.ScaleType.CENTER
setImageDrawable(
CopyIconDrawable(
secondaryColor(codeBlockStyle.color),
ceil(codeBlockStyle.fontSize * HEADER_ICON_SCALE).toInt(),
),
)
HeaderCopyButton(context, codeBlockStyle) { dynamicProps.copyLabel }.apply {
setOnClickListener { copyCode() }
}
@@ -210,10 +192,7 @@ class CodeBlockContainerView(
MeasureSpec.makeMeasureSpec((measuredWidth - borderW * 2).coerceAtLeast(0), MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
)
copyButton.measure(
MeasureSpec.makeMeasureSpec(headerH, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(headerH, MeasureSpec.EXACTLY),
)
copyButton.measureInBand()
val labelMaxWidth = (measuredWidth - inset * 2 - headerH).coerceAtLeast(0)
languageView.measure(
MeasureSpec.makeMeasureSpec(labelMaxWidth, MeasureSpec.AT_MOST),
@@ -230,8 +209,7 @@ class CodeBlockContainerView(
bottom: Int,
) {
val width = right - left
// The divider sits halfway into the code pane's top inset.
val headerCenterY = (headerH + inset / 2f) / 2f
val headerCenterY = copyButton.bandCenterY
val labelTop = (headerCenterY - languageView.measuredHeight / 2f).roundToInt()
languageView.layout(
inset,
@@ -240,16 +218,7 @@ class CodeBlockContainerView(
labelTop + languageView.measuredHeight,
)
val iconWidth = copyButton.drawable?.intrinsicWidth ?: copyButton.measuredWidth
val iconSlack = ((copyButton.measuredWidth - iconWidth) / 2).coerceAtLeast(0)
val buttonLeft = (width - inset - copyButton.measuredWidth + iconSlack).coerceAtLeast(0)
val buttonTop = (headerCenterY - copyButton.measuredHeight / 2f).roundToInt().coerceAtLeast(0)
copyButton.layout(
buttonLeft,
buttonTop,
buttonLeft + copyButton.measuredWidth,
buttonTop + copyButton.measuredHeight,
)
copyButton.layoutInBand(width)
scrollView.layout(borderW, headerH, width - borderW, bottom - top - borderW)
}
@@ -305,63 +274,22 @@ class CodeBlockContainerView(
clipboard.setPrimaryClip(ClipData.newPlainText("Code", text))
}
private class CopyIconDrawable(
color: Int,
private val size: Int,
) : Drawable() {
private val paint =
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeWidth = size / 20f
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
this.color = color
}
private val glyph = CopyGlyph()
override fun draw(canvas: Canvas) {
glyph.draw(canvas, bounds.width().toFloat(), paint)
}
override fun getIntrinsicWidth() = size
override fun getIntrinsicHeight() = size
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
paint.colorFilter = colorFilter
}
@Deprecated("Deprecated in Java")
override fun getOpacity() = PixelFormat.TRANSLUCENT
}
companion object {
private const val HEADER_LABEL_SCALE = 0.85f
// Drawable box for the copy glyph, as a multiple of the code font size.
// iOS sizes the SF Symbol by point size (kENRMHeaderIconScale = 0.72) but
// the symbol renders roughly half again as tall as its point size; this box
// is scaled up to land the drawn glyph at the same on-screen size.
private const val HEADER_ICON_SCALE = 1.08f
private val headerTypeface: Typeface = Typeface.create("sans-serif-medium", Typeface.NORMAL)
private fun secondaryColor(color: Int): Int = (color and 0x00FFFFFF) or (0x99 shl 24)
internal fun secondaryColor(color: Int): Int = (color and 0x00FFFFFF) or (0x99 shl 24)
private fun dividerColor(color: Int): Int = (color and 0x00FFFFFF) or (0x33 shl 24)
private fun contentInset(style: CodeBlockStyle): Int = ceil(style.padding + style.borderWidth).toInt()
internal fun contentInset(style: CodeBlockStyle): Int = ceil(style.padding + style.borderWidth).toInt()
private fun borderPx(style: CodeBlockStyle): Int = ceil(style.borderWidth).toInt()
// Header is the top content inset plus one label line; the code text
// view's own top inset then forms the single gap below the label.
private fun headerHeight(style: CodeBlockStyle): Int {
internal fun headerHeight(style: CodeBlockStyle): Int {
val paint =
TextPaint(Paint.ANTI_ALIAS_FLAG).apply {
textSize = style.fontSize * HEADER_LABEL_SCALE
@@ -0,0 +1,101 @@
package com.swmansion.enriched.markdown.segments
import android.content.Context
import android.graphics.Canvas
import android.graphics.ColorFilter
import android.graphics.Paint
import android.graphics.PixelFormat
import android.graphics.drawable.Drawable
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatImageButton
import com.swmansion.enriched.markdown.styles.CodeBlockStyle
import com.swmansion.enriched.markdown.views.CopyGlyph
import kotlin.math.ceil
import kotlin.math.roundToInt
/**
* The copy control at the trailing edge of a block's header band. Code blocks
* and quotes share it, so the band height, hit box, glyph and placement stay
* the same on both. The band is the code block header: one label line above
* the content inset.
*/
internal class HeaderCopyButton(
context: Context,
style: CodeBlockStyle,
private val label: () -> CharSequence,
) : AppCompatImageButton(context) {
/** Height of the band, and the side of the button's square hit box. */
val bandHeight: Int = CodeBlockContainerView.headerHeight(style)
private val inset: Int = CodeBlockContainerView.contentInset(style)
/** Vertical center of the band's content; the divider sits halfway into the inset below it. */
val bandCenterY: Float = (bandHeight + inset / 2f) / 2f
init {
background = null
scaleType = ImageView.ScaleType.CENTER
setImageDrawable(
CopyIconDrawable(
CodeBlockContainerView.secondaryColor(style.color),
ceil(style.fontSize * ICON_SCALE).toInt(),
),
)
}
// Read live so a runtime label change reaches TalkBack without a push.
override fun getContentDescription(): CharSequence = label()
fun measureInBand() {
val spec = MeasureSpec.makeMeasureSpec(bandHeight, MeasureSpec.EXACTLY)
measure(spec, spec)
}
/** Puts the glyph's trailing edge on the container's content inset. */
fun layoutInBand(containerWidth: Int) {
val iconWidth = drawable?.intrinsicWidth ?: bandHeight
val iconSlack = ((bandHeight - iconWidth) / 2).coerceAtLeast(0)
val left = (containerWidth - inset - bandHeight + iconSlack).coerceAtLeast(0)
val top = (bandCenterY - bandHeight / 2f).roundToInt().coerceAtLeast(0)
layout(left, top, left + bandHeight, top + bandHeight)
}
private class CopyIconDrawable(
color: Int,
private val size: Int,
) : Drawable() {
private val paint =
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
this.color = color
}
private val glyph = CopyGlyph()
override fun draw(canvas: Canvas) {
glyph.draw(canvas, bounds.width().toFloat(), paint)
}
override fun getIntrinsicWidth() = size
override fun getIntrinsicHeight() = size
override fun setAlpha(alpha: Int) {
paint.alpha = alpha
}
override fun setColorFilter(colorFilter: ColorFilter?) {
paint.colorFilter = colorFilter
}
@Deprecated("Deprecated in Java")
override fun getOpacity() = PixelFormat.TRANSLUCENT
}
private companion object {
// Glyph box as a multiple of the code font size; iOS uses the same scale.
const val ICON_SCALE = 1.08f
}
}
@@ -42,7 +42,10 @@ object CodeBlockNode {
language: String?,
fenceChar: String,
): String {
val fence = fenceChar.repeat(3)
// A fence must be longer than any run of its character in the code, or an inner
// fence (a Markdown example) closes the block early.
val longestRun = Regex("${Regex.escape(fenceChar)}+").findAll(code).maxOfOrNull { it.value.length } ?: 0
val fence = fenceChar.repeat(maxOf(3, longestRun + 1))
return "$fence${language.orEmpty()}\n$code\n$fence"
}
@@ -20,6 +20,12 @@ object MarkdownASTSerializer {
return buffer.toString()
}
/**
* Serializes the blocks inside a Blockquote back to markdown, without the
* quote's own `> ` prefix. A quote nested inside keeps its prefix.
*/
fun serializeBlockquoteBody(node: MarkdownASTNode): String = serializeBlockChildren(node).trimEnd('\n')
/**
* Serializes a Blockquote or Admonition node back to markdown, including
* the `> ` prefix on every line and `> [!TYPE]` header for admonitions.
@@ -31,8 +37,7 @@ object MarkdownASTSerializer {
val type = node.getAttribute("admonitionType")?.takeIf { it.isNotEmpty() } ?: "note"
sb.append("> [!${type.uppercase(java.util.Locale.ROOT)}]\n")
}
val body = serializeBlockChildren(node)
for (line in body.trimEnd('\n').split("\n")) {
for (line in serializeBlockquoteBody(node).split("\n")) {
sb.append("> ")
sb.append(line)
sb.append("\n")
@@ -220,6 +225,9 @@ object MarkdownASTSerializer {
lines.forEachIndexed { lineIdx, line ->
if (lineIdx == 0) {
buffer.append(prefix)
if (item.getAttribute("isTask") == "true") {
buffer.append(if (item.getAttribute("taskChecked") == "true") "[x] " else "[ ] ")
}
} else {
buffer.append(" ".repeat(prefix.length))
}
@@ -185,8 +185,8 @@ object ContextMenuPopup {
private val copyGlyph = CopyGlyph()
// COPY mirrors SF Symbol doc.on.doc, DOCUMENT mirrors doc.text; the copy
// glyph is shared with the header button in CodeBlockContainerView.
// COPY draws Lucide's Copy icon, DOCUMENT mirrors SF Symbol doc.text; the
// copy glyph is shared with HeaderCopyButton.
override fun draw(canvas: Canvas) {
val u = bounds.width() / 24f
if (icon == Icon.COPY) {
@@ -3,40 +3,23 @@ package com.swmansion.enriched.markdown.views
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.RectF
/**
* Draws the copy glyph so Android matches the SF Symbol doc.on.doc rendered on
* iOS: two portrait document pages with a folded (dog-eared) top-right corner,
* a front page in the lower-left laid over a back page in the upper-right.
*
* The back page is punched out where the front page (plus a hairline of
* clearance) covers it, so the front reads as sitting on top exactly as the SF
* Symbol does, instead of both outlines crossing. The clear is done inside an
* offscreen layer so the punched region reveals whatever background the drawable
* sits on, without the glyph needing to know that color.
*
* One instance is held per drawable rather than shared: the paths and clear
* paint are reused across draws to keep draw() allocation-free, and two drawables
* of different sizes must not share those buffers. All coordinates use a 24-unit
* grid scaled to the drawable width, matching the grid the iOS symbol is authored
* on.
* Lucide's Copy icon, the glyph the app's own copy controls use. The outline is
* authored on Lucide's 24-unit grid with its 2-unit stroke and scaled to the
* drawable width. Copyright Lucide Icons and Contributors (ISC); see COPY-ICON-LICENSE.
*/
internal class CopyGlyph {
private val back = Path()
private val front = Path()
private val backFold = Path()
private val frontFold = Path()
// Color and colorFilter are irrelevant under PorterDuff.CLEAR; only the
// widened stroke (set per draw) matters, so this is configured once.
private val clearPaint =
Paint(Paint.ANTI_ALIAS_FLAG).apply {
style = Paint.Style.FILL_AND_STROKE
strokeJoin = Paint.Join.ROUND
strokeCap = Paint.Cap.ROUND
xfermode = PorterDuffXfermode(PorterDuff.Mode.CLEAR)
private val outline =
Path().apply {
addRoundRect(RectF(8f, 8f, 22f, 22f), 2f, 2f, Path.Direction.CW)
moveTo(4f, 16f)
cubicTo(2.9f, 16f, 2f, 15.1f, 2f, 14f)
lineTo(2f, 4f)
cubicTo(2f, 2.9f, 2.9f, 2f, 4f, 2f)
lineTo(14f, 2f)
cubicTo(15.1f, 2f, 16f, 2.9f, 16f, 4f)
}
fun draw(
@@ -44,58 +27,12 @@ internal class CopyGlyph {
width: Float,
stroke: Paint,
) {
val u = width / 24f
val fold = 4f * u
val corner = 2f * u
buildPage(back, 9 * u, 1 * u, 20 * u, 17 * u, fold, corner)
buildPage(front, 3 * u, 7 * u, 14 * u, 23 * u, fold, corner)
buildFold(backFold, 20 * u, 1 * u, fold)
buildFold(frontFold, 14 * u, 7 * u, fold)
clearPaint.strokeWidth = stroke.strokeWidth * 3f
val saved = canvas.saveLayer(0f, 0f, width, width, null)
canvas.drawPath(back, stroke)
canvas.drawPath(backFold, stroke)
canvas.drawPath(front, clearPaint)
canvas.drawPath(front, stroke)
canvas.drawPath(frontFold, stroke)
val saved = canvas.save()
canvas.scale(width / 24f, width / 24f)
val callerStrokeWidth = stroke.strokeWidth
stroke.strokeWidth = 2f
canvas.drawPath(outline, stroke)
stroke.strokeWidth = callerStrokeWidth
canvas.restoreToCount(saved)
}
// A page outline whose top-right corner is cut back by fold, with the other
// three corners rounded by corner.
private fun buildPage(
path: Path,
l: Float,
t: Float,
r: Float,
b: Float,
fold: Float,
corner: Float,
) {
path.rewind()
path.moveTo(l, t + corner)
path.quadTo(l, t, l + corner, t)
path.lineTo(r - fold, t)
path.lineTo(r, t + fold)
path.lineTo(r, b - corner)
path.quadTo(r, b, r - corner, b)
path.lineTo(l + corner, b)
path.quadTo(l, b, l, b - corner)
path.close()
}
// The two inner edges of the folded-over corner, at the page's top-right.
private fun buildFold(
path: Path,
r: Float,
t: Float,
fold: Float,
) {
path.rewind()
path.moveTo(r - fold, t)
path.lineTo(r - fold, t + fold)
path.lineTo(r, t + fold)
}
}
@@ -0,0 +1,246 @@
package com.swmansion.enriched.markdown
import android.content.ClipboardManager
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Canvas
import android.graphics.Color
import android.view.ContextThemeWrapper
import android.view.View
import android.view.View.MeasureSpec
import android.widget.ImageButton
import com.facebook.react.bridge.JavaOnlyArray
import com.facebook.react.bridge.JavaOnlyMap
import com.facebook.react.uimanager.DisplayMetricsHolder
import com.swmansion.enriched.markdown.accessibility.AccessibilityLabels
import com.swmansion.enriched.markdown.parser.MarkdownASTNode
import com.swmansion.enriched.markdown.parser.MarkdownASTNode.NodeType
import com.swmansion.enriched.markdown.segments.BlockquoteContainerView
import com.swmansion.enriched.markdown.segments.DynamicBlockProps
import com.swmansion.enriched.markdown.segments.SegmentViewConfig
import com.swmansion.enriched.markdown.styles.StyleConfig
import com.swmansion.enriched.markdown.test.TestAstFactory.listItem
import com.swmansion.enriched.markdown.test.TestAstFactory.paragraph
import com.swmansion.enriched.markdown.test.TestAstFactory.taskListItem
import com.swmansion.enriched.markdown.test.TestAstFactory.text
import com.swmansion.enriched.markdown.test.TestAstFactory.unorderedList
import com.swmansion.enriched.markdown.utils.text.view.SelectionMenuConfig
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.RuntimeEnvironment
import org.robolectric.annotation.Config
import org.robolectric.annotation.GraphicsMode
/** The copy control on a quote: what it copies, and where it shows. */
@RunWith(RobolectricTestRunner::class)
@GraphicsMode(GraphicsMode.Mode.NATIVE)
@Config(manifest = Config.NONE, sdk = [34])
class BlockquoteCopyTest {
private val context: Context =
ContextThemeWrapper(RuntimeEnvironment.getApplication(), androidx.appcompat.R.style.Theme_AppCompat)
private fun quoteView(): BlockquoteContainerView {
DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(context)
// No border or background, so the copy glyph is the only thing a quote paints above its text.
val element =
JavaOnlyMap.of(
"fontFamily", "",
"fontWeight", "normal",
"fontStyle", "normal",
"fontSize", 16.0,
"lineHeight", 22.0,
"color", Color.BLACK.toDouble(),
"backgroundColor", 0.0,
"borderColor", 0.0,
"borderWidth", 0.0,
"borderRadius", 0.0,
"padding", 8.0,
"gapWidth", 8.0,
"marginTop", 0.0,
"marginBottom", 0.0,
"marginLeft", 20.0,
"itemSpacing", 4.0,
"bulletColor", Color.BLACK.toDouble(),
"bulletSize", 6.0,
"markerMinWidth", 0.0,
"markerColor", Color.BLACK.toDouble(),
"markerFontWeight", "normal",
"textAlign", "left",
"underline", false,
"checkedColor", 0.0,
"checkmarkColor", 0.0,
"checkedTextColor", 0.0,
"checkboxSize", 18.0,
"checkboxBorderRadius", 2.0,
"checkedStrikethrough", false,
"particles", JavaOnlyMap.of("density", 1.0, "speed", 1.0),
"solid", JavaOnlyMap.of("borderRadius", 0.0),
"fontScale", 0.7,
"baselineOffsetScale", 0.3,
)
val styles = JavaOnlyMap()
ELEMENTS.forEach { styles.putMap(it, element) }
styles.putArray("linkVariants", JavaOnlyArray())
val style = StyleConfig(styles, context, false, 1f)
val config =
SegmentViewConfig(
context = context,
style = style,
allowFontScaling = false,
maxFontSizeMultiplier = 1f,
accessibilityLabels = AccessibilityLabels(),
selectionMenuConfig = SelectionMenuConfig(),
textBreakStrategy = "simple",
selectable = true,
selectionColor = null,
selectionHandleColor = null,
contextMenuItemTexts = emptyList(),
dynamicProps = DynamicBlockProps().apply { copyLabel = "Copy" },
onLinkPress = null,
onLinkLongPress = null,
onTaskListItemPress = null,
onContextMenuItemPress = null,
)
return BlockquoteContainerView(context, config)
}
private fun node(
type: NodeType,
vararg children: MarkdownASTNode,
attributes: Map<String, String> = emptyMap(),
) = MarkdownASTNode(type, attributes = attributes, children = children.toList())
private fun quote(vararg children: MarkdownASTNode) = node(NodeType.Blockquote, *children)
private fun BlockquoteContainerView.copyButton(): ImageButton =
(0 until childCount).map { getChildAt(it) }.filterIsInstance<ImageButton>().single()
private fun BlockquoteContainerView.layoutAt(width: Int) {
measure(
MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
)
layout(0, 0, measuredWidth, measuredHeight)
}
private fun clipboardText(): String? {
val clipboard = context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
return clipboard.primaryClip?.getItemAt(0)?.text?.toString()
}
@Test fun copyButtonCopiesTheQuoteBodyWithItsFormatting() {
val view = quoteView()
view.applyBlockquoteNode(
quote(
paragraph(
node(NodeType.Strong, text("Hello")),
text(" team. See "),
node(NodeType.Link, text("the PR"), attributes = mapOf("url" to "https://example.com/pr")),
text(" - it's ready!"),
),
quote(paragraph(text("Nested reply"))),
unorderedList(
taskListItem(true, paragraph(text("Done"))),
taskListItem(false, paragraph(text("Pending"))),
listItem(paragraph(text("Plain"))),
),
),
)
assertEquals("Copy", view.copyButton().contentDescription)
view.copyButton().performClick()
// Prose punctuation stays as written: a plain-text target shows backslashes literally.
assertEquals(
"**Hello** team. See [the PR](https://example.com/pr) - it's ready!\n\n" +
"> Nested reply\n\n" +
"- [x] Done\n- [ ] Pending\n- Plain",
clipboardText(),
)
}
@Test fun copyButtonCopiesTheLatestStreamedBody() {
val view = quoteView()
view.applyBlockquoteNode(quote(paragraph(text("First draft"))))
view.applyBlockquoteNode(quote(paragraph(text("Second draft")), paragraph(text("With more"))))
view.copyButton().performClick()
assertEquals("Second draft\n\nWith more", clipboardText())
}
@Test fun codeBlockWithAnInnerFenceStaysOneBlock() {
val view = quoteView()
view.applyBlockquoteNode(
quote(
node(
NodeType.CodeBlock,
text("```js\nrun()\n```\n"),
attributes = mapOf("language" to "markdown", "fenceChar" to "`"),
),
),
)
view.copyButton().performClick()
assertEquals("````markdown\n```js\nrun()\n```\n````", clipboardText())
}
@Test fun nestedQuoteCopiesOnlyItsOwnBody() {
val view = quoteView()
view.applyBlockquoteNode(quote(paragraph(text("Outer")), quote(paragraph(text("Inner")))))
val nested = (0 until view.childCount).map { view.getChildAt(it) }.filterIsInstance<BlockquoteContainerView>().single()
nested.copyButton().performClick()
assertEquals("Inner", clipboardText())
}
@Test fun admonitionHasNoCopyButton() {
val view = quoteView()
view.applyBlockquoteNode(
node(NodeType.Admonition, paragraph(text("Careful")), attributes = mapOf("admonitionType" to "warning")),
)
assertEquals(View.GONE, view.copyButton().visibility)
}
@Test fun copyGlyphPaintsInsideTheHeaderBandAboveTheBody() {
val view = quoteView()
view.applyBlockquoteNode(quote(paragraph(text("Body"))))
view.layoutAt(320)
val button = view.copyButton()
val body = view.getChildAt(0)
assertTrue("The control sits above the body, not over it", button.bottom <= body.top)
assertTrue("The control stays inside the quote", button.left >= 0 && button.right <= view.width && button.top >= 0)
val bitmap = Bitmap.createBitmap(view.width, view.height, Bitmap.Config.ARGB_8888)
view.draw(Canvas(bitmap))
val band = IntArray(view.width * body.top)
bitmap.getPixels(band, 0, view.width, 0, 0, view.width, body.top)
bitmap.recycle()
assertTrue("The copy glyph must paint in the header band", band.any { Color.alpha(it) > 0 })
}
@Test fun emptyQuoteDisablesCopy() {
val view = quoteView()
view.applyBlockquoteNode(quote())
assertFalse(view.copyButton().isEnabled)
}
private companion object {
// Every element style the JS side sends; StyleConfig rejects a map that lacks one it reads.
val ELEMENTS =
listOf(
"paragraph", "h1", "h2", "h3", "h4", "h5", "h6", "strong", "em", "strikethrough", "underline", "link",
"code", "blockquote", "list", "codeBlock", "thematicBreak", "image", "inlineImage", "video", "table",
"taskList", "math", "inlineMath", "spoiler", "superscript", "subscript", "highlight",
)
}
}
@@ -80,11 +80,12 @@ static CGFloat ENRMAdmonitionHeaderToBodyGap(StyleConfig *config)
return round(config.blockquoteFontSize * 0.4);
}
// Vertical space reserved above the body for the header (0 for a plain quote).
static CGFloat ENRMAdmonitionHeaderReservedHeight(StyleConfig *config, BOOL isAdmonition)
// Vertical space reserved above the body: the copy control's header band for a
// plain quote, the title band for an admonition.
static CGFloat ENRMBlockquoteHeaderReservedHeight(StyleConfig *config, BOOL isAdmonition)
{
if (!isAdmonition) {
return 0;
return [ENRMCodeBlockContainerView headerCopyBandHeightForConfig:config];
}
return ENRMAdmonitionHeaderContentHeight(config) + ENRMAdmonitionHeaderToBodyGap(config);
}
@@ -93,7 +94,7 @@ static UIEdgeInsets ENRMBlockquoteContentInsetsForNode(StyleConfig *config, BOOL
{
CGFloat padding = config.blockquotePadding;
CGFloat left = ceil(config.blockquoteBorderWidth + config.blockquoteGapWidth + padding);
CGFloat top = ceil(padding + ENRMAdmonitionHeaderReservedHeight(config, isAdmonition));
CGFloat top = ceil(padding + ENRMBlockquoteHeaderReservedHeight(config, isAdmonition));
CGFloat vertical = ceil(padding);
CGFloat right = ceil(padding);
return UIEdgeInsetsMake(top, left, vertical, right);
@@ -112,6 +113,10 @@ static UIEdgeInsets ENRMBlockquoteContentInsets(StyleConfig *config)
@property (nonatomic, copy, nullable) NSString *admonitionType;
@property (nonatomic, copy) NSString *cachedMarkdown;
@property (nonatomic, copy) NSString *cachedPlainText;
// The quote's body without its own `> ` prefix, for the copy button.
@property (nonatomic, copy) NSString *cachedBodyMarkdown;
// Shown in the header band of a plain quote; hidden for an admonition.
@property (nonatomic, strong) ENRMHeaderCopyButton *headerCopyButton;
@end
#if !TARGET_OS_OSX
@@ -139,6 +144,11 @@ static UIEdgeInsets ENRMBlockquoteContentInsets(StyleConfig *config)
UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self];
[self addInteraction:contextMenu];
#endif
_cachedBodyMarkdown = @"";
_headerCopyButton = [ENRMCodeBlockContainerView headerCopyButtonForConfig:config
target:self
action:@selector(copyBodyToPasteboard)];
[self addSubview:_headerCopyButton];
self.segmentViewRegistry = [self buildChildRegistry];
}
return self;
@@ -148,18 +158,50 @@ static UIEdgeInsets ENRMBlockquoteContentInsets(StyleConfig *config)
{
self.admonitionType = ENRMAdmonitionTypeForNode(node);
self.contentInsets = ENRMBlockquoteContentInsetsForNode(self.config, self.admonitionType != nil);
self.cachedBodyMarkdown = markdownFromBlockquoteBody(node);
self.headerCopyButton.hidden = self.admonitionType != nil;
self.headerCopyButton.enabled = self.cachedBodyMarkdown.length > 0;
// The host sets dynamicProps after init, so read the label on each content update.
self.headerCopyButton.accessibilityLabel = self.dynamicProps.menuCopyLabel;
self.cachedMarkdown = markdownFromBlockquoteNode(node);
self.cachedPlainText = plainTextFromASTNode(node);
NSArray<ENRMRenderedSegment *> *rendered =
ENRMRenderBlockquoteChildren(node, self.config, self.allowFontScaling, self.lineBreakStrategy);
[self applySegments:rendered reset:NO];
#if !TARGET_OS_OSX
// Segment views are added after the control; keep it above them for touches.
[self bringSubviewToFront:self.headerCopyButton];
[self setNeedsDisplay];
#else
self.needsDisplay = YES;
#endif
}
#if !TARGET_OS_OSX
- (void)layoutSubviews
{
[super layoutSubviews];
[ENRMCodeBlockContainerView layoutHeaderCopyButton:self.headerCopyButton
width:self.bounds.size.width
config:self.config];
}
#else
- (void)layout
{
[super layout];
[ENRMCodeBlockContainerView layoutHeaderCopyButton:self.headerCopyButton
width:self.bounds.size.width
config:self.config];
}
#endif
- (void)copyBodyToPasteboard
{
if (self.cachedBodyMarkdown.length > 0) {
copyStringToPasteboard(self.cachedBodyMarkdown);
}
}
- (void)setAccessibilityLabels:(ENRMAccessibilityLabels *)accessibilityLabels
{
if (_accessibilityLabels == accessibilityLabels) {
@@ -7,6 +7,12 @@
NS_ASSUME_NONNULL_BEGIN
#if !TARGET_OS_OSX
typedef UIButton ENRMHeaderCopyButton;
#else
typedef NSButton ENRMHeaderCopyButton;
#endif
typedef void (^ENRMCodeBlockCopyBlock)(NSString *code, NSString *language);
typedef void (^ENRMCodeBlockPressBlock)(NSString *code, NSString *language);
@@ -14,6 +20,12 @@ typedef void (^ENRMCodeBlockPressBlock)(NSString *code, NSString *language);
- (instancetype)initWithConfig:(StyleConfig *)config;
// The header band and its copy control. Quotes show the same control, so the band
// height, hit box, glyph and placement live here for both.
+ (CGFloat)headerCopyBandHeightForConfig:(StyleConfig *)config;
+ (ENRMHeaderCopyButton *)headerCopyButtonForConfig:(StyleConfig *)config target:(id)target action:(SEL)action;
+ (void)layoutHeaderCopyButton:(ENRMHeaderCopyButton *)button width:(CGFloat)width config:(StyleConfig *)config;
- (void)applyCodeBlockNode:(MarkdownASTNode *)node;
- (CGFloat)measureHeight:(CGFloat)maxWidth;
@@ -22,12 +22,34 @@
// lines never wrap, the height is independent of the available width.
static const CGFloat kENRMHeaderLabelScale = 0.85;
// The copy glyph reads cleaner a touch smaller than the language label and at a
// regular (not medium) weight; sized independently so the two never couple.
static const CGFloat kENRMHeaderIconScale = 0.72;
// The copy glyph's box as a multiple of the code font size; Android uses the same
// scale. Sized independently of the language label so the two never couple.
static const CGFloat kENRMHeaderIconScale = 1.08;
static const CGFloat kENRMHeaderSecondaryAlpha = 0.6;
static const CGFloat kENRMHeaderDividerAlpha = 0.2;
// Lucide's Copy icon, the glyph the app's own copy controls use, on its 24-unit
// grid with its 2-unit stroke. Copyright Lucide Icons and Contributors (ISC); see COPY-ICON-LICENSE.
static void ENRMDrawCopyIcon(CGContextRef context, CGFloat size)
{
CGContextScaleCTM(context, size / 24.0, size / 24.0);
CGContextSetLineWidth(context, 2);
CGContextSetLineCap(context, kCGLineCapRound);
CGContextSetLineJoin(context, kCGLineJoinRound);
CGContextSetRGBStrokeColor(context, 0, 0, 0, 1);
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddRoundedRect(path, NULL, CGRectMake(8, 8, 14, 14), 2, 2);
CGPathMoveToPoint(path, NULL, 4, 16);
CGPathAddCurveToPoint(path, NULL, 2.9, 16, 2, 15.1, 2, 14);
CGPathAddLineToPoint(path, NULL, 2, 4);
CGPathAddCurveToPoint(path, NULL, 2, 2.9, 2.9, 2, 4, 2);
CGPathAddLineToPoint(path, NULL, 14, 2);
CGPathAddCurveToPoint(path, NULL, 15.1, 2, 16, 2.9, 16, 4);
CGContextAddPath(context, path);
CGContextStrokePath(context);
CGPathRelease(path);
}
// Height geometry and code-run construction shared by the instance layout path
// and the view-free measureHeightForCodeBlockNode:, so the two cannot drift.
@@ -231,6 +253,52 @@ static BOOL ENRMColorIsDark(RCTUIColor *color)
#endif
}
+ (CGFloat)headerCopyBandHeightForConfig:(StyleConfig *)config
{
return ENRMCodeBlockContentInset(config) + ENRMCodeBlockHeaderLabelLineHeight(ENRMCodeBlockHeaderFont(config));
}
+ (ENRMHeaderCopyButton *)headerCopyButtonForConfig:(StyleConfig *)config target:(id)target action:(SEL)action
{
#if !TARGET_OS_OSX
UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
CGFloat size = [config codeBlockFont].pointSize * kENRMHeaderIconScale;
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc] initWithSize:CGSizeMake(size, size)];
UIImage *image = [renderer imageWithActions:^(UIGraphicsImageRendererContext *context) {
ENRMDrawCopyIcon(context.CGContext, size);
}];
[button setImage:[image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
button.tintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
[button addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
#else
CGFloat size = [config codeBlockFont].pointSize * kENRMHeaderIconScale;
NSImage *copyImage = [NSImage imageWithSize:NSMakeSize(size, size) flipped:YES drawingHandler:^BOOL(NSRect rect) {
ENRMDrawCopyIcon(NSGraphicsContext.currentContext.CGContext, size);
return YES;
}];
copyImage.template = YES;
NSButton *button = [NSButton buttonWithImage:copyImage target:target action:action];
button.bordered = NO;
button.contentTintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
#endif
return button;
}
+ (void)layoutHeaderCopyButton:(ENRMHeaderCopyButton *)button width:(CGFloat)width config:(StyleConfig *)config
{
CGFloat headerH = [self headerCopyBandHeightForConfig:config];
CGFloat inset = ENRMCodeBlockContentInset(config);
CGFloat iconWidth = button.intrinsicContentSize.width;
if (iconWidth <= 0 || iconWidth > headerH) {
iconWidth = headerH;
}
CGFloat iconSlack = (headerH - iconWidth) / 2;
CGFloat buttonLeft = MAX(width - inset - headerH + iconSlack, 0);
CGFloat headerCenterY = (headerH + inset / 2) / 2;
CGFloat buttonTop = MAX(headerCenterY - headerH / 2, 0);
button.frame = CGRectMake(buttonLeft, buttonTop, headerH, headerH);
}
- (void)setPending:(BOOL)pending
{
if (_pending == pending) {
@@ -273,28 +341,18 @@ static BOOL ENRMColorIsDark(RCTUIColor *color)
UIContextMenuInteraction *contextMenu = [[UIContextMenuInteraction alloc] initWithDelegate:self];
[self addInteraction:contextMenu];
_copyButton = [UIButton buttonWithType:UIButtonTypeSystem];
UIImageSymbolConfiguration *symbolConfig =
[UIImageSymbolConfiguration configurationWithPointSize:[config codeBlockFont].pointSize * kENRMHeaderIconScale
weight:UIImageSymbolWeightRegular];
[_copyButton setImage:[UIImage systemImageNamed:@"doc.on.doc" withConfiguration:symbolConfig]
forState:UIControlStateNormal];
_copyButton.tintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
[_copyButton addTarget:self action:@selector(copyCodeToPasteboard) forControlEvents:UIControlEventTouchUpInside];
_copyButton = [ENRMCodeBlockContainerView headerCopyButtonForConfig:config
target:self
action:@selector(copyCodeToPasteboard)];
[self addSubview:_copyButton];
_tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleCodeBlockTap:)];
_tapRecognizer.delegate = self;
[self addGestureRecognizer:_tapRecognizer];
#else
NSImageSymbolConfiguration *symbolConfig =
[NSImageSymbolConfiguration configurationWithPointSize:[config codeBlockFont].pointSize * kENRMHeaderIconScale
weight:NSFontWeightRegular];
NSImage *copyImage = [[NSImage imageWithSystemSymbolName:@"doc.on.doc"
accessibilityDescription:nil] imageWithSymbolConfiguration:symbolConfig];
_copyButton = [NSButton buttonWithImage:copyImage target:self action:@selector(copyCodeToPasteboard)];
_copyButton.bordered = NO;
_copyButton.contentTintColor = [[config codeBlockColor] colorWithAlphaComponent:kENRMHeaderSecondaryAlpha];
_copyButton = [ENRMCodeBlockContainerView headerCopyButtonForConfig:config
target:self
action:@selector(copyCodeToPasteboard)];
[self addSubview:_copyButton];
#endif
}
@@ -363,15 +421,7 @@ static BOOL ENRMColorIsDark(RCTUIColor *color)
- (void)layoutHeaderButton
{
CGFloat headerH = [self headerHeight];
CGFloat iconWidth = _copyButton.intrinsicContentSize.width;
if (iconWidth <= 0 || iconWidth > headerH) {
iconWidth = headerH;
}
CGFloat iconSlack = (headerH - iconWidth) / 2;
CGFloat buttonLeft = MAX(self.bounds.size.width - [self contentInset] - headerH + iconSlack, 0);
CGFloat buttonTop = MAX([self headerCenterY] - headerH / 2, 0);
_copyButton.frame = CGRectMake(buttonLeft, buttonTop, headerH, headerH);
[ENRMCodeBlockContainerView layoutHeaderCopyButton:_copyButton width:self.bounds.size.width config:_config];
}
#if !TARGET_OS_OSX
@@ -40,7 +40,17 @@ NSString *ENRMCodeBlockFenceChar(MarkdownASTNode *node)
NSString *ENRMCodeBlockFencedMarkdown(NSString *code, NSString *language, NSString *fenceChar)
{
NSString *fence = [@"" stringByPaddingToLength:3 withString:fenceChar startingAtIndex:0];
// A fence must be longer than any run of its character in the code, or an inner
// fence (a Markdown example) closes the block early.
unichar fenceUnit = [fenceChar characterAtIndex:0];
NSUInteger longestRun = 0;
NSUInteger run = 0;
for (NSUInteger index = 0; index < code.length; index++) {
run = [code characterAtIndex:index] == fenceUnit ? run + 1 : 0;
longestRun = MAX(longestRun, run);
}
NSUInteger fenceLength = MAX((NSUInteger)3, longestRun + 1);
NSString *fence = [@"" stringByPaddingToLength:fenceLength withString:fenceChar startingAtIndex:0];
return [NSString stringWithFormat:@"%@%@\n%@\n%@", fence, language ?: @"", code, fence];
}
@@ -17,6 +17,10 @@ NSString *markdownFromASTNode(MarkdownASTNode *node);
/// Useful for extracting the markdown content of a container node (e.g. a table cell).
NSString *markdownFromASTNodeChildren(MarkdownASTNode *node);
/// Serializes the blocks inside a Blockquote to markdown, without the quote's own
/// `> ` prefix. A quote nested inside keeps its prefix.
NSString *markdownFromBlockquoteBody(MarkdownASTNode *node);
/// Serializes a Blockquote or Admonition node to full markdown, including `> ` line
/// prefixes and `> [!TYPE]` header for admonitions.
NSString *markdownFromBlockquoteNode(MarkdownASTNode *node);
@@ -194,6 +194,9 @@ static void appendListMarkdown(MarkdownASTNode *node, NSMutableString *buffer, B
NSString *indent = [@"" stringByPaddingToLength:prefix.length withString:@" " startingAtIndex:0];
for (NSUInteger l = 0; l < lines.count; l++) {
[buffer appendString:(l == 0) ? prefix : indent];
if (l == 0 && [item.attributes[@"isTask"] isEqualToString:@"true"]) {
[buffer appendString:[item.attributes[@"taskChecked"] isEqualToString:@"true"] ? @"[x] " : @"[ ] "];
}
[buffer appendString:lines[l]];
[buffer appendString:@"\n"];
}
@@ -327,6 +330,16 @@ NSString *markdownFromASTNodeChildren(MarkdownASTNode *node)
return [buffer copy];
}
NSString *markdownFromBlockquoteBody(MarkdownASTNode *node)
{
if (!node)
return @"";
NSMutableString *body = [NSMutableString string];
serializeBlockChildren(node, body);
return [body stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
}
NSString *markdownFromBlockquoteNode(MarkdownASTNode *node)
{
if (!node)
@@ -342,11 +355,7 @@ NSString *markdownFromBlockquoteNode(MarkdownASTNode *node)
[result appendFormat:@"> [!%@]\n", [type uppercaseString]];
}
NSMutableString *body = [NSMutableString string];
serializeBlockChildren(node, body);
NSString *trimmed = [body stringByTrimmingCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSArray<NSString *> *lines = [trimmed componentsSeparatedByString:@"\n"];
NSArray<NSString *> *lines = [markdownFromBlockquoteBody(node) componentsSeparatedByString:@"\n"];
for (NSString *line in lines) {
[result appendString:@"> "];
[result appendString:line];
@@ -46,8 +46,18 @@ function HeadingRenderer({
function BlockquoteRenderer({
node,
styles,
renderChildren
renderChildren,
capabilities
}) {
const CustomBlockquote = capabilities.renderers?.blockquote;
if (CustomBlockquote) {
return /*#__PURE__*/_jsx(CustomBlockquote, {
blockquoteProps: {
style: styles.blockquote
},
children: renderChildren(node)
});
}
return /*#__PURE__*/_jsx("blockquote", {
style: styles.blockquote,
children: renderChildren(node)
@@ -80,11 +90,14 @@ function AdmonitionRenderer({
fontSize: blockquote.fontSize,
lineHeight: 1.2
};
// The data attributes let a copy serializer write `> [!TYPE]` instead of the title.
return /*#__PURE__*/_jsxs("div", {
className: ENRM_ADMONITION_CLASS,
style: boxStyle,
"data-enrm-admonition-type": type,
children: [/*#__PURE__*/_jsxs("div", {
style: headerStyle,
"data-enrm-admonition-title": "",
children: [/*#__PURE__*/_jsx("svg", {
width: iconSize,
height: iconSize,
@@ -1,4 +1,4 @@
export type { MarkdownRenderers, CodeBlockRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
export type { MarkdownRenderers, CodeBlockRendererProps, BlockquoteRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
export type { LinkVariantStyle, LinkPillStyle } from './types/MarkdownStyle';
export type { LinkPillContent } from './types/MarkdownTextProps';
export type { LinkContextMenuItem, LinkRecognition, } from './types/MarkdownTextProps';
@@ -1,4 +1,4 @@
export type { MarkdownRenderers, CodeBlockRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
export type { MarkdownRenderers, CodeBlockRendererProps, BlockquoteRendererProps, LinkRendererProps, } from './types/MarkdownRenderers';
export { EnrichedMarkdownText, default } from './web/EnrichedMarkdownText';
export type { EnrichedMarkdownTextProps } from './types/MarkdownTextProps.web';
export type { MarkdownStyle, Md4cFlags } from './types/MarkdownStyle';
@@ -7,14 +7,19 @@ export interface CodeBlockRendererProps {
language: string;
}
export interface LinkRendererProps {
link: LinkPressEvent;
anchorProps: ComponentProps<'a'>;
children: ReactNode;
link: LinkPressEvent;
anchorProps: ComponentProps<'a'>;
children: ReactNode;
}
/** A plain quote. Admonitions keep the library's own renderer. */
export interface BlockquoteRendererProps {
blockquoteProps: ComponentProps<'blockquote'>;
children: ReactNode;
}
/** Custom web components. Overrides own their styling and interactions. */
export interface MarkdownRenderers {
blockquote?: ComponentType<BlockquoteRendererProps>;
codeBlock?: ComponentType<CodeBlockRendererProps>;
link?: ComponentType<LinkRendererProps>;
link?: ComponentType<LinkRendererProps>;
}
//# sourceMappingURL=MarkdownRenderers.d.ts.map
@@ -1,6 +1,7 @@
export type {
MarkdownRenderers,
CodeBlockRendererProps,
BlockquoteRendererProps,
LinkRendererProps,
} from './types/MarkdownRenderers';
export type { LinkVariantStyle, LinkPillStyle } from './types/MarkdownStyle';
@@ -1,6 +1,7 @@
export type {
MarkdownRenderers,
CodeBlockRendererProps,
BlockquoteRendererProps,
LinkRendererProps,
} from './types/MarkdownRenderers';
export { EnrichedMarkdownText, default } from './web/EnrichedMarkdownText';
@@ -14,8 +14,15 @@ export interface LinkRendererProps {
children: ReactNode;
}
/** A plain quote. Admonitions keep the library's own renderer. */
export interface BlockquoteRendererProps {
blockquoteProps: ComponentProps<'blockquote'>;
children: ReactNode;
}
/** Custom web components. Overrides own their styling and interactions. */
export interface MarkdownRenderers {
blockquote?: ComponentType<BlockquoteRendererProps>;
codeBlock?: ComponentType<CodeBlockRendererProps>;
link?: ComponentType<LinkRendererProps>;
}
@@ -37,7 +37,20 @@ function HeadingRenderer({ node, styles, renderChildren }: RendererProps) {
return <Tag style={styles[Tag]}>{renderChildren(node)}</Tag>;
}
function BlockquoteRenderer({ node, styles, renderChildren }: RendererProps) {
function BlockquoteRenderer({
node,
styles,
renderChildren,
capabilities,
}: RendererProps) {
const CustomBlockquote = capabilities.renderers?.blockquote;
if (CustomBlockquote) {
return (
<CustomBlockquote blockquoteProps={{ style: styles.blockquote }}>
{renderChildren(node)}
</CustomBlockquote>
);
}
return (
<blockquote style={styles.blockquote}>{renderChildren(node)}</blockquote>
);
@@ -70,9 +83,10 @@ function AdmonitionRenderer({
fontSize: blockquote.fontSize,
lineHeight: 1.2,
};
// The data attributes let a copy serializer write `> [!TYPE]` instead of the title.
return (
<div className={ENRM_ADMONITION_CLASS} style={boxStyle}>
<div style={headerStyle}>
<div className={ENRM_ADMONITION_CLASS} style={boxStyle} data-enrm-admonition-type={type}>
<div style={headerStyle} data-enrm-admonition-title="">
<svg
width={iconSize}
height={iconSize}
@@ -0,0 +1,70 @@
import { tmpdir } from "node:os";
import { expect, test } from "vitest";
import { connectMcpServer } from "./mcp-client-connection.js";
import { HttpMcpFixture } from "./providers/opencode/test-utils/mcp-fixtures.js";
test("closing finishes when an HTTP MCP server never answers the session termination", async () => {
const server = await HttpMcpFixture.start({
token: "token",
marker: "MARKER",
holdTermination: true,
});
try {
const connection = await connectMcpServer({
config: { type: "http", url: server.url, headers: { Authorization: "Bearer token" } },
cwd: tmpdir(),
env: {},
clientName: "paseo-test",
});
await connection.close();
expect(server.heldTerminations).toBe(1);
await expect(connection.callTool("marker", {})).rejects.toThrow("after its connection closed");
} finally {
await server.close();
}
});
test("a tool call starts a new session after the HTTP MCP server forgets the old one", async () => {
const server = await HttpMcpFixture.start({ token: "token", marker: "MARKER" });
try {
const connection = await connectMcpServer({
config: { type: "http", url: server.url, headers: { Authorization: "Bearer token" } },
cwd: tmpdir(),
env: {},
clientName: "paseo-test",
});
await expect(connection.callTool("marker", {})).resolves.toMatchObject({
content: [{ type: "text", text: "MARKER" }],
});
server.expireSessions();
await expect(connection.callTool("marker", {})).resolves.toMatchObject({
content: [{ type: "text", text: "MARKER" }],
});
expect(server.initializedSessions).toBe(2);
await connection.close();
expect(server.openSessions).toBe(0);
} finally {
await server.close();
}
});
test("connecting fails when an HTTP MCP server never answers the end of the handshake", async () => {
const server = await HttpMcpFixture.start({
token: "token",
marker: "MARKER",
holdInitialized: true,
});
try {
await expect(
connectMcpServer({
config: { type: "http", url: server.url, headers: { Authorization: "Bearer token" } },
cwd: tmpdir(),
env: {},
clientName: "paseo-test",
}),
).rejects.toThrow("MCP server did not connect within 10 seconds");
} finally {
await server.close();
}
}, 20_000);
@@ -0,0 +1,196 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import {
StreamableHTTPClientTransport,
StreamableHTTPError,
} from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { CallToolResultSchema, type Tool } from "@modelcontextprotocol/sdk/types.js";
import type { McpServerConfig } from "./agent-sdk-types.js";
import type { PaseoToolResult } from "./tools/types.js";
const SERVER_TIMEOUT_MS = 10_000;
const TERMINATE_TIMEOUT_MS = 2_000;
export type McpClientTool = Pick<Tool, "name" | "description" | "inputSchema">;
/**
* A live MCP client connection that Paseo hosts on behalf of one agent, for providers whose
* native MCP support cannot be scoped to a single session.
*/
export interface McpClientConnection {
readonly tools: readonly McpClientTool[];
/** Server instructions from the initialize result, when the server sends them. */
readonly instructions: string | undefined;
callTool(
name: string,
args: Record<string, unknown>,
signal?: AbortSignal,
): Promise<PaseoToolResult>;
close(): Promise<void>;
}
export interface ConnectMcpServerInput {
config: McpServerConfig;
/** Working directory for a stdio server. */
cwd: string;
/** Complete environment for a stdio server; the server's own `env` overlays it. */
env: NodeJS.ProcessEnv;
clientName: string;
}
export async function connectMcpServer(input: ConnectMcpServerInput): Promise<McpClientConnection> {
const { client, tools } = await openClient(input);
return createConnection(input, client, tools);
}
async function openClient(
input: ConnectMcpServerInput,
): Promise<{ client: Client; tools: McpClientTool[] }> {
const client = new Client({ name: input.clientName, version: "1.0.0" });
try {
// The SDK times out only the `initialize` request, not the `initialized` notification after it.
return await withDeadline(
(async () => {
await client.connect(createTransport(input));
const listed = await client.listTools();
return { client, tools: listed.tools };
})(),
SERVER_TIMEOUT_MS,
() => new Error(`MCP server did not connect within ${SERVER_TIMEOUT_MS / 1000} seconds`),
);
} catch (error) {
// Closing the client also aborts its pending requests.
await client.close().catch(() => undefined);
throw error;
}
}
function createConnection(
input: ConnectMcpServerInput,
initial: Client,
tools: readonly McpClientTool[],
): McpClientConnection {
let client = initial;
let renewing: Promise<Client> | undefined;
let closed: Promise<void> | undefined;
// A stateful HTTP server forgets a session when it restarts or expires it, and answers 404.
// The protocol then asks the client to start a new session.
function renew(stale: Client): Promise<Client> {
if (client !== stale) return Promise.resolve(client);
renewing ??= openClient(input)
.then(async (next) => {
if (closed) {
await terminate(next.client);
throw new Error("MCP connection closed while it reconnected");
}
client = next.client;
void terminate(stale);
return client;
})
.finally(() => {
renewing = undefined;
});
return renewing;
}
async function call(
target: Client,
name: string,
args: Record<string, unknown>,
signal?: AbortSignal,
) {
const raw = await target.callTool({ name, arguments: args }, undefined, { signal });
const result = CallToolResultSchema.parse(raw);
return {
content: result.content.map((item) => ({ ...item })),
...(result.structuredContent !== undefined
? { structuredContent: result.structuredContent }
: {}),
...(result.isError !== undefined ? { isError: result.isError } : {}),
};
}
return {
tools,
instructions: initial.getInstructions(),
async callTool(name, args, signal) {
if (closed) throw new Error(`MCP tool ${name} is unavailable after its connection closed`);
const target = client;
try {
return await call(target, name, args, signal);
} catch (error) {
if (!isExpiredSession(error)) throw error;
return await call(await renew(target), name, args, signal);
}
},
close() {
// A reconnect that is still running closes its own client once it sees `closed`.
closed ??= (renewing ?? Promise.resolve())
.catch(() => undefined)
.then(() => terminate(client));
return closed;
},
};
}
function isExpiredSession(error: unknown): boolean {
return error instanceof StreamableHTTPError && error.code === 404;
}
async function terminate(client: Client): Promise<void> {
// A stateful HTTP server keeps the session until the client ends it explicitly. Closing the
// client aborts a termination request that the server does not answer in time.
if (client.transport instanceof StreamableHTTPClientTransport)
await withDeadline(
client.transport.terminateSession(),
TERMINATE_TIMEOUT_MS,
() => new Error("MCP session termination timed out"),
).catch(() => undefined);
await client.close().catch(() => undefined);
}
/** Settles with the operation, or rejects with `timeout()` when `ms` passes first. */
async function withDeadline<T>(
operation: Promise<T>,
ms: number,
timeout: () => unknown,
): Promise<T> {
let timer: ReturnType<typeof setTimeout> | undefined;
const deadline = new Promise<never>((_, reject) => {
timer = setTimeout(() => reject(timeout()), ms);
});
try {
return await Promise.race([operation, deadline]);
} finally {
clearTimeout(timer);
}
}
function createTransport({ config, cwd, env }: ConnectMcpServerInput) {
if (config.type === "stdio") {
return new StdioClientTransport({
command: config.command,
args: config.args,
cwd,
env: definedEnvironment({ ...env, ...config.env }),
stderr: "ignore",
});
}
if (config.type === "http") {
return new StreamableHTTPClientTransport(new URL(config.url), {
requestInit: { headers: config.headers },
});
}
return new SSEClientTransport(new URL(config.url), {
requestInit: { headers: config.headers },
eventSourceInit: {
fetch: (url, init) =>
fetch(url, { ...init, headers: { ...init?.headers, ...config.headers } }),
},
});
}
function definedEnvironment(env: NodeJS.ProcessEnv): Record<string, string> {
return Object.fromEntries(
Object.entries(env).filter((entry): entry is [string, string] => entry[1] !== undefined),
);
}
@@ -150,6 +150,10 @@ function describeVersion(inspection: ProviderInstallationInspection): string {
return inspection.version?.trim() || "unknown";
}
function toProviderLaunch(launch: ProviderInstallationLaunch): ProviderLaunch {
return { command: launch.command, args: launch.args, env: launch.env };
}
class ProviderRuntime {
private connection: ProviderConnection | null = null;
connectedLaunch: ProviderLaunch | undefined;
@@ -212,13 +216,13 @@ class ProviderRuntime {
const launch = await this.resolveEffectiveLaunch();
if (!launch) return undefined;
if (!launch.resolved) throw new Error(`${launch.command} not found on PATH`);
return { command: launch.command, args: launch.args, env: launch.env };
return toProviderLaunch(launch);
}
async resolveUsageLaunch(): Promise<ProviderLaunch | undefined> {
const launch = await this.resolveEffectiveLaunch();
if (!launch?.resolved) return undefined;
return { command: launch.command, args: launch.args, env: launch.env };
return toProviderLaunch(launch);
}
async inspectInstallation(signal: AbortSignal): Promise<ProviderInspection> {
@@ -281,7 +285,11 @@ class ProviderRuntime {
async catalogCacheKey(options: FetchCatalogOptions): Promise<string | undefined> {
const callback = this.registration.getCatalogCacheKey;
if (!callback) return undefined;
return callback({ ...options, launch: await this.resolveLaunch() });
const launch = await this.resolveEffectiveLaunch();
// A missing executable gets its own catalogue, so refresh reports it unavailable instead of
// failing the key or reusing a catalogue cached while it was installed.
if (launch && !launch.resolved) return JSON.stringify(["unresolved", launch.command]);
return callback({ ...options, launch: launch && toProviderLaunch(launch) });
}
get negotiatedCapabilities(): readonly string[] {
@@ -1,6 +1,7 @@
import pino from "pino";
import { homedir } from "node:os";
import { resolve } from "node:path";
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { homedir, tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { describe, expect, test, vi } from "vitest";
import type {
ProviderEvent,
@@ -8,6 +9,7 @@ import type {
ProviderLaunch,
} from "@getpaseo/plugin/server/provider";
import { isPlatform } from "../../test-utils/platform.js";
import { createTestLogger } from "../../test-utils/test-logger.js";
import type {
AgentClient,
@@ -217,6 +219,97 @@ describe("ProviderSnapshotManager public surface", () => {
}
});
test("reports a plugin provider whose command is not installed as unavailable", async () => {
const manager = new ProviderSnapshotManager({ logger: createTestLogger() });
manager.replacePluginProviders([
{
id: "uninstalled-plugin",
label: "Uninstalled plugin",
command: ["paseo-test-command-that-is-not-installed"],
async getCatalogCacheKey({ launch }) {
if (!launch) throw new Error("requires a daemon-resolved executable");
return launch.command;
},
async status({ launch }) {
return launch ? { available: true } : { available: false, diagnostic: "Install it" };
},
async connect() {
throw new Error("an uninstalled provider is never connected");
},
},
]);
try {
const entry = await manager.getProvider({
provider: "uninstalled-plugin",
cwd: "/tmp/project",
wait: true,
});
expect(entry).toMatchObject({ status: "unavailable" });
expect(entry.error).toBeUndefined();
} finally {
manager.destroy();
}
});
test.skipIf(isPlatform("win32"))(
"reports a workspace-cached plugin provider as unavailable after its executable is removed",
async () => {
const directory = mkdtempSync(join(tmpdir(), "paseo-removed-plugin-"));
const executable = join(directory, "removed-plugin");
writeFileSync(executable, "#!/bin/sh\necho 1.0.0\n");
chmodSync(executable, 0o755);
const manager = new ProviderSnapshotManager({ logger: createTestLogger() });
manager.replacePluginProviders([
{
id: "removed-plugin",
label: "Removed plugin",
command: [executable],
// undefined asks the snapshot manager to cache the catalogue per workspace.
async getCatalogCacheKey() {
return undefined;
},
async status({ launch }) {
return launch ? { available: true } : { available: false, diagnostic: "Install it" };
},
async connect() {
let listener: ((event: ProviderEvent) => void) | undefined;
return {
version: 1,
capabilities: [],
async send(input) {
if (input.type === "catalog")
listener?.({
type: "catalog",
requestId: input.requestId,
catalog: { models: [{ id: "model", label: "Model" }], modes: [] },
});
},
onEvent(next) {
listener = next;
return () => {
listener = undefined;
};
},
async close() {},
};
},
},
]);
try {
const read = () =>
manager.getProvider({ provider: "removed-plugin", cwd: "/tmp/project", wait: true });
expect(await read()).toMatchObject({ status: "ready" });
rmSync(directory, { recursive: true, force: true });
expect(await read()).toMatchObject({ status: "unavailable" });
} finally {
manager.destroy();
rmSync(directory, { recursive: true, force: true });
}
},
);
test("carries a plugin provider icon and docs link in snapshot metadata", () => {
const iconSvg = '<svg viewBox="0 0 24 24"><path d="M4 4h16v16H4z" /></svg>';
const docsUrl = "https://example.com/docs";
@@ -1,16 +1,12 @@
import { createHash } from "node:crypto";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
import { CallToolResultSchema } from "@modelcontextprotocol/sdk/types.js";
import type { Logger } from "pino";
import type { McpServerConfig } from "../../agent-sdk-types.js";
import { connectMcpServer, type McpClientConnection } from "../../mcp-client-connection.js";
import type { PaseoToolResult } from "../../tools/types.js";
import type { OmpRpcHostToolDefinition } from "./rpc-types.js";
interface BridgedTool {
client: Client;
connection: McpClientConnection;
server: string;
tool: string;
}
@@ -20,12 +16,10 @@ export interface OmpBridgedToolIdentity {
tool: string;
}
const SERVER_TIMEOUT_MS = 10_000;
export class OmpMcpBridge {
readonly definitions: OmpRpcHostToolDefinition[] = [];
private readonly tools = new Map<string, BridgedTool>();
private readonly clients: Client[] = [];
private readonly connections: McpClientConnection[] = [];
private closed = false;
static async connect(
@@ -37,26 +31,31 @@ export class OmpMcpBridge {
const bridge = new OmpMcpBridge();
const connections = await Promise.all(
Object.entries(servers ?? {}).map(async ([serverName, config]) => {
const client = new Client({ name: "paseo-omp-mcp", version: "1.0.0" });
try {
const transport = makeTransport(config, cwd, env);
await client.connect(transport, { timeout: SERVER_TIMEOUT_MS });
const listed = await client.listTools(undefined, { timeout: SERVER_TIMEOUT_MS });
return { serverName, client, tools: listed.tools };
const connection = await connectMcpServer({
config,
cwd,
env,
clientName: "paseo-omp-mcp",
});
return { serverName, connection };
} catch (error) {
logger.warn({ err: error, server: serverName }, "OMP MCP server unavailable");
await client.close().catch(() => undefined);
return null;
}
}),
);
for (const connection of connections) {
if (!connection) continue;
const { serverName, client, tools } = connection;
bridge.clients.push(client);
for (const tool of tools) {
const { serverName } = connection;
bridge.connections.push(connection.connection);
for (const tool of connection.connection.tools) {
const name = bridgeName(serverName, tool.name);
bridge.tools.set(name, { client, server: serverName, tool: tool.name });
bridge.tools.set(name, {
connection: connection.connection,
server: serverName,
tool: tool.name,
});
bridge.definitions.push({
name,
label: `${serverName} / ${tool.name}`,
@@ -87,51 +86,17 @@ export class OmpMcpBridge {
): Promise<PaseoToolResult> {
const entry = this.tools.get(name);
if (!entry || this.closed) throw new Error(`MCP tool ${name} is unavailable`);
const raw = await entry.client.callTool({ name: entry.tool, arguments: args }, undefined, {
signal,
});
const result = CallToolResultSchema.parse(raw);
return {
content: result.content.map((item) => ({ ...item })),
...(result.structuredContent !== undefined
? { structuredContent: result.structuredContent }
: {}),
...(result.isError !== undefined ? { isError: result.isError } : {}),
};
return entry.connection.callTool(entry.tool, args, signal);
}
async close(): Promise<void> {
if (this.closed) return;
this.closed = true;
await Promise.all(this.clients.map((client) => client.close().catch(() => undefined)));
this.clients.length = 0;
await Promise.all(this.connections.map((connection) => connection.close()));
this.connections.length = 0;
}
}
function makeTransport(config: McpServerConfig, cwd: string, env: NodeJS.ProcessEnv) {
if (config.type === "stdio") {
return new StdioClientTransport({
command: config.command,
args: config.args,
cwd,
env: { ...env, ...config.env } as Record<string, string>,
stderr: "ignore",
});
}
if (config.type === "http") {
return new StreamableHTTPClientTransport(new URL(config.url), {
requestInit: { headers: config.headers },
});
}
return new SSEClientTransport(new URL(config.url), {
requestInit: { headers: config.headers },
eventSourceInit: {
fetch: (url, init) =>
fetch(url, { ...init, headers: { ...init?.headers, ...config.headers } }),
},
});
}
function bridgeName(server: string, tool: string): string {
const key = `${server}\0${tool}`;
const hash = createHash("sha256").update(key).digest("hex").slice(0, 12);
@@ -0,0 +1,317 @@
import { OpenCode } from "@opencode/client";
import { mkdir, mkdtemp, readFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import type { AgentLaunchContext, AgentSession, AgentSessionConfig } from "../agent-sdk-types.js";
import { OpenCodeBridge } from "./opencode/bridge.js";
import { provisionLocalBridge } from "./opencode/v2/bridge-provisioning.js";
import { OpenCodeV2AgentClient } from "./opencode/v2/agent.js";
import {
EXTERNAL_SERVER_PASSWORD_ENV,
EXTERNAL_SERVER_URL_ENV,
} from "./opencode/v2/external-server.js";
import {
HttpMcpFixture,
isProcessAlive,
writeStdioMcpFixture,
} from "./opencode/test-utils/mcp-fixtures.js";
import {
OPENCODE_V2_COMMAND,
SCRIPTED_MODEL,
ScriptedOpenCodeService,
scriptedCall,
type ScriptedRequest,
type ScriptedTool,
} from "./opencode/test-utils/v2-scripted-server.js";
import {
collectPermissions,
collectProviderSubagents,
} from "./opencode/test-utils/v2-local-e2e-helpers.js";
/** Where the OpenCode server runs: named by the user, found running, or started by Paseo. */
type Mode = "explicit" | "discovered" | "owned";
interface Fixture {
root: string;
/** An MCP server named `hub` in the user's own OpenCode configuration, when the test has one. */
userHub?: HttpMcpFixture;
project: string;
bridge: OpenCodeBridge;
service: ScriptedOpenCodeService;
client: OpenCodeV2AgentClient;
}
async function startFixture(mode: Mode, options: { userHub?: boolean } = {}): Promise<Fixture> {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-opencode-v2-shared-"));
const project = path.join(root, "project");
await mkdir(project, { recursive: true });
const bridge = new OpenCodeBridge({
paseoHome: path.join(root, "paseo"),
logger: createTestLogger(),
});
bridge.setManifestCatalog({ tools: new Map() });
await bridge.start();
const userHub = options.userHub
? // Its `marker` requires an input that the agents' `marker` does not have.
await HttpMcpFixture.start({ token: "user-token", marker: "USER_OK", requiredInput: "value" })
: undefined;
const service = await ScriptedOpenCodeService.start({
...(userHub
? {
mcpServers: {
hub: {
type: "remote",
url: userHub.url,
headers: { Authorization: "Bearer user-token" },
oauth: false,
},
},
}
: {}),
// A user installs the plugin on an explicit server; Paseo installs it on a discovered one.
beforeStart:
mode === "explicit"
? async ({ configDirectory }) =>
provisionLocalBridge({
configDirectory,
artifact: path.join(fileURLToPath(await bridge.materializeV2Plugin()), "server.js"),
})
: undefined,
});
const settings = {
explicit: {
env: {
[EXTERNAL_SERVER_URL_ENV]: service.url,
[EXTERNAL_SERVER_PASSWORD_ENV]: service.password,
},
},
discovered: { env: service.discoveryEnvironment },
// Process environment makes Paseo start its own server despite the registered service.
owned: {
command: { mode: "replace" as const, argv: [OPENCODE_V2_COMMAND] },
env: service.ownedEnvironment,
},
}[mode];
const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), bridge, settings });
return { root, project, bridge, service, client, ...(userHub ? { userHub } : {}) };
}
async function stopFixture(fixture: Fixture | undefined) {
if (!fixture) return;
await fixture.client.shutdown();
await fixture.service.stop();
await fixture.bridge.close();
await fixture.userHub?.close();
await rm(fixture.root, { recursive: true, force: true });
}
/** The create request Hub sends for an execution: its MCP endpoint, preapproval, and env. */
function hubLaunch(input: {
cwd: string;
agentId: string;
hub: HttpMcpFixture;
token: string;
secret: string;
stdio?: string;
}): { config: AgentSessionConfig; launch: AgentLaunchContext } {
return {
config: {
provider: "opencode",
cwd: input.cwd,
model: SCRIPTED_MODEL,
mcpServers: {
hub: {
type: "http",
url: input.hub.url,
headers: { Authorization: `Bearer ${input.token}` },
},
...(input.stdio
? { local: { type: "stdio" as const, command: process.execPath, args: [input.stdio] } }
: {}),
},
toolPolicy: {
preapproved: [
{ kind: "mcp", server: "hub", tool: "marker" },
{ kind: "mcp", server: "local", tool: "env" },
],
},
},
launch: {
agentId: input.agentId,
env: {
HUB_SECRET: input.secret,
PASEO_AGENT_PROVIDER: "opencode",
PASEO_HUB_CONFIG_JSON: JSON.stringify({ execution: input.agentId }),
PASEO_AGENT_ID: input.agentId,
PASEO_AGENT_CWD: input.cwd,
},
},
};
}
/** The tools a model request offers from the agents' `hub` and `local` MCP servers. */
function agentMcpTools(request: ScriptedRequest): ScriptedTool[] {
return request.tools.filter(
(tool) => tool.name.startsWith("hub_") || tool.name.startsWith("local_"),
);
}
function useFixture(mode: Mode, options: { userHub?: boolean } = {}) {
const state: { fixture?: Fixture; cleanups: Array<() => Promise<void>> } = { cleanups: [] };
beforeEach(async () => {
state.fixture = await startFixture(mode, options);
}, 60_000);
afterEach(async () => {
for (const cleanup of state.cleanups.splice(0).toReversed()) await cleanup();
await stopFixture(state.fixture);
state.fixture = undefined;
}, 60_000);
return state;
}
describe.each<Mode>(["explicit", "discovered", "owned"])("OpenCode v2 %s server", (mode) => {
const state = useFixture(mode);
test("lists models, runs Hub MCP tools, and exposes launch env to shells, stdio MCP, and subagents", async () => {
const { cleanups } = state;
const fixture = state.fixture!;
const { client, project } = fixture;
const catalog = await client.fetchCatalog({ scope: "workspace", cwd: project, force: false });
expect(catalog.models.map((model) => model.id)).toContain(SCRIPTED_MODEL);
const hub = await HttpMcpFixture.start({
token: "token-1",
marker: "HUB_OK_1",
instructions: "Always finish the Hub execution.",
});
cleanups.push(() => hub.close());
const stdio = await writeStdioMcpFixture(fixture.root);
const { config, launch } = hubLaunch({
cwd: project,
agentId: "agent-1",
hub,
token: "token-1",
secret: "secret-1",
stdio: stdio.script,
});
const session = await client.createSession(config, launch, { persistSession: false });
cleanups.push(() => session.close());
const permissions = collectPermissions(session);
const hubCall = scriptedCall("hub_marker");
const marker = await session.run(hubCall);
expect(marker.finalText).toBe("RESULT HUB_OK_1");
expect(marker.timeline).toEqual(
expect.arrayContaining([
expect.objectContaining({ type: "tool_call", name: "hub_marker", status: "completed" }),
]),
);
const stdioEnv = await session.run(scriptedCall("local_env", { name: "HUB_SECRET" }));
expect(stdioEnv.finalText).toBe("RESULT secret-1");
const shell = await session.run(
scriptedCall("shell", { command: 'printf %s "$HUB_SECRET"', description: "Print secret" }),
);
expect(shell.finalText).toContain("secret-1");
const subagents = collectProviderSubagents(session);
const childPrompt = scriptedCall("shell", {
command: 'printf %s "child:$HUB_SECRET"',
description: "Print secret",
});
await session.run(
scriptedCall("subagent", { agent: "general", description: "Print", prompt: childPrompt }),
);
await expect.poll(subagents.childText, { timeout: 30_000 }).toContain("child:secret-1");
expect(permissions).toEqual([]);
// OpenCode introduces the prompt it gives the subagent, so match the child request by its end.
const childRequest = fixture.service.agentRequests.find((request) =>
request.prompt.endsWith(childPrompt),
);
expect(childRequest?.tools.map((tool) => tool.name)).toContain("hub_marker");
// The model receives the server's instructions with the first request of each session.
expect(fixture.service.requestsFor(hubCall)[0]?.transcript).toContain(
"Always finish the Hub execution.",
);
expect(childRequest?.transcript).toContain("Always finish the Hub execution.");
}, 120_000);
});
describe.each<Mode>(["explicit", "discovered"])("OpenCode v2 %s shared service", (mode) => {
const state = useFixture(mode, { userHub: true });
test("isolates same-named MCP servers between sessions in one directory and closes them", async () => {
const { cleanups } = state;
const fixture = state.fixture!;
const { client, project, service } = fixture;
const hubs = await Promise.all(
[1, 2].map((index) =>
HttpMcpFixture.start({ token: `token-${index}`, marker: `HUB_OK_${index}` }),
),
);
for (const hub of hubs) cleanups.push(() => hub.close());
const stdio = await writeStdioMcpFixture(fixture.root);
const sessions: AgentSession[] = [];
for (const index of [1, 2]) {
const { config, launch } = hubLaunch({
cwd: project,
agentId: `agent-${index}`,
hub: hubs[index - 1]!,
token: `token-${index}`,
secret: `secret-${index}`,
...(index === 1 ? { stdio: stdio.script } : {}),
});
const session = await client.createSession(config, launch, { persistSession: false });
sessions.push(session);
cleanups.push(() => session.close());
}
const [first, second] = sessions;
// Each session prompts with its own text, so the scripted model sees which session asked.
const firstCall = `first ${scriptedCall("hub_marker")}`;
const secondCall = `second ${scriptedCall("hub_marker")}`;
expect((await first!.run(firstCall)).finalText).toBe("RESULT HUB_OK_1");
expect((await second!.run(secondCall)).finalText).toBe("RESULT HUB_OK_2");
const advertised = (prompt: string) => agentMcpTools(service.requestsFor(prompt)[0]!);
expect(advertised(firstCall)).toEqual([
expect.objectContaining({ name: "hub_marker", description: "Return HUB_OK_1" }),
expect.objectContaining({ name: "local_env" }),
]);
expect(advertised(secondCall)).toEqual([
expect.objectContaining({ name: "hub_marker", description: "Return HUB_OK_2" }),
]);
// A session the user opens in OpenCode itself sees no Paseo MCP tools. It keeps the
// same-named tool from the user's own OpenCode configuration.
const unrelatedPrompt = `unrelated ${scriptedCall("hub_marker")}`;
const opencode = OpenCode.make({
baseUrl: service.url,
headers: {
Authorization: `Basic ${Buffer.from(`opencode:${service.password}`).toString("base64")}`,
},
});
const unrelated = await opencode.session.create({
location: { directory: project },
agent: "build",
});
await opencode.session.prompt({ sessionID: unrelated.id, text: unrelatedPrompt });
await expect
.poll(() => service.requestsFor(unrelatedPrompt).length, { timeout: 30_000 })
.toBeGreaterThan(0);
expect(advertised(unrelatedPrompt)).toEqual([
expect.objectContaining({ name: "hub_marker", description: "Return USER_OK" }),
]);
expect(hubs.map((hub) => hub.openSessions)).toEqual([1, 1]);
const pid = Number(await readFile(stdio.pidFile, "utf8"));
expect(isProcessAlive(pid)).toBe(true);
await first!.close();
expect(hubs.map((hub) => hub.openSessions)).toEqual([0, 1]);
await expect.poll(() => isProcessAlive(pid), { timeout: 10_000 }).toBe(false);
// The remaining session keeps its own endpoint after the other one closes.
const afterClose = `after close ${scriptedCall("hub_marker")}`;
expect((await second!.run(afterClose)).finalText).toBe("RESULT HUB_OK_2");
}, 120_000);
});
@@ -11,7 +11,6 @@ import { expect, test } from "vitest";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import {
autoRespondToPermissions,
collectPermissions,
collectProviderSubagents,
collectRunningToolCalls,
collectStreamedAssistantText,
@@ -167,56 +166,6 @@ test("v2 handles live tool approvals and questions", async () => {
}
}, 120_000);
test("v2 invokes an injected MCP tool with exact preapproval", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-opencode-v2-mcp-"));
const fixture = path.join(root, "mcp.mjs");
await writeFile(
fixture,
`import { McpServer } from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/mcp.js"))};
import { StdioServerTransport } from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
const server = new McpServer({ name: "paseo-validation", version: "1.0.0" });
server.registerTool("marker", { description: "Return the validation marker", inputSchema: {} }, async () => ({ content: [{ type: "text", text: "PASEO_MCP_OK" }] }));
await server.connect(new StdioServerTransport());
`,
);
const client = new OpenCodeV2AgentClient({ logger: createTestLogger() });
let session: Awaited<ReturnType<typeof client.createSession>> | undefined;
try {
const active = await client.createSession(
{
provider: "opencode",
cwd: root,
model: process.env.OPENCODE_TEST_MODEL ?? "openai/gpt-6-astra",
mcpServers: { validation: { type: "stdio", command: process.execPath, args: [fixture] } },
toolPolicy: { preapproved: [{ server: "validation", tool: "marker" }] },
},
undefined,
{ persistSession: false },
);
session = active;
const permissions = collectPermissions(active);
const result = await active.run(
"Call the validation_marker MCP tool once and report its output. Do not use other tools.",
);
expect(result.finalText).toContain("PASEO_MCP_OK");
expect(result.timeline).toEqual(
expect.arrayContaining([
expect.objectContaining({
type: "tool_call",
name: "validation_marker",
status: "completed",
}),
]),
);
expect(permissions).toEqual([]);
} finally {
await session?.interrupt();
await session?.close();
await client.shutdown();
await rm(root, { recursive: true, force: true });
}
}, 120_000);
test("v2 stops a running tool before replacement work and imports the same session", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paseo-opencode-v2-stop-"));
const client = new OpenCodeV2AgentClient({ logger: createTestLogger() });
@@ -105,11 +105,15 @@ describe("OpenCodeBridge", () => {
inputSchema: serializePaseoToolInputParameters(catalog.getTool("echo_context")!),
},
],
mcpTools: [],
},
};
expect(await discover("")).toEqual(expected);
expect(await discover("?sessionID=bound")).toEqual(expected);
expect(await discover("?sessionID=disabled")).toEqual({ status: 200, body: { tools: [] } });
expect(await discover("?sessionID=disabled")).toEqual({
status: 200,
body: { tools: [], mcpTools: [] },
});
const missing = {
status: 404,
body: { error: "OpenCode session is not bound to a Paseo agent" },
@@ -469,6 +473,7 @@ describe("OpenCodeBridge", () => {
},
},
],
mcpTools: [],
});
const execution = await fetch(
@@ -861,6 +866,67 @@ describe("OpenCodeBridge", () => {
}
});
test("runs a session's MCP tools with their structured results and stops them on disconnect", async () => {
const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-bridge-mcp-"));
temporaryDirectories.push(paseoHome);
const bridge = new OpenCodeBridge({ paseoHome, logger: createTestLogger() });
await bridge.start();
const started = Promise.withResolvers<void>();
const stopped = Promise.withResolvers<unknown>();
const release = bridge.bindSession({
sessionId: "ses_mcp",
env: {},
mcp: {
tools: [
{ name: "hub_lookup", description: "Look up", inputSchema: { type: "object" } },
{ name: "hub_wait", description: "Wait", inputSchema: { type: "object" } },
],
instructions: "Use the lookup.",
async execute(name, _input, signal) {
if (name === "hub_lookup")
return { content: [], structuredContent: { answer: "the lookup value" } };
started.resolve();
signal?.addEventListener("abort", () => stopped.resolve(signal.reason));
return await new Promise(() => {});
},
},
});
try {
const { baseUrl, token } = bridge.sharedV2Connection();
const headers = { Authorization: `Bearer ${token}`, "Content-Type": "application/json" };
const route = (tool: string) =>
`${baseUrl}/_internal/opencode/sessions/ses_mcp/mcp-tools/${tool}`;
const context = await fetch(`${baseUrl}/_internal/opencode/sessions/ses_mcp/context?tools`, {
headers,
});
expect(await context.json()).toMatchObject({ mcpInstructions: "Use the lookup." });
const lookup = await fetch(route("hub_lookup"), { method: "POST", headers, body: "{}" });
expect(await lookup.json()).toEqual({
content: [{ type: "text", text: expect.stringContaining("the lookup value") }],
structuredContent: { answer: "the lookup value" },
});
// OpenCode aborts the request when the user stops the turn.
const abort = new AbortController();
const waiting = fetch(route("hub_wait"), {
method: "POST",
headers,
body: "{}",
signal: abort.signal,
}).catch(() => undefined);
await started.promise;
abort.abort();
await waiting;
await expect(stopped.promise).resolves.toEqual(
new Error("OpenCode tool request was aborted"),
);
} finally {
release();
await bridge.close();
}
});
test("returns actionable 4xx responses for invalid bridge requests", async () => {
const paseoHome = await mkdtemp(path.join(tmpdir(), "paseo-opencode-bridge-errors-"));
temporaryDirectories.push(paseoHome);
@@ -11,7 +11,12 @@ import {
addModelVisibleStructuredContent,
serializePaseoToolInputParameters,
} from "../../tools/paseo-tool-serialization.js";
import { PaseoToolInputError, type PaseoToolCatalog } from "../../tools/types.js";
import {
PaseoToolInputError,
type PaseoToolCatalog,
type PaseoToolResult,
} from "../../tools/types.js";
import type { McpClientTool } from "../../mcp-client-connection.js";
const INTERNAL_PREFIX = "/_internal/opencode";
const MAX_REQUEST_BYTES = 1024 * 1024;
@@ -33,9 +38,27 @@ interface OpenCodeBridgeOptions {
port?: number;
}
export interface OpenCodeBridgeMcpTool {
/** OpenCode's effective tool name, `<server>_<tool>`. */
name: string;
description: string;
inputSchema: McpClientTool["inputSchema"];
}
/** MCP servers Paseo hosts for one session; the v2 plugin exposes them to that session only. */
export interface OpenCodeBridgeMcp {
readonly tools: readonly OpenCodeBridgeMcpTool[];
/** Server instructions for the model, which the plugin adds to each request of the session. */
readonly instructions: string | undefined;
execute(name: string, input: unknown, signal?: AbortSignal): Promise<PaseoToolResult>;
}
interface OpenCodeSessionBinding {
env: Record<string, string>;
tools?: PaseoToolCatalog;
mcp?: OpenCodeBridgeMcp;
/** Prepares a descendant session before its first model request. */
adoptDescendant?: (sessionId: string) => Promise<void>;
}
interface BindOpenCodeSessionInput extends OpenCodeSessionBinding {
@@ -102,6 +125,8 @@ export class OpenCodeBridge {
const binding: OpenCodeSessionBinding = {
env: { ...input.env },
...(input.tools ? { tools: input.tools } : {}),
...(input.mcp ? { mcp: input.mcp } : {}),
...(input.adoptDescendant ? { adoptDescendant: input.adoptDescendant } : {}),
};
this.sessions.set(input.sessionId, binding);
return () => {
@@ -111,6 +136,11 @@ export class OpenCodeBridge {
};
}
/** Whether the session's bound MCP servers expose tools the v2 plugin must run. */
hasMcpTools(sessionId: string): boolean {
return (this.sessions.get(sessionId)?.mcp?.tools.length ?? 0) > 0;
}
decorateServerEnv(env: Record<string, string>): Record<string, string> {
const pluginUrl = this.requirePluginUrl();
const options: OpenCodePluginOptions = {
@@ -164,72 +194,75 @@ export class OpenCodeBridge {
sendJson(response, 401, { error: "Unauthorized" });
return;
}
const url = new URL(request.url ?? "/", this.requireBaseUrl());
if (request.method === "GET" && url.pathname === `${INTERNAL_PREFIX}/tools`) {
sendJson(response, 200, {
tools: this.serializeManifest(url.searchParams.get("sessionID")),
});
return;
}
const contextMatch = url.pathname.match(
new RegExp(`^${INTERNAL_PREFIX}/sessions/([^/]+)/context$`),
);
if (request.method === "GET" && contextMatch) {
const binding = this.sessions.get(decodeURIComponent(contextMatch[1]));
if (!binding) {
sendJson(response, 404, { error: "OpenCode session is not bound to a Paseo agent" });
return;
}
sendJson(response, 200, {
env: binding.env,
...(url.searchParams.has("tools")
? { tools: [...(binding.tools?.tools.keys() ?? [])] }
: {}),
});
return;
}
const toolMatch = url.pathname.match(
new RegExp(`^${INTERNAL_PREFIX}/sessions/([^/]+)/tools/([^/]+)$`),
);
if (request.method === "POST" && toolMatch) {
await this.executeTool({
sessionId: decodeURIComponent(toolMatch[1]),
toolName: decodeURIComponent(toolMatch[2]),
request,
response,
});
return;
}
sendJson(response, 404, { error: "Not found" });
await this.dispatch(request, response);
} catch (error) {
this.logger.warn({ err: error }, "OpenCode bridge request failed");
const failure = error instanceof Error ? error : new Error(String(error));
if (!response.headersSent) {
if (error instanceof OpenCodeBridgeClientError) {
sendJson(response, error.status, {
error: error.message,
...(error.details === undefined ? {} : { details: error.details }),
});
} else if (error instanceof PaseoToolInputError) {
sendJson(
response,
error.status,
error.issues
? { error: "Invalid tool input", issues: error.issues }
: { error: error.message },
);
} else {
sendJson(response, 500, { error: failure.message });
}
} else {
response.destroy(failure);
}
sendFailure(response, error);
}
}
private async dispatch(request: IncomingMessage, response: ServerResponse): Promise<void> {
const url = new URL(request.url ?? "/", this.requireBaseUrl());
if (request.method === "GET" && url.pathname === `${INTERNAL_PREFIX}/tools`) {
sendJson(response, 200, this.manifest(url.searchParams.get("sessionID")));
return;
}
const contextMatch = url.pathname.match(
new RegExp(`^${INTERNAL_PREFIX}/sessions/([^/]+)/context$`),
);
if (request.method === "GET" && contextMatch) {
const binding = this.requireBinding(decodeURIComponent(contextMatch[1]));
sendJson(response, 200, sessionContext(binding, url.searchParams.has("tools")));
return;
}
const mcpMatch = url.pathname.match(
new RegExp(`^${INTERNAL_PREFIX}/sessions/([^/]+)/mcp-tools/([^/]+)$`),
);
if (request.method === "POST" && mcpMatch) {
await this.executeMcpTool({
sessionId: decodeURIComponent(mcpMatch[1]),
toolName: decodeURIComponent(mcpMatch[2]),
request,
response,
});
return;
}
const descendantMatch = url.pathname.match(
new RegExp(`^${INTERNAL_PREFIX}/sessions/([^/]+)/descendants/([^/]+)$`),
);
if (request.method === "POST" && descendantMatch) {
const binding = this.requireBinding(decodeURIComponent(descendantMatch[1]));
await binding.adoptDescendant?.(decodeURIComponent(descendantMatch[2]));
sendJson(response, 200, {});
return;
}
const toolMatch = url.pathname.match(
new RegExp(`^${INTERNAL_PREFIX}/sessions/([^/]+)/tools/([^/]+)$`),
);
if (request.method === "POST" && toolMatch) {
await this.executeTool({
sessionId: decodeURIComponent(toolMatch[1]),
toolName: decodeURIComponent(toolMatch[2]),
request,
response,
});
return;
}
sendJson(response, 404, { error: "Not found" });
}
private manifest(sessionId: string | null) {
return {
tools: this.serializeManifest(sessionId),
mcpTools: sessionId === null ? [] : (this.sessions.get(sessionId)?.mcp?.tools ?? []),
};
}
private serializeManifest(sessionId: string | null): Array<Record<string, unknown>> {
let catalog: Pick<PaseoToolCatalog, "tools"> | null | undefined = this.manifestCatalog;
if (sessionId !== null) {
@@ -270,16 +303,33 @@ export class OpenCodeBridge {
throw new OpenCodeBridgeClientError(404, `Paseo tool not found: ${input.toolName}`);
}
const body = await readJsonBody(input.request);
const controller = new AbortController();
input.request.once("aborted", () =>
controller.abort(new Error("OpenCode tool request was aborted")),
);
const result = await binding.tools.executeTool(input.toolName, body, {
signal: controller.signal,
signal: abortOnDisconnect(input.response),
});
sendJson(input.response, 200, addModelVisibleStructuredContent(result));
}
private async executeMcpTool(input: {
sessionId: string;
toolName: string;
request: IncomingMessage;
response: ServerResponse;
}): Promise<void> {
const mcp = this.requireBinding(input.sessionId).mcp;
if (!mcp?.tools.some((tool) => tool.name === input.toolName))
throw new OpenCodeBridgeClientError(404, `MCP tool not found: ${input.toolName}`);
const body = await readJsonBody(input.request);
const result = await mcp.execute(input.toolName, body, abortOnDisconnect(input.response));
sendJson(input.response, 200, addModelVisibleStructuredContent(result));
}
private requireBinding(sessionId: string): OpenCodeSessionBinding {
const binding = this.sessions.get(sessionId);
if (!binding)
throw new OpenCodeBridgeClientError(404, "OpenCode session is not bound to a Paseo agent");
return binding;
}
private requireBaseUrl(): string {
if (!this.baseUrl) throw new Error("OpenCode bridge is not started");
return this.baseUrl;
@@ -409,6 +459,53 @@ async function readJsonBody(request: IncomingMessage): Promise<unknown> {
}
}
function sessionContext(binding: OpenCodeSessionBinding, withTools: boolean) {
if (!withTools) return { env: binding.env };
return {
env: binding.env,
tools: [...(binding.tools?.tools.keys() ?? [])],
mcpTools: binding.mcp?.tools ?? [],
mcpInstructions: binding.mcp?.instructions,
};
}
/**
* Aborts when OpenCode stops waiting for the response, for example when the user stops the turn.
* The request has ended by then, so only the response reports the disconnect.
*/
function abortOnDisconnect(response: ServerResponse): AbortSignal {
const controller = new AbortController();
response.once("close", () => {
if (!response.writableFinished)
controller.abort(new Error("OpenCode tool request was aborted"));
});
return controller.signal;
}
function sendFailure(response: ServerResponse, error: unknown): void {
const failure = error instanceof Error ? error : new Error(String(error));
if (response.headersSent) {
response.destroy(failure);
return;
}
if (error instanceof OpenCodeBridgeClientError) {
sendJson(response, error.status, {
error: error.message,
...(error.details === undefined ? {} : { details: error.details }),
});
} else if (error instanceof PaseoToolInputError) {
sendJson(
response,
error.status,
error.issues
? { error: "Invalid tool input", issues: error.issues }
: { error: error.message },
);
} else {
sendJson(response, 500, { error: failure.message });
}
}
function sendJson(response: ServerResponse, status: number, body: unknown): void {
response.writeHead(status, { "Content-Type": "application/json" });
response.end(JSON.stringify(body));
@@ -0,0 +1,148 @@
import { randomUUID } from "node:crypto";
import { writeFile } from "node:fs/promises";
import { createServer, type IncomingMessage, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import path from "node:path";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
import { z } from "zod";
interface HttpMcpOptions {
token: string;
/** Tool `marker` returns this text and advertises it in its description. */
marker: string;
instructions?: string;
/** Tool `marker` requires a string argument with this name. */
requiredInput?: string;
/** Accepts each session DELETE and never answers it, like an unresponsive server. */
holdTermination?: boolean;
/** Accepts the client's `notifications/initialized` and never answers it. */
holdInitialized?: boolean;
}
/** An authenticated Streamable HTTP MCP server, shaped like Hub's execution endpoint. */
export class HttpMcpFixture {
private readonly transports = new Map<string, StreamableHTTPServerTransport>();
/** Session DELETE requests left unanswered because of `holdTermination`. */
heldTerminations = 0;
/** Sessions that a client initialized, including expired ones. */
initializedSessions = 0;
private constructor(
private readonly server: Server,
readonly url: string,
) {}
static async start(options: HttpMcpOptions): Promise<HttpMcpFixture> {
let fixture!: HttpMcpFixture;
const server = createServer(async (request, response) => {
if (request.headers.authorization !== `Bearer ${options.token}`) {
response.writeHead(401).end();
return;
}
if (options.holdTermination && request.method === "DELETE") {
fixture.heldTerminations += 1;
return;
}
const body = request.method === "POST" ? await readJson(request) : undefined;
if (options.holdInitialized && isMethod(body, "notifications/initialized")) return;
const id = request.headers["mcp-session-id"];
if (typeof id === "string") {
const existing = fixture.transports.get(id);
// The protocol answers an unknown session with 404, so the client starts a new one.
if (existing) void existing.handleRequest(request, response, body);
else response.writeHead(404).end();
return;
}
const transport: StreamableHTTPServerTransport = new StreamableHTTPServerTransport({
sessionIdGenerator: () => randomUUID(),
onsessioninitialized: (sessionId) => {
fixture.transports.set(sessionId, transport);
fixture.initializedSessions += 1;
},
// A client ends its session with DELETE when it closes the connection.
onsessionclosed: (sessionId) => {
fixture.transports.delete(sessionId);
},
});
const mcp = new McpServer(
{ name: "hub", version: "1.0.0" },
options.instructions ? { instructions: options.instructions } : {},
);
mcp.registerTool(
"marker",
{
description: `Return ${options.marker}`,
inputSchema: options.requiredInput ? { [options.requiredInput]: z.string() } : {},
},
async () => ({ content: [{ type: "text", text: options.marker }] }),
);
void mcp.connect(transport).then(() => transport.handleRequest(request, response, body));
});
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
fixture = new HttpMcpFixture(
server,
`http://127.0.0.1:${(server.address() as AddressInfo).port}/mcp`,
);
return fixture;
}
/** Forgets every session, as a server does when it restarts. */
expireSessions(): void {
this.transports.clear();
}
/** MCP client sessions that have not been terminated. */
get openSessions(): number {
return this.transports.size;
}
async close(): Promise<void> {
await Promise.all([...this.transports.values()].map((transport) => transport.close()));
this.server.closeAllConnections();
await new Promise<void>((resolve) => this.server.close(() => resolve()));
}
}
async function readJson(request: IncomingMessage): Promise<unknown> {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
return JSON.parse(Buffer.concat(chunks).toString("utf8"));
}
function isMethod(body: unknown, method: string): boolean {
return typeof body === "object" && body !== null && "method" in body && body.method === method;
}
/**
* Writes a stdio MCP server whose `env` tool returns the value of `name` in its own environment.
* It records its pid in `<directory>/stdio-mcp.pid` so tests can prove it exited.
*/
export async function writeStdioMcpFixture(directory: string): Promise<{
script: string;
pidFile: string;
}> {
const script = path.join(directory, "stdio-mcp.mjs");
const pidFile = path.join(directory, "stdio-mcp.pid");
await writeFile(
script,
`import { writeFileSync } from "node:fs";
import { z } from ${JSON.stringify(import.meta.resolve("zod"))};
import { McpServer } from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/mcp.js"))};
import { StdioServerTransport } from ${JSON.stringify(import.meta.resolve("@modelcontextprotocol/sdk/server/stdio.js"))};
writeFileSync(${JSON.stringify(pidFile)}, String(process.pid));
const server = new McpServer({ name: "local", version: "1.0.0" });
server.registerTool("env", { description: "Read an environment variable", inputSchema: { name: z.string() } }, async ({ name }) => ({ content: [{ type: "text", text: process.env[name] ?? "<unset>" }] }));
await server.connect(new StdioServerTransport());
`,
);
return { script, pidFile };
}
export function isProcessAlive(pid: number): boolean {
try {
process.kill(pid, 0);
return true;
} catch {
return false;
}
}
@@ -27,7 +27,6 @@ export class V2Harness {
readonly creates: SessionCreateInput[] = [];
readonly prompts: string[] = [];
readonly environments: Array<{ sessionID: string; variables: Record<string, string> }> = [];
readonly mcpAdds: string[] = [];
readonly instructions = new Map<string, string>();
releases = 0;
active = false;
@@ -117,18 +116,8 @@ export class V2Harness {
provider: { list: unexpected },
command: { list: unexpected },
skill: { list: unexpected },
mcp: {
add: async (input) => {
this.mcpAdds.push(input.server);
},
list: async (input) => ({
location: { directory: input?.location?.directory ?? this.info.location.directory },
data: this.mcpAdds.map((name) => ({
name,
status: { status: "connected" as const },
})),
}),
},
// Paseo hosts session MCP servers itself; OpenCode's location-wide MCP is never used.
mcp: { add: unexpected, list: unexpected },
message: {
list: async (input) => {
if (input.cursor && input.order) throw new Error("cursor cannot be combined with order");
@@ -0,0 +1,305 @@
import { spawn, type ChildProcess } from "node:child_process";
import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { createServer, type IncomingMessage, type Server } from "node:http";
import type { AddressInfo } from "node:net";
import { tmpdir } from "node:os";
import path from "node:path";
import { setTimeout as delay } from "node:timers/promises";
/** A real OpenCode v2 binary; local end-to-end tests run against whatever this resolves to. */
export const OPENCODE_V2_COMMAND = process.env.PASEO_OPENCODE_V2_BIN ?? "opencode";
export const SCRIPTED_MODEL = "test/test-model";
export interface ScriptedTool {
name: string;
description: string;
parameters: unknown;
}
export interface ScriptedRequest {
/** The first user message, which names the conversation. */
prompt: string;
/** Every message the model received, including OpenCode's system and harness context. */
transcript: string;
tools: ScriptedTool[];
}
/**
* Asks the scripted model to call `tool` with `input`, then to report the tool output as
* `RESULT <output>`. A child session started with this prompt follows the same script.
*/
export function scriptedCall(tool: string, input: Record<string, unknown> = {}): string {
return JSON.stringify({ call: tool, input });
}
interface StartOptions {
/** Installs Paseo's plugin before the service starts, as a user does for an explicit server. */
beforeStart?: (paths: { configDirectory: string }) => Promise<void>;
/** The user's own OpenCode MCP servers, in OpenCode's `mcp.servers` configuration shape. */
mcpServers?: Record<string, unknown>;
}
/**
* A detached OpenCode v2 service with isolated state, backed by a scripted model. It stands in
* for the shared service a user runs, so it is never owned by the code under test.
*/
export class ScriptedOpenCodeService {
private constructor(
readonly requests: ScriptedRequest[],
readonly root: string,
readonly url: string,
readonly password: string,
private readonly process: ChildProcess,
private readonly llm: Server,
) {}
static async start(options: StartOptions = {}): Promise<ScriptedOpenCodeService> {
const root = await mkdtemp(path.join(tmpdir(), "paseo-opencode-v2-service-"));
const configDirectory = path.join(root, "config");
await mkdir(configDirectory, { recursive: true });
const requests: ScriptedRequest[] = [];
const llm = createServer((request, response) => {
void (async () => {
try {
const body = await respond(request);
response.writeHead(200, { "content-type": "text/event-stream" });
response.end(body);
} catch (error) {
response.writeHead(500, { "content-type": "application/json" });
response.end(JSON.stringify({ error: String(error) }));
}
})();
});
async function respond(request: IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
for await (const chunk of request) chunks.push(chunk as Buffer);
const body = JSON.parse(Buffer.concat(chunks).toString("utf8")) as ChatRequest;
const prompt = firstUserText(body.messages);
requests.push({
prompt,
transcript: body.messages.map(messageText).join("\n"),
tools: (body.tools ?? []).map((tool) => ({
name: tool.function.name,
description: tool.function.description ?? "",
parameters: tool.function.parameters,
})),
});
// OpenCode may add harness messages after a tool result, so answer the latest step.
const step = body.messages.findLast(
(message) =>
message.role === "tool" ||
(message.role === "user" && parseScript(messageText(message)) !== null),
);
if (step?.role === "tool") return textStream(`RESULT ${messageText(step)}`);
const script = step && parseScript(messageText(step));
if (!script) return textStream("OK");
return toolCallStream(`call-${requests.length}`, script.call, script.input);
}
await new Promise<void>((resolve) => llm.listen(0, "127.0.0.1", resolve));
const llmUrl = `http://127.0.0.1:${(llm.address() as AddressInfo).port}/v1`;
await writeFile(
path.join(configDirectory, "opencode.json"),
JSON.stringify({
...config(llmUrl),
...(options.mcpServers ? { mcp: { servers: options.mcpServers } } : {}),
}),
);
await options.beforeStart?.({ configDirectory });
const child = spawn(
OPENCODE_V2_COMMAND,
["serve", "--service", "--hostname", "127.0.0.1", "--port", "0"],
{
cwd: root,
detached: process.platform !== "win32",
stdio: ["ignore", "pipe", "pipe"],
env: { ...process.env, ...isolatedEnvironment(root) },
},
);
child.stdout?.on("data", () => undefined);
child.stderr?.on("data", () => undefined);
const registration = path.join(root, "state", "opencode", "service.json");
const deadline = Date.now() + 30_000;
while (true) {
const content = await readFile(registration, "utf8").catch(() => "");
const parsed = content ? (JSON.parse(content) as { url: string; password: string }) : null;
// The service registers before it serves requests.
if (parsed && (await isReady(parsed.url, parsed.password))) {
return new ScriptedOpenCodeService(requests, root, parsed.url, parsed.password, child, llm);
}
if (child.exitCode !== null || Date.now() > deadline) {
llm.close();
await rm(root, { recursive: true, force: true });
throw new Error(`OpenCode v2 service did not register (exit ${child.exitCode})`);
}
await delay(100);
}
}
/** Provider environment that lets Paseo discover this service, as with the user's own. */
get discoveryEnvironment(): Record<string, string> {
return {
XDG_STATE_HOME: path.join(this.root, "state"),
XDG_CONFIG_HOME: path.join(this.root, "xdg-config"),
OPENCODE_CONFIG_DIR: path.join(this.root, "config"),
};
}
/**
* Provider environment for a server Paseo starts itself with this service's model. It keeps the
* service's state directory, so the service's registration is present but must not be used.
*/
get ownedEnvironment(): Record<string, string> {
return {
...isolatedEnvironment(this.root),
XDG_DATA_HOME: path.join(this.root, "owned-data"),
};
}
get configDirectory(): string {
return path.join(this.root, "config");
}
/**
* Agent requests the scripted model received for the conversation started with `prompt`.
* OpenCode's title requests carry the same prompt but offer no tools, so they are left out.
*/
requestsFor(prompt: string): ScriptedRequest[] {
return this.agentRequests.filter((request) => request.prompt === prompt);
}
get agentRequests(): ScriptedRequest[] {
return this.requests.filter((request) => request.tools.length > 0);
}
async stop(): Promise<void> {
const exited = new Promise<void>((resolve) => {
if (this.process.exitCode !== null) resolve();
else this.process.once("exit", () => resolve());
});
if (this.process.pid && process.platform !== "win32") {
try {
process.kill(-this.process.pid, "SIGTERM");
} catch {
this.process.kill("SIGTERM");
}
} else this.process.kill("SIGTERM");
await Promise.race([exited, delay(10_000)]);
if (this.process.exitCode === null) this.process.kill("SIGKILL");
await new Promise<void>((resolve) => this.llm.close(() => resolve()));
await rm(this.root, { recursive: true, force: true });
}
}
async function isReady(url: string, password: string): Promise<boolean> {
const response = await fetch(new URL("/api/info", url), {
headers: { Authorization: `Basic ${Buffer.from(`opencode:${password}`).toString("base64")}` },
signal: AbortSignal.timeout(2_000),
}).catch(() => null);
return response?.ok === true;
}
function isolatedEnvironment(root: string): Record<string, string> {
return {
HOME: root,
OPENCODE_CONFIG_DIR: path.join(root, "config"),
OPENCODE_CONFIG_CONTENT: "{}",
OPENCODE_DISABLE_AUTOUPDATE: "true",
OPENCODE_DISABLE_MODELS_FETCH: "true",
// The scripted model calls shell and subagent directly, which full Code Mode moves inside execute.
OPENCODE_FLAGS: "-full_codemode",
XDG_CACHE_HOME: path.join(root, "cache"),
XDG_CONFIG_HOME: path.join(root, "xdg-config"),
XDG_DATA_HOME: path.join(root, "data"),
XDG_STATE_HOME: path.join(root, "state"),
};
}
function config(llmUrl: string) {
return {
update: "disable",
model: SCRIPTED_MODEL,
providers: {
test: {
name: "Test",
package: "aisdk:@ai-sdk/openai-compatible",
settings: { apiKey: "test-key", baseURL: llmUrl },
models: {
"test-model": {
name: "Test Model",
capabilities: { tools: true, input: ["text"], output: ["text"] },
cost: { input: 0, output: 0 },
limit: { context: 100_000, output: 10_000 },
},
},
},
},
};
}
interface ChatMessage {
role: string;
content?: string | Array<{ type: string; text?: string }> | null;
}
interface ChatRequest {
messages: ChatMessage[];
tools?: Array<{ function: { name: string; description?: string; parameters: unknown } }>;
}
function messageText(message: ChatMessage): string {
if (typeof message.content === "string") return message.content;
return (message.content ?? []).map((part) => part.text ?? "").join("");
}
function firstUserText(messages: ChatMessage[]): string {
const user = messages.find((message) => message.role === "user");
return user ? messageText(user).trim() : "";
}
function parseScript(prompt: string): { call: string; input: Record<string, unknown> } | null {
const start = prompt.indexOf('{"call"');
if (start === -1) return null;
const end = prompt.lastIndexOf("}");
return JSON.parse(prompt.slice(start, end + 1)) as {
call: string;
input: Record<string, unknown>;
};
}
function textStream(text: string): string {
return sse([
{ choices: [{ delta: { role: "assistant" }, finish_reason: null }], usage: null },
{ choices: [{ delta: { content: text }, finish_reason: null }], usage: null },
{ choices: [{ delta: {}, finish_reason: "stop" }], usage: null },
{ choices: [], usage: { prompt_tokens: 10, completion_tokens: 1, total_tokens: 11 } },
]);
}
function toolCallStream(id: string, name: string, input: unknown): string {
return sse([
{
choices: [
{
delta: {
role: "assistant",
tool_calls: [{ index: 0, id, type: "function", function: { name, arguments: "" } }],
},
finish_reason: null,
},
],
usage: null,
},
{
choices: [
{ delta: { tool_calls: [{ index: 0, function: { arguments: JSON.stringify(input) } }] } },
],
usage: null,
},
{ choices: [{ delta: {}, finish_reason: "tool_calls" }], usage: null },
{ choices: [], usage: { prompt_tokens: 10, completion_tokens: 1, total_tokens: 11 } },
]);
}
function sse(chunks: unknown[]): string {
return `${chunks.map((chunk) => `data: ${JSON.stringify(chunk)}\n\n`).join("")}data: [DONE]\n\n`;
}
@@ -787,11 +787,7 @@ describe("OpenCode v2 session lifecycle", () => {
second.prompts.push(input.text);
};
const session = await client.createSession(
{
provider: "opencode",
cwd: "/tmp/project",
mcpServers: { tools: { type: "stdio", command: "tools" } },
},
{ provider: "opencode", cwd: "/tmp/project" },
{ env: { TOKEN: "test" } },
);
const running = session.run("before exit");
@@ -802,7 +798,6 @@ describe("OpenCode v2 session lifecycle", () => {
try {
expect((await session.run("after exit")).finalText).toBe("recovered");
expect(second.prompts).toEqual(["after exit"]);
expect(second.mcpAdds).toEqual(["tools"]);
expect(second.environments).toMatchObject([
{ sessionID: "session", variables: { TOKEN: "test", PATH: process.env.PATH } },
]);
@@ -1128,12 +1123,12 @@ describe("OpenCode v2 session lifecycle", () => {
}
});
test("reuses the shared helper for sessions whose env is only agent identity", async () => {
test("shares the server for a launch environment, which reaches the session only", async () => {
const harness = new V2Harness();
const acquires: Array<{ env?: Record<string, string>; dedicated?: boolean }> = [];
let acquisitions = 0;
const runtime = {
acquire: async (input: { env?: Record<string, string>; dedicated?: boolean } = {}) => {
acquires.push(input);
acquire: async () => {
acquisitions += 1;
return harness.connection;
},
shutdown: async () => undefined,
@@ -1141,46 +1136,32 @@ describe("OpenCode v2 session lifecycle", () => {
const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime });
const session = await client.createSession(
{ provider: "opencode", cwd: "/tmp/project" },
{ agentId: "agent", env: { PASEO_AGENT_ID: "agent", PASEO_AGENT_CWD: "/tmp/project" } },
{ agentId: "agent", env: { HUB_SECRET: "secret", PASEO_AGENT_ID: "agent" } },
);
try {
expect(acquires).toEqual([{}]);
expect(acquisitions).toBe(1);
expect(harness.environments).toMatchObject([
{
sessionID: "session",
variables: { PASEO_AGENT_ID: "agent", PASEO_AGENT_CWD: "/tmp/project" },
},
{ sessionID: "session", variables: { HUB_SECRET: "secret", PASEO_AGENT_ID: "agent" } },
]);
} finally {
await session.close();
}
});
test("starts a dedicated helper when the session carries custom MCP", async () => {
test("rejects MCP servers without the Paseo bridge before creating an OpenCode session", async () => {
const harness = new V2Harness();
const acquires: Array<{ env?: Record<string, string>; dedicated?: boolean }> = [];
const runtime = {
acquire: async (input: { env?: Record<string, string>; dedicated?: boolean } = {}) => {
acquires.push(input);
return harness.connection;
},
shutdown: async () => undefined,
};
const client = new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime });
const session = await client.createSession(
{
const client = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: harness.runtime,
});
await expect(
client.createSession({
provider: "opencode",
cwd: "/tmp/project",
mcpServers: { custom: { type: "stdio", command: "custom", args: [] } },
},
{ agentId: "agent", env: { PASEO_AGENT_ID: "agent", PASEO_AGENT_CWD: "/tmp/project" } },
);
try {
expect(acquires).toHaveLength(1);
expect(acquires[0]?.dedicated).toBe(true);
} finally {
await session.close();
}
}),
).rejects.toThrow("OpenCode MCP servers require the Paseo tool bridge");
expect(harness.creates).toEqual([]);
});
test("refuses replacement work after a failed stop until Stop succeeds", async () => {
@@ -1,11 +1,7 @@
import { OpenCodeV2Session } from "./session.js";
import { V2_CAPABILITIES } from "./capabilities.js";
import {
controls,
permissionRules,
applyResumeOverrides,
requiresDedicatedV2Server,
} from "./configuration.js";
import { controls, permissionRules, applyResumeOverrides } from "./configuration.js";
import { SessionMcp } from "./session-mcp.js";
import { commands } from "./commands.js";
import { waitForLocationReady } from "./readiness.js";
@@ -44,6 +40,13 @@ import { V2Runtime, type V2Connection } from "./runtime.js";
import type { OpenCodeServiceSelection } from "./service-selection.js";
import { modelRef, modesFromV2, modelsFromV2 } from "./mapping.js";
interface PreparedLaunch {
launch: AgentLaunchContext | undefined;
/** The complete shell environment, when the launch sets one. */
environment: Record<string, string> | undefined;
mcp?: SessionMcp;
}
interface V2AgentOptions {
logger: Logger;
settings?: ProviderRuntimeSettings;
@@ -111,20 +114,30 @@ export class OpenCodeV2AgentClient implements AgentClient {
launch?: AgentLaunchContext,
options?: AgentCreateSessionOptions,
): Promise<AgentSession> {
const connection = await this.runtime.acquire(
requiresDedicatedV2Server(config, launch) ? { env: launch?.env, dedicated: true } : {},
);
const prepared = await this.prepareLaunch(config, launch, false);
try {
const info = await connection.client.session.create({
location: { directory: config.cwd },
title: config.title,
agent: config.modeId ?? "build",
model: config.model ? modelRef(config.model, config.thinkingOptionId) : undefined,
permissions: permissionRules(config),
});
return await this.attach(connection, info, config, launch, options?.persistSession !== false);
const connection = await this.runtime.acquire();
try {
const info = await connection.client.session.create({
location: { directory: config.cwd },
title: config.title,
agent: config.modeId ?? "build",
model: config.model ? modelRef(config.model, config.thinkingOptionId) : undefined,
permissions: permissionRules(config),
});
return await this.attach(
connection,
info,
config,
prepared,
options?.persistSession !== false,
);
} catch (error) {
await connection.release();
throw error;
}
} catch (error) {
await connection.release();
await prepared.mcp?.close();
throw error;
}
}
@@ -143,48 +156,60 @@ export class OpenCodeV2AgentClient implements AgentClient {
provider: "opencode",
cwd,
};
const connection =
this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain() ??
(await this.runtime.acquire(
requiresDedicatedV2Server(config, launch) ? { env: launch?.env, dedicated: true } : {},
));
const historyOnly = options?.purpose === "history";
const prepared = await this.prepareLaunch(config, launch, historyOnly);
try {
const info = await connection.client.session.get({
sessionID: handle.nativeHandle ?? handle.sessionId,
});
await applyResumeOverrides(connection.client, info, overrides);
return await this.attach(
connection,
info,
config,
launch,
true,
options?.purpose === "history",
);
const connection =
this.connections.get(handle.nativeHandle ?? handle.sessionId)?.retain() ??
(await this.runtime.acquire());
try {
const info = await connection.client.session.get({
sessionID: handle.nativeHandle ?? handle.sessionId,
});
await applyResumeOverrides(connection.client, info, overrides);
return await this.attach(connection, info, config, prepared, true, historyOnly);
} catch (error) {
await connection.release();
throw error;
}
} catch (error) {
await connection.release();
await prepared.mcp?.close();
throw error;
}
}
/**
* Resolves what the session receives from its launch. OpenCode's own MCP servers are shared by
* a location, so Paseo hosts each session's servers itself, before OpenCode sees the session.
*/
private async prepareLaunch(
config: AgentSessionConfig,
launch: AgentLaunchContext | undefined,
historyOnly: boolean,
): Promise<PreparedLaunch> {
const environment = launch?.env
? createProviderEnv({ runtimeSettings: this.options.settings, overlays: [launch.env] })
: undefined;
const servers = config.mcpServers ?? {};
if (historyOnly || Object.keys(servers).length === 0) return { launch, environment };
if (!this.options.bridge)
throw new Error("OpenCode MCP servers require the Paseo tool bridge, which is not running");
const mcp = await SessionMcp.connect({
servers,
cwd: config.cwd,
env: environment ?? createProviderEnv({ runtimeSettings: this.options.settings }),
});
return { launch, environment, mcp };
}
private async attach(
connection: V2Connection,
info: SessionInfo,
config: AgentSessionConfig,
launch: AgentLaunchContext | undefined,
{ launch, environment, mcp }: PreparedLaunch,
persist: boolean,
historyOnly = false,
) {
const acquire = () =>
this.runtime.acquire(
requiresDedicatedV2Server(config, launch) ? { env: launch?.env, dedicated: true } : {},
);
let ownedConnection = connection;
const bridge = this.options.bridge;
const unbind = bridge?.bindSession({
sessionId: info.id,
env: launch?.env ?? {},
tools: launch?.paseoTools,
});
const bound = new Map<string, () => void>();
const bindChild = (childId: string) => {
this.connections.set(childId, ownedConnection);
@@ -196,6 +221,19 @@ export class OpenCodeV2AgentClient implements AgentClient {
});
if (childUnbind) bound.set(childId, childUnbind);
};
// The bridge serves descendants before the session exists, so it reads the session late.
let session: OpenCodeV2Session | undefined;
let unbind: (() => void) | undefined;
unbind = bridge?.bindSession({
sessionId: info.id,
env: launch?.env ?? {},
tools: launch?.paseoTools,
mcp,
adoptDescendant: async (childId) => {
bindChild(childId);
await session?.adoptDescendant(childId);
},
});
this.connections.set(info.id, connection);
const releaseBindings = () => {
unbind?.();
@@ -208,25 +246,23 @@ export class OpenCodeV2AgentClient implements AgentClient {
if (owner === ownedConnection) this.connections.set(id, next);
ownedConnection = next;
};
const session = new OpenCodeV2Session(
session = new OpenCodeV2Session({
connection,
info,
config,
this.options.logger,
logger: this.options.logger,
persist,
Boolean(this.options.bridge),
releaseBindings,
requiresPaseoPlugin: Boolean(bridge),
environment,
mcp,
unbind: releaseBindings,
bindChild,
acquire,
acquire: () => this.runtime.acquire(),
moved,
historyOnly,
);
});
try {
await session.initialize(
launch?.env
? createProviderEnv({ runtimeSettings: this.options.settings, overlays: [launch.env] })
: undefined,
);
await session.initialize();
return session;
} catch (error) {
await session.close();
@@ -15,12 +15,17 @@ interface ChildrenOptions {
id: string;
emit(event: AgentStreamEvent): void;
reconcilePermissions(id: string): Promise<void>;
bindChild?: (id: string) => void;
/** Prepares a newly seen descendant session. */
adoptChild?: (id: string) => Promise<void>;
}
export class SessionChildren {
private readonly children = new Map<string, V2Timeline>();
private readonly childStates = new Map<string, string>();
constructor(private readonly options: ChildrenOptions) {}
/** Every descendant session seen so far. */
ids(): string[] {
return [...this.children.keys()];
}
async observe(event: import("@opencode/client").OpenCodeEvent) {
if (
event.type === "session.created" &&
@@ -57,9 +62,9 @@ export class SessionChildren {
await this.options.reconcilePermissions(info.id);
let timeline = this.children.get(info.id);
if (!timeline) {
timeline = new V2Timeline();
await this.options.adoptChild?.(info.id);
timeline = this.children.get(info.id) ?? new V2Timeline();
this.children.set(info.id, timeline);
this.options.bindChild?.(info.id);
}
const active = await this.options.client().session.active();
let status: "running" | "failed" | "canceled" | "completed" = "completed";
@@ -1,6 +1,6 @@
import { describe, expect, test } from "vitest";
import { controls, permissionRules, requiresDedicatedV2Server } from "./configuration.js";
import { controls, permissionRules } from "./configuration.js";
describe("OpenCode v2 permission rules", () => {
test("maps authored native permissions and exact injected MCP grants", () => {
@@ -19,43 +19,6 @@ describe("OpenCode v2 permission rules", () => {
});
});
describe("OpenCode v2 helper isolation", () => {
test("shares the helper for agent-identity environment only", () => {
expect(
requiresDedicatedV2Server(
{ provider: "opencode", cwd: "/tmp/project" },
{
agentId: "agent",
env: {
PASEO_AGENT_ID: "agent",
PASEO_AGENT_CWD: "/tmp/project",
PASEO_WORKSPACE_ID: "ws-1",
},
},
),
).toBe(false);
});
test("dedicates a helper for any other process environment", () => {
expect(
requiresDedicatedV2Server(
{ provider: "opencode", cwd: "/tmp/project" },
{ agentId: "agent", env: { CUSTOM_FLAG: "1" } },
),
).toBe(true);
});
test("dedicates a helper when the session carries custom MCP", () => {
expect(
requiresDedicatedV2Server({
provider: "opencode",
cwd: "/tmp/project",
mcpServers: { custom: { type: "stdio", command: "custom", args: [] } },
}),
).toBe(true);
});
});
describe("OpenCode v2 controls", () => {
test("describes the auto-accept toggle over the auto_accept option", () => {
expect(controls).toEqual([{ type: "toggle", key: "auto_accept", label: "Auto-accept" }]);
@@ -1,15 +1,12 @@
import type { SessionInfo, PermissionRuleset } from "@opencode/client";
import type { V2Api } from "./api.js";
import type {
AgentLaunchContext,
AgentOptionControl,
AgentSessionConfig,
} from "../../../agent-sdk-types.js";
import type { AgentOptionControl, AgentSessionConfig } from "../../../agent-sdk-types.js";
import { OpenCodeProviderOptionsSchema, buildOpenCodePermissionRules } from "../options.js";
import { modelRef } from "./mapping.js";
import { openCodeMcpToolName } from "./session-mcp.js";
export const controls: AgentOptionControl[] = [
{ type: "toggle", key: "auto_accept", label: "Auto-accept" },
@@ -21,7 +18,7 @@ export function permissionRules(config: AgentSessionConfig): PermissionRuleset {
undefined,
) ?? [];
const grants: PermissionRuleset = (config.toolPolicy?.preapproved ?? []).map((grant) => ({
action: `${grant.server.replace(/[^a-zA-Z0-9_-]/g, "_")}_${grant.tool.replace(/[^a-zA-Z0-9_-]/g, "_")}`,
action: openCodeMcpToolName(grant.server, grant.tool),
resource: "*",
effect: "allow",
}));
@@ -60,17 +57,3 @@ export async function applyResumeOverrides(
info.model = model;
}
}
// Agent identity env is applied per session through `session.environment`, so
// it must not force a dedicated server. Custom MCP is location-scoped, and any
// other env key belongs to the process, so both need isolation. Mirrors the v1
// adapter's `requiresDedicatedOpenCodeServer`.
const V2_SESSION_ENV_KEYS = new Set(["PASEO_AGENT_ID", "PASEO_AGENT_CWD", "PASEO_WORKSPACE_ID"]);
export function requiresDedicatedV2Server(
config: AgentSessionConfig,
launch?: AgentLaunchContext,
): boolean {
if (Object.keys(config.mcpServers ?? {}).length > 0) return true;
return Object.keys(launch?.env ?? {}).some((key) => !V2_SESSION_ENV_KEYS.has(key));
}
@@ -170,17 +170,6 @@ describe("V2Runtime against an external server", () => {
await runtime.shutdown();
});
test("rejects session configuration that requires process isolation", async () => {
const runtime = new V2Runtime({
logger: createTestLogger(),
externalServer: { url: "http://127.0.0.1:1" },
});
await expect(runtime.acquire({ dedicated: true })).rejects.toThrow(
"require an isolated server",
);
await runtime.shutdown();
});
test("rejects provider process environment on an explicit server", async () => {
const runtime = new V2Runtime({
logger: createTestLogger(),
@@ -17,7 +17,11 @@ import { resolveOpenCodeHomeDir } from "../paths.js";
import { OpenCodeHttpError } from "../http-error.js";
import { raceProviderRefreshAbort } from "../../../provider-refresh-deadline.js";
import { resolveExternalOpenCodeServer, type ExternalOpenCodeServer } from "./external-server.js";
import { selectOpenCodeService, type OpenCodeServiceSelection } from "./service-selection.js";
import {
processEnvironmentOverrides,
selectOpenCodeService,
type OpenCodeServiceSelection,
} from "./service-selection.js";
import { bridgeBindings, connectSharedService } from "./shared-service.js";
import {
hasManagedBridge,
@@ -57,8 +61,6 @@ export interface V2RuntimeOptions {
export interface V2RuntimeAcquireOptions {
fresh?: boolean;
dedicated?: boolean;
env?: Record<string, string>;
signal?: AbortSignal;
}
@@ -89,17 +91,9 @@ export class V2Runtime {
input.signal?.throwIfAborted();
this.assertBridgePort();
const selection = await raceProviderRefreshAbort(input.signal, this.selection);
let pending: Promise<Generation>;
if (selection.kind !== "owned") {
this.assertSharedConfiguration(input, selection);
this.current ??= this.startTracked();
pending = this.current;
} else if (input.env || input.dedicated) {
pending = this.startTracked(input.env);
} else {
if (!this.current) this.current = this.startTracked();
pending = this.current;
}
if (selection.kind === "explicit") this.assertExplicitConfiguration();
this.current ??= this.startTracked();
const pending = this.current;
let generation: Generation;
try {
generation = await raceProviderRefreshAbort(input.signal, pending);
@@ -143,29 +137,13 @@ export class V2Runtime {
throw new Error("PASEO_OPENCODE_BRIDGE_PORT changed; restart Paseo to apply the bridge port");
}
private assertSharedConfiguration(
input: V2RuntimeAcquireOptions,
selection: OpenCodeServiceSelection,
): void {
const connectionEnv = new Set([
"PASEO_OPENCODE_SERVER_URL",
"PASEO_OPENCODE_SERVER_PASSWORD",
"PASEO_OPENCODE_BRIDGE_URL",
"PASEO_OPENCODE_BRIDGE_PORT",
]);
if (selection.kind === "discovered") {
connectionEnv.add("XDG_CONFIG_HOME");
connectionEnv.add("XDG_STATE_HOME");
connectionEnv.add("OPENCODE_CONFIG_DIR");
}
const processOverrides = Object.keys(this.options.settings?.env ?? {}).filter(
(key) => !connectionEnv.has(key),
);
if (input.env || input.dedicated || processOverrides.length) {
// Discovery skips a service that cannot honor the provider environment; an explicit one cannot be skipped.
private assertExplicitConfiguration(): void {
const overrides = processEnvironmentOverrides(this.options.settings?.env);
if (overrides.length)
throw new Error(
`Custom OpenCode MCP servers or process environment require an isolated server and cannot be used with a shared OpenCode service${processOverrides.length ? `: ${processOverrides.join(", ")}` : ""}.`,
`OpenCode provider environment configures the server process and cannot be used with an existing OpenCode server: ${overrides.join(", ")}.`,
);
}
}
private lease(generation: Generation, pending: Promise<Generation>): V2Connection {
@@ -201,8 +179,8 @@ export class V2Runtime {
this.current = null;
}
private startTracked(env?: Record<string, string>): Promise<Generation> {
const pending = this.start(env);
private startTracked(): Promise<Generation> {
const pending = this.start();
this.starts.add(pending);
void pending.then(
(generation) =>
@@ -219,7 +197,7 @@ export class V2Runtime {
return pending;
}
private async start(env: Record<string, string> = {}): Promise<Generation> {
private async start(): Promise<Generation> {
const selection = await this.selection;
if (selection.kind !== "owned") {
const generation: Generation = {
@@ -242,7 +220,6 @@ export class V2Runtime {
const configured = {
...(inheritedConfig ? { OPENCODE_CONFIG_CONTENT: inheritedConfig } : {}),
...settings?.env,
...env,
};
const bridge = this.options.bridge;
const plugin = bridge
@@ -5,7 +5,7 @@ import { tmpdir } from "node:os";
import { expect, test } from "vitest";
import { selectOpenCodeService } from "./service-selection.js";
test("selects the registered service with its credential and ignores stale registration", async () => {
test("selects the registered service with its credential unless the provider configures the process", async () => {
const directory = await mkdtemp(path.join(tmpdir(), "paseo-service-"));
const file = path.join(directory, "service.json");
let requests = 0;
@@ -38,6 +38,24 @@ test("selects the registered service with its credential and ignores stale regis
await selectOpenCodeService({ file, explicit: { url: "http://explicit.test" } }),
).toEqual({ kind: "explicit", server: { url: "http://explicit.test" } });
expect(requests).toBe(1);
// Provider environment that configures the server process needs a server Paseo starts.
expect(
await selectOpenCodeService({
file,
env: { OPENCODE_CONFIG_CONTENT: "{}", PROVIDER_KEY: "key" },
}),
).toEqual({ kind: "owned" });
// Locating the service and the bridge is not process configuration.
expect(
await selectOpenCodeService({
file,
env: {
XDG_CONFIG_HOME: directory,
OPENCODE_CONFIG_DIR: directory,
PASEO_OPENCODE_BRIDGE_URL: "http://127.0.0.1:1",
},
}),
).toEqual({ kind: "discovered", server: { url, password: "secret" } });
await writeFile(file, JSON.stringify({ url, password: "secret", pid: process.pid + 1 }));
expect(await selectOpenCodeService({ file })).toEqual({ kind: "owned" });
} finally {
@@ -7,12 +7,33 @@ export type OpenCodeServiceSelection =
| { kind: "owned" }
| { kind: "explicit" | "discovered"; server: ExternalOpenCodeServer };
// Provider env keys that choose and reach a server rather than configure its process.
const CONNECTION_ENV = new Set([
"PASEO_OPENCODE_SERVER_URL",
"PASEO_OPENCODE_SERVER_PASSWORD",
"PASEO_OPENCODE_BRIDGE_URL",
"PASEO_OPENCODE_BRIDGE_PORT",
]);
// A discovered service is found through these, and its configuration directory is checked.
const DISCOVERY_ENV = new Set(["XDG_CONFIG_HOME", "XDG_STATE_HOME", "OPENCODE_CONFIG_DIR"]);
/** Provider env keys that only apply to an OpenCode process Paseo starts itself. */
export function processEnvironmentOverrides(
env: Record<string, string | undefined> | undefined,
kind: "explicit" | "discovered" = "explicit",
): string[] {
return Object.keys(env ?? {}).filter(
(key) => !CONNECTION_ENV.has(key) && !(kind === "discovered" && DISCOVERY_ENV.has(key)),
);
}
export async function selectOpenCodeService(input: {
explicit?: ExternalOpenCodeServer;
file?: string;
env?: Record<string, string | undefined>;
}): Promise<OpenCodeServiceSelection> {
if (input.explicit) return { kind: "explicit", server: input.explicit };
if (processEnvironmentOverrides(input.env, "discovered").length) return { kind: "owned" };
const state =
input.env?.XDG_STATE_HOME ??
process.env.XDG_STATE_HOME ??
@@ -0,0 +1,121 @@
import type { McpServerConfig } from "../../../agent-sdk-types.js";
import { connectMcpServer, type McpClientConnection } from "../../../mcp-client-connection.js";
import type { PaseoToolResult } from "../../../tools/types.js";
import type { OpenCodeBridgeMcpTool } from "../bridge.js";
/** OpenCode's effective name for an MCP tool, which is also its permission action. */
export function openCodeMcpToolName(server: string, tool: string): string {
return `${normalize(server)}_${normalize(tool)}`;
}
function normalize(name: string): string {
return name.replace(/[^a-zA-Z0-9_-]/g, "_");
}
interface SessionMcpTool extends OpenCodeBridgeMcpTool {
connection: McpClientConnection;
tool: string;
}
interface ConnectSessionMcpInput {
servers: Record<string, McpServerConfig>;
cwd: string;
/** The agent's complete launch environment, which stdio servers inherit. */
env: NodeJS.ProcessEnv;
}
/**
* The MCP servers of one OpenCode session, hosted by Paseo. OpenCode's own MCP configuration is
* shared by every session in a location, so Paseo connects these servers itself and exposes their
* tools to this session only, through the Paseo bridge.
*/
export class SessionMcp {
private closed: Promise<void> | undefined;
private constructor(
private readonly servers: ReadonlyArray<{ name: string; connection: McpClientConnection }>,
private readonly byName: ReadonlyMap<string, SessionMcpTool>,
) {}
static async connect(input: ConnectSessionMcpInput): Promise<SessionMcp> {
const settled = await Promise.allSettled(
Object.entries(input.servers).map(async ([name, config]) => {
try {
const connection = await connectMcpServer({
config,
cwd: input.cwd,
env: input.env,
clientName: "paseo-opencode",
});
return { name, connection };
} catch (error) {
throw new Error(
`OpenCode MCP server ${name} failed to connect: ${error instanceof Error ? error.message : String(error)}`,
{ cause: error },
);
}
}),
);
const servers = settled.flatMap((result) =>
result.status === "fulfilled" ? [result.value] : [],
);
const failure = settled.find((result) => result.status === "rejected");
const tools = new Map<string, SessionMcpTool>();
try {
if (failure) throw failure.reason;
for (const { name: server, connection } of servers)
for (const tool of connection.tools) {
const name = openCodeMcpToolName(server, tool.name);
if (tools.has(name))
throw new Error(`OpenCode MCP tool name ${name} is provided by more than one server`);
tools.set(name, {
name,
description: tool.description ?? "",
inputSchema: tool.inputSchema,
connection,
tool: tool.name,
});
}
} catch (error) {
await Promise.all(servers.map(({ connection }) => connection.close()));
throw error;
}
return new SessionMcp(servers, tools);
}
get tools(): OpenCodeBridgeMcpTool[] {
return [...this.byName.values()].map(({ name, description, inputSchema }) => ({
name,
description,
inputSchema,
}));
}
/** Server instructions in the shape OpenCode gives its own MCP servers. */
get instructions(): string | undefined {
const servers = this.servers.flatMap(({ name, connection }) =>
connection.instructions?.trim()
? [
` <server name="${name}">`,
...connection.instructions.split("\n").map((line) => ` ${line}`),
" </server>",
]
: [],
);
if (!servers.length) return undefined;
return ["<mcp_instructions>", ...servers, "</mcp_instructions>"].join("\n");
}
async execute(name: string, input: unknown, signal?: AbortSignal): Promise<PaseoToolResult> {
const tool = this.byName.get(name);
if (!tool) throw new Error(`MCP tool not found: ${name}`);
const args = input && typeof input === "object" ? (input as Record<string, unknown>) : {};
return tool.connection.callTool(tool.tool, args, signal);
}
close(): Promise<void> {
this.closed ??= Promise.all(this.servers.map(({ connection }) => connection.close())).then(
() => undefined,
);
return this.closed;
}
}
@@ -43,6 +43,25 @@ import { SessionPermissions } from "./permissions.js";
import { SessionUsage } from "./usage.js";
import { createSessionMetricsReporter } from "../../metrics.js";
import { replayedTurnMetrics, sessionMetrics } from "./metrics.js";
import type { SessionMcp } from "./session-mcp.js";
export interface OpenCodeV2SessionOptions {
connection: V2Connection;
info: SessionInfo;
config: AgentSessionConfig;
logger: Logger;
persist: boolean;
requiresPaseoPlugin: boolean;
/** The complete shell environment for this session and its descendants. */
environment?: Record<string, string>;
/** MCP servers Paseo hosts for this session; the session closes them. */
mcp?: SessionMcp;
unbind?: () => void;
bindChild?: (id: string) => void;
acquire?: () => Promise<V2Connection>;
moved?: (connection: V2Connection) => void;
historyOnly?: boolean;
}
export class OpenCodeV2Session implements AgentSession {
readonly provider = "opencode";
@@ -58,7 +77,6 @@ export class OpenCodeV2Session implements AgentSession {
private streamAbort = new AbortController();
private exited = false;
private reconnecting: Promise<void> | null = null;
private launchEnv: Record<string, string> | undefined;
private sync: Promise<void> = Promise.resolve();
private dirty = false;
private refreshTimer: ReturnType<typeof setTimeout> | null = null;
@@ -70,19 +88,33 @@ export class OpenCodeV2Session implements AgentSession {
private readonly reportSessionMetrics = createSessionMetricsReporter((metrics) =>
this.emit({ type: "session_metrics_updated", provider: "opencode", metrics }),
);
constructor(
private connection: V2Connection,
private info: SessionInfo,
private readonly config: AgentSessionConfig,
private readonly logger: Logger,
private readonly persist: boolean,
private readonly requiresPaseoPlugin: boolean,
private readonly unbind?: () => void,
bindChild?: (id: string) => void,
private readonly acquire?: () => Promise<V2Connection>,
private readonly moved?: (connection: V2Connection) => void,
private readonly historyOnly = false,
) {
private connection: V2Connection;
private info: SessionInfo;
private readonly config: AgentSessionConfig;
private readonly logger: Logger;
private readonly persist: boolean;
private readonly requiresPaseoPlugin: boolean;
// OpenCode replaces the whole local shell environment, rather than overlaying it.
private readonly environment: Record<string, string> | undefined;
private readonly mcp: SessionMcp | undefined;
private readonly unbind: (() => void) | undefined;
private readonly acquire: (() => Promise<V2Connection>) | undefined;
private readonly moved: ((connection: V2Connection) => void) | undefined;
private readonly historyOnly: boolean;
constructor(options: OpenCodeV2SessionOptions) {
const { info, config, bindChild } = options;
this.connection = options.connection;
this.info = info;
this.config = config;
this.logger = options.logger;
this.persist = options.persist;
this.requiresPaseoPlugin = options.requiresPaseoPlugin;
this.environment = options.environment;
this.mcp = options.mcp;
this.unbind = options.unbind;
this.acquire = options.acquire;
this.moved = options.moved;
this.historyOnly = options.historyOnly ?? false;
this.background = new OpenCodeBackgroundInventory({
id: info.id,
cwd: config.cwd,
@@ -104,7 +136,10 @@ export class OpenCodeV2Session implements AgentSession {
id: info.id,
emit: (event) => this.emit(event),
reconcilePermissions: (id) => this.permissions.reconcile(id),
bindChild,
adoptChild: async (id) => {
bindChild?.(id);
await this.adoptDescendant(id);
},
});
this.turns = new SessionTurns({
client: () => this.client,
@@ -151,9 +186,7 @@ export class OpenCodeV2Session implements AgentSession {
private get client() {
return this.connection.client;
}
async initialize(environment?: Record<string, string>) {
// OpenCode replaces the whole local shell environment, rather than overlaying it.
this.launchEnv = environment;
async initialize() {
this.watchExit(this.connection);
await this.configureConnection();
const location = { directory: this.config.cwd };
@@ -178,28 +211,6 @@ export class OpenCodeV2Session implements AgentSession {
await waitForLocationReady({ client: this.client, location, signal: this.abort.signal });
if (this.requiresPaseoPlugin)
await awaitPaseoPlugin({ client: this.client, location, signal: this.abort.signal });
for (const [server, config] of Object.entries(this.config.mcpServers ?? {})) {
await this.client.mcp.add({
server,
location,
config:
config.type === "stdio"
? {
type: "local",
command: [config.command, ...(config.args ?? [])],
environment: config.env,
codemode: false,
}
: {
type: "remote",
url: config.url,
headers: config.headers,
oauth: false,
codemode: false,
},
});
await this.awaitMcp(server);
}
if (this.historyOnly) return;
const system = composeSystemPromptParts(
this.config.systemPrompt,
@@ -219,6 +230,11 @@ export class OpenCodeV2Session implements AgentSession {
}
}
}
/** Gives a descendant session the shell environment, which OpenCode does not inherit. */
async adoptDescendant(sessionID: string) {
if (this.closed || this.historyOnly || !this.environment) return;
await this.client.session.environment({ sessionID, variables: this.environment });
}
private async startStream() {
let ready!: () => void;
let fail!: (error: unknown) => void;
@@ -284,22 +300,6 @@ export class OpenCodeV2Session implements AgentSession {
this.listeners.delete(callback);
};
}
private async awaitMcp(server: string) {
const signal = AbortSignal.any([this.abort.signal, AbortSignal.timeout(30_000)]);
while (true) {
const catalog = await this.client.mcp.list(
{ location: { directory: this.config.cwd } },
{ signal },
);
const entry = catalog.data.find((item) => item.name === server);
if (entry?.status.status === "connected") return;
if (entry && entry.status.status !== "pending") {
const reason = entry.status.status === "failed" ? entry.status.error : entry.status.status;
throw new Error(`OpenCode MCP server ${server} failed to connect: ${reason}`);
}
await delay(50, undefined, { signal });
}
}
private emit(event: AgentStreamEvent) {
for (const listener of this.listeners) listener(event);
}
@@ -532,8 +532,9 @@ export class OpenCodeV2Session implements AgentSession {
await this.connection.bindSession(this.id, this.config.cwd);
// Session environments are process-local. Reapply this agent's snapshot before
// reconciling a new connection, including event-stream reconnections.
if (this.launchEnv)
await this.client.session.environment({ sessionID: this.id, variables: this.launchEnv });
if (this.environment)
await this.client.session.environment({ sessionID: this.id, variables: this.environment });
for (const id of this.children.ids()) await this.adoptDescendant(id);
await this.reconcile();
await this.children.reconcile(this.id);
await this.turns.reconcile();
@@ -668,6 +669,7 @@ export class OpenCodeV2Session implements AgentSession {
try {
if (!this.persist) await this.client.session.remove({ sessionID: this.id });
} finally {
await this.mcp?.close();
await this.connection.release();
}
this.listeners.clear();
@@ -13,9 +13,14 @@ export async function registerSharedBridge(context) {
const state = await import(new URL("./state.mjs", import.meta.url).href);
const { bindings, definitions } = state.stateFor(context.location);
const registrations = new Map();
const adopted = new Set();
// Same-named tools that OpenCode registered before Paseo's MCP tools, by tool name.
const natives = new Map();
// MCP tools run only after OpenCode's own permission check, which older servers lack.
const runsMcpTools = typeof context.permission?.assert === "function";
let updating = Promise.resolve();
async function request(binding, pathname, body, allowMissing = false, signal) {
const requestSignal = body === undefined ? AbortSignal.timeout(5_000) : signal;
const requestSignal = signal ?? (body === undefined ? AbortSignal.timeout(5_000) : undefined);
const response = await fetch(new URL(`/_internal/opencode${pathname}`, binding.baseUrl), {
method: body === undefined ? "GET" : "POST",
headers: { Authorization: `Bearer ${binding.token}`, "Content-Type": "application/json" },
@@ -69,6 +74,88 @@ export async function registerSharedBridge(context) {
});
if (conflicts.length > 0) await retireUnusedDefinitions(conflicts);
for (const definition of manifest.tools) await installDefinition(definition);
if (runsMcpTools)
for (const definition of manifest.mcpTools ?? []) await installMcpTool(definition.name);
}
// One registration serves every session that has an MCP tool of this name. The context hook
// gives each session its own definition, and execution routes to that session's server.
async function installMcpTool(name) {
const key = mcpKey(name);
if (registrations.has(key)) return;
const registration = await context.tool.transform((editor) => {
// The user's own OpenCode configuration can register a tool with the same name. Sessions
// that do not have a Paseo MCP tool of that name keep that tool. OpenCode validates input
// against the registered schema, so it stays permissive for both tools.
const native = editor.get?.(name);
if (native) natives.set(name, native);
else natives.delete(name);
editor.add({
name,
description: `MCP tool ${name} provided by Paseo`,
input: { type: "object", additionalProperties: true },
options: { codemode: false },
async execute(input, call) {
const scope = await find(call.sessionID);
if (!scope || !(await ownsMcpTool(scope, name))) {
if (native) return withoutOutput(await native.execute(input, call));
throw new Error(
scope
? `MCP tool ${name} is not available to this session`
: "OpenCode session is not bound to a Paseo agent",
);
}
await context.permission.assert({
sessionID: call.sessionID,
agent: call.agent,
action: name,
resources: ["*"],
save: ["*"],
metadata: { input: input ?? {} },
source: { type: "tool", messageID: call.messageID, id: call.id },
});
const result = await request(
scope,
`/sessions/${encodeURIComponent(scope.sessionID)}/mcp-tools/${encodeURIComponent(name)}`,
input ?? {},
false,
call.signal,
);
if (result.isError)
throw new Error(
result.content
.flatMap((part) => (part.type === "text" ? [part.text] : []))
.join("\n")
.trim() || "MCP tool returned an error",
);
return {
content: result.content.map(toOpenCodeContent),
metadata: { paseoMcpTool: name },
};
},
});
});
registrations.set(key, registration);
definitions.set(key, { mcpTool: name });
}
async function ownsMcpTool(scope, name) {
const own = await request(
scope,
`/sessions/${encodeURIComponent(scope.sessionID)}/context?tools`,
);
return (own.mcpTools ?? []).some((tool) => tool.name === name);
}
// A child session starts its first request right away, so Paseo prepares it, including its
// environment, before the request is built.
async function adopt(scope, sessionID) {
if (scope.sessionID === sessionID || adopted.has(sessionID)) return;
await request(
scope,
`/sessions/${encodeURIComponent(scope.sessionID)}/descendants/${encodeURIComponent(sessionID)}`,
{},
true,
AbortSignal.timeout(10_000),
);
adopted.add(sessionID);
}
async function retireUnusedDefinitions(conflicts) {
// A tool name is registered once per location. Another session can still
@@ -128,7 +215,9 @@ export async function registerSharedBridge(context) {
}
// Reinstall live tools before this plugin generation is made visible.
// Definitions are kept in memory, so unavailable owners cannot delay reload.
for (const definition of definitions.values()) await installDefinition(definition);
for (const definition of definitions.values())
if (definition.mcpTool === undefined) await installDefinition(definition);
else if (runsMcpTools) await installMcpTool(definition.mcpTool);
const object = { type: "object", additionalProperties: true };
const rpc = await context.rpc.register(
{
@@ -164,7 +253,7 @@ export async function registerSharedBridge(context) {
}
await install(input);
bindings.set(input.sessionID, { baseUrl: input.baseUrl, token: input.token });
return {};
return { features: { mcpTools: runsMcpTools } };
});
updating = next;
return await next;
@@ -195,14 +284,29 @@ export async function registerSharedBridge(context) {
);
const filter = await context.session.hook("context", async (input) => {
const binding = await find(input.sessionID);
if (binding) await adopt(binding, input.sessionID);
const scope =
binding &&
(await request(binding, `/sessions/${encodeURIComponent(binding.sessionID)}/context?tools`));
const allowed = new Set((scope?.tools ?? []).map((name) => `paseo_${name}`));
const mcpTools = new Map((scope?.mcpTools ?? []).map((tool) => [tool.name, tool]));
for (const name of Object.keys(input.tools)) {
if (definitions.has(mcpKey(name))) {
const own = mcpTools.get(name);
const native = natives.get(name);
if (own) input.tools[name] = { description: own.description, input: own.inputSchema };
else if (native)
input.tools[name] = { description: native.description, input: native.input };
else delete input.tools[name];
continue;
}
if (name.startsWith("paseo_") && name !== STRUCTURED_OUTPUT_TOOL && !allowed.has(name))
delete input.tools[name];
}
// The instructions of Paseo-hosted MCP servers go with every request of the session and its
// descendants. OpenCode loads instruction entries before this hook runs, so an entry written
// when a child is adopted would miss the child's first request.
if (scope?.mcpInstructions) input.system.push({ type: "text", text: scope.mcpInstructions });
});
return async () => {
await filter.dispose();
@@ -211,10 +315,24 @@ export async function registerSharedBridge(context) {
};
}
// Paseo's MCP tool declares no output schema, so a same-named tool's output becomes content.
function withoutOutput({ output, ...result }) {
if (result.content !== undefined || output === undefined) return result;
return {
...result,
content: [{ type: "text", text: typeof output === "string" ? output : JSON.stringify(output) }],
};
}
function mcpKey(name) {
return `mcp:${name}`;
}
function toOpenCodeContent(part) {
if (part.type === "image")
return { type: "file", uri: `data:${part.mimeType};base64,${part.data}`, mime: part.mimeType };
return part;
if (part.type === "text") return part;
return { type: "text", text: JSON.stringify(part) };
}
function formatErrorDetail(details) {
@@ -22,13 +22,22 @@ interface ToolDefinition {
name: string;
description: string;
}
interface McpTestTool {
name: string;
execute(
input: unknown,
call: { sessionID: string; agent: string; messageID: string; id: string },
): Promise<unknown>;
}
interface TestContext {
sessionID: string;
tools: Record<string, unknown>;
system: unknown[];
}
// The fake OpenCode context has no permission service, as on OpenCode before 2.0.29.
const BOUND_WITHOUT_MCP = { features: { mcpTools: false } };
test("a shared plugin binds Paseo sessions without involving unrelated sessions", async () => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-shared-bridge-"));
const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
@@ -162,7 +171,7 @@ test("a shared plugin binds Paseo sessions without involving unrelated sessions"
try {
await expect(
rpc.bind({ sessionID: "paseo", ...restarted.sharedV2Connection() }),
).resolves.toEqual({});
).resolves.toEqual(BOUND_WITHOUT_MCP);
} finally {
releaseRestarted();
await restarted.close();
@@ -217,7 +226,9 @@ test("a shared plugin rebinds a session after the previous bridge stops listenin
hook: async () => ({ dispose: async () => {} }),
},
});
await expect(rpc.bind({ sessionID: "paseo", ...plugin.options })).resolves.toEqual({});
await expect(rpc.bind({ sessionID: "paseo", ...plugin.options })).resolves.toEqual(
BOUND_WITHOUT_MCP,
);
await current.start();
// The restarted daemon owns the agent again, so its bridge serves this session.
releaseCurrent = current.bindSession({ sessionId: "paseo", env: {} });
@@ -227,7 +238,7 @@ test("a shared plugin rebinds a session after the previous bridge stops listenin
});
await expect(
rpc.bind({ sessionID: "paseo", ...current.sharedV2Connection() }),
).resolves.toEqual({});
).resolves.toEqual(BOUND_WITHOUT_MCP);
} finally {
await dispose?.();
releaseCurrent?.();
@@ -338,7 +349,7 @@ test.each([false, true])(
await old.close();
await next.start();
addSession(next, "first", { echo: "echo v2" });
await expect(location.bind(next, "first")).resolves.toEqual({});
await expect(location.bind(next, "first")).resolves.toEqual(BOUND_WITHOUT_MCP);
expect(await location.visible("first")).toHaveProperty("paseo_echo.description", "echo v2");
expect(await location.visible("peer")).toHaveProperty("paseo_extra");
} finally {
@@ -378,6 +389,180 @@ test("binding another session at the same location preserves the first session's
}
});
test("a shared plugin gives each session its own MCP tools behind OpenCode's permission check", async () => {
const home = await mkdtemp(path.join(tmpdir(), "paseo-shared-bridge-mcp-"));
const bridge = new OpenCodeBridge({ paseoHome: home, logger: createTestLogger() });
bridge.setManifestCatalog({ tools: new Map() });
await bridge.start();
const adopted: string[] = [];
const sessionMcp = (marker: string) => ({
tools: [
{
name: "hub_marker",
description: `Return ${marker}`,
inputSchema: { type: "object" as const },
},
// Only session A has `local_env`, which the user's own OpenCode configuration also has.
...(marker === "A"
? [
{
name: "local_env",
description: "Paseo env",
inputSchema: { type: "object" as const },
},
]
: []),
],
instructions: `Use ${marker}`,
execute: async (name: string, input: unknown) => ({
content: [{ type: "text" as const, text: `${name}:${marker}:${JSON.stringify(input)}` }],
}),
});
const releases = ["a", "b"].map((id) =>
bridge.bindSession({
sessionId: id,
env: {},
mcp: sessionMcp(id.toUpperCase()),
adoptDescendant: async (child) => {
adopted.push(`${id}>${child}`);
},
}),
);
let dispose: (() => Promise<void>) | undefined;
try {
const plugin = await bridge.materializeV2Plugin();
const module = await import(pathToFileURL(path.join(fileURLToPath(plugin), "server.js")).href);
const installed = new Map<string, McpTestTool>();
const natives = new Map<string, McpTestTool & { description: string; input: unknown }>([
[
"local_env",
{
name: "local_env",
description: "User env",
input: { type: "object" },
execute: async () => ({ output: { from: "user" } }),
},
],
]);
const hooks: Array<(input: TestContext) => Promise<void>> = [];
const asserted: unknown[] = [];
let rpc: Record<string, (input: Binding) => Promise<unknown>> = {};
const parents: Record<string, string> = { child: "a" };
dispose = await module.default.setup({
options: {},
location: { directory: home },
...Object.fromEntries(
["provider", "model", "agent", "command", "skill"].map((name) => [
name,
{ reload: async () => {} },
]),
),
rpc: {
register: async (_definition: unknown, handlers: typeof rpc) => {
rpc = handlers;
return { dispose: async () => {} };
},
},
tool: {
transform: async (
fn: (editor: {
get(name: string): McpTestTool | undefined;
add(item: McpTestTool): void;
}) => void,
) => {
fn({ get: (name) => natives.get(name), add: (item) => installed.set(item.name, item) });
return { dispose: async () => {} };
},
},
permission: {
assert: async (request: unknown) => {
asserted.push(request);
},
},
session: {
context: async () => [],
get: async ({ sessionID }: { sessionID: string }) => ({
parentID: parents[sessionID] ?? "",
}),
hook: async (_name: string, fn: (input: TestContext) => Promise<void>) => {
hooks.push(fn);
return { dispose: async () => {} };
},
},
});
for (const sessionID of ["a", "b"])
await expect(rpc.bind({ sessionID, ...bridge.sharedV2Connection() })).resolves.toEqual({
features: { mcpTools: true },
});
const requestFor = async (sessionID: string) => {
const input = {
sessionID,
tools: { hub_marker: {}, local_env: { description: "User env" }, native: {} },
system: [],
};
for (const hook of hooks) await hook(input);
return input;
};
const contextFor = async (sessionID: string) => (await requestFor(sessionID)).tools;
expect(await contextFor("a")).toEqual({
hub_marker: { description: "Return A", input: { type: "object" } },
local_env: { description: "Paseo env", input: { type: "object" } },
native: {},
});
expect(await contextFor("b")).toEqual({
hub_marker: { description: "Return B", input: { type: "object" } },
local_env: { description: "User env", input: { type: "object" } },
native: {},
});
expect(await contextFor("other")).toEqual({
local_env: { description: "User env", input: { type: "object" } },
native: {},
});
// OpenCode validates input against the registration, so it accepts both tools' input.
expect(installed.get("local_env")).toMatchObject({
input: { type: "object", additionalProperties: true },
});
// A descendant uses its root's servers and instructions from its first request, and is
// adopted once.
const child = await requestFor("child");
expect(child.tools).toMatchObject({ hub_marker: { description: "Return A" } });
expect(child.system).toEqual([{ type: "text", text: "Use A" }]);
await contextFor("child");
expect(adopted).toEqual(["a>child"]);
expect((await requestFor("other")).system).toEqual([]);
const call = { agent: "build", messageID: "message", id: "call" };
const hub = installed.get("hub_marker")!;
await expect(hub.execute({ q: 1 }, { ...call, sessionID: "child" })).resolves.toMatchObject({
content: [{ type: "text", text: 'hub_marker:A:{"q":1}' }],
});
await expect(hub.execute({}, { ...call, sessionID: "b" })).resolves.toMatchObject({
content: [{ type: "text", text: "hub_marker:B:{}" }],
});
await expect(hub.execute({}, { ...call, sessionID: "other" })).rejects.toThrow(
"not bound to a Paseo agent",
);
// A session without its own `local_env` runs the user's tool, which checks its own permission.
const env = installed.get("local_env")!;
await expect(env.execute({}, { ...call, sessionID: "b" })).resolves.toEqual({
content: [{ type: "text", text: '{"from":"user"}' }],
});
await expect(env.execute({}, { ...call, sessionID: "a" })).resolves.toMatchObject({
content: [{ type: "text", text: "local_env:A:{}" }],
});
expect(asserted).toEqual([
expect.objectContaining({ sessionID: "child", action: "hub_marker", resources: ["*"] }),
expect.objectContaining({ sessionID: "b", action: "hub_marker", resources: ["*"] }),
expect.objectContaining({ sessionID: "a", action: "local_env", resources: ["*"] }),
]);
} finally {
await dispose?.();
for (const release of releases) release();
await bridge.close();
await rm(home, { recursive: true, force: true });
}
});
test("a refused connection is the only probe failure that clears a binding", async () => {
const source = new URL("./shared-bridge-plugin.mjs", import.meta.url).href;
const { isRefused } = (await import(source)) as { isRefused: (error: unknown) => boolean };
@@ -162,6 +162,11 @@ function validateBridgeAddress(
);
}
interface BindOutput {
error?: unknown;
features?: { mcpTools?: boolean };
}
export function bridgeBindings(
client: ReturnType<typeof OpenCode.make>,
bridge: OpenCodeBridge | undefined,
@@ -187,8 +192,13 @@ export function bridgeBindings(
{ cause: error },
);
}
if (result.output && typeof result.output === "object" && "error" in result.output)
throw new Error(String(result.output.error));
const output = result.output as BindOutput | undefined;
if (output?.error !== undefined) throw new Error(String(output.error));
// An OpenCode older than 2.0.29, or a plugin from an older Paseo, ignores MCP tools.
if (bridge.hasMcpTools(sessionId) && output?.features?.mcpTools !== true)
throw new Error(
`This OpenCode server cannot run the agent's MCP servers. Update OpenCode to 2.0.29 or newer${pluginDirectory ? `, install the Paseo plugin from ${pluginDirectory}, and restart the server` : ""}.`,
);
},
unbindSession: async (sessionId, cwd) => {
if (bridge)
@@ -4,6 +4,7 @@ import { CLIENT_CAPS } from "@getpaseo/protocol/client-capabilities";
import { expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { OpenCodeBridge } from "../agent/providers/opencode/bridge.js";
import { OpenCodeV2AgentClient } from "../agent/providers/opencode/v2/agent.js";
import { V2Harness } from "../agent/providers/opencode/test-utils/v2-harness.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
@@ -27,10 +28,20 @@ async function createWorkingRecipient(options: { olderClient?: boolean } = {}) {
runtime.prompts.push(input.text);
if (runtime.prompts.length === 1) runtime.startExecution();
};
// The daemon always runs the bridge, which gives OpenCode agents their Paseo tools.
const bridge = new OpenCodeBridge({
paseoHome: path.join(root, "bridge"),
logger: createTestLogger(),
});
await bridge.start();
const daemon = await createTestPaseoDaemon({
agentClients: {
...createTestAgentClients(),
opencode: new OpenCodeV2AgentClient({ logger: createTestLogger(), runtime: runtime.runtime }),
opencode: new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: runtime.runtime,
bridge,
}),
},
paseoHomeRoot: path.join(root, "daemon"),
staticDir: path.join(root, "static"),
@@ -46,6 +57,7 @@ async function createWorkingRecipient(options: { olderClient?: boolean } = {}) {
const close = async () => {
await client.close();
await daemon.close();
await bridge.close();
await rm(root, { recursive: true, force: true });
};
try {
@@ -4,6 +4,7 @@ import type { FormInfo } from "@opencode/client";
import { expect, test } from "vitest";
import { createTestLogger } from "../../test-utils/test-logger.js";
import { OpenCodeBridge } from "../agent/providers/opencode/bridge.js";
import { OpenCodeV2AgentClient } from "../agent/providers/opencode/v2/agent.js";
import { V2Harness } from "../agent/providers/opencode/test-utils/v2-harness.js";
import { createTestAgentClients } from "../test-utils/fake-agent-client.js";
@@ -38,9 +39,16 @@ async function createQuestionHarness() {
runtime.prompts.push(input.text);
if (runtime.prompts.length === 1) runtime.startExecution();
};
// The daemon always runs the bridge, which gives OpenCode agents their Paseo tools.
const bridge = new OpenCodeBridge({
paseoHome: path.join(root, "bridge"),
logger: createTestLogger(),
});
await bridge.start();
const provider = new OpenCodeV2AgentClient({
logger: createTestLogger(),
runtime: runtime.runtime,
bridge,
});
const daemon = await createTestPaseoDaemon({
agentClients: { ...createTestAgentClients(), opencode: provider },
@@ -78,12 +86,14 @@ async function createQuestionHarness() {
async close() {
await client.close();
await daemon.close();
await bridge.close();
await rm(root, { recursive: true, force: true });
},
};
} catch (error) {
await client.close();
await daemon.close();
await bridge.close();
await rm(root, { recursive: true, force: true });
throw error;
}
+70 -26
View File
@@ -36,6 +36,8 @@
# bottom-edge disclosure collapsing near the end landed at the end instead of in place.
# 13. Recalculate the rendered range when drawDistance changes (LegendListInner). Chat uses
# a small window for initial placement and schedules expansion after initial reveal.
# 14. Check first layout readiness even with a cached range (calculateItemsInView). A settled
# range with no rows needs no measurements, such as when a tall footer fills the viewport.
#
# Upgrading: drop each hunk whose fix the new version ships, regenerate with
# `npx patch-package @legendapp/list`, and copy this header back on top.
@@ -56,7 +58,7 @@ index 983e937..970ba51 100644
* Returns a stable item type used for pooling and size estimation.
*/
diff --git a/node_modules/@legendapp/list/react-native.js b/node_modules/@legendapp/list/react-native.js
index eeb3fb0..33d6241 100644
index eeb3fb0..ae5656e 100644
--- a/node_modules/@legendapp/list/react-native.js
+++ b/node_modules/@legendapp/list/react-native.js
@@ -1497,7 +1497,15 @@ function getItemSize(ctx, key, index, data, useAverageSize, preferCachedSize, no
@@ -228,7 +230,28 @@ index eeb3fb0..33d6241 100644
}
return idsInView;
}
@@ -5176,8 +5218,13 @@ var NATIVE_LAYOUT_MEASUREMENT_EPSILON = 1 / PixelRatio.get() + FLOATING_POINT_SL
@@ -4737,7 +4779,8 @@ function calculateItemsInView(ctx, params = {}) {
if (projectedBufferAdjustment !== 0) {
scheduleRenderRangeProjectionSettle(ctx);
}
- if (enableScrollForNextCalculateItemsInView && !suppressInitialScrollSideEffects && !dataChanged && !forceFullItemPositions && scrollForNextCalculateItemsInView) {
+ // Paseo patch: the cached range skips the first layout readiness check below.
+ if (enableScrollForNextCalculateItemsInView && state.didContainersLayout && !suppressInitialScrollSideEffects && !dataChanged && !forceFullItemPositions && scrollForNextCalculateItemsInView) {
const { top, bottom } = scrollForNextCalculateItemsInView;
if (top === null && bottom === null) {
state.scrollForNextCalculateItemsInView = void 0;
@@ -5081,7 +5124,9 @@ function calculateItemsInView(ctx, params = {}) {
}
maybeEmitFirstVisibleItemChanged(state, visibleRange.startNoBuffer);
if (!queuedInitialLayout && !state.didContainersLayout) {
- const isInitialLayoutReady = hasActiveInitialScroll(state) ? checkAllSizesKnown(state, state.startBuffered, state.endBuffered) : checkAllSizesKnown(state, state.startNoBuffer, state.endNoBuffer) || checkAllSizesKnown(state, state.startBuffered, state.endBuffered);
+ // Paseo patch: a tall footer can fill the settled viewport and its render buffer.
+ const isRenderRangeEmpty = data.length > 0 && startBuffered === null;
+ const isInitialLayoutReady = hasActiveInitialScroll(state) ? checkAllSizesKnown(state, state.startBuffered, state.endBuffered) : isRenderRangeEmpty || checkAllSizesKnown(state, state.startNoBuffer, state.endNoBuffer) || checkAllSizesKnown(state, state.startBuffered, state.endBuffered);
if (isInitialLayoutReady) {
setDidLayout(ctx);
handleInitialScrollLayoutReady(ctx);
@@ -5176,8 +5221,13 @@ var NATIVE_LAYOUT_MEASUREMENT_EPSILON = 1 / PixelRatio.get() + FLOATING_POINT_SL
function isWithinEpsilon(delta) {
return Math.abs(delta) <= NATIVE_LAYOUT_MEASUREMENT_EPSILON;
}
@@ -244,7 +267,7 @@ index eeb3fb0..33d6241 100644
}
// src/core/updateItemSizes.ts
@@ -5291,6 +5338,11 @@ function updateItemSizesBatch(ctx, measurements) {
@@ -5291,6 +5341,11 @@ function updateItemSizesBatch(ctx, measurements) {
const result = {};
const previousTotalSize = state.totalSize;
for (const measurement of measurements) {
@@ -256,7 +279,7 @@ index eeb3fb0..33d6241 100644
const ownsMeasuredItem = measurement.containerId === void 0 || isContainerItemCurrent(ctx, measurement.containerId, measurement.itemKey);
if (ownsMeasuredItem) {
const index = state.indexByKey.get(measurement.itemKey);
@@ -5414,7 +5466,7 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif
@@ -5414,7 +5469,7 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif
state.fixedItemSizeKeys.add(itemKey);
}
const prevSizeKnown = sizesKnown.get(itemKey);
@@ -265,7 +288,7 @@ index eeb3fb0..33d6241 100644
return 0;
}
const size = Platform.OS === "web" ? Math.round(rawSize) : roundSize(rawSize);
@@ -6283,6 +6335,10 @@ function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
@@ -6283,6 +6338,10 @@ function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
// src/components/Containers.native.tsx
var useCommittedMinSize = IsNewArchitecture ? () => useArr$(["totalSize"])[0] : () => void 0;
@@ -276,7 +299,7 @@ index eeb3fb0..33d6241 100644
var ContainersLayer = typedMemo(function ContainersLayer2({
children,
freshDataTransitionEpoch,
@@ -6290,7 +6346,7 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
@@ -6290,7 +6349,7 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
}) {
const ctx = useStateContext();
const columnWrapperStyle = ctx.columnWrapperStyle;
@@ -285,7 +308,7 @@ index eeb3fb0..33d6241 100644
const minSize = useCommittedMinSize();
const [readyToRender, numColumns, otherAxisSize = 0] = useArr$(["readyToRender", "numColumns", "otherAxisSize"]);
const isVisible = useFreshDataTransitionVisibility(!!readyToRender, freshDataTransitionEpoch);
@@ -6513,6 +6569,14 @@ var AlignItemsAtEndSpacer = typedMemo(function AlignItemsAtEndSpacer2({ horizont
@@ -6513,6 +6572,14 @@ var AlignItemsAtEndSpacer = typedMemo(function AlignItemsAtEndSpacer2({ horizont
null
);
});
@@ -300,7 +323,7 @@ index eeb3fb0..33d6241 100644
var ListComponent = typedMemo(function ListComponent2({
canRender,
freshDataTransitionEpoch,
@@ -6651,7 +6715,7 @@ var ListComponent = typedMemo(function ListComponent2({
@@ -6651,7 +6718,7 @@ var ListComponent = typedMemo(function ListComponent2({
style: autoOtherAxisStyle ? [autoOtherAxisStyle, style] : style
},
/* @__PURE__ */ React2__namespace.createElement(ScrollAdjust, null),
@@ -309,7 +332,7 @@ index eeb3fb0..33d6241 100644
ListEmptyComponent && getComponent(ListEmptyComponent),
shouldRenderAlignItemsAtEndSpacer && /* @__PURE__ */ React2__namespace.createElement(AlignItemsAtEndSpacer, { horizontal }),
canRender && !ListEmptyComponent && /* @__PURE__ */ React2__namespace.createElement(
@@ -6665,7 +6729,7 @@ var ListComponent = typedMemo(function ListComponent2({
@@ -6665,7 +6732,7 @@ var ListComponent = typedMemo(function ListComponent2({
stickyHeaderConfig
}
),
@@ -318,7 +341,7 @@ index eeb3fb0..33d6241 100644
IS_DEV && ENABLE_DEVMODE
);
});
@@ -7886,7 +7950,10 @@ function setPaddingTop(ctx, { stylePaddingTop }) {
@@ -7886,7 +7953,10 @@ function setPaddingTop(ctx, { stylePaddingTop }) {
const state = ctx.state;
if (stylePaddingTop !== void 0) {
const prevStylePaddingTop = peek$(ctx, "stylePaddingTop") || 0;
@@ -330,7 +353,7 @@ index eeb3fb0..33d6241 100644
let prevTotalSize = peek$(ctx, "totalSize") || 0;
set$(ctx, "totalSize", prevTotalSize + prevStylePaddingTop);
state.timeoutSetPaddingTop = setTimeout(() => {
@@ -7989,6 +8056,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
@@ -7989,6 +8059,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
estimatedListSize,
extraData,
getFixedItemSize,
@@ -338,7 +361,7 @@ index eeb3fb0..33d6241 100644
getItemType,
horizontal,
rtl,
@@ -8282,6 +8350,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
@@ -8282,6 +8353,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
dataVersion,
drawDistance,
estimatedItemSize,
@@ -346,7 +369,7 @@ index eeb3fb0..33d6241 100644
getFixedItemSize: useWrapIfItem(getFixedItemSize),
getItemType: useWrapIfItem(getItemType),
hasExternalScroll,
@@ -8549,6 +8618,15 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
@@ -8549,6 +8621,15 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
doMaintainScrollAtEnd(ctx);
}
}, [!!maintainScrollAtEndConfig]);
@@ -363,7 +386,7 @@ index eeb3fb0..33d6241 100644
React2.useLayoutEffect(() => {
const previousPins = previousAlwaysRenderIndices.current;
diff --git a/node_modules/@legendapp/list/react-native.mjs b/node_modules/@legendapp/list/react-native.mjs
index fe5f415..8219839 100644
index fe5f415..f20d5fb 100644
--- a/node_modules/@legendapp/list/react-native.mjs
+++ b/node_modules/@legendapp/list/react-native.mjs
@@ -1476,7 +1476,15 @@ function getItemSize(ctx, key, index, data, useAverageSize, preferCachedSize, no
@@ -535,7 +558,28 @@ index fe5f415..8219839 100644
}
return idsInView;
}
@@ -5155,8 +5197,13 @@ var NATIVE_LAYOUT_MEASUREMENT_EPSILON = 1 / PixelRatio.get() + FLOATING_POINT_SL
@@ -4716,7 +4758,8 @@ function calculateItemsInView(ctx, params = {}) {
if (projectedBufferAdjustment !== 0) {
scheduleRenderRangeProjectionSettle(ctx);
}
- if (enableScrollForNextCalculateItemsInView && !suppressInitialScrollSideEffects && !dataChanged && !forceFullItemPositions && scrollForNextCalculateItemsInView) {
+ // Paseo patch: the cached range skips the first layout readiness check below.
+ if (enableScrollForNextCalculateItemsInView && state.didContainersLayout && !suppressInitialScrollSideEffects && !dataChanged && !forceFullItemPositions && scrollForNextCalculateItemsInView) {
const { top, bottom } = scrollForNextCalculateItemsInView;
if (top === null && bottom === null) {
state.scrollForNextCalculateItemsInView = void 0;
@@ -5060,7 +5103,9 @@ function calculateItemsInView(ctx, params = {}) {
}
maybeEmitFirstVisibleItemChanged(state, visibleRange.startNoBuffer);
if (!queuedInitialLayout && !state.didContainersLayout) {
- const isInitialLayoutReady = hasActiveInitialScroll(state) ? checkAllSizesKnown(state, state.startBuffered, state.endBuffered) : checkAllSizesKnown(state, state.startNoBuffer, state.endNoBuffer) || checkAllSizesKnown(state, state.startBuffered, state.endBuffered);
+ // Paseo patch: a tall footer can fill the settled viewport and its render buffer.
+ const isRenderRangeEmpty = data.length > 0 && startBuffered === null;
+ const isInitialLayoutReady = hasActiveInitialScroll(state) ? checkAllSizesKnown(state, state.startBuffered, state.endBuffered) : isRenderRangeEmpty || checkAllSizesKnown(state, state.startNoBuffer, state.endNoBuffer) || checkAllSizesKnown(state, state.startBuffered, state.endBuffered);
if (isInitialLayoutReady) {
setDidLayout(ctx);
handleInitialScrollLayoutReady(ctx);
@@ -5155,8 +5200,13 @@ var NATIVE_LAYOUT_MEASUREMENT_EPSILON = 1 / PixelRatio.get() + FLOATING_POINT_SL
function isWithinEpsilon(delta) {
return Math.abs(delta) <= NATIVE_LAYOUT_MEASUREMENT_EPSILON;
}
@@ -551,7 +595,7 @@ index fe5f415..8219839 100644
}
// src/core/updateItemSizes.ts
@@ -5270,6 +5317,11 @@ function updateItemSizesBatch(ctx, measurements) {
@@ -5270,6 +5320,11 @@ function updateItemSizesBatch(ctx, measurements) {
const result = {};
const previousTotalSize = state.totalSize;
for (const measurement of measurements) {
@@ -563,7 +607,7 @@ index fe5f415..8219839 100644
const ownsMeasuredItem = measurement.containerId === void 0 || isContainerItemCurrent(ctx, measurement.containerId, measurement.itemKey);
if (ownsMeasuredItem) {
const index = state.indexByKey.get(measurement.itemKey);
@@ -5393,7 +5445,7 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif
@@ -5393,7 +5448,7 @@ function updateOneItemSize(ctx, itemKey, sizeObj, resolvedMeasurementItem, notif
state.fixedItemSizeKeys.add(itemKey);
}
const prevSizeKnown = sizesKnown.get(itemKey);
@@ -572,7 +616,7 @@ index fe5f415..8219839 100644
return 0;
}
const size = Platform.OS === "web" ? Math.round(rawSize) : roundSize(rawSize);
@@ -6262,6 +6314,10 @@ function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
@@ -6262,6 +6317,10 @@ function useFreshDataTransitionVisibility(readyToRender, transitionEpoch) {
// src/components/Containers.native.tsx
var useCommittedMinSize = IsNewArchitecture ? () => useArr$(["totalSize"])[0] : () => void 0;
@@ -583,7 +627,7 @@ index fe5f415..8219839 100644
var ContainersLayer = typedMemo(function ContainersLayer2({
children,
freshDataTransitionEpoch,
@@ -6269,7 +6325,7 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
@@ -6269,7 +6328,7 @@ var ContainersLayer = typedMemo(function ContainersLayer2({
}) {
const ctx = useStateContext();
const columnWrapperStyle = ctx.columnWrapperStyle;
@@ -592,7 +636,7 @@ index fe5f415..8219839 100644
const minSize = useCommittedMinSize();
const [readyToRender, numColumns, otherAxisSize = 0] = useArr$(["readyToRender", "numColumns", "otherAxisSize"]);
const isVisible = useFreshDataTransitionVisibility(!!readyToRender, freshDataTransitionEpoch);
@@ -6492,6 +6548,14 @@ var AlignItemsAtEndSpacer = typedMemo(function AlignItemsAtEndSpacer2({ horizont
@@ -6492,6 +6551,14 @@ var AlignItemsAtEndSpacer = typedMemo(function AlignItemsAtEndSpacer2({ horizont
null
);
});
@@ -607,7 +651,7 @@ index fe5f415..8219839 100644
var ListComponent = typedMemo(function ListComponent2({
canRender,
freshDataTransitionEpoch,
@@ -6630,7 +6694,7 @@ var ListComponent = typedMemo(function ListComponent2({
@@ -6630,7 +6697,7 @@ var ListComponent = typedMemo(function ListComponent2({
style: autoOtherAxisStyle ? [autoOtherAxisStyle, style] : style
},
/* @__PURE__ */ React2.createElement(ScrollAdjust, null),
@@ -616,7 +660,7 @@ index fe5f415..8219839 100644
ListEmptyComponent && getComponent(ListEmptyComponent),
shouldRenderAlignItemsAtEndSpacer && /* @__PURE__ */ React2.createElement(AlignItemsAtEndSpacer, { horizontal }),
canRender && !ListEmptyComponent && /* @__PURE__ */ React2.createElement(
@@ -6644,7 +6708,7 @@ var ListComponent = typedMemo(function ListComponent2({
@@ -6644,7 +6711,7 @@ var ListComponent = typedMemo(function ListComponent2({
stickyHeaderConfig
}
),
@@ -625,7 +669,7 @@ index fe5f415..8219839 100644
IS_DEV && ENABLE_DEVMODE
);
});
@@ -7865,7 +7929,10 @@ function setPaddingTop(ctx, { stylePaddingTop }) {
@@ -7865,7 +7932,10 @@ function setPaddingTop(ctx, { stylePaddingTop }) {
const state = ctx.state;
if (stylePaddingTop !== void 0) {
const prevStylePaddingTop = peek$(ctx, "stylePaddingTop") || 0;
@@ -637,7 +681,7 @@ index fe5f415..8219839 100644
let prevTotalSize = peek$(ctx, "totalSize") || 0;
set$(ctx, "totalSize", prevTotalSize + prevStylePaddingTop);
state.timeoutSetPaddingTop = setTimeout(() => {
@@ -7968,6 +8035,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
@@ -7968,6 +8038,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
estimatedListSize,
extraData,
getFixedItemSize,
@@ -645,7 +689,7 @@ index fe5f415..8219839 100644
getItemType,
horizontal,
rtl,
@@ -8261,6 +8329,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
@@ -8261,6 +8332,7 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
dataVersion,
drawDistance,
estimatedItemSize,
@@ -653,7 +697,7 @@ index fe5f415..8219839 100644
getFixedItemSize: useWrapIfItem(getFixedItemSize),
getItemType: useWrapIfItem(getItemType),
hasExternalScroll,
@@ -8528,6 +8597,15 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
@@ -8528,6 +8600,15 @@ var LegendListInner = typedForwardRef(function LegendListInner2(props, forwarded
doMaintainScrollAtEnd(ctx);
}
}, [!!maintainScrollAtEndConfig]);