mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-04 06:06:26 +00:00
Compare commits
13
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
acde63e614 | ||
|
|
25d9ed2985 | ||
|
|
b947c229c6 | ||
|
|
2e3d9b375a | ||
|
|
9cb4726c30 | ||
|
|
1544282593 | ||
|
|
61d2ad1585 | ||
|
|
512f21ba64 | ||
|
|
646b65e617 | ||
|
|
302afe1104 | ||
|
|
b14f61ce27 | ||
|
|
6b808bc67b | ||
|
|
624c26aa91 |
@@ -232,9 +232,11 @@ at-least-once wakeup, without turn attribution or exactly-once delivery.
|
||||
A turn end is not always a settled child. A child can end its turn with work that will start its next
|
||||
turn by itself: a running turn, queued messages, a pending provider wake-up
|
||||
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
|
||||
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
|
||||
crons, change-request watches, and other daemon background items never count: they are external
|
||||
triggers, not work the caller is waiting for.
|
||||
wake-ups), or the child's own outstanding finish subscriptions as a caller. Queued finish notices
|
||||
(`agent-notification`) and turns started only by finish notices do not count as pending work
|
||||
unless a real prompt is batched into or steered into the turn. Heartbeats, recurring crons,
|
||||
change-request watches, and other daemon background items never count: they are external triggers,
|
||||
not work the caller is waiting for.
|
||||
|
||||
Every turn end reports `finished` at once, unless the child already sent an agent message to its
|
||||
caller during that turn and started no further tool work afterwards. In that case the child's
|
||||
@@ -243,8 +245,9 @@ ends silently, and a watch with pending work keeps following silently until a la
|
||||
the work drains. Starting another non-reporting tool call or a new turn clears that mark (plain text output after the
|
||||
message does not), and errors, permission requests, cancellations, and closes are never suppressed. When work is still
|
||||
pending on an unreported turn end, the notice names it and the subscription follows the child: each
|
||||
later turn end reports `finished` again, and the child settling with nothing pending sends a final
|
||||
`finished` and removes the subscription, even when the work drains without another turn. Reporting
|
||||
later turn end reports `finished` again, except that a turn started only by finish notices while
|
||||
already following keeps following without another interim notice; the child settling with nothing
|
||||
pending still sends the final `finished` and removes the subscription, even when the work drains without another turn. Reporting
|
||||
at once keeps a long-lived task, such as a dev server, from leaving the caller without the child's
|
||||
reply. Following is what lets the caller hear the reply a background task wakes up later
|
||||
([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change that leaves work pending
|
||||
|
||||
+2
-3
@@ -216,17 +216,16 @@ not change the shipped scroll view. Keep this behavior in the app's compiled nat
|
||||
|
||||
## F-Droid / source-only Android builds
|
||||
|
||||
F-Droid builds should set `PASEO_FDROID_BUILD=1` for `npm ci` (or `npm install`), Expo prebuild, and Gradle:
|
||||
F-Droid builds should set `PASEO_FDROID_BUILD=1` when running Expo prebuild:
|
||||
|
||||
```bash
|
||||
PASEO_FDROID_BUILD=1 npm ci
|
||||
cd packages/app
|
||||
PASEO_FDROID_BUILD=1 APP_VARIANT=production npx expo prebuild --platform android --clean --non-interactive
|
||||
cd android
|
||||
PASEO_FDROID_BUILD=1 ./gradlew assembleRelease --no-daemon --max-workers=1 -Dorg.gradle.parallel=false
|
||||
```
|
||||
|
||||
Setting `PASEO_FDROID_BUILD=1` during install makes `packages/react-native-enriched-markdown/postinstall.mjs` skip downloading the prebuilt iOS RaTeX XCFramework into the source tree. The flag must also be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications. Setting `PASEO_FDROID_BUILD=1` also disables native RaTeX math in `react-native-enriched-markdown` and falls back to raw LaTeX text without requiring a Rust toolchain.
|
||||
The flag must be present for both prebuild and Gradle because Gradle starts Metro for the release bundle. Keep the source build serial and daemon-free as shown above: compiling every Expo module can exhaust memory when Gradle workers run in parallel. The profile enables source-built Expo modules, excludes the proprietary camera, Firebase notification, and Expo development-client native modules, disables Gradle dependency metadata, and substitutes JavaScript stubs for camera and notifications. The resulting app supports direct and pasted-link pairing but not QR scanning or push notifications.
|
||||
|
||||
For a single-ABI APK, pass React Native's architecture property to Gradle:
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ The package keeps the npm tarball's layout, including its build output:
|
||||
- `android/generated` and `ios/generated` are checked-in codegen output (`includesGeneratedCode`). A change to a native component spec regenerates both; `scripts/postinstall-patches.test.mjs` compares them against the specs.
|
||||
- `src/web/wasm/md4c.js` and `lib/module/web/wasm/md4c.js` are an Emscripten build of `cpp/md4c`, `cpp/parser` and `cpp/wasm`. A parser change rebuilds both, or web keeps the old behavior while iOS and Android change. Run `cpp/wasm/build.sh` with `OUT_DIR` set to `src/web/wasm`, in `emscripten/emsdk:4.0.10` with the `-s GROWABLE_ARRAYBUFFERS=0` line removed. That version reproduces the committed JavaScript glue and has no such setting. The `lib/module` copy is the Babel output of the new file.
|
||||
- Upstream's Gradle, CMake and CocoaPods scripts detect upstream's own monorepo by the paths `packages/core` and a root `vendor/`. Do not add either path to this repository.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`, and downloads RaTeX into `ios/vendor` when `enableMath` is true (unless `PASEO_FDROID_BUILD=1`). The `enriched-markdown` block in `packages/app/package.json` chooses the languages and enables native math.
|
||||
- `postinstall.mjs` downloads the tree-sitter grammars into the ignored `cpp/highlight/vendor/grammars` and `vendor/tree-sitter`. The `enriched-markdown` block in `packages/app/package.json` chooses the languages.
|
||||
|
||||
CI does not build native code or run the fork's Robolectric suites. Run `npm run test:android --workspace=@getpaseo/app` for Android changes. Native changes require a client rebuild; JavaScript refresh cannot enable compiled grammars.
|
||||
|
||||
@@ -46,17 +46,7 @@ Some fork changes are backports. A sync past the upstream version drops them in
|
||||
|
||||
## Engine constraints
|
||||
|
||||
Built-in LaTeX math is enabled by default, and video is disabled. Task lists and admonitions are enabled, and task checkboxes stay read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing, and details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
### LaTeX math
|
||||
|
||||
`components/markdown/math.ts` accepts `$...$`, `$$...$$`, `\(...\)`, `\[...\]`, and closed `math` fences (` ```math ` or `~~~math`). Inline `$...$` requires non-alphanumeric outer boundaries, no inner edge spaces, and no leading currency number or shell prose. Escaped `\[1, 2\]` citations, `$PATH`, regexes, and `latex` or `tex` code fences stay literal. Non-math messages skip scanning with a fast character check and do not trigger an `mdast` parse. Adapted expressions canonicalize to `$...$` or `$$...$$` for `md4c`, escape table pipes inside table rows, and flank adjacent CJK characters with hair spaces.
|
||||
|
||||
On web and Electron, `react-native-enriched-markdown` loads KaTeX (`htmlAndMathml` output with `.woff2` fonts) lazily when a document contains a math node. It caches rendered HTML in a 256-entry LRU and skips root-font overrides on `.katex` elements. Selection copy restores `[data-math-source]` to `$...$` or `$$\n...\n$$` without hidden `.katex-mathml` or `annotation` nodes. Chat Find ignores `.katex-mathml`, `annotation`, and `annotation-xml` nodes as well.
|
||||
|
||||
On iOS and Android, native views render with RaTeX (`enableMath: true` in `packages/app/package.json`). F-Droid builds (`PASEO_FDROID_BUILD=1`) disable native RaTeX in Gradle and `postinstall.mjs`, falling back to raw LaTeX. On 32-bit `x86` Android devices without `libratex_ffi.so`, the math views catch `Throwable` and render raw LaTeX text.
|
||||
|
||||
While streaming, `streaming.ts` keeps open `$$`, `\[`, and `math` fences in the unsealed tail so equations never split across blocks. Incomplete inline and display math stays withheld or literal until its closing delimiter arrives.
|
||||
Math and video are disabled. Task lists and admonitions are enabled; task checkboxes are read-only. Source adaptation spaces adjacent empty GFM table delimiters before escaping prose spoiler delimiters and decodes entity text before the engine can discard it. Code spans and fences keep their literal source. Comment HTML is normalized to Markdown before parsing; details show their summary and body expanded. `<br>` becomes a Markdown hard break, except inside a table, where a newline would end the row. There it becomes U+2028, and `cpp/parser/MD4CParser.cpp` turns U+2028 back into a line break in table cell text, never in code.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
@@ -445,6 +445,16 @@ workspace only. Location controls hosting, not context. An agent panel target ke
|
||||
when moved between hosts. Explorer configuration can create workspace-context panels and remove
|
||||
existing agent-context instances, but it cannot create an agent panel without an agent-aware command.
|
||||
|
||||
`AgentChat` renders the agent tab's own chain (`AgentPanelContent` in
|
||||
`packages/app/src/panels/agent-panel.tsx`) through `packages/app/src/agent-embed`. The chain takes
|
||||
a `ConversationSurface` instead of reading the pane: a pane has a tab to retarget and a pill track,
|
||||
an embed has neither, so its composer handles `/clear` by opening the agent's workspace and the
|
||||
track is never mounted. The embed publishes itself as a viewer with `useViewedAgent`, the hook the
|
||||
workspace sheet uses, so the tab and every embed of one agent share the sync's single observation.
|
||||
`controls: "none"` is the composer's `message` input mode (`composer/input-mode.ts`). Key focus
|
||||
follows the pane rule: the embed the user last pressed owns Escape and send, while its pane or
|
||||
screen is in front.
|
||||
|
||||
Command Center callbacks use the selected host's existing `PaseoApi` for normal Paseo operations.
|
||||
They use typed plugin RPC only for plugin-specific backend work. Surface and panel navigation
|
||||
belongs to the app; plugins do not receive Expo Router or workspace-layout store access.
|
||||
|
||||
Generated
-1
@@ -37620,7 +37620,6 @@
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"htmlparser2": "^12.0.0",
|
||||
"i18next": "^26.3.0",
|
||||
"katex": "^0.16.47",
|
||||
"lucide-react-native": "^1.50.0",
|
||||
"markdown-it": "^10.0.0",
|
||||
"mdast-util-from-markdown": "2.0.3",
|
||||
|
||||
@@ -51,16 +51,18 @@ test("lists connected clients with scopes and navigates Pair a device → Relay
|
||||
});
|
||||
try {
|
||||
await openDevicesPage(page, daemon);
|
||||
await expectConnectedClientRow(page, "This device", "Full access");
|
||||
await expandConnectedClientRow(page, "This device");
|
||||
await expect(
|
||||
page
|
||||
.getByTestId("devices-connected-clients-card")
|
||||
.getByText("access.manage", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expectConnectedClientRow(page, /^Chrome on /, "Full access");
|
||||
await expandConnectedClientRow(page, /^Chrome on /);
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
await expect(card.getByText("IP address", { exact: true })).toBeVisible();
|
||||
await expect(card.getByText("127.0.0.1", { exact: true })).toBeVisible();
|
||||
await expect(card.getByText("access.manage", { exact: true })).toHaveCount(0);
|
||||
|
||||
await viewer.connect();
|
||||
await expectConnectedClientRow(page, "Test Phone", "Read-only");
|
||||
await expandConnectedClientRow(page, "Test Phone");
|
||||
await expect(card.getByText("daemon.read", { exact: true })).toBeVisible();
|
||||
await expect(card.getByText("workspace.read", { exact: true })).toBeVisible();
|
||||
|
||||
await openPairDeviceModal(page);
|
||||
await expectPairingOffer(page);
|
||||
|
||||
@@ -0,0 +1,349 @@
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { openCommandCenter } from "../support/helpers/command-center";
|
||||
import {
|
||||
openAgentRoute,
|
||||
seedMockAgentWorkspace,
|
||||
type MockAgentWorkspace,
|
||||
} from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { pluginRequirements } from "../support/helpers/plugin-fixture";
|
||||
|
||||
const PLUGIN_ID = "agent-chat-focus-e2e";
|
||||
const SCREEN_TITLE = "Embeds";
|
||||
const PHONE = { width: 390, height: 844 };
|
||||
|
||||
interface EmbedComposer {
|
||||
controls?: "all" | "none";
|
||||
}
|
||||
|
||||
/**
|
||||
* A screen with one `AgentChat` per agent under a header of its own, plus a client slash command
|
||||
* that a full composer runs and a `controls: "none"` composer sends as text. A button opens the
|
||||
* first agent's chat in a plugin modal too, and a workspace panel shows the same chats side by side.
|
||||
*/
|
||||
function pluginSource(input: { agentIds: string[]; composer: EmbedComposer }): string {
|
||||
return `import { useCallback } from "react";
|
||||
import { Pressable, Text, View } from "react-native";
|
||||
import { AgentChat, Modal, SidebarRow } from "@getpaseo/plugin/client/ui";
|
||||
import { useState } from "react";
|
||||
|
||||
const AGENT_IDS = ${JSON.stringify(input.agentIds)};
|
||||
const COMPOSER = ${JSON.stringify(input.composer)};
|
||||
|
||||
function Embeds() {
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
return (
|
||||
<View style={{ flex: 1 }}>
|
||||
<Text testID="plugin-header" style={{ padding: 8 }}>Embedded agents</Text>
|
||||
<Pressable accessibilityRole="button" onPress={() => setModalOpen(true)}>
|
||||
<Text>Open in modal</Text>
|
||||
</Pressable>
|
||||
<Modal title="Agent in a modal" open={modalOpen} onOpenChange={setModalOpen}>
|
||||
<Modal.Content scrollable={false}>
|
||||
<AgentChat agentId={AGENT_IDS[0]} composer={COMPOSER} testID="modal-embed" />
|
||||
</Modal.Content>
|
||||
</Modal>
|
||||
<View style={{ flex: 1, flexDirection: "row" }}>
|
||||
{AGENT_IDS.map((agentId) => (
|
||||
<View key={agentId} style={{ flex: 1, minWidth: 0 }}>
|
||||
<AgentChat agentId={agentId} composer={COMPOSER} testID={"embed-" + agentId} />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function Board() {
|
||||
return (
|
||||
<View style={{ flex: 1, flexDirection: "row" }}>
|
||||
{AGENT_IDS.map((agentId) => (
|
||||
<View key={agentId} style={{ flex: 1, minWidth: 0 }}>
|
||||
<AgentChat agentId={agentId} composer={COMPOSER} testID={"panel-embed-" + agentId} />
|
||||
</View>
|
||||
))}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
function EmbedsItem({ currentScreen, openScreen }) {
|
||||
const open = useCallback(() => openScreen({ screenId: "main" }), [openScreen]);
|
||||
return <SidebarRow icon="Bot" active={currentScreen?.screenId === "main"} onPress={open} />;
|
||||
}
|
||||
|
||||
export default function contribute(plugin) {
|
||||
plugin.addScreen({ id: "main", title: "${SCREEN_TITLE}", Component: Embeds });
|
||||
plugin.addSidebarHeaderItem({ id: "main", title: "${SCREEN_TITLE}", Component: EmbedsItem });
|
||||
plugin.addWorkspacePanel({ id: "board", title: "Board", icon: "Bot", context: "workspace", Component: Board });
|
||||
plugin.addCommandCenterItem({
|
||||
id: "board",
|
||||
title: "Open embeds board",
|
||||
icon: "Bot",
|
||||
context: "workspace",
|
||||
onSelect({ openPanel }) {
|
||||
openPanel("board");
|
||||
},
|
||||
});
|
||||
plugin.addSlashCommand({
|
||||
name: "stamp",
|
||||
context: "agent",
|
||||
description: "Stamp the agent",
|
||||
argumentHint: "",
|
||||
onSubmit() {},
|
||||
});
|
||||
return () => {};
|
||||
}`;
|
||||
}
|
||||
|
||||
interface Scenario {
|
||||
agents: MockAgentWorkspace[];
|
||||
embed(agentId: string): ReturnType<Page["getByTestId"]>;
|
||||
}
|
||||
|
||||
async function withEmbeds(
|
||||
page: Page,
|
||||
input: { agents: { title: string; model: string; prompt: string }[]; composer: EmbedComposer },
|
||||
run: (scenario: Scenario) => Promise<void>,
|
||||
): Promise<void> {
|
||||
const agents: MockAgentWorkspace[] = [];
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
const directory = await mkdtemp(path.join(tmpdir(), "paseo-agent-chat-focus-"));
|
||||
try {
|
||||
for (const agent of input.agents) {
|
||||
agents.push(
|
||||
await seedMockAgentWorkspace({
|
||||
repoPrefix: "agent-chat-focus-",
|
||||
title: agent.title,
|
||||
model: agent.model,
|
||||
initialPrompt: agent.prompt,
|
||||
}),
|
||||
);
|
||||
}
|
||||
await writeFile(
|
||||
path.join(directory, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(directory, "index.client.tsx"),
|
||||
pluginSource({ agentIds: agents.map((agent) => agent.agentId), composer: input.composer }),
|
||||
);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(directory);
|
||||
await gotoAppShell(page);
|
||||
await page.getByRole("button", { name: SCREEN_TITLE, exact: true }).click();
|
||||
const embed = (agentId: string) => page.getByTestId(`embed-${agentId}`);
|
||||
for (const agent of agents) {
|
||||
await expect(embed(agent.agentId).getByTestId("user-message").first()).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
}
|
||||
await run({ agents, embed });
|
||||
} finally {
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client
|
||||
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false })
|
||||
.catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
for (const agent of agents) await agent.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function agentStatus(agent: MockAgentWorkspace): Promise<string | null> {
|
||||
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
|
||||
return fetched?.agent.status ?? null;
|
||||
}
|
||||
|
||||
/** Clicks land on text, not on a field, so Escape routes as the interrupt shortcut. */
|
||||
async function expectEscapeInterruptsOnlyTheFocusedEmbed(
|
||||
page: Page,
|
||||
input: { left: MockAgentWorkspace; right: MockAgentWorkspace; embed: Scenario["embed"] },
|
||||
): Promise<void> {
|
||||
const { left, right, embed } = input;
|
||||
await test.step("Escape after a click outside the embeds interrupts neither", async () => {
|
||||
await page.getByTestId("plugin-header").click();
|
||||
await page.keyboard.press("Escape");
|
||||
});
|
||||
await test.step("Escape after a click in the left embed interrupts only it", async () => {
|
||||
await embed(left.agentId).getByTestId("user-message").first().click();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("idle");
|
||||
// Interrupts go out in order, so a stray one from the first Escape has landed by now.
|
||||
expect(await agentStatus(right)).toBe("running");
|
||||
});
|
||||
await test.step("Escape after a click in the right embed interrupts it", async () => {
|
||||
await embed(right.agentId).getByTestId("user-message").first().click();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("idle");
|
||||
});
|
||||
}
|
||||
|
||||
test('controls: "none" sends a plugin slash command to the agent as typed', async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await withEmbeds(
|
||||
page,
|
||||
{
|
||||
agents: [{ title: "Slash agent", model: "e2e-fast-stream", prompt: "Say hello." }],
|
||||
composer: { controls: "none" },
|
||||
},
|
||||
async ({ agents: [agent], embed }) => {
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const box = embed(agent.agentId).getByRole("textbox", { name: "Message agent..." });
|
||||
await box.fill("/stamp the invoices");
|
||||
await box.press("Enter");
|
||||
await expect(embed(agent.agentId).getByTestId("user-message").last()).toContainText(
|
||||
"/stamp the invoices",
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("Escape interrupts only the embed that has focus", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await withEmbeds(
|
||||
page,
|
||||
{
|
||||
agents: [
|
||||
{ title: "Left agent", model: "one-minute-stream", prompt: "Keep running left." },
|
||||
{ title: "Right agent", model: "one-minute-stream", prompt: "Keep running right." },
|
||||
],
|
||||
composer: { controls: "none" },
|
||||
},
|
||||
async ({ agents: [left, right], embed }) => {
|
||||
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("running");
|
||||
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("running");
|
||||
|
||||
await expectEscapeInterruptsOnlyTheFocusedEmbed(page, { left, right, embed });
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("a phone-width plugin modal shows an agent's chat", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await withEmbeds(
|
||||
page,
|
||||
{
|
||||
agents: [{ title: "Modal agent", model: "e2e-fast-stream", prompt: "Say hello." }],
|
||||
composer: { controls: "none" },
|
||||
},
|
||||
async () => {
|
||||
// At phone width the modal is a bottom sheet whose body renders under the app's root
|
||||
// portal host, outside the plugin screen's React tree.
|
||||
await page.setViewportSize(PHONE);
|
||||
await page.getByRole("button", { name: "Open in modal", exact: true }).click();
|
||||
await expect(page.getByText("Agent in a modal", { exact: true })).toBeVisible();
|
||||
const modalEmbed = page.getByTestId("modal-embed");
|
||||
await expect(modalEmbed.getByTestId("user-message").first()).toContainText("Say hello.", {
|
||||
timeout: 30_000,
|
||||
});
|
||||
await expect(modalEmbed.getByRole("textbox", { name: "Message agent..." })).toBeVisible();
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
/** Picks the embed's current mode again from its picker, which draws at the overlay root. */
|
||||
async function pickCurrentMode(page: Page, embed: ReturnType<Page["getByTestId"]>): Promise<void> {
|
||||
const trigger = embed.getByRole("button", { name: /^Select agent mode \(/ });
|
||||
const label = /^Select agent mode \((.+)\)$/.exec(
|
||||
(await trigger.getAttribute("aria-label")) ?? "",
|
||||
)?.[1];
|
||||
expect(label).toBeTruthy();
|
||||
await trigger.click();
|
||||
const popup = page.getByTestId("combobox-desktop-container").last();
|
||||
await expect(popup).toBeVisible({ timeout: 10_000 });
|
||||
await popup.getByRole("button", { name: label, exact: true }).click();
|
||||
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
|
||||
}
|
||||
|
||||
test("a full-composer embed applies a slash suggestion picked with the pointer", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
await withEmbeds(
|
||||
page,
|
||||
{
|
||||
agents: [{ title: "Suggestion agent", model: "e2e-fast-stream", prompt: "Say hello." }],
|
||||
composer: {},
|
||||
},
|
||||
async ({ agents: [agent], embed }) => {
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const box = embed(agent.agentId).getByRole("textbox", { name: "Message agent..." });
|
||||
await box.click();
|
||||
await box.pressSequentially("/sta");
|
||||
// The list draws in the floating-panel portal, outside the embed's own nodes.
|
||||
const suggestion = page
|
||||
.getByTestId("composer-autocomplete-popover")
|
||||
.getByText("/stamp", { exact: true });
|
||||
await expect(suggestion).toBeVisible({ timeout: 30_000 });
|
||||
await suggestion.click();
|
||||
await expect(box).toHaveValue(/^\/stamp\s*$/);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("a portaled mode picker keeps its embed focused for Escape", async ({ page }) => {
|
||||
test.setTimeout(240_000);
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await withEmbeds(
|
||||
page,
|
||||
{
|
||||
agents: [
|
||||
{ title: "Left agent", model: "one-minute-stream", prompt: "Keep running left." },
|
||||
{ title: "Right agent", model: "one-minute-stream", prompt: "Keep running right." },
|
||||
],
|
||||
composer: {},
|
||||
},
|
||||
async ({ agents: [left, right], embed }) => {
|
||||
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("running");
|
||||
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("running");
|
||||
|
||||
await pickCurrentMode(page, embed(left.agentId));
|
||||
await page.keyboard.press("Escape");
|
||||
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("idle");
|
||||
expect(await agentStatus(right)).toBe("running");
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test("embeds in one workspace panel keep their own composers", async ({ page }) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.setViewportSize({ width: 1440, height: 900 });
|
||||
await withEmbeds(
|
||||
page,
|
||||
{
|
||||
agents: [
|
||||
{ title: "Left agent", model: "e2e-fast-stream", prompt: "Say hello left." },
|
||||
{ title: "Right agent", model: "e2e-fast-stream", prompt: "Say hello right." },
|
||||
],
|
||||
composer: {},
|
||||
},
|
||||
async ({ agents: [left, right] }) => {
|
||||
await openAgentRoute(page, left);
|
||||
const commands = await openCommandCenter(page);
|
||||
await commands.getByTestId("command-center-input").fill("Open embeds board");
|
||||
await commands.getByRole("button", { name: "Open embeds board", exact: true }).click();
|
||||
const leftEmbed = page.getByTestId(`panel-embed-${left.agentId}`);
|
||||
const rightEmbed = page.getByTestId(`panel-embed-${right.agentId}`);
|
||||
await expect(leftEmbed.getByTestId("user-message").first()).toBeVisible({ timeout: 30_000 });
|
||||
await expect(rightEmbed.getByTestId("user-message").first()).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// The fullscreen control shows on a phone once the draft runs past two lines.
|
||||
await page.setViewportSize(PHONE);
|
||||
await leftEmbed
|
||||
.getByRole("textbox", { name: "Message agent..." })
|
||||
.fill("First line\nSecond line\nThird line\nFourth line");
|
||||
await leftEmbed.getByRole("button", { name: "Fullscreen", exact: true }).click();
|
||||
await expect(leftEmbed.getByTestId("composer-fullscreen")).toBeVisible();
|
||||
await expect(rightEmbed.getByTestId("composer-fullscreen")).toHaveCount(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
import { expect, test, type Page } from "../support/fixtures";
|
||||
import { gotoAppShell } from "../support/helpers/app";
|
||||
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
|
||||
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
|
||||
import { copyPluginExample } from "../support/helpers/plugin-fixture";
|
||||
|
||||
const PLUGIN_ID = "agent-chat-example";
|
||||
const AGENT_TITLE = "Billing retries";
|
||||
const FIRST_PROMPT = "Summarize the billing retry failures.";
|
||||
|
||||
function embed(page: Page) {
|
||||
return page.getByTestId("example-agent-chat");
|
||||
}
|
||||
|
||||
async function openAgentInEmbed(page: Page): Promise<void> {
|
||||
await gotoAppShell(page);
|
||||
await page.getByRole("button", { name: "Agents", exact: true }).click();
|
||||
await page
|
||||
.getByTestId("example-agent-list")
|
||||
.getByRole("button", { name: AGENT_TITLE, exact: true })
|
||||
.click();
|
||||
}
|
||||
|
||||
async function sendFromEmbed(page: Page, text: string): Promise<void> {
|
||||
const box = embed(page).getByRole("textbox", { name: "Message agent..." });
|
||||
await box.fill(text);
|
||||
await box.press("Enter");
|
||||
}
|
||||
|
||||
test.describe("AgentChat", () => {
|
||||
test("a plugin screen embeds an agent's chat with the composer it chose", async ({
|
||||
page,
|
||||
context,
|
||||
}) => {
|
||||
test.setTimeout(180_000);
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
const agent = await seedMockAgentWorkspace({
|
||||
repoPrefix: "plugin-agent-chat-",
|
||||
title: AGENT_TITLE,
|
||||
initialPrompt: FIRST_PROMPT,
|
||||
});
|
||||
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
|
||||
const previous = await client.getDaemonConfig();
|
||||
const example = await copyPluginExample("agent-chat");
|
||||
try {
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
await client.installDirectoryPlugin(example.directory);
|
||||
await openAgentInEmbed(page);
|
||||
|
||||
await test.step("controls: none is a message box and Send", async () => {
|
||||
await expect(embed(page).getByTestId("user-message")).toContainText(FIRST_PROMPT);
|
||||
await expect(embed(page).getByTestId("assistant-message").first()).toBeVisible();
|
||||
await expect(
|
||||
embed(page).getByRole("textbox", { name: "Message agent..." }),
|
||||
).toHaveAttribute("placeholder", "Message this agent");
|
||||
await expect(embed(page).getByTestId("agent-controls-toolbar")).toHaveCount(0);
|
||||
await expect(embed(page).getByTestId("message-input-attach-button")).toHaveCount(0);
|
||||
await expect(embed(page).getByTestId("context-window-meter")).toHaveCount(0);
|
||||
const choices = await page.getByTestId("example-composer-choices").boundingBox();
|
||||
const chat = await embed(page).boundingBox();
|
||||
expect(chat!.y).toBeGreaterThanOrEqual(choices!.y + choices!.height);
|
||||
});
|
||||
|
||||
await test.step("a message sent from the embed streams into it", async () => {
|
||||
await sendFromEmbed(page, "Check the invoice PDFs next.");
|
||||
await expect(embed(page).getByTestId("user-message").last()).toContainText(
|
||||
"Check the invoice PDFs next.",
|
||||
);
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
});
|
||||
|
||||
await test.step("slash text in the simple box reaches the agent as typed", async () => {
|
||||
await sendFromEmbed(page, "/exit");
|
||||
await expect(embed(page).getByTestId("user-message").last()).toContainText("/exit");
|
||||
await agent.client.waitForFinish(agent.agentId, 30_000);
|
||||
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
|
||||
expect(fetched?.agent.archivedAt ?? null).toBeNull();
|
||||
});
|
||||
|
||||
await test.step("the full composer is the agent tab's", async () => {
|
||||
await page.getByRole("button", { name: "Full", exact: true }).click();
|
||||
await expect(embed(page).getByTestId("agent-controls-toolbar")).toBeVisible();
|
||||
await expect(embed(page).getByTestId("message-input-attach-button")).toBeVisible();
|
||||
await expect(embed(page).getByTestId("context-window-meter")).toBeVisible();
|
||||
});
|
||||
|
||||
await test.step("composer={false} shows the conversation without a composer", async () => {
|
||||
await page.getByRole("button", { name: "No composer", exact: true }).click();
|
||||
await expect(embed(page).getByTestId("user-message").first()).toContainText(FIRST_PROMPT);
|
||||
await expect(embed(page).getByRole("textbox", { name: "Message agent..." })).toHaveCount(0);
|
||||
});
|
||||
|
||||
await test.step("the agent's tab and the embed stay live together", async () => {
|
||||
await page.getByRole("button", { name: "Simple", exact: true }).click();
|
||||
const tab = await context.newPage();
|
||||
await openAgentRoute(tab, { workspaceId: agent.workspaceId, agentId: agent.agentId });
|
||||
const tabBox = tab.getByRole("textbox", { name: "Message agent..." }).first();
|
||||
await tabBox.fill("Sent from the tab.");
|
||||
await tabBox.press("Enter");
|
||||
await expect(embed(page).getByTestId("user-message").last()).toContainText(
|
||||
"Sent from the tab.",
|
||||
);
|
||||
await sendFromEmbed(page, "Sent from the embed.");
|
||||
await expect(tab.getByTestId("user-message").last()).toContainText("Sent from the embed.");
|
||||
await tab.close();
|
||||
});
|
||||
} finally {
|
||||
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
|
||||
await client
|
||||
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false })
|
||||
.catch(() => undefined);
|
||||
await client.close().catch(() => undefined);
|
||||
await example.cleanup();
|
||||
await agent.cleanup();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -76,19 +76,21 @@ export async function openDevicesPage(page: Page, daemon: PairingHost): Promise<
|
||||
|
||||
export async function expectConnectedClientRow(
|
||||
page: Page,
|
||||
title: string,
|
||||
title: string | RegExp,
|
||||
scopeLabel: string,
|
||||
): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
const row = card.getByRole("button", { name: title, exact: true });
|
||||
const row = card.getByRole("button", { name: title, exact: typeof title === "string" });
|
||||
await expect(row).toBeVisible();
|
||||
await expect(card.getByText(scopeLabel, { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expandConnectedClientRow(page: Page, title: string): Promise<void> {
|
||||
export async function expandConnectedClientRow(page: Page, title: string | RegExp): Promise<void> {
|
||||
const card = page.getByTestId("devices-connected-clients-card");
|
||||
await card.getByRole("button", { name: title, exact: true }).click();
|
||||
await expect(card.getByText("Permissions", { exact: true })).toBeVisible();
|
||||
const toggle = card.getByRole("button", { name: title, exact: typeof title === "string" });
|
||||
await toggle.click();
|
||||
await expect(toggle).toHaveAttribute("aria-expanded", "true");
|
||||
await expect(card.getByText("Access", { exact: true }).first()).toBeVisible();
|
||||
}
|
||||
|
||||
export async function returnFromRelayToWaysToConnect(page: Page): Promise<void> {
|
||||
|
||||
@@ -188,7 +188,12 @@ export interface SeedDaemonClient {
|
||||
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
|
||||
refreshAgent(agentId: string): Promise<unknown>;
|
||||
fetchAgent(options: { agentId: string }): Promise<{
|
||||
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
|
||||
agent: {
|
||||
id: string;
|
||||
status: string;
|
||||
archivedAt?: string | null;
|
||||
pendingPermissions: Array<{ id: string }>;
|
||||
};
|
||||
} | null>;
|
||||
getLastServerInfoMessage(): {
|
||||
features?: {
|
||||
|
||||
Vendored
-4
@@ -1,5 +1 @@
|
||||
declare module "*.css";
|
||||
declare module "*.woff2" {
|
||||
const src: string;
|
||||
export default src;
|
||||
}
|
||||
|
||||
@@ -17,9 +17,6 @@ const customWebPlatform = (process.env.PASEO_WEB_PLATFORM ?? "")
|
||||
.toLowerCase();
|
||||
|
||||
const config = getDefaultConfig(projectRoot);
|
||||
if (!config.resolver.assetExts.includes("woff2")) {
|
||||
config.resolver.assetExts.push("woff2");
|
||||
}
|
||||
config.cacheVersion = isWatchdogBuild ? "watchdog" : "standard";
|
||||
const defaultResolveRequest = config.resolver.resolveRequest ?? resolve;
|
||||
|
||||
|
||||
@@ -41,7 +41,7 @@
|
||||
"dev:ios": "npm --prefix ../.. run build:client && cross-env APP_VARIANT=development expo run:ios",
|
||||
"build:apk": "npm --prefix ../.. run build:apk",
|
||||
"build:apk:arm64": "npm --prefix ../.. run build:apk:arm64",
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --tests '*MathRenderingFallbackTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
"test:android": "expo prebuild --platform android --no-install && cd android && ./gradlew :paseo-native-trace:testReleaseUnitTest :paseo-hardware-keyboard:testReleaseUnitTest :expo-modules-core:testReleaseUnitTest --tests expo.modules.kotlin.activityresult.AppContextActivityResultRegistryRecreationTest :react-native-enriched-markdown:testReleaseUnitTest --tests '*InlineCodeFormattingTest' --tests '*ListRenderingTest' --tests '*TaskListInteractionTest' --tests '*ListBlockquoteMeasurementTest' --tests '*BlockquoteCopyTest' --tests '*CodeBlockCopyButtonConstructionTest' --tests '*LongPressSelectionInterceptTest' --no-daemon --max-workers=2 -Dorg.gradle.parallel=false"
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/commands": "6.10.4",
|
||||
@@ -110,7 +110,6 @@
|
||||
"fast-deep-equal": "^3.1.3",
|
||||
"htmlparser2": "^12.0.0",
|
||||
"i18next": "^26.3.0",
|
||||
"katex": "^0.16.47",
|
||||
"lucide-react-native": "^1.50.0",
|
||||
"markdown-it": "^10.0.0",
|
||||
"mdast-util-from-markdown": "2.0.3",
|
||||
@@ -179,7 +178,7 @@
|
||||
"ws": "^8.20.0"
|
||||
},
|
||||
"enriched-markdown": {
|
||||
"enableMath": true,
|
||||
"enableMath": false,
|
||||
"enableCodeHighlight": true,
|
||||
"codeHighlightLanguages": [
|
||||
"json",
|
||||
|
||||
@@ -51,35 +51,61 @@
|
||||
}
|
||||
</style>
|
||||
<style>
|
||||
button,
|
||||
a,
|
||||
input,
|
||||
textarea,
|
||||
select,
|
||||
[role="button"],
|
||||
[role="link"],
|
||||
[role="textbox"],
|
||||
[role="combobox"],
|
||||
[role="tab"],
|
||||
[role="switch"],
|
||||
[role="checkbox"],
|
||||
[role="slider"],
|
||||
[role="menuitem"],
|
||||
[tabindex],
|
||||
/* Only interactive controls that can overlap a window drag surface
|
||||
emit -webkit-app-region: no-drag. Controls in ordinary window content
|
||||
rely on normal DOM hit testing so scrolled viewports and parked
|
||||
browser webviews never emit unclipped no-drag boxes over the titlebar. */
|
||||
:is(
|
||||
[data-window-drag-region] ~ *,
|
||||
[style*="-webkit-app-region: drag"],
|
||||
[style*="-webkit-app-region:drag"],
|
||||
#overlay-root,
|
||||
[data-window-overlay-host],
|
||||
[role="dialog"],
|
||||
[aria-modal="true"]
|
||||
)
|
||||
:is(
|
||||
button,
|
||||
a,
|
||||
input,
|
||||
textarea,
|
||||
select,
|
||||
[role="button"],
|
||||
[role="link"],
|
||||
[role="textbox"],
|
||||
[role="combobox"],
|
||||
[role="tab"],
|
||||
[role="switch"],
|
||||
[role="checkbox"],
|
||||
[role="slider"],
|
||||
[role="menuitem"],
|
||||
[tabindex],
|
||||
[contenteditable="true"]
|
||||
),
|
||||
[data-window-drag-region]
|
||||
~ :is(
|
||||
button,
|
||||
a,
|
||||
input,
|
||||
textarea,
|
||||
select,
|
||||
[role="button"],
|
||||
[role="link"],
|
||||
[role="textbox"],
|
||||
[role="combobox"],
|
||||
[role="tab"],
|
||||
[role="switch"],
|
||||
[role="checkbox"],
|
||||
[role="slider"],
|
||||
[role="menuitem"],
|
||||
[tabindex],
|
||||
[contenteditable="true"]
|
||||
),
|
||||
[data-window-no-drag],
|
||||
[contenteditable="true"] {
|
||||
[data-window-no-drag] * {
|
||||
-webkit-app-region: no-drag !important;
|
||||
}
|
||||
|
||||
/* Electron does not clip app-region rectangles to scroll viewports.
|
||||
Content-only viewports emit no window regions, including from their
|
||||
controls. Visible controls here use normal DOM hit testing.
|
||||
Use initial: Blink parses the explicit value none as no-drag. */
|
||||
[data-window-content],
|
||||
[data-window-content] * {
|
||||
-webkit-app-region: initial !important;
|
||||
}
|
||||
|
||||
/* Suppress the browser's default focus outline — it appears on mouse
|
||||
clicks and looks out of place against our themed surfaces. Keep a
|
||||
themed ring for keyboard users via :focus-visible. The ring is the active
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import type { View, ViewProps } from "react-native";
|
||||
import type { RefObject } from "react";
|
||||
|
||||
/**
|
||||
* Native: a touch that starts in the embed claims it, as a touch claims a workspace pane. The
|
||||
* capture handler declines the responder, so the touch still reaches what was pressed.
|
||||
*/
|
||||
export function useClaimFocusProps(
|
||||
claim: () => void,
|
||||
): Pick<ViewProps, "onStartShouldSetResponderCapture"> & { ref?: RefObject<View | null> } {
|
||||
const handleTouch = useCallback(() => {
|
||||
claim();
|
||||
return false;
|
||||
}, [claim]);
|
||||
return useMemo(() => ({ onStartShouldSetResponderCapture: handleTouch }), [handleTouch]);
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
import { useEffect, useMemo, useRef, type RefObject } from "react";
|
||||
import type { View, ViewProps } from "react-native";
|
||||
|
||||
/**
|
||||
* Web: a pointer press or focus move in the embed's DOM claims it, as one claims a workspace pane
|
||||
* (`split-container`). Pickers and menus the embed opens draw outside its DOM, so pressing them
|
||||
* leaves the claim where it is.
|
||||
*/
|
||||
export function useClaimFocusProps(
|
||||
claim: () => void,
|
||||
): Pick<ViewProps, "onStartShouldSetResponderCapture"> & { ref?: RefObject<View | null> } {
|
||||
const ref = useRef<View | null>(null);
|
||||
useEffect(() => {
|
||||
const node: unknown = ref.current;
|
||||
if (!(node instanceof HTMLElement)) return undefined;
|
||||
node.addEventListener("pointerdown", claim, true);
|
||||
node.addEventListener("focusin", claim, true);
|
||||
return () => {
|
||||
node.removeEventListener("pointerdown", claim, true);
|
||||
node.removeEventListener("focusin", claim, true);
|
||||
};
|
||||
}, [claim]);
|
||||
return useMemo(() => ({ ref }), []);
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { useCallback, useContext, useEffect, useSyncExternalStore } from "react";
|
||||
import { NavigationContext } from "expo-router/react-navigation";
|
||||
import { useEnclosingPaneFocus } from "@/panels/pane-context";
|
||||
|
||||
/**
|
||||
* Which embed owns the composer's key handlers (Escape interrupts, send, mode cycling). Embeds
|
||||
* follow the workspace's pane rule: the embed the user last pressed or focused owns them until
|
||||
* the user presses another embed. A press elsewhere, such as in the plugin's own UI or in a
|
||||
* picker the embed opened, leaves the owner as it is.
|
||||
*/
|
||||
let focusedEmbedId: string | null = null;
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
function subscribe(listener: () => void): () => void {
|
||||
listeners.add(listener);
|
||||
return () => listeners.delete(listener);
|
||||
}
|
||||
|
||||
function setFocusedEmbed(next: string | null): void {
|
||||
if (focusedEmbedId === next) return;
|
||||
focusedEmbedId = next;
|
||||
for (const listener of listeners) listener();
|
||||
}
|
||||
|
||||
/** The embed's key focus, and the claim its root calls on a press or focus move inside it. */
|
||||
export function useEmbedFocus(embedId: string): { isFocused: boolean; claim: () => void } {
|
||||
const read = useCallback(() => focusedEmbedId === embedId, [embedId]);
|
||||
const isFocused = useSyncExternalStore(subscribe, read, read);
|
||||
const claim = useCallback(() => setFocusedEmbed(embedId), [embedId]);
|
||||
useEffect(
|
||||
() => () => {
|
||||
if (focusedEmbedId === embedId) setFocusedEmbed(null);
|
||||
},
|
||||
[embedId],
|
||||
);
|
||||
return { isFocused, claim };
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the surface around the embed is the one the user is on: the pane it sits in, or else
|
||||
* the screen. A plugin screen stays mounted under the next one, and its embeds must not keep the
|
||||
* keys there. Outside any screen (a modal at the app root) the surface counts as shown.
|
||||
*/
|
||||
export function useEmbedSurfaceActive(): boolean {
|
||||
const pane = useEnclosingPaneFocus();
|
||||
const navigation = useContext(NavigationContext);
|
||||
const subscribeToRoute = useCallback(
|
||||
(listener: () => void) => {
|
||||
if (!navigation) return () => {};
|
||||
const removeFocus = navigation.addListener("focus", listener);
|
||||
const removeBlur = navigation.addListener("blur", listener);
|
||||
return () => {
|
||||
removeFocus();
|
||||
removeBlur();
|
||||
};
|
||||
},
|
||||
[navigation],
|
||||
);
|
||||
const readRoute = useCallback(() => navigation?.isFocused() ?? true, [navigation]);
|
||||
const isRouteFocused = useSyncExternalStore(subscribeToRoute, readRoute, readRoute);
|
||||
return pane ? pane.isInteractive : isRouteFocused;
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
import { useId, useMemo } from "react";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { LocalComposerEditingScope } from "@/composer/editing-session";
|
||||
import {
|
||||
AgentPanelContent,
|
||||
type ConversationSurface,
|
||||
type EmbeddedComposer,
|
||||
} from "@/panels/agent-panel";
|
||||
import { createPaneFocusContextValue, PaneFocusProvider } from "@/panels/pane-context";
|
||||
import { RetainedChatContent } from "@/panels/retained-chat-content";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useViewedAgent } from "@/timeline/use-viewed-agent";
|
||||
import { useClaimFocusProps } from "./claim-focus";
|
||||
import { useEmbedFocus, useEmbedSurfaceActive } from "./focus";
|
||||
|
||||
export type { EmbeddedComposer } from "@/panels/agent-panel";
|
||||
|
||||
export interface AgentEmbedProps {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
/** `null` shows the conversation without a composer. */
|
||||
composer: EmbeddedComposer | null;
|
||||
testID?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* An agent's conversation outside the workspace: the agent tab's own chain, with its loading,
|
||||
* catch-up, error and archived states, and no tab chrome.
|
||||
*
|
||||
* The embed is a viewer like the workspace sheet, so the agent's timeline stays live while it is
|
||||
* mounted and shares the tab's observation when the agent is also open in a tab.
|
||||
*
|
||||
* Several embeds can share a screen. Like workspace panes, the one the user last pressed owns the
|
||||
* composer's key handlers, and only while its pane or screen is the one in front. Each embed edits
|
||||
* in its own composer session, even inside a workspace panel that has one of its own.
|
||||
*/
|
||||
export function AgentEmbed({ serverId, agentId, composer, testID }: AgentEmbedProps) {
|
||||
const viewerId = `embed:${useId()}`;
|
||||
useViewedAgent({ sourceId: viewerId, serverId, agentId });
|
||||
const isSurfaceActive = useEmbedSurfaceActive();
|
||||
const { isFocused, claim } = useEmbedFocus(viewerId);
|
||||
const claimProps = useClaimFocusProps(claim);
|
||||
const isPaneFocused = composer !== null && isSurfaceActive && isFocused;
|
||||
const surface = useMemo<ConversationSurface>(
|
||||
() => ({ kind: "embed", id: viewerId, composer, isActive: isSurfaceActive }),
|
||||
[composer, isSurfaceActive, viewerId],
|
||||
);
|
||||
const focus = useMemo(
|
||||
() => createPaneFocusContextValue({ isWorkspaceFocused: isSurfaceActive, isPaneFocused }),
|
||||
[isPaneFocused, isSurfaceActive],
|
||||
);
|
||||
const target = useMemo(() => ({ kind: "agent" as const, agentId }), [agentId]);
|
||||
const workspaceId = useSessionStore((state) => {
|
||||
const session = state.sessions[serverId];
|
||||
return (
|
||||
session?.agents.get(agentId)?.workspaceId ??
|
||||
session?.agentDetails.get(agentId)?.workspaceId ??
|
||||
""
|
||||
);
|
||||
});
|
||||
|
||||
return (
|
||||
<View {...claimProps} style={styles.root} testID={testID}>
|
||||
<PaneFocusProvider value={focus}>
|
||||
{/* Keyed like a pane's session, which follows its target. */}
|
||||
<LocalComposerEditingScope key={agentId}>
|
||||
<RetainedChatContent>
|
||||
<AgentPanelContent
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
target={target}
|
||||
surface={surface}
|
||||
isPaneFocused={isPaneFocused}
|
||||
/>
|
||||
</RetainedChatContent>
|
||||
</LocalComposerEditingScope>
|
||||
</PaneFocusProvider>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create({
|
||||
root: { flex: 1, minHeight: 0 },
|
||||
});
|
||||
@@ -122,26 +122,3 @@ it("keeps text around nested plugin blocks in separate occurrences", () => {
|
||||
expect(findRenderedMatches(row, "details").map((range) => range.toString())).toEqual(["details"]);
|
||||
expect(findRenderedMatches(row, "beta").map((range) => range.toString())).toEqual(["beta"]);
|
||||
});
|
||||
|
||||
it("ignores KaTeX MathML and annotations while keeping block math as a boundary", () => {
|
||||
const row = content(
|
||||
[
|
||||
"<p>Before ",
|
||||
'<span role="math" aria-label="alpha" data-display="inline" data-math-source="$alpha$">',
|
||||
'<span class="katex">',
|
||||
'<span class="katex-mathml"><math><semantics><mrow><mi>alpha</mi></mrow><annotation encoding="application/x-tex">alpha</annotation><annotation-xml encoding="MathML-Content"><ci>alpha</ci></annotation-xml></semantics></math></span>',
|
||||
'<span class="katex-html" aria-hidden="true"><span>alpha</span></span>',
|
||||
"</span>",
|
||||
"</span>",
|
||||
" after</p>",
|
||||
'<span role="math" aria-label="x^2" data-display="block" data-math-source="$$\nx^2\n$$">block fallback</span>',
|
||||
"<p>next</p>",
|
||||
].join(""),
|
||||
);
|
||||
|
||||
expect(findRenderedMatches(row, "alpha")).toEqual([]);
|
||||
expect(findRenderedMatches(row, "Before").map((range) => range.toString())).toEqual(["Before"]);
|
||||
expect(findRenderedMatches(row, "after").map((range) => range.toString())).toEqual(["after"]);
|
||||
expect(findRenderedMatches(row, "fallbacknext")).toEqual([]);
|
||||
expect(findRenderedMatches(row, "after fallbacknext")).toEqual([]);
|
||||
});
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
const BLOCKS = [
|
||||
...["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"].flatMap((tag) => [
|
||||
tag,
|
||||
`[data-paseo-markdown-tag="${tag}"]`,
|
||||
]),
|
||||
'[role="math"][data-display="block"]',
|
||||
].join(",");
|
||||
const BLOCKS = ["p", "pre", "li", "td", "th", "h1", "h2", "h3", "h4", "h5", "h6"]
|
||||
.flatMap((tag) => [tag, `[data-paseo-markdown-tag="${tag}"]`])
|
||||
.join(",");
|
||||
const IGNORED =
|
||||
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], .katex-mathml, annotation, annotation-xml, button, [role="button"], svg, script, style';
|
||||
'[data-paseo-markdown-ignore="true"], [aria-hidden="true"], button, [role="button"], svg, script, style';
|
||||
|
||||
/** Rendered rows carrying a source message identity, in reading order. */
|
||||
export function findMessageRows(root: HTMLElement | null, messageId: string): HTMLElement[] {
|
||||
|
||||
@@ -948,3 +948,46 @@ it.each([false, true])(
|
||||
expect(opened.groupsByHostId.size).toBe(0);
|
||||
},
|
||||
);
|
||||
|
||||
it("folds a completed turn whose plugin replaces every tool and reasoning row", () => {
|
||||
const present = createStreamPresentation();
|
||||
const timestamp = new Date();
|
||||
const tail: StreamItem[] = [
|
||||
{ kind: "user_message", id: "prompt", text: "Work", timestamp },
|
||||
{ kind: "thought", id: "reasoning", text: "Plan", status: "ready", timestamp },
|
||||
toolCall("one", "Bash"),
|
||||
{ kind: "assistant_message", id: "reply", text: "Done", timestamp },
|
||||
];
|
||||
const toolPlugin = installedTransform(installProbe("tool_call"));
|
||||
const reasoningPlugin = installedTransform(installProbe("reasoning"));
|
||||
const input = {
|
||||
...presentationOptions,
|
||||
tail,
|
||||
head: [],
|
||||
display: "collapseTurns" as const,
|
||||
isTurnActive: false,
|
||||
};
|
||||
const transform: TimelineItemTransform = (item) =>
|
||||
toolPlugin(item)?.flatMap((card) => [card, { ...card, id: `${card.id}/detail` }]) ??
|
||||
reasoningPlugin(item);
|
||||
const control = present({ ...input, transform: undefined });
|
||||
expect(control.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"turn_summary",
|
||||
"assistant_message",
|
||||
]);
|
||||
const closed = present({ ...input, transform });
|
||||
expect(closed.tail.map((item) => item.kind)).toEqual(control.tail.map((item) => item.kind));
|
||||
expect(closed.turns.summaryRowsByHostId.get("prompt")?.tools).toEqual(
|
||||
control.turns.summaryRowsByHostId.get("prompt")?.tools,
|
||||
);
|
||||
const opened = present({ ...input, transform, expandedTurnHostIds: new Set(["prompt"]) });
|
||||
expect(opened.tail.map((item) => item.kind)).toEqual([
|
||||
"user_message",
|
||||
"turn_summary",
|
||||
"plugin",
|
||||
"plugin",
|
||||
"plugin",
|
||||
"assistant_message",
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -1702,7 +1702,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
|
||||
!liveAuxiliary;
|
||||
|
||||
return (
|
||||
<div style={viewportStyle} data-window-content>
|
||||
<div style={viewportStyle}>
|
||||
<div
|
||||
ref={handleScrollContainerRef}
|
||||
// Let clicks focus the feed for browser keyboard scrolling without adding a Tab stop.
|
||||
|
||||
@@ -45,9 +45,14 @@ function summarizeTurn(
|
||||
getGroupedCalls: CollapseTurnsInput["getGroupedCalls"],
|
||||
): OverviewSummary {
|
||||
const calls: (ToolCallItem | ThoughtItem)[] = [];
|
||||
const countedSources = new Set<string>();
|
||||
for (const item of items) {
|
||||
if ((item.kind === "tool_call" || item.kind === "thought") && !isTurnTrigger(item))
|
||||
calls.push(...(getGroupedCalls(item.id) ?? [item]));
|
||||
const source = item.kind === "plugin" ? item.source : item;
|
||||
if (!source || (source.kind !== "tool_call" && source.kind !== "thought")) continue;
|
||||
if (isTurnTrigger(source) || countedSources.has(source.id)) continue;
|
||||
// One source tool call can render as several plugin cards.
|
||||
countedSources.add(source.id);
|
||||
calls.push(...(getGroupedCalls(source.id) ?? [source]));
|
||||
}
|
||||
return summarizeToolCalls(calls);
|
||||
}
|
||||
|
||||
@@ -54,6 +54,7 @@ import { AppearanceStyleBoundary } from "@/components/appearance-style-boundary"
|
||||
import { LeftSidebar } from "@/components/left-sidebar";
|
||||
import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
|
||||
import { DesktopWindowControls } from "@/components/desktop/window-controls";
|
||||
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
|
||||
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
|
||||
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
|
||||
@@ -606,6 +607,7 @@ function CompactSidebarHost({
|
||||
return (
|
||||
<View
|
||||
collapsable={false}
|
||||
dataSet={visible ? WINDOW_OVERLAY_HOST_DATASET : undefined}
|
||||
style={[
|
||||
layoutStyles.compactSidebarHost,
|
||||
{ opacity: visible ? 1 : 0 },
|
||||
|
||||
@@ -1,39 +0,0 @@
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { applyRootUiFont } from "./apply-root-font.web";
|
||||
|
||||
describe("applyRootUiFont", () => {
|
||||
afterEach(() => {
|
||||
document.getElementById("paseo-ui-font")?.remove();
|
||||
document.documentElement.style.removeProperty("--paseo-ui-font");
|
||||
document.body.replaceChildren();
|
||||
});
|
||||
|
||||
it("applies the UI font to prose while excluding monospace, role=math, and KaTeX subtrees", () => {
|
||||
applyRootUiFont("'Custom UI Font', sans-serif");
|
||||
|
||||
const root = document.createElement("div");
|
||||
root.id = "root";
|
||||
root.innerHTML = `
|
||||
<p id="prose">Prose</p>
|
||||
<code data-pmono="true" style="font-family: monospace"><span id="mono">code</span></code>
|
||||
<span id="math-host" role="math" style="font-family: KaTeX_Main"><span id="katex-root" class="katex"><span id="katex-glyph">x</span></span></span>
|
||||
`;
|
||||
document.body.append(root);
|
||||
|
||||
expect(getComputedStyle(document.getElementById("prose")!).fontFamily).toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("mono")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("math-host")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("katex-root")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
expect(getComputedStyle(document.getElementById("katex-glyph")!).fontFamily).not.toContain(
|
||||
"Custom UI Font",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -7,10 +7,9 @@
|
||||
// beats both RN-web's base font and Unistyles' generated classes (0,1,0) — no reliance
|
||||
// on stylesheet order. Code/diff/terminal surfaces carry `data-pmono` (and have their
|
||||
// subtree excluded via `:not([data-pmono] *)`) so they keep their monospace font.
|
||||
// KaTeX math containers carry `role="math"` and `.katex` and keep KaTeX font faces.
|
||||
const STYLE_ID = "paseo-ui-font";
|
||||
const RULE =
|
||||
':is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *):not([role="math"]):not([role="math"] *):not(.katex):not(.katex *){font-family:var(--paseo-ui-font);}';
|
||||
":is(#root, #overlay-root) *:not([data-pmono]):not([data-pmono] *){font-family:var(--paseo-ui-font);}";
|
||||
|
||||
export function applyRootUiFont(uiFontStack: string): void {
|
||||
if (typeof document === "undefined") return;
|
||||
|
||||
@@ -997,11 +997,7 @@ describe("quote copy", () => {
|
||||
});
|
||||
|
||||
/** Renders Markdown through the web engine with the app's renderers, as a message does. */
|
||||
async function renderMarkdown(
|
||||
markdown: string,
|
||||
lastText: string,
|
||||
latexMath = false,
|
||||
): Promise<HTMLElement> {
|
||||
async function renderMarkdown(markdown: string, lastText: string): Promise<HTMLElement> {
|
||||
if (!host || !root) {
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
@@ -1021,7 +1017,7 @@ describe("quote copy", () => {
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath, admonitions: true },
|
||||
md4cFlags: { latexMath: false, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
@@ -1139,102 +1135,4 @@ describe("quote copy", () => {
|
||||
|
||||
expect(createElementClipboardContent(quote)).toBeNull();
|
||||
});
|
||||
|
||||
it("copies rendered inline and display math inside a quote as LaTeX", async () => {
|
||||
const rendered = await renderMarkdown(
|
||||
"> Inline $E = mc^2$ and:\n>\n> $$\nx^2\n$$",
|
||||
"Inline",
|
||||
true,
|
||||
);
|
||||
await vi.waitFor(() =>
|
||||
expect(rendered.querySelectorAll(".katex").length).toBeGreaterThanOrEqual(2),
|
||||
);
|
||||
|
||||
const content = createElementClipboardContent(fixtureElement(rendered, "blockquote"));
|
||||
|
||||
expect(content?.plainText).toBe("Inline $E = mc^2$ and:\n\n$$\nx^2\n$$");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math selection 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;
|
||||
});
|
||||
|
||||
async function renderMathMarkdown(markdown: string): Promise<HTMLElement> {
|
||||
host = document.createElement("div");
|
||||
host.setAttribute("data-testid", "assistant-message");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
flushSync(() =>
|
||||
root!.render(
|
||||
h(
|
||||
QueryClientProvider,
|
||||
{ client: queryClient },
|
||||
h(
|
||||
I18nextProvider,
|
||||
{ i18n },
|
||||
h(ToastApiProvider, {
|
||||
api: toast,
|
||||
children: h(EnrichedMarkdownText, {
|
||||
markdown,
|
||||
flavor: "github",
|
||||
md4cFlags: { latexMath: true, admonitions: true },
|
||||
renderers: WEB_RENDERERS,
|
||||
}),
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
const rendered = host;
|
||||
await vi.waitFor(() => expect(rendered.querySelector(".katex")).not.toBeNull());
|
||||
return rendered;
|
||||
}
|
||||
|
||||
it("copies inline math as $tex$ and display math as $$\\ntex\\n$$ without leaking MathML", async () => {
|
||||
const rendered = await renderMathMarkdown(
|
||||
"Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.",
|
||||
);
|
||||
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(rendered));
|
||||
expect(content?.plainText).toBe("Before $a_i < b_j$ after.\n\n$$\n\\frac{1}{2}\n$$\n\nEnd.");
|
||||
expect(content?.html).not.toContain("<em>");
|
||||
expect(content?.html).toContain("$a_i < b_j$");
|
||||
});
|
||||
|
||||
it("copies a standalone selected math formula as its LaTeX source", async () => {
|
||||
const rendered = await renderMathMarkdown("Equation $E = mc^2$ here.");
|
||||
const mathEl = fixtureElement(rendered, '[role="math"]');
|
||||
|
||||
const content = createAssistantSelectionClipboardContent(selectNodeContents(mathEl));
|
||||
expect(content?.plainText).toBe("$E = mc^2$");
|
||||
});
|
||||
|
||||
it("strips .katex-mathml, annotation, and annotation-xml on partial math selection", async () => {
|
||||
const rendered = await renderMathMarkdown("Formula $a + b + c$ end.");
|
||||
const mathmlAnnotation = fixtureElement(rendered, ".katex-mathml annotation");
|
||||
const katexHtml = fixtureElement(rendered, ".katex-html");
|
||||
const firstLeaf = tokenText(katexHtml, "a");
|
||||
const secondLeaf = tokenText(katexHtml, "b");
|
||||
|
||||
// Partial selection inside .katex-html
|
||||
const partial = copyBetween([firstLeaf, 0], [secondLeaf, 1]);
|
||||
expect(partial?.plainText).toBe("a+b");
|
||||
expect(partial?.plainText).not.toContain("a + b + c");
|
||||
|
||||
// Selection starting inside .katex-mathml annotation and ending inside .katex-html
|
||||
const crossing = copyBetween([textNode(mathmlAnnotation), 0], [secondLeaf, 1]);
|
||||
expect(crossing?.plainText).toBe("a+b");
|
||||
expect(crossing?.plainText).not.toContain("a + b + c");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,7 +6,6 @@ import {
|
||||
type MarkdownClipboardContent,
|
||||
} from "@/utils/rich-clipboard";
|
||||
import {
|
||||
KATEX_MATHML_SELECTOR,
|
||||
MARKDOWN_ADMONITION_TITLE_ATTRIBUTE,
|
||||
MARKDOWN_ADMONITION_TYPE_ATTRIBUTE,
|
||||
MARKDOWN_COPY_IMAGE_SOURCES_ATTRIBUTE,
|
||||
@@ -21,8 +20,6 @@ import {
|
||||
MARKDOWN_COPY_TAG_ATTRIBUTE,
|
||||
MARKDOWN_COPY_RECOGNIZED_LINK_ATTRIBUTE,
|
||||
MARKDOWN_COPY_UNWRAP_ATTRIBUTE,
|
||||
MARKDOWN_MATH_DISPLAY_ATTRIBUTE,
|
||||
MARKDOWN_MATH_SOURCE_ATTRIBUTE,
|
||||
TRAILING_CODE_LINE_BREAKS,
|
||||
} from "./markup";
|
||||
|
||||
@@ -109,17 +106,6 @@ function createTurndown(flavor: "markdown" | "plain"): TurndownService {
|
||||
return `\n\n${`[!${type}]\n${body}`.replace(/^/gm, "> ")}\n\n`;
|
||||
},
|
||||
});
|
||||
// Rendered math copies back as `$tex$` (inline) or `$$\ntex\n$$` (block).
|
||||
turndown.addRule("mathSource", {
|
||||
filter: (node) => node.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE),
|
||||
replacement: (_content, node) => {
|
||||
const element = node as Element;
|
||||
const source = element.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE) ?? "";
|
||||
const isBlock = element.getAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE) === "block";
|
||||
const formatted = flavor === "markdown" ? turndown.escape(source) : source;
|
||||
return isBlock ? `\n\n${formatted}\n\n` : formatted;
|
||||
},
|
||||
});
|
||||
turndown.addRule("gfmStrikethrough", {
|
||||
filter: ["del", "s"],
|
||||
replacement: (content) => `~~${content}~~`,
|
||||
@@ -425,19 +411,12 @@ function nodeAtPath(root: Node, path: number[]): Node {
|
||||
}
|
||||
|
||||
function removeUnselectedSemantics(range: Range, source: Element, clone: Element): void {
|
||||
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], [${MARKDOWN_MATH_SOURCE_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
|
||||
const selector = `[${MARKDOWN_COPY_TAG_ATTRIBUTE}], a, ${SEMANTIC_TAGS}`;
|
||||
const originals = Array.from(source.querySelectorAll(selector));
|
||||
const copies = Array.from(clone.querySelectorAll(selector));
|
||||
|
||||
originals.forEach((original, index) => {
|
||||
const copy = copies[index];
|
||||
if (original.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
|
||||
if (copy && (!range.intersectsNode(original) || !hasSelectedAllContents(range, original))) {
|
||||
copy.removeAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
|
||||
copy.removeAttribute(MARKDOWN_MATH_DISPLAY_ATTRIBUTE);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (copy) copySemanticAttributes(original, copy);
|
||||
if (!copy || shouldPreserveSemanticElement(range, original)) {
|
||||
if (copy) {
|
||||
@@ -461,9 +440,6 @@ function shouldPreserveSemanticElement(range: Range, element: Element): boolean
|
||||
if (!range.intersectsNode(element)) {
|
||||
return false;
|
||||
}
|
||||
if (element.hasAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE)) {
|
||||
return hasSelectedAllContents(range, element);
|
||||
}
|
||||
const tag = semanticTag(element);
|
||||
// An image has no part to select, so touching it selects all of it.
|
||||
if (tag === "p" || tag === "img" || isTableStructure(tag)) {
|
||||
@@ -614,9 +590,7 @@ function selectsNothingOutside(range: Range, element: Element): boolean {
|
||||
|
||||
function hasMarkdownContent(fragment: DocumentFragment, includeIgnored: boolean): boolean {
|
||||
if (!includeIgnored) {
|
||||
for (const ignored of fragment.querySelectorAll(
|
||||
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
|
||||
)) {
|
||||
for (const ignored of fragment.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
|
||||
ignored.remove();
|
||||
}
|
||||
}
|
||||
@@ -707,19 +681,8 @@ function selectedMessageParts(range: Range): SelectedMessagePart[] | null {
|
||||
});
|
||||
}
|
||||
|
||||
function restoreMathSources(container: HTMLElement): void {
|
||||
for (const math of container.querySelectorAll(`[${MARKDOWN_MATH_SOURCE_ATTRIBUTE}]`)) {
|
||||
const source = math.getAttribute(MARKDOWN_MATH_SOURCE_ATTRIBUTE);
|
||||
if (source !== null) {
|
||||
math.textContent = source;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function restoreMarkdownElements(container: HTMLElement): void {
|
||||
for (const ignored of container.querySelectorAll(
|
||||
`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}], ${KATEX_MATHML_SELECTOR}`,
|
||||
)) {
|
||||
for (const ignored of container.querySelectorAll(`[${MARKDOWN_COPY_IGNORE_ATTRIBUTE}]`)) {
|
||||
ignored.remove();
|
||||
}
|
||||
|
||||
@@ -769,11 +732,7 @@ function restoreMarkdownElements(container: HTMLElement): void {
|
||||
element.replaceWith(...element.childNodes);
|
||||
}
|
||||
|
||||
restoreMathSources(container);
|
||||
|
||||
const presentational = Array.from(
|
||||
container.querySelectorAll(`div, span:not([${MARKDOWN_MATH_SOURCE_ATTRIBUTE}])`),
|
||||
);
|
||||
const presentational = Array.from(container.querySelectorAll("div, span"));
|
||||
for (const element of presentational.toReversed()) {
|
||||
element.replaceWith(...element.childNodes);
|
||||
}
|
||||
|
||||
@@ -13,10 +13,6 @@ 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";
|
||||
/** Set by the Markdown library's web KaTeX renderer on rendered math elements. */
|
||||
export const MARKDOWN_MATH_SOURCE_ATTRIBUTE = "data-math-source";
|
||||
export const MARKDOWN_MATH_DISPLAY_ATTRIBUTE = "data-display";
|
||||
export const KATEX_MATHML_SELECTOR = ".katex-mathml, annotation, annotation-xml";
|
||||
|
||||
/**
|
||||
* Trailing line breaks, with any indentation that followed the last one.
|
||||
|
||||
@@ -10,23 +10,23 @@ import { isNative } from "@/constants/platform";
|
||||
* - titlebarpart.css:249-260 → top-edge resizer, no-drag, 4px
|
||||
*
|
||||
* VS Code's drag region is a static DOM element — no z-index, no pointer-events,
|
||||
* no state, no event listeners. Interactive elements get no-drag from their own
|
||||
* CSS (global backstop in index.html). The drag region never re-renders.
|
||||
* no state, no event listeners. Interactive controls only receive no-drag when
|
||||
* they sit inside a drag container, an overlay/modal host, or an explicit
|
||||
* window-owned chrome slot (see public/index.html). Controls in ordinary window
|
||||
* content emit no app regions and use normal DOM hit testing, so scrolled
|
||||
* viewports and parked browser webviews cannot subtract unclipped rects from
|
||||
* the titlebar.
|
||||
*
|
||||
* The resizer is Windows/Linux only (titlebarpart.css:249 scopes to .windows/.linux).
|
||||
* On macOS, Electron handles edge resize natively.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Marks a scroll viewport as window content: it and its descendants emit no window
|
||||
* regions, because Electron does not clip app-region rects to scroll viewports.
|
||||
* See the `[data-window-content]` rule in public/index.html.
|
||||
*/
|
||||
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
|
||||
|
||||
/** Reserves a clickable area for a control mounted outside the titlebar rail. */
|
||||
/** Reserves a clickable area for a window-owned control mounted outside a drag container. */
|
||||
export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" };
|
||||
|
||||
/** Marks an in-app overlay/portal host whose interactive controls can float over the titlebar. */
|
||||
export const WINDOW_OVERLAY_HOST_DATASET = { "window-overlay-host": "" };
|
||||
|
||||
export const titlebarDragSurfaceStyle: React.CSSProperties = {
|
||||
cursor: "default",
|
||||
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
|
||||
@@ -64,7 +64,7 @@ export function TitlebarDragRegion() {
|
||||
return (
|
||||
<>
|
||||
{/* Drag overlay — VS Code .titlebar-drag-region (titlebarpart.css:57-64) */}
|
||||
<div style={DRAG_OVERLAY_STYLE} />
|
||||
<div data-window-drag-region="" style={DRAG_OVERLAY_STYLE} />
|
||||
{/* Top-edge resizer — VS Code .resizer (titlebarpart.css:249-256) */}
|
||||
<div style={TOP_RESIZER_STYLE} />
|
||||
</>
|
||||
|
||||
@@ -12,6 +12,7 @@ import {
|
||||
getDesktopWindowControlsPresentation,
|
||||
type DesktopWindowControlsPresentation,
|
||||
} from "@/desktop/window-chrome-presentation";
|
||||
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import { useCustomDesktopWindowControls } from "@/utils/desktop-window";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
|
||||
@@ -143,6 +144,7 @@ export function DesktopWindowControls() {
|
||||
|
||||
return (
|
||||
<View
|
||||
dataSet={WINDOW_NO_DRAG_DATASET}
|
||||
style={[styles.controls, { height: presentation.controlHeight }]}
|
||||
testID="desktop-window-controls"
|
||||
>
|
||||
|
||||
@@ -2,6 +2,7 @@ import { createContext, useContext, useCallback, useState, useId, type ReactNode
|
||||
import { View, type LayoutChangeEvent } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Portal, PortalHost } from "@gorhom/portal";
|
||||
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { EdgeFade } from "@/components/ui/edge-fade";
|
||||
|
||||
@@ -74,7 +75,11 @@ export function FloatingHeaderLayout({ header, floating, children }: FloatingHea
|
||||
</View>
|
||||
</View>
|
||||
) : null}
|
||||
<View style={styles.statusOverlay} pointerEvents="box-none">
|
||||
<View
|
||||
style={styles.statusOverlay}
|
||||
dataSet={WINDOW_OVERLAY_HOST_DATASET}
|
||||
pointerEvents="box-none"
|
||||
>
|
||||
<PortalHost name={overlayHostName} />
|
||||
</View>
|
||||
</View>
|
||||
|
||||
@@ -5,6 +5,7 @@ import { router } from "expo-router";
|
||||
import { ArrowLeft } from "lucide-react-native";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
|
||||
import {
|
||||
@@ -17,6 +18,7 @@ import {
|
||||
HEADER_INNER_HEIGHT_MOBILE,
|
||||
HEADER_TOP_PADDING_MOBILE,
|
||||
} from "@/constants/layout";
|
||||
import { WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { useTopBand } from "@/window-layout";
|
||||
|
||||
@@ -75,27 +77,30 @@ export function CompactHeader({
|
||||
|
||||
return (
|
||||
<IconButtonChromeProvider value="header-island">
|
||||
<View style={rootStyle}>
|
||||
<View
|
||||
style={[
|
||||
usesTitlebarHeight ? styles.titlebarRow : styles.row,
|
||||
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
|
||||
]}
|
||||
>
|
||||
<View style={styles.island}>
|
||||
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
|
||||
<WindowChromeSafeArea placement="inline" style={styles.chromeContainer}>
|
||||
<TitlebarDragRegion />
|
||||
<View style={rootStyle}>
|
||||
<View
|
||||
style={[
|
||||
usesTitlebarHeight ? styles.titlebarRow : styles.row,
|
||||
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
|
||||
]}
|
||||
>
|
||||
<View style={styles.island}>
|
||||
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
|
||||
</View>
|
||||
<View style={styles.titleGroup}>
|
||||
<CompactHeaderTitle
|
||||
loading={loading}
|
||||
title={title}
|
||||
titleTestID={titleTestID}
|
||||
subtitle={subtitle}
|
||||
/>
|
||||
</View>
|
||||
{actions ? <View style={styles.island}>{actions}</View> : null}
|
||||
</View>
|
||||
<View style={styles.titleGroup}>
|
||||
<CompactHeaderTitle
|
||||
loading={loading}
|
||||
title={title}
|
||||
titleTestID={titleTestID}
|
||||
subtitle={subtitle}
|
||||
/>
|
||||
</View>
|
||||
{actions ? <View style={styles.island}>{actions}</View> : null}
|
||||
</View>
|
||||
</View>
|
||||
</WindowChromeSafeArea>
|
||||
</IconButtonChromeProvider>
|
||||
);
|
||||
}
|
||||
@@ -154,6 +159,9 @@ function BackButton({ onBack }: { onBack?: () => void }) {
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
chromeContainer: {
|
||||
position: "relative",
|
||||
},
|
||||
root: {
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
|
||||
import { View, type StyleProp, type ViewStyle } from "react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { PanelLeft } from "lucide-react-native";
|
||||
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import { HeaderToggleButton, headerIconSlotStyle } from "./header-toggle-button";
|
||||
import { selectIsAgentListOpen, usePanelStore } from "@/stores/panel-store";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
@@ -50,10 +51,12 @@ function SidebarMenuToggleButton({
|
||||
tooltipSide = "right",
|
||||
testID = "menu-button",
|
||||
nativeID = "menu-button",
|
||||
dataSet,
|
||||
}: Omit<SidebarMenuToggleProps, "style"> & {
|
||||
isMobile: boolean;
|
||||
extraMutedIdleIcon?: boolean;
|
||||
resolvedStyle: StyleProp<ViewStyle>;
|
||||
dataSet?: Record<string, string>;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const isOpen = usePanelStore((state) => selectIsAgentListOpen(state, { isCompact: isMobile }));
|
||||
@@ -77,6 +80,7 @@ function SidebarMenuToggleButton({
|
||||
tooltipSide={tooltipSide}
|
||||
testID={testID}
|
||||
nativeID={nativeID}
|
||||
dataSet={dataSet}
|
||||
style={resolvedStyle}
|
||||
accessible
|
||||
accessibilityRole="button"
|
||||
@@ -128,6 +132,7 @@ export function WindowSidebarMenuToggle({ style, ...props }: SidebarMenuTogglePr
|
||||
{...props}
|
||||
isMobile={false}
|
||||
extraMutedIdleIcon
|
||||
dataSet={WINDOW_NO_DRAG_DATASET}
|
||||
resolvedStyle={resolvedStyle}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -37,10 +37,7 @@ import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-nativ
|
||||
import { scheduleOnRN } from "react-native-worklets";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import {
|
||||
TitlebarDragRegion,
|
||||
WINDOW_CONTENT_DATASET,
|
||||
} from "@/components/desktop/titlebar-drag-region";
|
||||
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
|
||||
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
|
||||
import {
|
||||
resolveDesktopSidebarInsetLeft,
|
||||
@@ -698,15 +695,13 @@ function MobileSidebar({
|
||||
|
||||
interface SidebarNavScrollProps {
|
||||
closeGestureRef: RefObject<GestureType | undefined>;
|
||||
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
|
||||
windowContent?: boolean;
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
|
||||
// divider below it. The divider is a sibling because Unistyles does not patch the
|
||||
// gesture-handler ScrollView.
|
||||
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
|
||||
function SidebarNavScroll({ closeGestureRef, children }: SidebarNavScrollProps) {
|
||||
return (
|
||||
<>
|
||||
{platformIsNative ? (
|
||||
@@ -723,7 +718,6 @@ function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarN
|
||||
</GHScrollView>
|
||||
) : (
|
||||
<ScrollView
|
||||
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
|
||||
style={styles.navScroll}
|
||||
showsVerticalScrollIndicator={false}
|
||||
alwaysBounceVertical={false}
|
||||
@@ -899,11 +893,8 @@ function DesktopSidebar({
|
||||
</View>
|
||||
) : null}
|
||||
</View>
|
||||
{/* The drag overlay stays above this viewport: Electron does not clip
|
||||
app-region rects to scroll viewports, so a scrolled-out row would
|
||||
still claim its no-drag rect. */}
|
||||
{hasNavRows ? (
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
|
||||
<SidebarNavScroll closeGestureRef={closeGestureRef}>
|
||||
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
|
||||
</SidebarNavScroll>
|
||||
) : null}
|
||||
|
||||
@@ -1,535 +0,0 @@
|
||||
export interface LineEnd {
|
||||
contentEnd: number;
|
||||
nextLineStart: number;
|
||||
}
|
||||
|
||||
export interface BlockquoteStrip {
|
||||
quoteDepth: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface IndentMeasure {
|
||||
spaces: number;
|
||||
offset: number;
|
||||
}
|
||||
|
||||
export interface ListMarkerMatch {
|
||||
markerEnd: number;
|
||||
contentIndent: number;
|
||||
markerChar: string;
|
||||
}
|
||||
|
||||
export interface FenceOpenerMatch {
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
fenceOffset: number;
|
||||
indent: number;
|
||||
info: string;
|
||||
}
|
||||
|
||||
export interface BlockScanState {
|
||||
listIndents: number[];
|
||||
listQuoteDepth: number;
|
||||
inParagraph: boolean;
|
||||
prevQuoteDepth: number;
|
||||
inIndentedCode: boolean;
|
||||
indentedCodeQuoteDepth: number;
|
||||
indentedCodeMinIndent: number;
|
||||
}
|
||||
|
||||
export type BlockLine =
|
||||
| { kind: "blank"; quoteDepth: number; afterQuotes: number }
|
||||
| { kind: "indented-code"; quoteDepth: number; afterQuotes: number }
|
||||
| {
|
||||
kind: "fence";
|
||||
quoteDepth: number;
|
||||
afterQuotes: number;
|
||||
fenceOffset: number;
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
info: string;
|
||||
maxCloseIndent: number;
|
||||
contentStripIndent: number;
|
||||
inList: boolean;
|
||||
listMinIndent: number;
|
||||
firstLinePrefix: string;
|
||||
continuationPrefix: string;
|
||||
}
|
||||
| { kind: "text"; quoteDepth: number; afterQuotes: number; containerIndent: number };
|
||||
|
||||
export function isWhitespaceChar(ch: string | undefined): boolean {
|
||||
return ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
|
||||
}
|
||||
|
||||
export function isAsciiPunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (
|
||||
(code >= 0x21 && code <= 0x2f) ||
|
||||
(code >= 0x3a && code <= 0x40) ||
|
||||
(code >= 0x5b && code <= 0x60) ||
|
||||
(code >= 0x7b && code <= 0x7e)
|
||||
);
|
||||
}
|
||||
|
||||
export function isAsciiAlnum(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (code >= 48 && code <= 57) || (code >= 65 && code <= 90) || (code >= 97 && code <= 122);
|
||||
}
|
||||
|
||||
export function findLineEnd(source: string, from: number): LineEnd {
|
||||
let i = from;
|
||||
while (i < source.length) {
|
||||
const code = source.charCodeAt(i);
|
||||
if (code === 10) return { contentEnd: i, nextLineStart: i + 1 };
|
||||
if (code === 13) {
|
||||
const next = i + 1 < source.length && source.charCodeAt(i + 1) === 10 ? i + 2 : i + 1;
|
||||
return { contentEnd: i, nextLineStart: next };
|
||||
}
|
||||
i++;
|
||||
}
|
||||
return { contentEnd: source.length, nextLineStart: source.length };
|
||||
}
|
||||
|
||||
export function stripBlockquotesAt(source: string, from: number, limit: number): BlockquoteStrip {
|
||||
let offset = from;
|
||||
let quoteDepth = 0;
|
||||
while (offset < limit) {
|
||||
let spaces = 0;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === " " && spaces < 3) {
|
||||
cursor++;
|
||||
spaces++;
|
||||
}
|
||||
if (cursor >= limit || source[cursor] !== ">") break;
|
||||
quoteDepth++;
|
||||
cursor++;
|
||||
if (cursor < limit && (source[cursor] === " " || source[cursor] === "\t")) cursor++;
|
||||
offset = cursor;
|
||||
}
|
||||
return { quoteDepth, offset };
|
||||
}
|
||||
|
||||
export function measureIndentAt(source: string, from: number, limit: number): IndentMeasure {
|
||||
let spaces = 0;
|
||||
let offset = from;
|
||||
while (offset < limit) {
|
||||
const ch = source[offset];
|
||||
if (ch === " ") {
|
||||
spaces++;
|
||||
offset++;
|
||||
} else if (ch === "\t") {
|
||||
spaces += 4 - (spaces % 4);
|
||||
offset++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { spaces, offset };
|
||||
}
|
||||
|
||||
export function isBlankRange(source: string, from: number, limit: number): boolean {
|
||||
for (let i = from; i < limit; i++) {
|
||||
if (source[i] !== " " && source[i] !== "\t") return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function isThematicBreakText(trimmed: string): boolean {
|
||||
return /^(?:([-*_])(?:[ \t]*\1){2,})[ \t]*$/.test(trimmed);
|
||||
}
|
||||
|
||||
function parseListMarkerPrefix(
|
||||
source: string,
|
||||
offset: number,
|
||||
limit: number,
|
||||
disallowOrderedNonOne: boolean,
|
||||
): { markerChars: number; after: number; markerChar: string } | null {
|
||||
const ch = source[offset];
|
||||
if (ch === "-" || ch === "*" || ch === "+") {
|
||||
if ((ch === "-" || ch === "*") && isThematicBreakText(source.slice(offset, limit))) {
|
||||
return null;
|
||||
}
|
||||
return { markerChars: 1, after: offset + 1, markerChar: ch };
|
||||
}
|
||||
if (ch < "0" || ch > "9") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] >= "0" && source[cursor] <= "9" && cursor - offset < 9) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor >= limit || (source[cursor] !== "." && source[cursor] !== ")")) return null;
|
||||
if (disallowOrderedNonOne && Number(source.slice(offset, cursor)) !== 1) return null;
|
||||
return { markerChars: cursor + 1 - offset, after: cursor + 1, markerChar: ch };
|
||||
}
|
||||
|
||||
function measureMarkerSeparator(
|
||||
source: string,
|
||||
after: number,
|
||||
limit: number,
|
||||
startColumn: number,
|
||||
): { extraSpaces: number; endPos: number } {
|
||||
let col = startColumn;
|
||||
let extraSpaces = 0;
|
||||
let pos = after;
|
||||
while (pos < limit) {
|
||||
const ws = source[pos];
|
||||
if (ws === " ") {
|
||||
extraSpaces += 1;
|
||||
col += 1;
|
||||
pos++;
|
||||
} else if (ws === "\t") {
|
||||
const tabWidth = 4 - (col % 4);
|
||||
extraSpaces += tabWidth;
|
||||
col += tabWidth;
|
||||
pos++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { extraSpaces, endPos: pos };
|
||||
}
|
||||
|
||||
export function matchListMarkerAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent = 3,
|
||||
options?: { allowEmpty?: boolean; disallowOrderedNonOne?: boolean },
|
||||
): ListMarkerMatch | null {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit) return null;
|
||||
|
||||
const prefix = parseListMarkerPrefix(
|
||||
source,
|
||||
offset,
|
||||
limit,
|
||||
options?.disallowOrderedNonOne ?? false,
|
||||
);
|
||||
if (!prefix) return null;
|
||||
|
||||
const { extraSpaces, endPos } = measureMarkerSeparator(
|
||||
source,
|
||||
prefix.after,
|
||||
limit,
|
||||
spaces + prefix.markerChars,
|
||||
);
|
||||
|
||||
if (extraSpaces === 0) {
|
||||
if (endPos === limit && options?.allowEmpty) {
|
||||
return {
|
||||
markerEnd: endPos,
|
||||
contentIndent: spaces + prefix.markerChars + 1,
|
||||
markerChar: prefix.markerChar,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// CommonMark §5.2: >=5 spaces after a marker keeps 4+ spaces as an indented code block.
|
||||
const consumed = extraSpaces >= 5 ? 1 : extraSpaces;
|
||||
const markerEnd = extraSpaces >= 5 ? prefix.after + 1 : endPos;
|
||||
return {
|
||||
markerEnd,
|
||||
contentIndent: spaces + prefix.markerChars + consumed,
|
||||
markerChar: prefix.markerChar,
|
||||
};
|
||||
}
|
||||
|
||||
export function parseFenceOpenerAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent: number,
|
||||
): FenceOpenerMatch | null {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit) return null;
|
||||
const ch = source[offset];
|
||||
if (ch !== "`" && ch !== "~") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === ch) cursor++;
|
||||
const length = cursor - offset;
|
||||
if (length < 3) return null;
|
||||
const info = source.slice(cursor, limit);
|
||||
if (ch === "`" && info.includes("`")) return null;
|
||||
return { char: ch, length, fenceOffset: offset, indent: spaces, info };
|
||||
}
|
||||
|
||||
export function isClosingFenceAt(
|
||||
source: string,
|
||||
from: number,
|
||||
limit: number,
|
||||
maxIndent: number,
|
||||
char: "`" | "~",
|
||||
minLength: number,
|
||||
): boolean {
|
||||
const { spaces, offset } = measureIndentAt(source, from, limit);
|
||||
if (spaces > maxIndent || offset >= limit || source[offset] !== char) return false;
|
||||
let cursor = offset;
|
||||
while (cursor < limit && source[cursor] === char) cursor++;
|
||||
if (cursor - offset < minLength) return false;
|
||||
while (cursor < limit) {
|
||||
if (source[cursor] !== " " && source[cursor] !== "\t") return false;
|
||||
cursor++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function checkFenceContainerExit(
|
||||
source: string,
|
||||
lineStart: number,
|
||||
contentEnd: number,
|
||||
openQuoteDepth: number,
|
||||
listMinIndent: number,
|
||||
): { exited: boolean; quoteDepth: number; afterQuotes: number } {
|
||||
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
|
||||
if (quoteDepth < openQuoteDepth) {
|
||||
return { exited: true, quoteDepth, afterQuotes };
|
||||
}
|
||||
if (
|
||||
listMinIndent > 0 &&
|
||||
quoteDepth === openQuoteDepth &&
|
||||
!isBlankRange(source, afterQuotes, contentEnd) &&
|
||||
measureIndentAt(source, afterQuotes, contentEnd).spaces < listMinIndent
|
||||
) {
|
||||
return { exited: true, quoteDepth, afterQuotes };
|
||||
}
|
||||
return { exited: false, quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
export function createBlockScanState(): BlockScanState {
|
||||
return {
|
||||
listIndents: [],
|
||||
listQuoteDepth: 0,
|
||||
inParagraph: false,
|
||||
prevQuoteDepth: 0,
|
||||
inIndentedCode: false,
|
||||
indentedCodeQuoteDepth: 0,
|
||||
indentedCodeMinIndent: 0,
|
||||
};
|
||||
}
|
||||
|
||||
function syncListContainer(state: BlockScanState, quoteDepth: number, spaces: number): number {
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listIndents.length = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
if (quoteDepth !== state.listQuoteDepth) return 0;
|
||||
while (state.listIndents.length > 0 && spaces < state.listIndents[state.listIndents.length - 1]) {
|
||||
state.listIndents.pop();
|
||||
}
|
||||
return state.listIndents.length > 0 ? state.listIndents[state.listIndents.length - 1] : 0;
|
||||
}
|
||||
|
||||
function peelLineListMarkers(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
afterQuotes: number,
|
||||
contentEnd: number,
|
||||
quoteDepth: number,
|
||||
initialIndent: number,
|
||||
): { cursor: number; containerIndent: number; peeledList: boolean } {
|
||||
let cursor = afterQuotes;
|
||||
let containerIndent = initialIndent;
|
||||
let peeledList = false;
|
||||
let marker = matchListMarkerAt(source, cursor, contentEnd, containerIndent + 3, {
|
||||
allowEmpty: !state.inParagraph,
|
||||
disallowOrderedNonOne: state.inParagraph,
|
||||
});
|
||||
while (marker) {
|
||||
const markerBase = cursor === afterQuotes ? 0 : containerIndent;
|
||||
const totalIndent = markerBase + marker.contentIndent;
|
||||
state.listIndents.push(totalIndent);
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
containerIndent = totalIndent;
|
||||
cursor = marker.markerEnd;
|
||||
peeledList = true;
|
||||
marker = matchListMarkerAt(source, cursor, contentEnd, 3, { allowEmpty: true });
|
||||
}
|
||||
return { cursor, containerIndent, peeledList };
|
||||
}
|
||||
|
||||
function startIndentedCode(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
containerIndent: number,
|
||||
): BlockLine {
|
||||
state.inIndentedCode = true;
|
||||
state.indentedCodeQuoteDepth = quoteDepth;
|
||||
state.indentedCodeMinIndent = containerIndent + 4;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "indented-code", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
function isContinuationIndentedCode(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
spaces: number,
|
||||
): boolean {
|
||||
if (!state.inIndentedCode) return false;
|
||||
if (quoteDepth === state.indentedCodeQuoteDepth && spaces >= state.indentedCodeMinIndent) {
|
||||
return true;
|
||||
}
|
||||
state.inIndentedCode = false;
|
||||
return false;
|
||||
}
|
||||
|
||||
function classifyBlankBlockLine(
|
||||
state: BlockScanState,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
): BlockLine {
|
||||
state.inParagraph = false;
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listIndents.length = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
if (state.inIndentedCode && quoteDepth < state.indentedCodeQuoteDepth) {
|
||||
state.inIndentedCode = false;
|
||||
}
|
||||
return { kind: "blank", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
function classifyTextBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
cursor: number,
|
||||
contentEnd: number,
|
||||
quoteDepth: number,
|
||||
afterQuotes: number,
|
||||
containerIndent: number,
|
||||
peeledList: boolean,
|
||||
): BlockLine {
|
||||
const { spaces: trimmedSpaces, offset: trimmedOffset } = measureIndentAt(
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
);
|
||||
const relSpaces = peeledList ? trimmedSpaces : trimmedSpaces - containerIndent;
|
||||
const trimmed = source.slice(trimmedOffset, contentEnd);
|
||||
const endsParagraph =
|
||||
relSpaces <= 3 &&
|
||||
(/^#{1,6}(?:[ \t]|$)/.test(trimmed) ||
|
||||
isThematicBreakText(trimmed) ||
|
||||
(state.inParagraph && !peeledList && /^(?:-+|=+)[ \t]*$/.test(trimmed)));
|
||||
state.inParagraph = !endsParagraph;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "text", quoteDepth, afterQuotes, containerIndent };
|
||||
}
|
||||
|
||||
function buildFenceBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
lineStart: number,
|
||||
afterQuotes: number,
|
||||
quoteDepth: number,
|
||||
containerIndent: number,
|
||||
peeledList: boolean,
|
||||
opener: FenceOpenerMatch,
|
||||
): BlockLine {
|
||||
state.inParagraph = false;
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
const quotePrefix = source.slice(lineStart, afterQuotes);
|
||||
const contentStripIndent = peeledList ? containerIndent + opener.indent : opener.indent;
|
||||
const inList = quoteDepth === state.listQuoteDepth && state.listIndents.length > 0;
|
||||
return {
|
||||
kind: "fence",
|
||||
quoteDepth,
|
||||
afterQuotes,
|
||||
fenceOffset: opener.fenceOffset,
|
||||
char: opener.char,
|
||||
length: opener.length,
|
||||
info: opener.info,
|
||||
maxCloseIndent: containerIndent + 3,
|
||||
contentStripIndent,
|
||||
inList,
|
||||
listMinIndent: inList ? containerIndent : 0,
|
||||
firstLinePrefix: source.slice(lineStart, opener.fenceOffset),
|
||||
continuationPrefix: `${quotePrefix}${" ".repeat(contentStripIndent)}`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Classify one line in CommonMark block order (quotes -> blank -> indented code ->
|
||||
* list markers -> fenced code -> ATX/Setext/thematic-break -> paragraph text) so math
|
||||
* scanners skip nested-list code fences and indented code blocks identically to md4c.
|
||||
*/
|
||||
export function classifyBlockLine(
|
||||
state: BlockScanState,
|
||||
source: string,
|
||||
lineStart: number,
|
||||
contentEnd: number,
|
||||
): BlockLine {
|
||||
const { quoteDepth, offset: afterQuotes } = stripBlockquotesAt(source, lineStart, contentEnd);
|
||||
|
||||
if (isBlankRange(source, afterQuotes, contentEnd)) {
|
||||
return classifyBlankBlockLine(state, quoteDepth, afterQuotes);
|
||||
}
|
||||
|
||||
if (quoteDepth > state.prevQuoteDepth) {
|
||||
state.inParagraph = false;
|
||||
state.inIndentedCode = false;
|
||||
}
|
||||
|
||||
const { spaces } = measureIndentAt(source, afterQuotes, contentEnd);
|
||||
if (isContinuationIndentedCode(state, quoteDepth, spaces)) {
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "indented-code", quoteDepth, afterQuotes };
|
||||
}
|
||||
|
||||
const baseIndent = syncListContainer(state, quoteDepth, spaces);
|
||||
if (!state.inParagraph && spaces >= baseIndent + 4) {
|
||||
return startIndentedCode(state, quoteDepth, afterQuotes, baseIndent);
|
||||
}
|
||||
|
||||
const { cursor, containerIndent, peeledList } = peelLineListMarkers(
|
||||
state,
|
||||
source,
|
||||
afterQuotes,
|
||||
contentEnd,
|
||||
quoteDepth,
|
||||
baseIndent,
|
||||
);
|
||||
if (peeledList) {
|
||||
state.inParagraph = false;
|
||||
const afterMarker = measureIndentAt(source, cursor, contentEnd);
|
||||
if (afterMarker.offset < contentEnd && afterMarker.spaces >= 4) {
|
||||
return startIndentedCode(state, quoteDepth, afterQuotes, containerIndent);
|
||||
}
|
||||
if (isBlankRange(source, cursor, contentEnd)) {
|
||||
state.prevQuoteDepth = quoteDepth;
|
||||
return { kind: "text", quoteDepth, afterQuotes: cursor, containerIndent };
|
||||
}
|
||||
}
|
||||
|
||||
const opener = parseFenceOpenerAt(
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
peeledList ? 3 : containerIndent + 3,
|
||||
);
|
||||
if (opener) {
|
||||
return buildFenceBlockLine(
|
||||
state,
|
||||
source,
|
||||
lineStart,
|
||||
afterQuotes,
|
||||
quoteDepth,
|
||||
containerIndent,
|
||||
peeledList,
|
||||
opener,
|
||||
);
|
||||
}
|
||||
|
||||
return classifyTextBlockLine(
|
||||
state,
|
||||
source,
|
||||
cursor,
|
||||
contentEnd,
|
||||
quoteDepth,
|
||||
afterQuotes,
|
||||
containerIndent,
|
||||
peeledList,
|
||||
);
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { decodeString } from "micromark-util-decode-string";
|
||||
import type { Nodes } from "mdast";
|
||||
import { isOffsetInRanges, scanMarkdownMath, type MathRange } from "./math";
|
||||
|
||||
const ATTRIBUTE = String.raw`\s+[A-Za-z_:][\w.:-]*(?:\s*=\s*(?:[^\s"'=<>\x60]+|'[^']*'|"[^"]*"))?`;
|
||||
const TAG = String.raw`<(?:[A-Za-z][A-Za-z0-9-]*(?:${ATTRIBUTE})*\s*\/?|\/[A-Za-z][A-Za-z0-9-]*\s*)>`;
|
||||
@@ -56,14 +55,12 @@ export function normalizeMarkdownHtml(source: string): string {
|
||||
} else if ("children" in node) node.children.forEach(protectCode);
|
||||
}
|
||||
protectCode(tree);
|
||||
const mathRanges = scanMarkdownMath(source);
|
||||
const protectedRanges = mergeRanges(codeRanges, mathRanges);
|
||||
// Only `<br>` reads these, so a source without one skips the extra parse.
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, protectedRanges) : [];
|
||||
const tableRanges = /<br/i.test(source) ? collectTableRanges(source, codeRanges) : [];
|
||||
const links: (string | undefined)[] = [];
|
||||
let previousTag: { name: string; end: number } | null = null;
|
||||
const convert = (raw: string, offset: number): string => {
|
||||
if (isOffsetInRanges(offset, protectedRanges)) return raw;
|
||||
if (codeRanges.some(({ start, end }) => offset >= start && offset < end)) return raw;
|
||||
if (raw.startsWith("<!--")) return "";
|
||||
const summary = /^<summary\b[^>]*>([\s\S]*?)<\/summary\s*>$/i.exec(raw);
|
||||
if (summary) {
|
||||
@@ -264,19 +261,3 @@ function collectTableRanges(
|
||||
);
|
||||
return tableRanges;
|
||||
}
|
||||
|
||||
function mergeRanges(a: readonly MathRange[], b: readonly MathRange[]): MathRange[] {
|
||||
if (a.length === 0 && b.length === 0) return [];
|
||||
const sorted = [...a, ...b].sort((left, right) => left.start - right.start);
|
||||
const merged: MathRange[] = [{ ...sorted[0] }];
|
||||
for (let i = 1; i < sorted.length; i++) {
|
||||
const current = sorted[i];
|
||||
const last = merged[merged.length - 1];
|
||||
if (current.start <= last.end) {
|
||||
if (current.end > last.end) last.end = current.end;
|
||||
} else {
|
||||
merged.push({ ...current });
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -1,277 +0,0 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { flushSync } from "react-dom";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { I18nextProvider } from "react-i18next";
|
||||
import {
|
||||
EnrichedMarkdownText,
|
||||
getLoadedKaTeX,
|
||||
preloadMarkdownParser,
|
||||
registerKaTeXStyleLoader,
|
||||
} from "react-native-enriched-markdown";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { applyRootUiFont } from "@/appearance/apply-root-font.web";
|
||||
import { ToastApiProvider } from "@/contexts/toast-api-context";
|
||||
import { i18n } from "@/i18n/i18next";
|
||||
import { darkTheme, lightTheme } from "@/styles/theme";
|
||||
import { ensureKaTeXStyles } from "./katex-styles.web";
|
||||
import { MarkdownRenderer } from "./renderer";
|
||||
import { createMarkdownStyles } from "./styles";
|
||||
import { WEB_RENDERERS } from "./renderers.web";
|
||||
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
const toast = { show: () => () => {}, copied: () => {}, error: () => {} };
|
||||
const queryClient = new QueryClient();
|
||||
const MATH_FLAGS = { latexMath: true, admonitions: true };
|
||||
|
||||
function wrapProviders(node: React.ReactNode) {
|
||||
return (
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<ToastApiProvider api={toast}>{node}</ToastApiProvider>
|
||||
</I18nextProvider>
|
||||
</QueryClientProvider>
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await i18n.changeLanguage("en");
|
||||
await preloadMarkdownParser();
|
||||
container = document.createElement("div");
|
||||
container.id = "root";
|
||||
document.body.append(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
flushSync(() => root.unmount());
|
||||
container.remove();
|
||||
document.getElementById("paseo-ui-font")?.remove();
|
||||
document.documentElement.style.removeProperty("--paseo-ui-font");
|
||||
});
|
||||
|
||||
describe("web KaTeX math rendering", () => {
|
||||
it("does not load KaTeX when rendering prose without math", async () => {
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<MarkdownRenderer text="Costs $5 and $10, or $100/mo, with $PATH and \[1, 2\]." />,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
expect(container.querySelector('[role="math"]')).toBeNull();
|
||||
expect(container.textContent).toContain("Costs $5 and $10, or $100/mo");
|
||||
expect(container.textContent).toContain("$PATH");
|
||||
});
|
||||
|
||||
it("falls back to raw LaTeX when stylesheet loading fails and recovers on retry", async () => {
|
||||
let shouldFail = true;
|
||||
registerKaTeXStyleLoader(async () => {
|
||||
if (shouldFail) throw new Error("Simulated KaTeX CSS chunk failure");
|
||||
ensureKaTeXStyles();
|
||||
});
|
||||
|
||||
try {
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text="Inline $x^2 + 1$ and $$y^2$$" />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const mathNodes = container.querySelectorAll('[role="math"]');
|
||||
expect(mathNodes.length).toBe(2);
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 40));
|
||||
|
||||
expect(getLoadedKaTeX()).toBeNull();
|
||||
expect(container.querySelector('[role="math"] .katex')).toBeNull();
|
||||
expect(container.textContent).toContain("$x^2 + 1$");
|
||||
expect(container.textContent).toContain("$$y^2$$");
|
||||
|
||||
shouldFail = false;
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text="Recovered $x^2 + 1$ and $$y^2$$" />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(2);
|
||||
});
|
||||
expect(getLoadedKaTeX()).not.toBeNull();
|
||||
expect(document.getElementById("paseo-katex-css")).not.toBeNull();
|
||||
} finally {
|
||||
registerKaTeXStyleLoader(() => {
|
||||
ensureKaTeXStyles();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("lazily loads KaTeX and .woff2-only CSS for math, renders all 5 syntaxes, and renders synchronously on second mount", async () => {
|
||||
applyRootUiFont("'Custom UI Font', sans-serif");
|
||||
|
||||
const markdown = [
|
||||
"Inline $E = mc^2$ and \\(a^2 + b^2 = c^2\\).",
|
||||
"",
|
||||
"$$x^2 + y^2 = z^2$$",
|
||||
"",
|
||||
"\\[\\int_0^1 x^2\\,dx\\]",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{i=1}^n i",
|
||||
"```",
|
||||
].join("\n");
|
||||
|
||||
flushSync(() => {
|
||||
root.render(wrapProviders(<MarkdownRenderer text={markdown} />));
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(5);
|
||||
});
|
||||
|
||||
expect(getLoadedKaTeX()).not.toBeNull();
|
||||
|
||||
const styleEl = document.getElementById("paseo-katex-css");
|
||||
expect(styleEl).not.toBeNull();
|
||||
const css = styleEl?.textContent ?? "";
|
||||
expect(css).toContain(".woff2");
|
||||
expect(css).not.toContain('.woff")');
|
||||
expect(css).not.toContain('.ttf")');
|
||||
|
||||
const mathNodes = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(mathNodes.map((el) => el.dataset.display)).toEqual([
|
||||
"inline",
|
||||
"inline",
|
||||
"block",
|
||||
"block",
|
||||
"block",
|
||||
]);
|
||||
expect(mathNodes[0]?.dataset.mathSource).toBe("$E = mc^2$");
|
||||
expect(mathNodes[2]?.dataset.mathSource).toBe("$$\nx^2 + y^2 = z^2\n$$");
|
||||
expect(mathNodes[0]?.querySelector(".katex-mathml")).not.toBeNull();
|
||||
expect(mathNodes[0]?.querySelector(".katex-html")).not.toBeNull();
|
||||
|
||||
// KaTeX font is preserved even when applyRootUiFont is active on #root.
|
||||
const mathInner = mathNodes[0]!.querySelector<HTMLElement>(".katex")!;
|
||||
expect(getComputedStyle(mathInner).fontFamily).toContain("KaTeX_Main");
|
||||
|
||||
// Second mount renders synchronously from module cache without raw-TeX flash.
|
||||
const secondHost = document.createElement("div");
|
||||
document.body.append(secondHost);
|
||||
const secondRoot = createRoot(secondHost);
|
||||
try {
|
||||
flushSync(() => {
|
||||
secondRoot.render(
|
||||
wrapProviders(
|
||||
<EnrichedMarkdownText
|
||||
markdown="Instant $x + 1$"
|
||||
flavor="github"
|
||||
md4cFlags={MATH_FLAGS}
|
||||
renderers={WEB_RENDERERS}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
});
|
||||
// Immediately available after synchronous flushSync without waiting for timers.
|
||||
expect(secondHost.querySelector('[role="math"] .katex')).not.toBeNull();
|
||||
} finally {
|
||||
flushSync(() => secondRoot.unmount());
|
||||
secondHost.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it.each([
|
||||
["light", lightTheme],
|
||||
["dark", darkTheme],
|
||||
] as const)(
|
||||
"renders display and inline math cleanly in %s theme with horizontal scroll",
|
||||
async (_name, theme) => {
|
||||
const { markdownStyle } = createMarkdownStyles(theme, { blockGap: 16 });
|
||||
const wideEquation = `$$${Array.from({ length: 12 }, (_, i) => `x_{${i}}`).join(" + ")}$$`;
|
||||
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<EnrichedMarkdownText
|
||||
markdown={`Inline $x$ and:\n\n${wideEquation}`}
|
||||
markdownStyle={markdownStyle}
|
||||
flavor="github"
|
||||
md4cFlags={MATH_FLAGS}
|
||||
renderers={WEB_RENDERERS}
|
||||
/>,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex').length).toBe(2);
|
||||
});
|
||||
|
||||
const blockMath = container.querySelector<HTMLElement>(
|
||||
'[role="math"][data-display="block"]',
|
||||
)!;
|
||||
expect(blockMath.style.backgroundColor).toBe("transparent");
|
||||
expect(blockMath.style.overflowX).toBe("auto");
|
||||
expect(blockMath.style.textAlign).toBe("center");
|
||||
},
|
||||
);
|
||||
|
||||
it("renders accurate formula output across inline/display mode and repeated renders past cache turnover", async () => {
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(
|
||||
<MarkdownRenderer text={"Inline $x_0$ vs display:\n\n$$x_0$$\n\nRepeated $x_0$."} />,
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(3);
|
||||
});
|
||||
|
||||
const htmlText = (el: HTMLElement | undefined) =>
|
||||
el?.querySelector(".katex-html")?.textContent?.replace(/\u200B/g, "");
|
||||
const annotationText = (el: HTMLElement | undefined) =>
|
||||
el?.querySelector(".katex-mathml annotation")?.textContent;
|
||||
|
||||
const initialMath = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(initialMath.map((el) => el.dataset.display)).toEqual(["inline", "block", "inline"]);
|
||||
expect(initialMath[0]?.querySelector(".katex-display")).toBeNull();
|
||||
expect(initialMath[1]?.querySelector(".katex-display")).not.toBeNull();
|
||||
expect(htmlText(initialMath[0])).toBe("x0");
|
||||
expect(htmlText(initialMath[1])).toBe("x0");
|
||||
expect(htmlText(initialMath[2])).toBe("x0");
|
||||
expect(annotationText(initialMath[0])).toBe("x_0");
|
||||
expect(annotationText(initialMath[1])).toBe("x_0");
|
||||
|
||||
// Exceed the 256-entry render cache and re-render earlier formulas to verify evicted entries stay accurate.
|
||||
const manyFormulas = Array.from({ length: 265 }, (_, i) => `$a_{${i}}$`).join(" ");
|
||||
flushSync(() => {
|
||||
root.render(
|
||||
wrapProviders(<MarkdownRenderer text={`${manyFormulas} $x_0$ $$x_0$$ $a_{0}$`} />),
|
||||
);
|
||||
});
|
||||
|
||||
await vi.waitFor(() => {
|
||||
expect(container.querySelectorAll('[role="math"] .katex-html').length).toBe(268);
|
||||
});
|
||||
|
||||
const rendered = Array.from(container.querySelectorAll<HTMLElement>('[role="math"]'));
|
||||
expect(htmlText(rendered[0])).toBe("a0");
|
||||
expect(annotationText(rendered[0])).toBe("a_{0}");
|
||||
expect(htmlText(rendered[264])).toBe("a264");
|
||||
expect(annotationText(rendered[264])).toBe("a_{264}");
|
||||
expect(rendered[265]?.dataset.display).toBe("inline");
|
||||
expect(htmlText(rendered[265])).toBe("x0");
|
||||
expect(rendered[266]?.dataset.display).toBe("block");
|
||||
expect(htmlText(rendered[266])).toBe("x0");
|
||||
expect(rendered[267]?.dataset.mathSource).toBe("$a_{0}$");
|
||||
expect(htmlText(rendered[267])).toBe("a0");
|
||||
expect(annotationText(rendered[267])).toBe("a_{0}");
|
||||
});
|
||||
});
|
||||
@@ -1,437 +0,0 @@
|
||||
import { parseMarkdown } from "react-native-enriched-markdown/src/web/parseMarkdown";
|
||||
import type { ASTNode } from "react-native-enriched-markdown/src/web/types";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
import { adaptMarkdownMath, findBlockMathSpans, scanMarkdownMath } from "./math";
|
||||
import { prepareMarkdownSource } from "./source";
|
||||
|
||||
const MATH_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
|
||||
const NO_MATH_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
|
||||
function collectNodes(node: ASTNode, result: ASTNode[] = []): ASTNode[] {
|
||||
result.push(node);
|
||||
node.children?.forEach((child) => collectNodes(child, result));
|
||||
return result;
|
||||
}
|
||||
|
||||
function collectMathNodes(ast: ASTNode): { type: string; content: string }[] {
|
||||
return collectNodes(ast)
|
||||
.filter((node) => node.type === "LatexMathInline" || node.type === "LatexMathDisplay")
|
||||
.map((node) => ({
|
||||
type: node.type,
|
||||
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
|
||||
}));
|
||||
}
|
||||
|
||||
function collectText(node: ASTNode): string {
|
||||
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") return "";
|
||||
if (node.type === "Text") return node.content ?? "";
|
||||
return (node.children ?? []).map(collectText).join("");
|
||||
}
|
||||
|
||||
describe("math source adaptation — currency, shell, regex, and literal prose", () => {
|
||||
it.each([
|
||||
["Costs $5 and $10.", "Costs $5 and $10."],
|
||||
["Costs $5 and 10$", "Costs $5 and 10$"],
|
||||
["From $100/mo to $200/mo", "From $100/mo to $200/mo"],
|
||||
["Costs $100/mo (or 200$)", "Costs $100/mo (or 200$)"],
|
||||
["Total: $5 ($)", "Total: $5 ($)"],
|
||||
["Costs $5. Run $ ls", "Costs $5. Run $ ls"],
|
||||
["Pay $10 and get $ back", "Pay $10 and get $ back"],
|
||||
["I have $ 5 and $ 10", "I have $ 5 and $ 10"],
|
||||
["Price is US$5 or CA$10", "Price is US$5 or CA$10"],
|
||||
["Set $PATH and $HOME", "Set $PATH and $HOME"],
|
||||
["Use $PATH with /^foo$/", "Use $PATH with /^foo$/"],
|
||||
["Save $5 with sed s/foo$/bar/", "Save $5 with sed s/foo$/bar/"],
|
||||
["Check $HOME then foo$", "Check $HOME then foo$"],
|
||||
["$3$4", "$3$4"],
|
||||
["Costs $50k or $10M or $2B today", "Costs $50k or $10M or $2B today"],
|
||||
["Costs $5! Or $10)?", "Costs $5! Or $10)?"],
|
||||
["Escaped \\$x\\$", "Escaped $x$"],
|
||||
["See citation \\[1, 2\\]", "See citation [1, 2]"],
|
||||
])(
|
||||
"keeps %s literal when parsed with latexMath: true and latexMath: false",
|
||||
async (source, expectedText) => {
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
for (const flags of [MATH_FLAGS, NO_MATH_FLAGS]) {
|
||||
const ast = await parseMarkdown(rendered, flags);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
expect(collectText(ast)).toBe(expectedText);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("leaves inline code and latex/tex code fences literal", async () => {
|
||||
const inlineCode = "Use `$x$` and ``$$y$$`` and `\\(z\\)`";
|
||||
const preparedInline = prepareMarkdownSource(inlineCode).render();
|
||||
expect(preparedInline).toBe(inlineCode);
|
||||
const inlineAst = await parseMarkdown(preparedInline, MATH_FLAGS);
|
||||
expect(collectMathNodes(inlineAst)).toEqual([]);
|
||||
|
||||
for (const lang of ["latex", "tex"]) {
|
||||
const fence = `\`\`\`${lang}\n\\documentclass{article}\n$x = 1$\n\`\`\``;
|
||||
const preparedFence = prepareMarkdownSource(fence).render();
|
||||
expect(preparedFence).toBe(fence);
|
||||
const fenceAst = await parseMarkdown(preparedFence, MATH_FLAGS);
|
||||
expect(collectMathNodes(fenceAst)).toEqual([]);
|
||||
expect(collectNodes(fenceAst).some((node) => node.type === "CodeBlock")).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves list-nested fenced code blocks containing blank lines, $, \\(, and $$ verbatim", async () => {
|
||||
const nested = [
|
||||
"1. Install:",
|
||||
" - Run this:",
|
||||
"",
|
||||
" ```bash",
|
||||
' export PATH="$HOME/bin:$PATH"',
|
||||
"",
|
||||
" grep -E '\\(foo\\)' log.txt",
|
||||
" ```",
|
||||
].join("\n");
|
||||
const renderedNested = prepareMarkdownSource(nested).render();
|
||||
expect(renderedNested).toBe(nested);
|
||||
const nestedAst = await parseMarkdown(renderedNested, MATH_FLAGS);
|
||||
expect(collectMathNodes(nestedAst)).toEqual([]);
|
||||
const nestedCodeBlock = collectNodes(nestedAst).find((node) => node.type === "CodeBlock");
|
||||
expect(nestedCodeBlock).toBeDefined();
|
||||
expect(collectText(nestedCodeBlock!)).toBe(
|
||||
"export PATH=\"$HOME/bin:$PATH\"\n\ngrep -E '\\(foo\\)' log.txt\n",
|
||||
);
|
||||
|
||||
const deepNested = [
|
||||
"1. Outer:",
|
||||
" 1. Inner:",
|
||||
" - Leaf:",
|
||||
"",
|
||||
" ```sh",
|
||||
" echo $HOME",
|
||||
"",
|
||||
" printf '%s\\n' '\\(a+b\\)' '$$x^2$$'",
|
||||
" ```",
|
||||
].join("\n");
|
||||
const renderedDeep = prepareMarkdownSource(deepNested).render();
|
||||
expect(renderedDeep).toBe(deepNested);
|
||||
const deepAst = await parseMarkdown(renderedDeep, MATH_FLAGS);
|
||||
expect(collectMathNodes(deepAst)).toEqual([]);
|
||||
const deepCodeBlock = collectNodes(deepAst).find((node) => node.type === "CodeBlock");
|
||||
expect(deepCodeBlock).toBeDefined();
|
||||
expect(collectText(deepCodeBlock!)).toBe(
|
||||
"echo $HOME\n\nprintf '%s\\n' '\\(a+b\\)' '$$x^2$$'\n",
|
||||
);
|
||||
expect(scanMarkdownMath(deepNested)).toEqual([]);
|
||||
expect(findBlockMathSpans(deepNested)).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves CommonMark 4-space and tab indented code blocks verbatim", async () => {
|
||||
const atStart = [
|
||||
' export PATH="$HOME/bin:$PATH"',
|
||||
" grep -E '\\(foo\\)' log.txt",
|
||||
" echo $$x^2$$",
|
||||
].join("\n");
|
||||
const renderedStart = prepareMarkdownSource(atStart).render();
|
||||
expect(renderedStart).toBe(atStart);
|
||||
const startAst = await parseMarkdown(renderedStart, MATH_FLAGS);
|
||||
expect(collectMathNodes(startAst)).toEqual([]);
|
||||
const startCode = collectNodes(startAst).find((node) => node.type === "CodeBlock");
|
||||
expect(startCode).toBeDefined();
|
||||
expect(collectText(startCode!)).toBe(
|
||||
"export PATH=\"$HOME/bin:$PATH\"\ngrep -E '\\(foo\\)' log.txt\necho $$x^2$$\n",
|
||||
);
|
||||
|
||||
const afterBlank = [
|
||||
"Run this:",
|
||||
"",
|
||||
" echo $HOME",
|
||||
" echo \\(foo\\)",
|
||||
" echo $$x^2$$",
|
||||
"",
|
||||
"\techo $USER",
|
||||
].join("\n");
|
||||
const renderedAfterBlank = prepareMarkdownSource(afterBlank).render();
|
||||
expect(renderedAfterBlank).toBe(afterBlank);
|
||||
const afterBlankAst = await parseMarkdown(renderedAfterBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(afterBlankAst)).toEqual([]);
|
||||
const afterBlankCodes = collectNodes(afterBlankAst).filter((node) => node.type === "CodeBlock");
|
||||
expect(afterBlankCodes).toHaveLength(1);
|
||||
expect(collectText(afterBlankCodes[0]!)).toBe(
|
||||
"echo $HOME\necho \\(foo\\)\necho $$x^2$$\n\necho $USER\n",
|
||||
);
|
||||
expect(scanMarkdownMath(afterBlank)).toEqual([]);
|
||||
expect(findBlockMathSpans(afterBlank)).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves later non-math fences after prose", async () => {
|
||||
const source = "Intro.\n\n~~~sh\necho $PATH\n~~~";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toBe(source);
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
const codeBlock = collectNodes(ast).find((node) => node.type === "CodeBlock");
|
||||
expect(collectText(codeBlock!)).toBe("echo $PATH\n");
|
||||
});
|
||||
|
||||
it("exits an unclosed list-nested fence when the enclosing list ends and adapts later math", async () => {
|
||||
const withBlank = "- ~~~sh\n echo ok\n\nOutside \\(x+1\\).";
|
||||
const renderedWithBlank = prepareMarkdownSource(withBlank).render();
|
||||
expect(renderedWithBlank).toBe("- ~~~sh\n echo ok\n\nOutside $x+1$.");
|
||||
const astWithBlank = await parseMarkdown(renderedWithBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(astWithBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
|
||||
|
||||
const noBlank = "- ~~~sh\n echo ok\nOutside \\(x+1\\).";
|
||||
const astRaw = await parseMarkdown(noBlank, MATH_FLAGS);
|
||||
// Verify md4c closes the list fence immediately on unindented non-blank lines too.
|
||||
expect(collectNodes(astRaw).some((node) => node.type === "CodeBlock")).toBe(true);
|
||||
const renderedNoBlank = prepareMarkdownSource(noBlank).render();
|
||||
const astNoBlank = await parseMarkdown(renderedNoBlank, MATH_FLAGS);
|
||||
expect(collectMathNodes(astNoBlank)).toEqual([{ type: "LatexMathInline", content: "x+1" }]);
|
||||
});
|
||||
|
||||
it("ignores escaped \\\\( and \\\\[ and HTML comments", async () => {
|
||||
const source = "Literal \\\\(x\\\\) and \\\\[y\\\\] and <!-- $hidden$ -->";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
expect(collectText(ast)).toContain("\\(x\\)");
|
||||
expect(collectText(ast)).toContain("\\[y\\]");
|
||||
});
|
||||
|
||||
it("protects <autolinks> containing dollar signs", async () => {
|
||||
const source = "Visit <https://example.com/$5> and pay $10";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toContain("<https://example.com/$5>");
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([]);
|
||||
const link = collectNodes(ast).find((node) => node.type === "Link");
|
||||
expect(link?.attributes?.url).toBe("https://example.com/$5");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math source adaptation — valid inline and display math", () => {
|
||||
it.each([
|
||||
["$x$", "x"],
|
||||
["$a_i$", "a_i"],
|
||||
["$E = mc^2$", "E = mc^2"],
|
||||
["$2^k$", "2^k"],
|
||||
["$3x + 1$", "3x + 1"],
|
||||
["$0.5\\theta$", "0.5\\theta"],
|
||||
["$1/2$", "1/2"],
|
||||
["$5+2$", "5+2"],
|
||||
["$10 \\times 20$", "10 \\times 20"],
|
||||
["$\\theta \\in [0.5, 1.0]$", "\\theta \\in [0.5, 1.0]"],
|
||||
["$k$-means", "k"],
|
||||
["公式$x=1$的值", "x=1"],
|
||||
["\\(a^2 + b^2 = c^2\\)", "a^2 + b^2 = c^2"],
|
||||
["$x < y$ and $a > b$", "x < y"],
|
||||
["$a < b > c$", "a < b > c"],
|
||||
["Paragraph line\n with 4-space indented continuation $x$", "x"],
|
||||
])("parses inline math %s through md4c", async (source, firstContent) => {
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const mathNodes = collectMathNodes(ast);
|
||||
expect(mathNodes.length).toBeGreaterThanOrEqual(1);
|
||||
expect(mathNodes[0]).toMatchObject({
|
||||
type: "LatexMathInline",
|
||||
content: firstContent,
|
||||
});
|
||||
});
|
||||
|
||||
it("parses both $x < y$ and $a > b$ without HTML mangling", async () => {
|
||||
const source = "$x < y$ and $a > b$";
|
||||
const ast = await parseMarkdown(prepareMarkdownSource(source).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([
|
||||
{ type: "LatexMathInline", content: "x < y" },
|
||||
{ type: "LatexMathInline", content: "a > b" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("inserts hair space around CJK-flanked math and preserves surrounding CJK text", async () => {
|
||||
const source = "公式$x=1$的值";
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
expect(rendered).toBe("公式\u200A$x=1$\u200A的值");
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
expect(collectMathNodes(ast)).toEqual([{ type: "LatexMathInline", content: "x=1" }]);
|
||||
expect(collectText(ast)).toBe("公式\u200A\u200A的值");
|
||||
});
|
||||
|
||||
it("escapes GFM table pipes inside math without splitting columns", async () => {
|
||||
const source = [
|
||||
"| Metric | Formula | Norm |",
|
||||
"| --- | --- | --- |",
|
||||
"| Cond | $P(A|B)$ | $\\|x\\|$ |",
|
||||
].join("\n");
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const table = collectNodes(ast).find((node) => node.type === "Table");
|
||||
const bodyRow = table?.children?.find((node) => node.type === "TableBody")?.children?.[0];
|
||||
expect(bodyRow?.children).toHaveLength(3);
|
||||
expect(collectMathNodes(bodyRow!)).toEqual([
|
||||
{ type: "LatexMathInline", content: "P(A\\vert B)" },
|
||||
{ type: "LatexMathInline", content: "\\Vert x\\Vert " },
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps matrix & and || intact inside math when mdast runs", async () => {
|
||||
const source = [
|
||||
"Before & ||spoiler||",
|
||||
"",
|
||||
"$$",
|
||||
"\\begin{pmatrix}",
|
||||
"a & b \\\\",
|
||||
"c & d",
|
||||
"\\end{pmatrix}",
|
||||
"$$",
|
||||
"",
|
||||
"Norm $\\|x\\| + ||y||$ and <end>.",
|
||||
].join("\n");
|
||||
const rendered = prepareMarkdownSource(source).render();
|
||||
const ast = await parseMarkdown(rendered, MATH_FLAGS);
|
||||
const mathNodes = collectMathNodes(ast);
|
||||
expect(mathNodes).toHaveLength(2);
|
||||
expect(mathNodes[0].type).toBe("LatexMathDisplay");
|
||||
expect(mathNodes[0].content).toContain("a & b \\\\");
|
||||
expect(mathNodes[1]).toEqual({
|
||||
type: "LatexMathInline",
|
||||
content: "\\|x\\| + ||y||",
|
||||
});
|
||||
const text = collectText(ast);
|
||||
expect(text).toContain("Before & ||spoiler||");
|
||||
expect(text).toContain("<end>.");
|
||||
});
|
||||
|
||||
it("parses display math syntaxes: $$, multiline $$ with blank lines/comments, \\[...\\], and ```math", async () => {
|
||||
const single = await parseMarkdown(prepareMarkdownSource("$$E = mc^2$$").render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(single)).toEqual([{ type: "LatexMathDisplay", content: "E = mc^2" }]);
|
||||
|
||||
const multilineBlank = [
|
||||
"$$",
|
||||
"x = 1 % first variable",
|
||||
"% whole line comment",
|
||||
"",
|
||||
"y = 50\\% + 2 % trailing comment",
|
||||
"$$",
|
||||
].join("\n");
|
||||
const multiAst = await parseMarkdown(
|
||||
prepareMarkdownSource(multilineBlank).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
const multiMath = collectMathNodes(multiAst);
|
||||
expect(multiMath).toHaveLength(1);
|
||||
expect(multiMath[0].type).toBe("LatexMathDisplay");
|
||||
expect(multiMath[0].content).toContain("x = 1");
|
||||
expect(multiMath[0].content).toContain("y = 50\\% + 2");
|
||||
expect(multiMath[0].content).not.toContain("first variable");
|
||||
expect(multiMath[0].content).not.toContain("whole line comment");
|
||||
expect(multiMath[0].content).not.toContain("trailing comment");
|
||||
|
||||
const bracketSource = "\\[ \\int_0^1 x^2\\,dx \\]";
|
||||
const bracketAst = await parseMarkdown(
|
||||
prepareMarkdownSource(bracketSource).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(bracketAst)).toEqual([
|
||||
{ type: "LatexMathDisplay", content: " \\int_0^1 x^2\\,dx " },
|
||||
]);
|
||||
|
||||
const fencedMath = "```math\n\\sum_{i=1}^n i\n```";
|
||||
const fencedAst = await parseMarkdown(prepareMarkdownSource(fencedMath).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(fencedAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(fencedAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(fencedAst)[0].content?.trim()).toBe("\\sum_{i=1}^n i");
|
||||
|
||||
const tildeMath = "~~~math\na^2 + b^2 = c^2\n~~~";
|
||||
const tildeAst = await parseMarkdown(prepareMarkdownSource(tildeMath).render(), MATH_FLAGS);
|
||||
expect(collectMathNodes(tildeAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(tildeAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(tildeAst)[0].content?.trim()).toBe("a^2 + b^2 = c^2");
|
||||
|
||||
const proseThenMath = "Intro.\n\n~~~math\nx=1\n~~~";
|
||||
const proseThenMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(proseThenMath).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(proseThenMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(proseThenMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(proseThenMathAst)[0].content?.trim()).toBe("x=1");
|
||||
|
||||
const listMathFence = "1. Compute:\n\n ```math\n x = 1\n ```";
|
||||
const listMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(listMathFence).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(listMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(listMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(listMathAst)[0].content?.trim()).toBe("x = 1");
|
||||
expect(collectNodes(listMathAst).some((node) => node.type === "OrderedList")).toBe(true);
|
||||
|
||||
const nestedListMathFence = "1. Outer:\n - Inner:\n\n ```math\n y = 2\n ```";
|
||||
const nestedListMathAst = await parseMarkdown(
|
||||
prepareMarkdownSource(nestedListMathFence).render(),
|
||||
MATH_FLAGS,
|
||||
);
|
||||
expect(collectMathNodes(nestedListMathAst)).toHaveLength(1);
|
||||
expect(collectMathNodes(nestedListMathAst)[0].type).toBe("LatexMathDisplay");
|
||||
expect(collectMathNodes(nestedListMathAst)[0].content?.trim()).toBe("y = 2");
|
||||
expect(collectNodes(nestedListMathAst).some((node) => node.type === "UnorderedList")).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
it("escapes internal unescaped $ inside \\(...\\), \\[...\\], and ```math", async () => {
|
||||
const paren = prepareMarkdownSource("\\(\\text{cost } $5\\)").render();
|
||||
expect(paren).toBe("$\\text{cost } \\$5$");
|
||||
const parenAst = await parseMarkdown(paren, MATH_FLAGS);
|
||||
expect(collectMathNodes(parenAst)).toEqual([
|
||||
{ type: "LatexMathInline", content: "\\text{cost } \\$5" },
|
||||
]);
|
||||
|
||||
const bracket = prepareMarkdownSource("\\[\\text{cost } $5\\]").render();
|
||||
const bracketAst = await parseMarkdown(bracket, MATH_FLAGS);
|
||||
expect(collectMathNodes(bracketAst)).toEqual([
|
||||
{ type: "LatexMathDisplay", content: "\\text{cost } \\$5" },
|
||||
]);
|
||||
|
||||
const fenced = prepareMarkdownSource("```math\n\\text{cost } $5\n```").render();
|
||||
const fencedAst = await parseMarkdown(fenced, MATH_FLAGS);
|
||||
expect(collectMathNodes(fencedAst)[0].content?.trim()).toBe("\\text{cost } \\$5");
|
||||
});
|
||||
|
||||
it("keeps unclosed ```math, $$, \\[, \\(, and $ literal", () => {
|
||||
expect(adaptMarkdownMath("```math\n\\frac{a}{").source).toBe("```math\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("$$\n\\frac{a}{").source).toBe("\\$\\$\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("\\[\n\\frac{a}{").source).toBe("\\[\n\\frac{a}{");
|
||||
expect(adaptMarkdownMath("$\\alpha +").source).toBe("\\$\\alpha +");
|
||||
expect(adaptMarkdownMath("\\(\\alpha +").source).toBe("\\(\\alpha +");
|
||||
});
|
||||
|
||||
it("protects math ranges in normalizeMarkdownHtml", () => {
|
||||
expect(normalizeMarkdownHtml("$a < b > c$ and <b>bold</b>")).toBe("$a < b > c$ and **bold**");
|
||||
expect(normalizeMarkdownHtml("$$\n<div>x</div>\n$$")).toBe("$$\n<div>x</div>\n$$");
|
||||
expect(
|
||||
normalizeMarkdownHtml("<details><summary>Proof</summary>\n\n$a < b > c$\n</details>"),
|
||||
).toBe("**Proof**\n\n\n\n$a < b > c$\n");
|
||||
});
|
||||
});
|
||||
|
||||
describe("math fast path invariants", () => {
|
||||
it("bails out immediately on plain prose without math triggers", () => {
|
||||
const prose = "Plain markdown with **bold**, `code`, and [link](https://example.com).";
|
||||
expect(scanMarkdownMath(prose)).toEqual([]);
|
||||
const adapted = adaptMarkdownMath(prose);
|
||||
expect(adapted.source).toBe(prose);
|
||||
expect(adapted.mathRanges).toEqual([]);
|
||||
});
|
||||
|
||||
it("preserves plain prose and canonicalizes math-only prose synchronously through prepareMarkdownSource", () => {
|
||||
const plain = "Plain prose without special triggers.";
|
||||
expect(prepareMarkdownSource(plain).render()).toBe(plain);
|
||||
|
||||
const mathSource =
|
||||
"Inline $E = mc^2$, paren \\(a+b\\), display $$x^2 + y^2$$.\n\n```math\nz = 1\n```";
|
||||
const rendered = prepareMarkdownSource(mathSource).render();
|
||||
expect(rendered).toContain("$E = mc^2$");
|
||||
expect(rendered).toContain("$a+b$");
|
||||
expect(rendered).toContain("$$\nz = 1\n$$");
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -806,37 +806,9 @@ it.each([
|
||||
color: theme.colors.accentBright,
|
||||
});
|
||||
expect(style.thematicBreak?.color).toBe(theme.colors.border);
|
||||
expect(style.math).toMatchObject({
|
||||
color: theme.colors.foreground,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
marginTop: 0,
|
||||
marginBottom: 16,
|
||||
textAlign: "center",
|
||||
});
|
||||
expect(style.inlineMath).toMatchObject({
|
||||
color: theme.colors.foreground,
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it("uses muted text colour for math when compact and muted", () => {
|
||||
const { markdownStyle: style } = createMarkdownStyles(darkTheme, {
|
||||
compact: true,
|
||||
muted: true,
|
||||
blockGap: 12,
|
||||
});
|
||||
expect(style.math).toMatchObject({
|
||||
color: darkTheme.colors.foregroundMuted,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
marginTop: 0,
|
||||
marginBottom: 12,
|
||||
textAlign: "center",
|
||||
});
|
||||
expect(style.inlineMath).toEqual({ color: darkTheme.colors.foregroundMuted });
|
||||
});
|
||||
|
||||
it.each([darkTheme, lightTheme])("supplies the theme selection colour to the renderer", (theme) => {
|
||||
expect(createMarkdownStyles(theme, { blockGap: 16 })).toHaveProperty(
|
||||
"selectionColor",
|
||||
@@ -1470,69 +1442,3 @@ describe("web Markdown parser preload", () => {
|
||||
expect(ast?.children?.map((node) => node.type)).toEqual(["Heading", "Paragraph"]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("math preparation compatibility with latexMath false and true", () => {
|
||||
it("renders currency literally with latexMath: false while enabling math with latexMath: true", async () => {
|
||||
const source =
|
||||
"Costs $5 and $10; inline $E = mc^2$, \\(a+b\\), \\[c+d\\], and:\n\n```math\nx^2\n```";
|
||||
const prepared = prepareMarkdownSource(source).render();
|
||||
|
||||
const noMathAst = await parseMarkdown(prepared, {
|
||||
latexMath: false,
|
||||
hardSoftBreaks: true,
|
||||
admonitions: true,
|
||||
});
|
||||
const noMathText = JSON.stringify(noMathAst);
|
||||
expect(noMathText).toContain("Costs $5 and $10");
|
||||
expect(noMathText).not.toContain("LatexMath");
|
||||
|
||||
const mathAst = await parseMarkdown(prepared, {
|
||||
latexMath: true,
|
||||
hardSoftBreaks: true,
|
||||
admonitions: true,
|
||||
});
|
||||
const mathNodes: { type: string; content: string }[] = [];
|
||||
const walk = (node: ASTNode) => {
|
||||
if (node.type === "LatexMathInline" || node.type === "LatexMathDisplay") {
|
||||
mathNodes.push({
|
||||
type: node.type,
|
||||
content: (node.children ?? []).map((child) => child.content ?? "").join(""),
|
||||
});
|
||||
}
|
||||
node.children?.forEach(walk);
|
||||
};
|
||||
walk(mathAst);
|
||||
expect(mathNodes.map((n) => [n.type, n.content.trim()])).toEqual([
|
||||
["LatexMathInline", "E = mc^2"],
|
||||
["LatexMathInline", "a+b"],
|
||||
["LatexMathDisplay", "c+d"],
|
||||
["LatexMathDisplay", "x^2"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("web KaTeX .woff2-only stylesheet sync", () => {
|
||||
it("includes all 20 .woff2 fonts from katex and drops .woff/.ttf fallbacks", async () => {
|
||||
const fs = await import("node:fs");
|
||||
const path = await import("node:path");
|
||||
const katexCssPath = require.resolve("katex/dist/katex.min.css");
|
||||
const katexFontsDir = path.join(path.dirname(katexCssPath), "fonts");
|
||||
const woff2Files = fs
|
||||
.readdirSync(katexFontsDir)
|
||||
.filter((name) => name.endsWith(".woff2"))
|
||||
.sort();
|
||||
expect(woff2Files).toHaveLength(20);
|
||||
|
||||
const katexStylesSource = fs.readFileSync(
|
||||
path.resolve(__dirname, "katex-styles.web.ts"),
|
||||
"utf8",
|
||||
);
|
||||
for (const fontFile of woff2Files) {
|
||||
expect(katexStylesSource).toContain(`katex/dist/fonts/${fontFile}`);
|
||||
}
|
||||
expect(katexStylesSource).not.toContain('.woff")');
|
||||
expect(katexStylesSource).not.toContain('.ttf")');
|
||||
expect(katexStylesSource).toContain(".katex{");
|
||||
expect(katexStylesSource).toContain(".enrm-text .katex-display{margin:0}");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -35,7 +35,7 @@ export type { MarkdownDestinations };
|
||||
export type MarkdownSoftBreaks = "break" | "join";
|
||||
|
||||
const ThemedMarkdown = withUnistyles(EnrichedMarkdownText);
|
||||
const MD4C_FLAGS = { latexMath: true, hardSoftBreaks: true, admonitions: true };
|
||||
const MD4C_FLAGS = { latexMath: false, hardSoftBreaks: true, admonitions: true };
|
||||
const JOINED_SOFT_BREAKS_MD4C_FLAGS = { ...MD4C_FLAGS, hardSoftBreaks: false };
|
||||
|
||||
// Reading the breakpoint here makes Unistyles restyle the text when the layout crosses it.
|
||||
|
||||
@@ -8,11 +8,10 @@ import {
|
||||
type ComponentProps,
|
||||
type MouseEvent,
|
||||
} from "react";
|
||||
import {
|
||||
registerKaTeXStyleLoader,
|
||||
type CodeBlockRendererProps,
|
||||
type LinkRendererProps,
|
||||
type MarkdownRenderers,
|
||||
import type {
|
||||
CodeBlockRendererProps,
|
||||
LinkRendererProps,
|
||||
MarkdownRenderers,
|
||||
} from "react-native-enriched-markdown";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { useFileLink } from "@/assistant-file-links";
|
||||
@@ -152,11 +151,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
},
|
||||
}));
|
||||
|
||||
registerKaTeXStyleLoader(async () => {
|
||||
const mod = await import("./katex-styles.web");
|
||||
mod.ensureKaTeXStyles();
|
||||
});
|
||||
|
||||
export const WEB_RENDERERS: MarkdownRenderers = {
|
||||
codeBlock: WebCodeBlock,
|
||||
link: WebLink,
|
||||
|
||||
@@ -2,7 +2,6 @@ import { pluginOverviewUrl } from "@getpaseo/protocol/plugin-overview";
|
||||
import { classifyAssistantFileLink } from "@/assistant-file-links";
|
||||
import { ASSISTANT_FILE_EXTENSIONS } from "@/assistant-file-links/extensions";
|
||||
import { normalizeMarkdownHtml } from "./html";
|
||||
import { adaptMarkdownMath, isOffsetInRanges } from "./math";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { AssistantFileLinkSource } from "@/assistant-file-links";
|
||||
@@ -232,8 +231,6 @@ export function prepareMarkdownSource(
|
||||
} = {},
|
||||
) {
|
||||
source = normalizeMarkdownHtml(source);
|
||||
const { source: adaptedSource, mathRanges } = adaptMarkdownMath(source);
|
||||
source = adaptedSource;
|
||||
const images: MarkdownImage[] = [];
|
||||
let tree: Root | undefined;
|
||||
const getTree = () =>
|
||||
@@ -354,59 +351,53 @@ export function prepareMarkdownSource(
|
||||
edits.push({ start, end: labelStart, text: "" });
|
||||
edits.push({ start: labelEnd, end, text: "" });
|
||||
}
|
||||
function adaptTableHeaderGap(start: number, previous?: Nodes, line?: number) {
|
||||
if (previous?.type !== "paragraph" || previous.position?.end.line !== (line ?? -1) - 1) return;
|
||||
// MD4C only recognizes a table header on the first line of a paragraph.
|
||||
const lineStart =
|
||||
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
|
||||
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
|
||||
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
|
||||
const boundary = lineStart - newline.length;
|
||||
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
|
||||
}
|
||||
function adaptTableRow(start: number, end: number) {
|
||||
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
|
||||
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
|
||||
const row = source.slice(start, end);
|
||||
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
|
||||
if (isOffsetInRanges(start + match.index, mathRanges)) continue;
|
||||
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
|
||||
}
|
||||
}
|
||||
function adaptTextNode(start: number, end: number) {
|
||||
const slice = source.slice(start, end);
|
||||
const text = slice.replace(
|
||||
/(?<!\\)(?:(&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);)|(\|\|))/g,
|
||||
(match, entity: string | undefined, _bars: string | undefined, offset: number) => {
|
||||
if (isOffsetInRanges(start + offset, mathRanges)) return match;
|
||||
if (entity) return decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&");
|
||||
return "\\|\\|";
|
||||
},
|
||||
);
|
||||
if (text !== slice) edits.push({ start, end, text });
|
||||
}
|
||||
function visit(node: Nodes, previous?: Nodes) {
|
||||
const position = node.position;
|
||||
if (position?.start.offset !== undefined && position.end.offset !== undefined) {
|
||||
const start = position.start.offset;
|
||||
const end = position.end.offset;
|
||||
if (node.type === "paragraph") splitStandaloneImages(node, start, end);
|
||||
if (node.type === "table") adaptTableHeaderGap(start, previous, position.start.line);
|
||||
if (!isOffsetInRanges(start, mathRanges)) {
|
||||
if (httpsOnly) {
|
||||
dropUnsafeDestination(node, start, end);
|
||||
} else if (node.type === "link") {
|
||||
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
|
||||
if (title !== null)
|
||||
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
|
||||
if (
|
||||
node.type === "table" &&
|
||||
previous?.type === "paragraph" &&
|
||||
previous.position?.end.line === position.start.line - 1
|
||||
) {
|
||||
// MD4C only recognizes a table header on the first line of a paragraph.
|
||||
const lineStart =
|
||||
Math.max(source.lastIndexOf("\n", start - 1), source.lastIndexOf("\r", start - 1)) + 1;
|
||||
const newline = source.slice(lineStart - 2, lineStart).replace(/[^\r\n]/g, "");
|
||||
const blank = source.slice(lineStart, start).replace(/[^>]/g, " ").trimEnd();
|
||||
const boundary = lineStart - newline.length;
|
||||
edits.push({ start: boundary, end: lineStart, text: `${newline}${blank}${newline}` });
|
||||
}
|
||||
if (httpsOnly) {
|
||||
dropUnsafeDestination(node, start, end);
|
||||
} else if (node.type === "link") {
|
||||
const title = workspaceHoverTitle(node, source.slice(start, end), workspaceRoot);
|
||||
if (title !== null)
|
||||
edits.push({ start: end - 1, end: end - 1, text: ` ${JSON.stringify(title)}` });
|
||||
}
|
||||
if (node.type === "tableRow") {
|
||||
// MD4C's always-enabled spoiler extension otherwise consumes adjacent cell
|
||||
// delimiters. Spaces keep empty GFM cells empty without producing spoilers.
|
||||
const row = source.slice(start, end);
|
||||
for (const match of row.matchAll(/(?<!\\)\|(?=\|)/g)) {
|
||||
edits.push({ start: start + match.index + 1, end: start + match.index + 1, text: " " });
|
||||
}
|
||||
}
|
||||
if (node.type === "tableRow") adaptTableRow(start, end);
|
||||
if (node.type === "image" || node.type === "imageReference") {
|
||||
if (!isOffsetInRanges(start, mathRanges)) collectImage(node, start, end);
|
||||
collectImage(node, start, end);
|
||||
return;
|
||||
}
|
||||
if (node.type === "text") adaptTextNode(start, end);
|
||||
if (node.type === "text") {
|
||||
const text = source
|
||||
.slice(start, end)
|
||||
.replace(/(?<!\\)&(?:#(?:[xX][\da-fA-F]+|\d+)|[a-zA-Z][a-zA-Z\d]+);/g, (entity) =>
|
||||
decodeString(entity).replace(/[!-/:-@[-`{-~]/g, "\\$&"),
|
||||
)
|
||||
.replace(/(?<!\\)\|\|/g, "\\|\\|");
|
||||
if (text !== source.slice(start, end)) edits.push({ start, end, text });
|
||||
}
|
||||
}
|
||||
if ("children" in node)
|
||||
node.children.forEach((child, index) => visit(child, node.children[index - 1]));
|
||||
|
||||
@@ -1,22 +1,3 @@
|
||||
import {
|
||||
checkFenceContainerExit,
|
||||
isAsciiAlnum,
|
||||
isAsciiPunctuation,
|
||||
isBlankRange,
|
||||
isClosingFenceAt,
|
||||
matchListMarkerAt,
|
||||
measureIndentAt,
|
||||
parseFenceOpenerAt,
|
||||
stripBlockquotesAt,
|
||||
} from "./block-scan";
|
||||
import {
|
||||
isUnclosedInlineMathCandidate,
|
||||
matchClosedBracketMath,
|
||||
matchClosedDollarDisplayMath,
|
||||
matchClosedInlineMath,
|
||||
matchClosedParenMath,
|
||||
} from "./math";
|
||||
|
||||
/**
|
||||
* Sentinel destination for incomplete links while streaming. Web renders it as a
|
||||
* non-interactive link-styled span; native styles it as a link and ignores taps.
|
||||
@@ -34,17 +15,8 @@ interface OpenFence {
|
||||
char: "`" | "~";
|
||||
length: number;
|
||||
lineStart: number;
|
||||
lastLineStart: number;
|
||||
quoteDepth: number;
|
||||
maxCloseIndent: number;
|
||||
listMinIndent: number;
|
||||
hasContent: boolean;
|
||||
}
|
||||
|
||||
interface OpenDisplayMath {
|
||||
kind: "$$" | "\\[";
|
||||
withholdFrom: number;
|
||||
quoteDepth: number;
|
||||
hasContent: boolean;
|
||||
}
|
||||
|
||||
@@ -52,9 +24,7 @@ interface FenceScanCheckpoint {
|
||||
/** Exact prefix of completed lines already scanned (ends at `\n` or `\r`, or is `""`). */
|
||||
scannedPrefix: string;
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
listContentIndent: number;
|
||||
listQuoteDepth: number;
|
||||
/** Start offset of the most recent closing fence line, or -1 if none. */
|
||||
lastClosedFenceLineStart: number;
|
||||
}
|
||||
@@ -140,20 +110,76 @@ function lastCompletedLineEnd(source: string): number {
|
||||
return lastBreak === -1 ? 0 : lastBreak + 1;
|
||||
}
|
||||
|
||||
/** Strip leading CommonMark blockquote markers (`> `) and return quote depth + content offset. */
|
||||
function stripBlockquotes(text: string): { quoteDepth: number; offset: number } {
|
||||
return stripBlockquotesAt(text, 0, text.length);
|
||||
let offset = 0;
|
||||
let quoteDepth = 0;
|
||||
while (offset < text.length) {
|
||||
let spaces = 0;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === " " && spaces < 3) {
|
||||
cursor++;
|
||||
spaces++;
|
||||
}
|
||||
if (text[cursor] !== ">") break;
|
||||
quoteDepth++;
|
||||
cursor++;
|
||||
if (text[cursor] === " " || text[cursor] === "\t") cursor++;
|
||||
offset = cursor;
|
||||
}
|
||||
return { quoteDepth, offset };
|
||||
}
|
||||
|
||||
function measureIndent(text: string, from: number): { spaces: number; offset: number } {
|
||||
return measureIndentAt(text, from, text.length);
|
||||
let spaces = 0;
|
||||
let offset = from;
|
||||
while (offset < text.length) {
|
||||
const ch = text[offset];
|
||||
if (ch === " ") {
|
||||
spaces++;
|
||||
offset++;
|
||||
} else if (ch === "\t") {
|
||||
spaces += 4 - (spaces % 4);
|
||||
offset++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { spaces, offset };
|
||||
}
|
||||
|
||||
function matchListMarker(
|
||||
text: string,
|
||||
from: number,
|
||||
maxIndent = Number.POSITIVE_INFINITY,
|
||||
): { markerEnd: number; contentIndent: number } | null {
|
||||
return matchListMarkerAt(text, from, text.length, maxIndent);
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (offset >= text.length) return null;
|
||||
const ch = text[offset];
|
||||
if (ch === "-" || ch === "*" || ch === "+") {
|
||||
const after = offset + 1;
|
||||
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
|
||||
return { markerEnd: after + 1, contentIndent: spaces + 2 };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (ch >= "0" && ch <= "9") {
|
||||
let cursor = offset;
|
||||
while (
|
||||
cursor < text.length &&
|
||||
text[cursor] >= "0" &&
|
||||
text[cursor] <= "9" &&
|
||||
cursor - offset < 9
|
||||
) {
|
||||
cursor++;
|
||||
}
|
||||
if (cursor < text.length && (text[cursor] === "." || text[cursor] === ")")) {
|
||||
const after = cursor + 1;
|
||||
if (after < text.length && (text[after] === " " || text[after] === "\t")) {
|
||||
return { markerEnd: after + 1, contentIndent: spaces + (after - offset) + 1 };
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function parseFenceOpener(
|
||||
@@ -161,7 +187,17 @@ function parseFenceOpener(
|
||||
from: number,
|
||||
maxIndent: number,
|
||||
): { char: "`" | "~"; length: number; info: string } | null {
|
||||
return parseFenceOpenerAt(text, from, text.length, maxIndent);
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (spaces > maxIndent || offset >= text.length) return null;
|
||||
const ch = text[offset];
|
||||
if (ch !== "`" && ch !== "~") return null;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === ch) cursor++;
|
||||
const length = cursor - offset;
|
||||
if (length < 3) return null;
|
||||
const info = text.slice(cursor);
|
||||
if (ch === "`" && info.includes("`")) return null;
|
||||
return { char: ch, length, info };
|
||||
}
|
||||
|
||||
function isClosingFence(
|
||||
@@ -171,7 +207,16 @@ function isClosingFence(
|
||||
char: "`" | "~",
|
||||
minLength: number,
|
||||
): boolean {
|
||||
return isClosingFenceAt(text, from, text.length, maxIndent, char, minLength);
|
||||
const { spaces, offset } = measureIndent(text, from);
|
||||
if (spaces > maxIndent || offset >= text.length || text[offset] !== char) return false;
|
||||
let cursor = offset;
|
||||
while (cursor < text.length && text[cursor] === char) cursor++;
|
||||
if (cursor - offset < minLength) return false;
|
||||
while (cursor < text.length) {
|
||||
if (text[cursor] !== " " && text[cursor] !== "\t") return false;
|
||||
cursor++;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function isPartialClosingFence(
|
||||
@@ -192,191 +237,18 @@ function isPartialClosingFence(
|
||||
}
|
||||
|
||||
function isBlankRest(text: string, from: number): boolean {
|
||||
return isBlankRange(text, from, text.length);
|
||||
for (let i = from; i < text.length; i++) {
|
||||
if (text[i] !== " " && text[i] !== "\t") return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
interface FenceStepState {
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
listContentIndent: number;
|
||||
listQuoteDepth: number;
|
||||
lastClosedFenceLineStart: number;
|
||||
}
|
||||
|
||||
function hasTrailingOddBackslash(text: string): boolean {
|
||||
let backslashes = 0;
|
||||
for (let i = text.length - 1; i >= 0 && text[i] === "\\"; i--) backslashes++;
|
||||
return backslashes % 2 === 1;
|
||||
}
|
||||
|
||||
function hasTrailingPartialDoubleDollarCloser(text: string): boolean {
|
||||
if (!text.endsWith("$")) return false;
|
||||
if (text.length >= 2 && text[text.length - 2] === "$") return false;
|
||||
return !hasTrailingOddBackslash(text.slice(0, -1));
|
||||
}
|
||||
|
||||
function findSameLineBracketClose(text: string, from: number): number {
|
||||
let j = from;
|
||||
while (j < text.length) {
|
||||
if (text[j] === "\\" && text[j + 1] === "]") return j + 2;
|
||||
if (text[j] === "\\" && j + 1 < text.length) {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function findSameLineDoubleDollarClose(text: string, from: number): number {
|
||||
let j = from;
|
||||
while (j < text.length) {
|
||||
if (text[j] === "\\" && j + 1 < text.length) {
|
||||
j += 2;
|
||||
continue;
|
||||
}
|
||||
if (text[j] === "$" && text[j + 1] === "$") {
|
||||
let closeEnd = j;
|
||||
while (closeEnd < text.length && text[closeEnd] === "$") closeEnd++;
|
||||
if (closeEnd - j === 2) return closeEnd;
|
||||
j = closeEnd;
|
||||
continue;
|
||||
}
|
||||
j++;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function openDisplayMathFromLine(
|
||||
kind: "$$" | "\\[",
|
||||
text: string,
|
||||
from: number,
|
||||
openIndex: number,
|
||||
restStart: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
): OpenDisplayMath {
|
||||
const withholdFrom = isBlankRest(text.slice(from, openIndex), 0)
|
||||
? lineStart
|
||||
: lineStart + openIndex;
|
||||
const rest = text.slice(restStart);
|
||||
const effectiveRest =
|
||||
kind === "\\[" && isTrailingPartialLine && hasTrailingOddBackslash(rest)
|
||||
? rest.slice(0, -1)
|
||||
: rest;
|
||||
return {
|
||||
kind,
|
||||
withholdFrom,
|
||||
quoteDepth,
|
||||
hasContent: !isBlankRest(effectiveRest, 0),
|
||||
};
|
||||
}
|
||||
|
||||
function scanLineForDisplayMath(
|
||||
text: string,
|
||||
from: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
state: FenceStepState,
|
||||
): void {
|
||||
let k = from;
|
||||
while (k < text.length) {
|
||||
const ch = text[k];
|
||||
if (ch === "\\") {
|
||||
if (text[k + 1] === "[") {
|
||||
const closeEnd = findSameLineBracketClose(text, k + 2);
|
||||
if (closeEnd !== -1) {
|
||||
k = closeEnd;
|
||||
continue;
|
||||
}
|
||||
state.openDisplayMath = openDisplayMathFromLine(
|
||||
"\\[",
|
||||
text,
|
||||
from,
|
||||
k,
|
||||
k + 2,
|
||||
lineStart,
|
||||
quoteDepth,
|
||||
isTrailingPartialLine,
|
||||
);
|
||||
return;
|
||||
}
|
||||
k += k + 1 < text.length && isAsciiPunctuation(text[k + 1]) ? 2 : 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === "`") {
|
||||
let runEnd = k;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd++;
|
||||
const closePos = findMatchingBacktickRun(text, runEnd, runEnd - k);
|
||||
k = closePos !== -1 ? closePos + (runEnd - k) : runEnd;
|
||||
continue;
|
||||
}
|
||||
if (ch === "$") {
|
||||
let runEnd = k;
|
||||
while (runEnd < text.length && text[runEnd] === "$") runEnd++;
|
||||
if (runEnd - k === 2) {
|
||||
const closeEnd = findSameLineDoubleDollarClose(text, runEnd);
|
||||
if (closeEnd !== -1) {
|
||||
k = closeEnd;
|
||||
continue;
|
||||
}
|
||||
state.openDisplayMath = openDisplayMathFromLine(
|
||||
"$$",
|
||||
text,
|
||||
from,
|
||||
k,
|
||||
runEnd,
|
||||
lineStart,
|
||||
quoteDepth,
|
||||
isTrailingPartialLine,
|
||||
);
|
||||
return;
|
||||
}
|
||||
k = runEnd;
|
||||
continue;
|
||||
}
|
||||
k++;
|
||||
}
|
||||
}
|
||||
|
||||
function stepOpenDisplayMathLine(
|
||||
text: string,
|
||||
offset: number,
|
||||
lineStart: number,
|
||||
quoteDepth: number,
|
||||
isTrailingPartialLine: boolean,
|
||||
state: FenceStepState,
|
||||
): boolean {
|
||||
const open = state.openDisplayMath!;
|
||||
if (quoteDepth < open.quoteDepth) {
|
||||
state.openDisplayMath = null;
|
||||
return false;
|
||||
}
|
||||
const closeEnd =
|
||||
open.kind === "$$"
|
||||
? findSameLineDoubleDollarClose(text, offset)
|
||||
: findSameLineBracketClose(text, offset);
|
||||
if (closeEnd !== -1) {
|
||||
state.openDisplayMath = null;
|
||||
state.lastClosedFenceLineStart = lineStart;
|
||||
scanLineForDisplayMath(text, closeEnd, lineStart, quoteDepth, isTrailingPartialLine, state);
|
||||
return true;
|
||||
}
|
||||
const rest = text.slice(offset);
|
||||
let effectiveRest = rest;
|
||||
if (isTrailingPartialLine) {
|
||||
if (open.kind === "$$" && hasTrailingPartialDoubleDollarCloser(rest)) {
|
||||
effectiveRest = rest.slice(0, -1);
|
||||
} else if (open.kind === "\\[" && hasTrailingOddBackslash(rest)) {
|
||||
effectiveRest = rest.slice(0, -1);
|
||||
}
|
||||
}
|
||||
if (!isBlankRest(effectiveRest, 0)) open.hasContent = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
function stepFenceLine(
|
||||
text: string,
|
||||
lineStart: number,
|
||||
@@ -386,17 +258,8 @@ function stepFenceLine(
|
||||
const { quoteDepth, offset } = stripBlockquotes(text);
|
||||
|
||||
if (state.openFence !== null) {
|
||||
if (
|
||||
checkFenceContainerExit(
|
||||
text,
|
||||
0,
|
||||
text.length,
|
||||
state.openFence.quoteDepth,
|
||||
state.openFence.listMinIndent,
|
||||
).exited
|
||||
) {
|
||||
// Leaving the blockquote or enclosing list closes any fence opened inside it.
|
||||
state.lastClosedFenceLineStart = state.openFence.lastLineStart;
|
||||
if (quoteDepth < state.openFence.quoteDepth) {
|
||||
// Leaving the blockquote closes any fence opened inside it.
|
||||
state.openFence = null;
|
||||
} else if (
|
||||
isClosingFence(
|
||||
@@ -411,7 +274,6 @@ function stepFenceLine(
|
||||
state.openFence = null;
|
||||
return;
|
||||
} else {
|
||||
state.openFence.lastLineStart = lineStart;
|
||||
const partialCloser =
|
||||
isTrailingPartialLine &&
|
||||
quoteDepth === state.openFence.quoteDepth &&
|
||||
@@ -427,62 +289,34 @@ function stepFenceLine(
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
state.openDisplayMath !== null &&
|
||||
stepOpenDisplayMathLine(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isBlankRest(text, offset)) {
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listContentIndent = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (quoteDepth < state.listQuoteDepth) {
|
||||
state.listContentIndent = 0;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
}
|
||||
if (isBlankRest(text, offset)) return;
|
||||
|
||||
let cursor = offset;
|
||||
let lineIndentBase = quoteDepth === state.listQuoteDepth ? state.listContentIndent : 0;
|
||||
let lineIndentBase = state.listContentIndent;
|
||||
const { spaces: firstSpaces } = measureIndent(text, cursor);
|
||||
if (quoteDepth === state.listQuoteDepth && firstSpaces < state.listContentIndent) {
|
||||
if (firstSpaces < state.listContentIndent) {
|
||||
state.listContentIndent = 0;
|
||||
lineIndentBase = 0;
|
||||
}
|
||||
let peeledList = false;
|
||||
let marker = matchListMarker(text, cursor, lineIndentBase + 3);
|
||||
let marker = matchListMarker(text, cursor);
|
||||
while (marker) {
|
||||
const markerBase = cursor === offset ? 0 : lineIndentBase;
|
||||
const totalIndent = markerBase + marker.contentIndent;
|
||||
state.listContentIndent = totalIndent;
|
||||
state.listQuoteDepth = quoteDepth;
|
||||
lineIndentBase = totalIndent;
|
||||
state.listContentIndent = marker.contentIndent;
|
||||
lineIndentBase = marker.contentIndent;
|
||||
cursor = marker.markerEnd;
|
||||
peeledList = true;
|
||||
marker = matchListMarker(text, cursor, 3);
|
||||
marker = matchListMarker(text, cursor);
|
||||
}
|
||||
|
||||
const opener = parseFenceOpener(text, cursor, peeledList ? 3 : lineIndentBase + 3);
|
||||
const opener = parseFenceOpener(text, cursor, lineIndentBase + 3);
|
||||
if (opener) {
|
||||
state.openFence = {
|
||||
char: opener.char,
|
||||
length: opener.length,
|
||||
lineStart,
|
||||
lastLineStart: lineStart,
|
||||
quoteDepth,
|
||||
maxCloseIndent: lineIndentBase + 3,
|
||||
listMinIndent: lineIndentBase,
|
||||
hasContent: false,
|
||||
};
|
||||
return;
|
||||
}
|
||||
|
||||
scanLineForDisplayMath(text, offset, lineStart, quoteDepth, isTrailingPartialLine, state);
|
||||
}
|
||||
|
||||
function advanceFenceRange(source: string, from: number, to: number, state: FenceStepState): void {
|
||||
@@ -505,28 +339,18 @@ function cloneOpenFence(fence: OpenFence | null): OpenFence | null {
|
||||
return fence ? { ...fence } : null;
|
||||
}
|
||||
|
||||
function cloneOpenDisplayMath(math: OpenDisplayMath | null): OpenDisplayMath | null {
|
||||
return math ? { ...math } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Incrementally advance fence and display-math tracking across completed lines so steady-state
|
||||
* Incrementally advance fence tracking across completed lines so steady-state
|
||||
* streaming frames within a line scan 0 prior lines, and each newline scans 1 line.
|
||||
*/
|
||||
function resolveFenceState(
|
||||
source: string,
|
||||
checkpoint: FenceScanCheckpoint | null,
|
||||
): {
|
||||
openFence: OpenFence | null;
|
||||
openDisplayMath: OpenDisplayMath | null;
|
||||
lastClosedFenceLineStart: number;
|
||||
} {
|
||||
): { openFence: OpenFence | null; lastClosedFenceLineStart: number } {
|
||||
const completedEnd = lastCompletedLineEnd(source);
|
||||
const state: FenceStepState = {
|
||||
openFence: null,
|
||||
openDisplayMath: null,
|
||||
listContentIndent: 0,
|
||||
listQuoteDepth: 0,
|
||||
lastClosedFenceLineStart: -1,
|
||||
};
|
||||
|
||||
@@ -537,9 +361,7 @@ function resolveFenceState(
|
||||
source.startsWith(checkpoint.scannedPrefix);
|
||||
if (matchedPrefix && checkpoint) {
|
||||
state.openFence = cloneOpenFence(checkpoint.openFence);
|
||||
state.openDisplayMath = cloneOpenDisplayMath(checkpoint.openDisplayMath);
|
||||
state.listContentIndent = checkpoint.listContentIndent;
|
||||
state.listQuoteDepth = checkpoint.listQuoteDepth;
|
||||
state.lastClosedFenceLineStart = checkpoint.lastClosedFenceLineStart;
|
||||
scanFrom = checkpoint.scannedPrefix.length;
|
||||
}
|
||||
@@ -551,9 +373,7 @@ function resolveFenceState(
|
||||
if (checkpoint && (!matchedPrefix || completedEnd !== checkpoint.scannedPrefix.length)) {
|
||||
checkpoint.scannedPrefix = source.slice(0, completedEnd);
|
||||
checkpoint.openFence = cloneOpenFence(state.openFence);
|
||||
checkpoint.openDisplayMath = cloneOpenDisplayMath(state.openDisplayMath);
|
||||
checkpoint.listContentIndent = state.listContentIndent;
|
||||
checkpoint.listQuoteDepth = state.listQuoteDepth;
|
||||
checkpoint.lastClosedFenceLineStart = state.lastClosedFenceLineStart;
|
||||
}
|
||||
|
||||
@@ -563,7 +383,6 @@ function resolveFenceState(
|
||||
|
||||
return {
|
||||
openFence: state.openFence,
|
||||
openDisplayMath: state.openDisplayMath,
|
||||
lastClosedFenceLineStart: state.lastClosedFenceLineStart,
|
||||
};
|
||||
}
|
||||
@@ -844,6 +663,17 @@ function isWhitespaceChar(ch: string | undefined): boolean {
|
||||
return ch === undefined || ch === " " || ch === "\t" || ch === "\n" || ch === "\r";
|
||||
}
|
||||
|
||||
function isAsciiPunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
const code = ch.charCodeAt(0);
|
||||
return (
|
||||
(code >= 0x21 && code <= 0x2f) ||
|
||||
(code >= 0x3a && code <= 0x40) ||
|
||||
(code >= 0x5b && code <= 0x60) ||
|
||||
(code >= 0x7b && code <= 0x7e)
|
||||
);
|
||||
}
|
||||
|
||||
function isUnicodePunctuation(ch: string | undefined): boolean {
|
||||
if (!ch) return false;
|
||||
if (isAsciiPunctuation(ch)) return true;
|
||||
@@ -1031,7 +861,6 @@ interface InlineScanState {
|
||||
stack: InlineStackEntry[];
|
||||
openCode: { pos: number; length: number; contentStart: number } | null;
|
||||
openHtmlPos: number | null;
|
||||
openInlineMathPos: number | null;
|
||||
trailingBackslash: boolean;
|
||||
}
|
||||
|
||||
@@ -1324,7 +1153,7 @@ function stripPartialEmphCloser(output: string, entry: EmphEntry): string {
|
||||
|
||||
function unwindInlineState(source: string, state: InlineScanState): string {
|
||||
let output = source;
|
||||
const { openCode, openHtmlPos, openInlineMathPos, trailingBackslash, stack } = state;
|
||||
const { openCode, openHtmlPos, trailingBackslash, stack } = state;
|
||||
|
||||
if (openCode) {
|
||||
let codeContent = output.slice(openCode.contentStart);
|
||||
@@ -1338,8 +1167,6 @@ function unwindInlineState(source: string, state: InlineScanState): string {
|
||||
: output.slice(0, openCode.contentStart) + codeContent + "`".repeat(openCode.length);
|
||||
} else if (openHtmlPos !== null) {
|
||||
output = output.slice(0, openHtmlPos);
|
||||
} else if (openInlineMathPos !== null) {
|
||||
output = output.slice(0, openInlineMathPos);
|
||||
} else if (trailingBackslash) {
|
||||
output = output.slice(0, -1);
|
||||
}
|
||||
@@ -1383,56 +1210,6 @@ function scanBacktickToken(source: string, i: number, state: InlineScanState): n
|
||||
return null;
|
||||
}
|
||||
|
||||
function isOnTrailingLine(source: string, from: number): boolean {
|
||||
return source.indexOf("\n", from) === -1 && source.indexOf("\r", from) === -1;
|
||||
}
|
||||
|
||||
function scanInlineBackslashToken(
|
||||
source: string,
|
||||
i: number,
|
||||
state: InlineScanState,
|
||||
): number | null {
|
||||
if (source[i + 1] === "(") {
|
||||
const closedParen = matchClosedParenMath(source, i);
|
||||
if (closedParen !== -1) return closedParen;
|
||||
if (isOnTrailingLine(source, i + 2)) {
|
||||
if (i + 2 === source.length) state.openInlineMathPos = i;
|
||||
return null;
|
||||
}
|
||||
}
|
||||
if (source[i + 1] === "[") {
|
||||
const closedBracket = matchClosedBracketMath(source, i);
|
||||
if (closedBracket !== -1) return closedBracket;
|
||||
}
|
||||
if (i + 1 === source.length) {
|
||||
state.trailingBackslash = true;
|
||||
return null;
|
||||
}
|
||||
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
|
||||
}
|
||||
|
||||
function scanInlineDollarToken(source: string, i: number, state: InlineScanState): number | null {
|
||||
if (source[i + 1] === "$") {
|
||||
const closedDisplay = matchClosedDollarDisplayMath(source, i);
|
||||
if (closedDisplay !== -1) return closedDisplay;
|
||||
let runEnd = i;
|
||||
while (runEnd < source.length && source[runEnd] === "$") runEnd++;
|
||||
return runEnd;
|
||||
}
|
||||
const closedInline = matchClosedInlineMath(source, i);
|
||||
if (closedInline !== -1) return closedInline;
|
||||
if (isOnTrailingLine(source, i + 1)) {
|
||||
const charBefore = i > 0 ? source[i - 1] : undefined;
|
||||
const validOpenerFlank = charBefore !== "\\" && charBefore !== "$" && !isAsciiAlnum(charBefore);
|
||||
if (i + 1 === source.length && validOpenerFlank) {
|
||||
state.openInlineMathPos = i;
|
||||
return null;
|
||||
}
|
||||
if (isUnclosedInlineMathCandidate(source, i)) return null;
|
||||
}
|
||||
return i + 1;
|
||||
}
|
||||
|
||||
function stepInlineScanner(
|
||||
source: string,
|
||||
i: number,
|
||||
@@ -1442,8 +1219,13 @@ function stepInlineScanner(
|
||||
): number | null {
|
||||
const ch = source[i];
|
||||
if (ch === "\n") return lineContentStarts.get(i + 1) ?? i + 1;
|
||||
if (ch === "\\") return scanInlineBackslashToken(source, i, state);
|
||||
if (ch === "$") return scanInlineDollarToken(source, i, state);
|
||||
if (ch === "\\") {
|
||||
if (i + 1 === source.length) {
|
||||
state.trailingBackslash = true;
|
||||
return null;
|
||||
}
|
||||
return i + (isAsciiPunctuation(source[i + 1]) ? 2 : 1);
|
||||
}
|
||||
if (ch === "`") return scanBacktickToken(source, i, state);
|
||||
if (ch === "<") return scanHtmlToken(source, i, state);
|
||||
if (ch === "[" || (ch === "!" && source[i + 1] === "[")) {
|
||||
@@ -1466,7 +1248,6 @@ function stabilizeInlineBlock(
|
||||
stack: [],
|
||||
openCode: null,
|
||||
openHtmlPos: null,
|
||||
openInlineMathPos: null,
|
||||
trailingBackslash: false,
|
||||
};
|
||||
|
||||
@@ -1478,74 +1259,42 @@ function stabilizeInlineBlock(
|
||||
const hasOpenState =
|
||||
state.openCode !== null ||
|
||||
state.openHtmlPos !== null ||
|
||||
state.openInlineMathPos !== null ||
|
||||
state.stack.length > 0 ||
|
||||
state.trailingBackslash;
|
||||
return hasOpenState ? unwindInlineState(source, state) : source;
|
||||
}
|
||||
|
||||
function stabilizeOpenFence(
|
||||
source: string,
|
||||
openFence: OpenFence,
|
||||
endsWithNewline: boolean,
|
||||
): string {
|
||||
if (!openFence.hasContent) {
|
||||
return source.slice(0, openFence.lineStart);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
const last = prevLineSlice(source, source.length);
|
||||
if (last) {
|
||||
const lastText = lineText(source, last);
|
||||
const lastQ = stripBlockquotes(lastText);
|
||||
if (
|
||||
lastQ.quoteDepth === openFence.quoteDepth &&
|
||||
(isPartialClosingFence(
|
||||
lastText,
|
||||
lastQ.offset,
|
||||
openFence.maxCloseIndent,
|
||||
openFence.char,
|
||||
openFence.length,
|
||||
) ||
|
||||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
|
||||
) {
|
||||
return source.slice(0, last.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function stabilizeOpenDisplayMath(
|
||||
source: string,
|
||||
openDisplayMath: OpenDisplayMath,
|
||||
endsWithNewline: boolean,
|
||||
): string {
|
||||
if (!openDisplayMath.hasContent) {
|
||||
return source.slice(0, openDisplayMath.withholdFrom);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
if (openDisplayMath.kind === "$$" && hasTrailingPartialDoubleDollarCloser(source)) {
|
||||
return source.slice(0, -1);
|
||||
}
|
||||
if (openDisplayMath.kind === "\\[" && hasTrailingOddBackslash(source)) {
|
||||
return source.slice(0, -1);
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
function stabilizeWithCheckpoint(source: string, checkpoint: FenceScanCheckpoint | null): string {
|
||||
if (source.length === 0) return source;
|
||||
const endsWithNewline = sourceEndsWithNewline(source);
|
||||
|
||||
// 1. Fenced code blocks & display math blocks — O(new lines) when incremental.
|
||||
const { openFence, openDisplayMath, lastClosedFenceLineStart } = resolveFenceState(
|
||||
source,
|
||||
checkpoint,
|
||||
);
|
||||
if (openFence !== null) return stabilizeOpenFence(source, openFence, endsWithNewline);
|
||||
if (openDisplayMath !== null) {
|
||||
return stabilizeOpenDisplayMath(source, openDisplayMath, endsWithNewline);
|
||||
// 1. Fenced code blocks (top-level, quoted, or inside lists) — O(new lines) when incremental.
|
||||
const { openFence, lastClosedFenceLineStart } = resolveFenceState(source, checkpoint);
|
||||
if (openFence !== null) {
|
||||
if (!openFence.hasContent) {
|
||||
return source.slice(0, openFence.lineStart);
|
||||
}
|
||||
if (!endsWithNewline) {
|
||||
const last = prevLineSlice(source, source.length);
|
||||
if (last) {
|
||||
const lastText = lineText(source, last);
|
||||
const lastQ = stripBlockquotes(lastText);
|
||||
if (
|
||||
lastQ.quoteDepth === openFence.quoteDepth &&
|
||||
(isPartialClosingFence(
|
||||
lastText,
|
||||
lastQ.offset,
|
||||
openFence.maxCloseIndent,
|
||||
openFence.char,
|
||||
openFence.length,
|
||||
) ||
|
||||
(openFence.quoteDepth > 0 && isBlankRest(lastText, lastQ.offset)))
|
||||
) {
|
||||
return source.slice(0, last.start);
|
||||
}
|
||||
}
|
||||
}
|
||||
return source;
|
||||
}
|
||||
|
||||
// 2. Trailing GFM table — O(table rows) backwards from EOF.
|
||||
@@ -1581,9 +1330,7 @@ export function createStreamingMarkdownStabilizer(): StreamingMarkdownStabilizer
|
||||
const checkpoint: FenceScanCheckpoint = {
|
||||
scannedPrefix: "",
|
||||
openFence: null,
|
||||
openDisplayMath: null,
|
||||
listContentIndent: 0,
|
||||
listQuoteDepth: 0,
|
||||
lastClosedFenceLineStart: -1,
|
||||
};
|
||||
return {
|
||||
|
||||
@@ -544,119 +544,3 @@ describe("stabilizeStreamingMarkdown — fences, tables, HTML, and full prefix s
|
||||
expect(incremental.stabilize("Plain\nCheck `inline")).toBe("Plain\nCheck `inline`");
|
||||
}, 20000);
|
||||
});
|
||||
|
||||
describe("streaming Markdown math safety", () => {
|
||||
it("keeps open multiline $$, \\[, and ```math blocks in the tail without splitting mid-equation", () => {
|
||||
const blocks = ["$$\na = 1\n\nb = 2\n", "\\[\na = 1\n\nb = 2\n", "```math\na = 1\n\nb = 2\n"];
|
||||
for (const openMath of blocks) {
|
||||
const source = `Intro.\n\n${openMath}`;
|
||||
const split = splitOnce(source);
|
||||
expect(split.head).toBe("Intro.\n\n");
|
||||
expect(split.tail).toBe(openMath);
|
||||
}
|
||||
|
||||
// Even after a blank-line $$ or \[ block closes, it stays together until a following block arrives.
|
||||
const closedDollar = "Intro.\n\n$$\na = 1\n\nb = 2\n$$\n";
|
||||
expect(splitOnce(closedDollar)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail: "$$\na = 1\n\nb = 2\n$$\n",
|
||||
});
|
||||
expect(splitOnce(`${closedDollar}\nAfter.\n`)).toEqual({
|
||||
head: closedDollar + "\n",
|
||||
tail: "After.\n",
|
||||
});
|
||||
|
||||
const closedBracket = "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n";
|
||||
expect(splitOnce(closedBracket)).toEqual({
|
||||
head: "Intro.\n\n",
|
||||
tail: "Intro.\n\n\\[\na = 1\n\nb = 2\n\\]\n".slice("Intro.\n\n".length),
|
||||
});
|
||||
expect(splitOnce(`${closedBracket}\nAfter.\n`)).toEqual({
|
||||
head: closedBracket + "\n",
|
||||
tail: "After.\n",
|
||||
});
|
||||
});
|
||||
|
||||
it("withholds dangling math openers and partial closers without auto-closing partial TeX", () => {
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n$$")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n$$\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n\\[")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n\\[\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```math")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Intro\n\n```math\n")).toBe("Intro\n\n");
|
||||
expect(stabilizeStreamingMarkdown("Formula: $")).toBe("Formula: ");
|
||||
expect(stabilizeStreamingMarkdown("Formula: \\(")).toBe("Formula: ");
|
||||
// Currency/escaped trailing dollars are not math openers.
|
||||
expect(stabilizeStreamingMarkdown("Price is US$")).toBe("Price is US$");
|
||||
expect(stabilizeStreamingMarkdown("Escaped \\$")).toBe("Escaped \\$");
|
||||
|
||||
// Partial TeX content stays literal and is never auto-closed or mangled by inline emphasis/links.
|
||||
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{")).toBe("$$\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{")).toBe("\\[\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("```math\n\\frac{a}{")).toBe("```math\n\\frac{a}{");
|
||||
expect(stabilizeStreamingMarkdown("Compute $\\alpha + *x")).toBe("Compute $\\alpha + *x");
|
||||
expect(stabilizeStreamingMarkdown("Compute \\(\\alpha + [a")).toBe("Compute \\(\\alpha + [a");
|
||||
|
||||
// Partial closing markers inside open display math are withheld until completed.
|
||||
expect(stabilizeStreamingMarkdown("$$\n\\frac{a}{b}\n$")).toBe("$$\n\\frac{a}{b}\n");
|
||||
expect(stabilizeStreamingMarkdown("\\[\n\\frac{a}{b}\n\\")).toBe("\\[\n\\frac{a}{b}\n");
|
||||
|
||||
// Currency dollars do not suppress emphasis stabilization later on the line.
|
||||
expect(stabilizeStreamingMarkdown("Costs $5 and **bold")).toBe("Costs $5 and **bold**");
|
||||
// Closed inline math protects internal * / _ from emphasis stabilization.
|
||||
expect(stabilizeStreamingMarkdown("Compute $a * b$ and **bold")).toBe(
|
||||
"Compute $a * b$ and **bold**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("Compute \\(a * b\\) and **bold")).toBe(
|
||||
"Compute \\(a * b\\) and **bold**",
|
||||
);
|
||||
|
||||
// An unclosed list-nested fence ends once a non-blank line exits the list container.
|
||||
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside\n$$")).toBe(
|
||||
"- ~~~sh\n echo ok\nOutside\n",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- ~~~sh\n echo ok\nOutside **bo")).toBe(
|
||||
"- ~~~sh\n echo ok\nOutside **bo**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- ```sh\n echo ok\nOutside **bo")).toBe(
|
||||
"- ```sh\n echo ok\nOutside **bo**",
|
||||
);
|
||||
expect(stabilizeStreamingMarkdown("- item\n - ```\n code\n back **bo")).toBe(
|
||||
"- item\n - ```\n code\n back **bo**",
|
||||
);
|
||||
// Exiting a deeper quote clears stale list indent so outer quoted code stays open.
|
||||
expect(stabilizeStreamingMarkdown("> > - item\n>\n> ~~~sh\n> echo **bo")).toBe(
|
||||
"> > - item\n>\n> ~~~sh\n> echo **bo",
|
||||
);
|
||||
});
|
||||
|
||||
it("maintains incremental stabilizer parity and idempotence across math streaming prefixes", () => {
|
||||
const sample = [
|
||||
"Inline $a * b$ and \\(c_1 + d_2\\).",
|
||||
"",
|
||||
"$$",
|
||||
"x = 1",
|
||||
"",
|
||||
"y = 2",
|
||||
"$$",
|
||||
"",
|
||||
"\\[",
|
||||
"\\int_0^1 x^2\\,dx",
|
||||
"\\]",
|
||||
"",
|
||||
"```math",
|
||||
"\\sum_{i=1}^n i",
|
||||
"```",
|
||||
"",
|
||||
"Done.",
|
||||
].join("\n");
|
||||
|
||||
const incremental = createStreamingMarkdownStabilizer();
|
||||
for (let end = 0; end <= sample.length; end++) {
|
||||
const prefix = sample.slice(0, end);
|
||||
const stabilized = stabilizeStreamingMarkdown(prefix);
|
||||
expect(incremental.stabilize(prefix), `incremental parity at ${end}`).toBe(stabilized);
|
||||
expect(stabilizeStreamingMarkdown(stabilized), `idempotent at ${end}`).toBe(stabilized);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,7 +2,6 @@ import { fromMarkdown } from "mdast-util-from-markdown";
|
||||
import { gfmTable } from "micromark-extension-gfm-table";
|
||||
import { gfmTableFromMarkdown } from "mdast-util-gfm-table";
|
||||
import type { Nodes, Root } from "mdast";
|
||||
import { findBlockMathSpans } from "./math";
|
||||
|
||||
export {
|
||||
createStreamingMarkdownStabilizer,
|
||||
@@ -81,24 +80,12 @@ export function createStreamingMarkdownSplitter(
|
||||
partStarts = [0];
|
||||
return;
|
||||
}
|
||||
const mathSpans = findBlockMathSpans(open);
|
||||
let settled = 0;
|
||||
for (let index = 0; index < tree.children.length - 1; index++) {
|
||||
if (needsDocumentContext(tree.children[index])) break;
|
||||
// mdast starts some nodes after their indentation; the next parser needs it too.
|
||||
const nextStart = tree.children[index + 1].position!.start.offset!;
|
||||
const splitAt = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
let crossesMath = false;
|
||||
let insideUnclosedMath = false;
|
||||
for (const span of mathSpans) {
|
||||
if (splitAt > span.start && splitAt < span.end) {
|
||||
crossesMath = true;
|
||||
if (span.end === Number.POSITIVE_INFINITY) insideUnclosedMath = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (insideUnclosedMath) break;
|
||||
if (!crossesMath) settled = splitAt;
|
||||
settled = open.lastIndexOf("\n", nextStart - 1) + 1;
|
||||
}
|
||||
if (settled === 0) return;
|
||||
if (boundary - partStarts[partStarts.length - 1] >= HEAD_PART_LENGTH) partStarts.push(boundary);
|
||||
|
||||
@@ -103,17 +103,6 @@ export function createMarkdownStyles(
|
||||
inlineImage: { size: paragraph.lineHeight },
|
||||
image: { ...block, height: 320, resizeMode: "contain", borderRadius: 8 },
|
||||
thematicBreak: { ...block, color: theme.colors.border, height: 1 },
|
||||
math: {
|
||||
fontSize,
|
||||
color: paragraph.color,
|
||||
backgroundColor: "transparent",
|
||||
padding: 8,
|
||||
...block,
|
||||
textAlign: "center",
|
||||
},
|
||||
inlineMath: {
|
||||
color: paragraph.color,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -252,13 +252,7 @@ export function SplitContainer({
|
||||
const renderRoot = useMemo(() => wrapRootPaneForStableMount(splitRoot.root), [splitRoot.root]);
|
||||
const panesShareWorkspaceHeader = hasMultipleVisiblePanes(splitRoot.root);
|
||||
const sharedCompactHeader = useMemo(
|
||||
() =>
|
||||
panesShareWorkspaceHeader ? (
|
||||
<WindowChromeSafeArea placement="inline">
|
||||
<TitlebarDragRegion />
|
||||
{renderCompactHeader(null)}
|
||||
</WindowChromeSafeArea>
|
||||
) : null,
|
||||
() => (panesShareWorkspaceHeader ? renderCompactHeader(null) : null),
|
||||
[panesShareWorkspaceHeader, renderCompactHeader],
|
||||
);
|
||||
return (
|
||||
@@ -800,16 +794,13 @@ const SplitPaneView = memo(function SplitPaneView({
|
||||
});
|
||||
const compactHeader = useMemo(
|
||||
() =>
|
||||
ownsWorkspaceHeader ? (
|
||||
<WindowChromeSafeArea placement="inline">
|
||||
<TitlebarDragRegion />
|
||||
{renderCompactHeader({
|
||||
ownsWorkspaceHeader
|
||||
? renderCompactHeader({
|
||||
tabs: paneTabs,
|
||||
activeTabKey: activeTabDescriptor?.key ?? "",
|
||||
actions: compactHeaderActions,
|
||||
})}
|
||||
</WindowChromeSafeArea>
|
||||
) : null,
|
||||
})
|
||||
: null,
|
||||
[
|
||||
ownsWorkspaceHeader,
|
||||
renderCompactHeader,
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from "react";
|
||||
import { StyleSheet, View } from "react-native";
|
||||
import { PortalHost } from "@gorhom/portal";
|
||||
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import {
|
||||
createFloatingPanelHosts,
|
||||
type FloatingPanelHostRect,
|
||||
@@ -57,7 +58,13 @@ export function FloatingPanelPortalHost({
|
||||
}, [name]);
|
||||
|
||||
return (
|
||||
<View ref={hostRef} collapsable={false} pointerEvents="box-none" style={styles.host}>
|
||||
<View
|
||||
ref={hostRef}
|
||||
collapsable={false}
|
||||
dataSet={WINDOW_OVERLAY_HOST_DATASET}
|
||||
pointerEvents="box-none"
|
||||
style={styles.host}
|
||||
>
|
||||
<PortalHost name={name} />
|
||||
</View>
|
||||
);
|
||||
|
||||
@@ -185,6 +185,13 @@ export function ComposerEditingScope({
|
||||
const scope = useMemo(() => ({ tabId, targetKey }), [tabId, targetKey]);
|
||||
return <ScopeContext.Provider value={scope}>{children}</ScopeContext.Provider>;
|
||||
}
|
||||
/**
|
||||
* Composers inside edit in sessions of their own, apart from the workspace tab around them: a
|
||||
* plugin's `AgentChat` in a panel must not share the panel's fullscreen, caret or command target.
|
||||
*/
|
||||
export function LocalComposerEditingScope({ children }: { children: ReactNode }) {
|
||||
return <ScopeContext.Provider value={null}>{children}</ScopeContext.Provider>;
|
||||
}
|
||||
export function useComposerEditingSession(
|
||||
purpose: ComposerInputMode,
|
||||
provided?: ComposerEditingSession,
|
||||
|
||||
@@ -80,6 +80,7 @@ interface SearchCall {
|
||||
}
|
||||
|
||||
interface HarnessInput {
|
||||
enabled?: boolean;
|
||||
initialAttachments?: UserComposerAttachment[];
|
||||
initialCwd?: string;
|
||||
initialText?: string;
|
||||
@@ -137,6 +138,7 @@ function useHarness(client: ForgeSearchClient, input: HarnessInput = {}) {
|
||||
input.initialAttachments ?? [],
|
||||
);
|
||||
const autoAttach = useComposerForgeAutoAttach({
|
||||
enabled: input.enabled ?? true,
|
||||
text,
|
||||
remoteUrl: input.remote ?? remoteUrl,
|
||||
attachments,
|
||||
@@ -190,6 +192,27 @@ describe("useComposerForgeAutoAttach", () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("leaves pasted links as text in a composer that takes no attachments", async () => {
|
||||
vi.useFakeTimers();
|
||||
const client = createSearchClient([pr101]);
|
||||
const onChangeRequestDetected = vi.fn();
|
||||
const { result } = renderHook(
|
||||
() => useHarness(client, { enabled: false, onChangeRequestDetected }),
|
||||
{ wrapper: createWrapper() },
|
||||
);
|
||||
|
||||
act(() => {
|
||||
result.current.setText("Please review https://github.com/acme/paseo/pull/101");
|
||||
});
|
||||
expect(result.current.isResolving).toBe(false);
|
||||
await flushDebounce();
|
||||
|
||||
expect(result.current.attachments).toEqual([]);
|
||||
expect(onChangeRequestDetected).not.toHaveBeenCalled();
|
||||
expect(client.calls).toEqual([]);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it("adds a matching pasted GitLab MR URL as a composer attachment", async () => {
|
||||
vi.useFakeTimers();
|
||||
const client = createSearchClient([gitlabMr73]);
|
||||
|
||||
@@ -19,6 +19,8 @@ import { forgeItemKey } from "./attachments/forge-item-key";
|
||||
const AUTO_ATTACH_DEBOUNCE_MS = 300;
|
||||
|
||||
interface ComposerForgeAutoAttachInput {
|
||||
/** Whether links in the text become attachments: off for a composer that takes none. */
|
||||
enabled: boolean;
|
||||
text: string;
|
||||
remoteUrl: string | null | undefined;
|
||||
attachments: UserComposerAttachment[];
|
||||
@@ -164,6 +166,11 @@ export function useComposerForgeAutoAttach(
|
||||
);
|
||||
}
|
||||
|
||||
/** The forge links in the text that auto-attach would act on. */
|
||||
function linkedForgeRefs(params: ComposerForgeAutoAttachInput): ForgeRef[] {
|
||||
return params.enabled ? extractForgeRefs(params.text, params.remoteUrl) : [];
|
||||
}
|
||||
|
||||
function getLookupCandidateKey(
|
||||
params: ComposerForgeAutoAttachInput,
|
||||
removedRefKeys: ReadonlySet<string>,
|
||||
@@ -175,7 +182,7 @@ function getLookupCandidateRefs(
|
||||
params: ComposerForgeAutoAttachInput,
|
||||
removedRefKeys: ReadonlySet<string>,
|
||||
): ForgeRef[] {
|
||||
return extractForgeRefs(params.text, params.remoteUrl).filter((ref) => {
|
||||
return linkedForgeRefs(params).filter((ref) => {
|
||||
const key = forgeRefKey(ref);
|
||||
return !removedRefKeys.has(key) && !hasForgeAttachment(params.attachments, ref);
|
||||
});
|
||||
@@ -196,7 +203,7 @@ function getLookupRelevanceKey(
|
||||
params: ComposerForgeAutoAttachInput,
|
||||
removedRefKeys: ReadonlySet<string>,
|
||||
): string {
|
||||
return extractForgeRefs(params.text, params.remoteUrl)
|
||||
return linkedForgeRefs(params)
|
||||
.map(forgeRefKey)
|
||||
.filter((key) => !removedRefKeys.has(key))
|
||||
.sort()
|
||||
@@ -204,7 +211,7 @@ function getLookupRelevanceKey(
|
||||
}
|
||||
|
||||
function getPresentChangeRequestKey(params: ComposerForgeAutoAttachInput): string {
|
||||
return extractForgeRefs(params.text, params.remoteUrl)
|
||||
return linkedForgeRefs(params)
|
||||
.filter((ref) => ref.kind === "change_request")
|
||||
.map(forgeRefKey)
|
||||
.sort()
|
||||
@@ -248,7 +255,7 @@ function suppressRefsCarriedAcrossTargets({
|
||||
previousTargetRef.current = { serverId: params.serverId, cwd: params.cwd };
|
||||
if (!targetChanged) return;
|
||||
|
||||
for (const ref of extractForgeRefs(params.text, params.remoteUrl)) {
|
||||
for (const ref of linkedForgeRefs(params)) {
|
||||
removedRefKeys.add(forgeRefKey(ref));
|
||||
}
|
||||
}
|
||||
@@ -261,7 +268,7 @@ function notifyNewChangeRequestRefs({
|
||||
presentChangeRequestKeysRef: RefObject<Set<string>>;
|
||||
}): void {
|
||||
const currentKeys = new Set(
|
||||
extractForgeRefs(params.text, params.remoteUrl)
|
||||
linkedForgeRefs(params)
|
||||
.filter((ref) => ref.kind === "change_request")
|
||||
.map(forgeRefKey),
|
||||
);
|
||||
@@ -449,7 +456,7 @@ function refsReadyForLookup({
|
||||
return [];
|
||||
}
|
||||
|
||||
return extractForgeRefs(params.text, params.remoteUrl).filter((ref) => {
|
||||
return linkedForgeRefs(params).filter((ref) => {
|
||||
const key = forgeRefKey(ref);
|
||||
return (
|
||||
!removedRefKeys.has(key) &&
|
||||
@@ -489,9 +496,7 @@ async function fetchForgeRefSearch({
|
||||
}
|
||||
|
||||
function isRefStillPresent(ref: ForgeRef, params: ComposerForgeAutoAttachInput): boolean {
|
||||
return extractForgeRefs(params.text, params.remoteUrl).some(
|
||||
(candidate) => forgeRefKey(candidate) === forgeRefKey(ref),
|
||||
);
|
||||
return linkedForgeRefs(params).some((candidate) => forgeRefKey(candidate) === forgeRefKey(ref));
|
||||
}
|
||||
|
||||
function isSameLookupTarget(
|
||||
|
||||
@@ -123,7 +123,10 @@ import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
|
||||
import { AutocompletePopover } from "@/components/ui/autocomplete-popover";
|
||||
import type { AutocompleteOption } from "@/components/ui/autocomplete";
|
||||
import { useAgentAutocomplete } from "@/hooks/use-agent-autocomplete";
|
||||
import { usePluginClientSlashCommands } from "@/plugins/client-slash-commands";
|
||||
import {
|
||||
type PluginClientSlashCommand,
|
||||
usePluginClientSlashCommands,
|
||||
} from "@/plugins/client-slash-commands";
|
||||
import {
|
||||
executePluginClientSlashCommand,
|
||||
resolvePluginClientSlashCommand,
|
||||
@@ -226,6 +229,7 @@ type AttachmentListUpdater =
|
||||
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
|
||||
|
||||
const EMPTY_ATTACHMENT_SCOPE_KEYS: readonly string[] = [];
|
||||
const NO_PLUGIN_CLIENT_SLASH_COMMANDS: PluginClientSlashCommand[] = [];
|
||||
|
||||
function noop() {}
|
||||
const noopCallback = () => {};
|
||||
@@ -1402,6 +1406,8 @@ function ComposerContentImpl({
|
||||
const [isForgeResolving, setIsForgeResolving] = useState(false);
|
||||
const forgeConfiguration = useMemo(
|
||||
() => ({
|
||||
// A mode without attachments sends text as written, so links stay text.
|
||||
enabled: mode.showAttachments,
|
||||
remoteUrl: resolveCheckoutRemoteUrl(checkoutStatusQuery.status),
|
||||
attachments,
|
||||
client,
|
||||
@@ -1414,6 +1420,7 @@ function ComposerContentImpl({
|
||||
onChangeRequestAdded: onForgeChangeRequestAutoAttach,
|
||||
}),
|
||||
[
|
||||
mode.showAttachments,
|
||||
checkoutStatusQuery.status,
|
||||
attachments,
|
||||
client,
|
||||
@@ -1456,11 +1463,16 @@ function ComposerContentImpl({
|
||||
onChangeAttachments: setSelectedAttachments,
|
||||
anchorRef: attachButtonRef,
|
||||
});
|
||||
const pluginClientSlashCommands = usePluginClientSlashCommands({
|
||||
const installedPluginClientSlashCommands = usePluginClientSlashCommands({
|
||||
serverId,
|
||||
workspaceId,
|
||||
agentId,
|
||||
});
|
||||
// One switch for every client-side command, built-in or plugin, on the send and queue paths.
|
||||
const handlesClientCommands = mode.runsClientCommands;
|
||||
const pluginClientSlashCommands = handlesClientCommands
|
||||
? installedPluginClientSlashCommands
|
||||
: NO_PLUGIN_CLIENT_SLASH_COMMANDS;
|
||||
const isComposerLocked = resolveIsComposerLocked(submitBehavior, isSubmitLoading);
|
||||
const keyboardHandlerIdRef = useRef(
|
||||
`message-input:${serverId}:${agentId}:${Math.random().toString(36).slice(2)}`,
|
||||
@@ -1569,6 +1581,7 @@ function ComposerContentImpl({
|
||||
|
||||
const runClientSlashCommand = useCallback(
|
||||
(command: ClientSlashCommand): boolean => {
|
||||
if (!handlesClientCommands) return false;
|
||||
if (command.execution !== "immediate" || !onClientSlashCommand) {
|
||||
return false;
|
||||
}
|
||||
@@ -1595,6 +1608,7 @@ function ComposerContentImpl({
|
||||
[
|
||||
blurOnSubmit,
|
||||
clearDraft,
|
||||
handlesClientCommands,
|
||||
onClientSlashCommand,
|
||||
resetSuppression,
|
||||
setSelectedAttachments,
|
||||
@@ -1631,6 +1645,22 @@ function ComposerContentImpl({
|
||||
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
|
||||
);
|
||||
|
||||
/** Runs `text` as a client command when it is one; false sends it to the agent. */
|
||||
const runComposerClientCommand = useCallback(
|
||||
(text: string, hasAttachments: boolean): boolean => {
|
||||
const clientSlashCommand = resolveClientSlashCommand({ text, hasAttachments });
|
||||
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) return true;
|
||||
const pluginSlashCommand = resolvePluginClientSlashCommand({
|
||||
text,
|
||||
commands: pluginClientSlashCommands,
|
||||
});
|
||||
if (!pluginSlashCommand) return false;
|
||||
runPluginClientSlashCommand(pluginSlashCommand, hasAttachments);
|
||||
return true;
|
||||
},
|
||||
[pluginClientSlashCommands, runClientSlashCommand, runPluginClientSlashCommand],
|
||||
);
|
||||
|
||||
const { pickImages } = useImageAttachmentPicker();
|
||||
const { pickFiles } = useFilePicker();
|
||||
const agentIdRef = useRef(agentId);
|
||||
@@ -1923,21 +1953,7 @@ function ComposerContentImpl({
|
||||
const handleSubmit = useCallback(
|
||||
(payload: MessagePayload) => {
|
||||
const outgoingAttachments = buildOutgoingAttachments(attachments);
|
||||
const clientSlashCommand = resolveClientSlashCommand({
|
||||
text: payload.text,
|
||||
hasAttachments: outgoingAttachments.length > 0,
|
||||
});
|
||||
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) {
|
||||
return;
|
||||
}
|
||||
const pluginSlashCommand = resolvePluginClientSlashCommand({
|
||||
text: payload.text,
|
||||
commands: pluginClientSlashCommands,
|
||||
});
|
||||
if (pluginSlashCommand) {
|
||||
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
|
||||
return;
|
||||
}
|
||||
if (runComposerClientCommand(payload.text, outgoingAttachments.length > 0)) return;
|
||||
|
||||
if (blurOnSubmit) {
|
||||
messageInputRef.current?.blur();
|
||||
@@ -1948,9 +1964,7 @@ function ComposerContentImpl({
|
||||
attachments,
|
||||
blurOnSubmit,
|
||||
buildOutgoingAttachments,
|
||||
runClientSlashCommand,
|
||||
pluginClientSlashCommands,
|
||||
runPluginClientSlashCommand,
|
||||
runComposerClientCommand,
|
||||
sendMessageWithContent,
|
||||
],
|
||||
);
|
||||
@@ -2191,31 +2205,10 @@ function ComposerContentImpl({
|
||||
const handleQueue = useCallback(
|
||||
(payload: MessagePayload) => {
|
||||
const outgoingAttachments = buildOutgoingAttachments(attachments);
|
||||
const clientSlashCommand = resolveClientSlashCommand({
|
||||
text: payload.text,
|
||||
hasAttachments: outgoingAttachments.length > 0,
|
||||
});
|
||||
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) {
|
||||
return;
|
||||
}
|
||||
const pluginSlashCommand = resolvePluginClientSlashCommand({
|
||||
text: payload.text,
|
||||
commands: pluginClientSlashCommands,
|
||||
});
|
||||
if (pluginSlashCommand) {
|
||||
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
|
||||
return;
|
||||
}
|
||||
if (runComposerClientCommand(payload.text, outgoingAttachments.length > 0)) return;
|
||||
void sendMessageWithContent(payload.text, outgoingAttachments);
|
||||
},
|
||||
[
|
||||
attachments,
|
||||
buildOutgoingAttachments,
|
||||
pluginClientSlashCommands,
|
||||
runClientSlashCommand,
|
||||
runPluginClientSlashCommand,
|
||||
sendMessageWithContent,
|
||||
],
|
||||
[attachments, buildOutgoingAttachments, runComposerClientCommand, sendMessageWithContent],
|
||||
);
|
||||
|
||||
// An open autocomplete owns the arrows; otherwise they may recall sent messages.
|
||||
@@ -2305,9 +2298,10 @@ function ComposerContentImpl({
|
||||
],
|
||||
);
|
||||
|
||||
const showsUsage = mode.showUsage;
|
||||
const beforeVoiceContent = useMemo(
|
||||
() =>
|
||||
hasAgent ? (
|
||||
hasAgent && showsUsage ? (
|
||||
<View style={styles.contextWindowMeterSlot}>
|
||||
<ContextWindowMeter
|
||||
serverId={serverId}
|
||||
@@ -2322,6 +2316,7 @@ function ComposerContentImpl({
|
||||
) : null,
|
||||
[
|
||||
hasAgent,
|
||||
showsUsage,
|
||||
serverId,
|
||||
agentId,
|
||||
agentState.contextWindowMaxTokens,
|
||||
@@ -2615,7 +2610,8 @@ function ComposerContentImpl({
|
||||
onGenericFiles: handleGenericFilesDropped,
|
||||
onWorkspaceFile: handleWorkspaceFileDropped,
|
||||
},
|
||||
{ disabled: isSubmitLoadingVisible },
|
||||
// A mode without attachments refuses files by any route, not only the button.
|
||||
{ disabled: isSubmitLoadingVisible || !mode.showAttachments },
|
||||
);
|
||||
|
||||
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
|
||||
@@ -2713,9 +2709,9 @@ function ComposerContentImpl({
|
||||
cwd={cwd}
|
||||
attachmentMenuItems={attachmentMenuItems}
|
||||
onAttachButtonRef={handleAttachButtonRef}
|
||||
onAddImages={addImages}
|
||||
onPasteFiles={handlePasteFiles}
|
||||
onPasteImages={handleNativePasteImages}
|
||||
onAddImages={mode.showAttachments ? addImages : undefined}
|
||||
onPasteFiles={mode.showAttachments ? handlePasteFiles : undefined}
|
||||
onPasteImages={mode.showAttachments ? handleNativePasteImages : undefined}
|
||||
client={client}
|
||||
isReadyForDictation={isDictationReady}
|
||||
placeholder={messagePlaceholder}
|
||||
|
||||
@@ -1,13 +1,16 @@
|
||||
/**
|
||||
* What a composer is being used for. `Composer` and `MessageInput` are one
|
||||
* component with two jobs, not two components: a terminal prompt still wants
|
||||
* component with several jobs, not several components: a terminal prompt still wants
|
||||
* the same bordered surface, grow-on-newline, submit button, focus handling,
|
||||
* and keyboard shift that a chat message gets.
|
||||
*
|
||||
* `message` is a chat composer reduced to a text box and Send: what the user types
|
||||
* reaches the agent as written, with nothing the app interprets on the way.
|
||||
*
|
||||
* Callers pick a mode and nothing else. What a mode implies lives here, so the
|
||||
* two presentations cannot drift apart one prop at a time.
|
||||
* presentations cannot drift apart one prop at a time.
|
||||
*/
|
||||
export type ComposerInputMode = "chat" | "terminal";
|
||||
export type ComposerInputMode = "chat" | "message" | "terminal";
|
||||
|
||||
export interface ComposerInputModePresentation {
|
||||
/** Attachments, dictation/voice, slash-and-@ autocomplete, and the model/mode
|
||||
@@ -16,6 +19,11 @@ export interface ComposerInputModePresentation {
|
||||
showVoice: boolean;
|
||||
showAutocomplete: boolean;
|
||||
showAgentControls: boolean;
|
||||
/** The context window and cost meter beside Send. */
|
||||
showUsage: boolean;
|
||||
/** Client slash commands, built-in (`/exit`, `/clear`) and plugin, run in the
|
||||
* app instead of being sent. */
|
||||
runsClientCommands: boolean;
|
||||
/** Argv is read character by character, so it gets the terminal's own font. */
|
||||
isMonospace: boolean;
|
||||
/** i18n key for the text input's accessible name. */
|
||||
@@ -28,6 +36,18 @@ const PRESENTATION_BY_MODE: Record<ComposerInputMode, ComposerInputModePresentat
|
||||
showVoice: true,
|
||||
showAutocomplete: true,
|
||||
showAgentControls: true,
|
||||
showUsage: true,
|
||||
runsClientCommands: true,
|
||||
isMonospace: false,
|
||||
accessibilityLabelKey: "composer.input.accessibilityLabel",
|
||||
},
|
||||
message: {
|
||||
showAttachments: false,
|
||||
showVoice: false,
|
||||
showAutocomplete: false,
|
||||
showAgentControls: false,
|
||||
showUsage: false,
|
||||
runsClientCommands: false,
|
||||
isMonospace: false,
|
||||
accessibilityLabelKey: "composer.input.accessibilityLabel",
|
||||
},
|
||||
@@ -36,6 +56,8 @@ const PRESENTATION_BY_MODE: Record<ComposerInputMode, ComposerInputModePresentat
|
||||
showVoice: false,
|
||||
showAutocomplete: false,
|
||||
showAgentControls: false,
|
||||
showUsage: false,
|
||||
runsClientCommands: true,
|
||||
isMonospace: true,
|
||||
accessibilityLabelKey: "composer.input.terminalAccessibilityLabel",
|
||||
},
|
||||
|
||||
@@ -257,6 +257,8 @@ export interface DesktopInvokeBridge {
|
||||
|
||||
export interface DesktopHostBridge {
|
||||
platform?: string;
|
||||
deviceName?: string;
|
||||
osVersion?: string;
|
||||
windowChromeMode?: string;
|
||||
browserHostLabel?: string;
|
||||
browserHostInstanceId?: string;
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
|
||||
export interface AppClientIdentity {
|
||||
clientType: "mobile" | "browser";
|
||||
clientInfo: HelloClientInfo;
|
||||
}
|
||||
|
||||
export interface DesktopIdentityInput {
|
||||
platform?: string;
|
||||
deviceName?: string;
|
||||
osVersion?: string;
|
||||
browserHostLabel?: string;
|
||||
}
|
||||
|
||||
export interface WebNavigatorUserAgentData {
|
||||
platform?: string;
|
||||
brands?: ReadonlyArray<{ brand: string; version?: string }>;
|
||||
}
|
||||
|
||||
export interface WebIdentityInput {
|
||||
userAgent?: string;
|
||||
userAgentData?: WebNavigatorUserAgentData;
|
||||
}
|
||||
|
||||
export interface NativePlatformConstantsInput {
|
||||
Model?: string;
|
||||
Manufacturer?: string;
|
||||
Brand?: string;
|
||||
Release?: string;
|
||||
systemName?: string;
|
||||
osVersion?: string;
|
||||
interfaceIdiom?: string;
|
||||
}
|
||||
|
||||
export interface NativeIdentityInput {
|
||||
os: string;
|
||||
version?: string | number;
|
||||
constants?: NativePlatformConstantsInput;
|
||||
deviceName?: string | null;
|
||||
}
|
||||
|
||||
const LEGACY_WINDOW_SUFFIX_PATTERN = /\s*·\s*Window\s+\d+(?:\s*\([0-9A-Fa-f]+\))?$/;
|
||||
|
||||
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
|
||||
const normalized = raw?.toLowerCase();
|
||||
if (normalized === "darwin" || normalized === "macos") return "macos";
|
||||
if (normalized === "linux") return "linux";
|
||||
if (normalized === "win32" || normalized === "windows") return "windows";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function osNameForDesktopPlatform(platform: HelloClientPlatform): string | undefined {
|
||||
if (platform === "macos") return "macOS";
|
||||
if (platform === "linux") return "Linux";
|
||||
if (platform === "windows") return "Windows";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function normalizeNonEmpty(
|
||||
value: string | null | undefined,
|
||||
maxLength: number,
|
||||
): string | undefined {
|
||||
const trimmed = value?.trim();
|
||||
return trimmed ? trimmed.slice(0, maxLength) : undefined;
|
||||
}
|
||||
|
||||
function cleanDesktopName(desktop: DesktopIdentityInput): string | undefined {
|
||||
const explicit = normalizeNonEmpty(desktop.deviceName, 128);
|
||||
if (explicit) return explicit;
|
||||
// COMPAT(legacyBrowserHostLabel): added in v0.19.x, strip window suffix from older Electron preloads without --paseo-device-name; remove after 2027-06-15.
|
||||
const stripped = desktop.browserHostLabel?.replace(LEGACY_WINDOW_SUFFIX_PATTERN, "").trim();
|
||||
return stripped ? stripped.slice(0, 128) : undefined;
|
||||
}
|
||||
|
||||
export function resolveDesktopClientIdentity(desktop: DesktopIdentityInput): AppClientIdentity {
|
||||
const platform = mapDesktopPlatform(desktop.platform);
|
||||
const osName = osNameForDesktopPlatform(platform);
|
||||
const name = cleanDesktopName(desktop);
|
||||
const osVersion = normalizeNonEmpty(desktop.osVersion, 48);
|
||||
|
||||
return {
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "desktop",
|
||||
platform,
|
||||
...(name ? { name } : {}),
|
||||
...(osName ? { osName } : {}),
|
||||
...(osVersion ? { osVersion } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function parseBrowserNameFromBrands(
|
||||
brands: ReadonlyArray<{ brand: string; version?: string }> | undefined,
|
||||
): string | undefined {
|
||||
if (!brands || brands.length === 0) return undefined;
|
||||
const names = brands.map((entry) => entry.brand);
|
||||
if (names.some((brand) => /Microsoft Edge/i.test(brand))) return "Edge";
|
||||
if (names.some((brand) => /Opera/i.test(brand))) return "Opera";
|
||||
if (names.some((brand) => /Brave/i.test(brand))) return "Brave";
|
||||
if (names.some((brand) => /Google Chrome/i.test(brand))) return "Chrome";
|
||||
if (names.some((brand) => /Chromium/i.test(brand))) return "Chrome";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parseBrowserNameFromUserAgent(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) return undefined;
|
||||
if (/Edg(?:A|iOS)?\//.test(userAgent)) return "Edge";
|
||||
if (/OPR\//.test(userAgent)) return "Opera";
|
||||
if (/(?:Firefox|FxiOS)\//.test(userAgent)) return "Firefox";
|
||||
if (/(?:Chrome|CriOS)\//.test(userAgent) && !/Edg(?:A|iOS)?\//.test(userAgent)) return "Chrome";
|
||||
if (/Safari\//.test(userAgent) && !/(?:Chrome|CriOS)\//.test(userAgent)) return "Safari";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parseOsNameFromPlatformHint(platform: string | undefined): string | undefined {
|
||||
if (!platform) return undefined;
|
||||
const normalized = platform.trim().toLowerCase();
|
||||
if (normalized === "macos" || normalized === "mac os" || normalized === "macintel")
|
||||
return "macOS";
|
||||
if (normalized === "windows" || normalized === "win32") return "Windows";
|
||||
if (normalized === "linux") return "Linux";
|
||||
if (normalized === "android") return "Android";
|
||||
if (normalized === "ios") return "iOS";
|
||||
if (normalized === "chrome os" || normalized === "chromeos") return "ChromeOS";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function parseOsNameFromUserAgent(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) return undefined;
|
||||
if (/iPhone|iPad|iPod/.test(userAgent)) return "iOS";
|
||||
if (/Android/.test(userAgent)) return "Android";
|
||||
if (/CrOS/.test(userAgent)) return "ChromeOS";
|
||||
if (/Windows NT|Win64|WOW64/.test(userAgent)) return "Windows";
|
||||
if (/Macintosh|Mac OS X/.test(userAgent)) return "macOS";
|
||||
if (/Linux|X11/.test(userAgent)) return "Linux";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolveWebClientIdentity(input: WebIdentityInput): AppClientIdentity {
|
||||
const browserName =
|
||||
parseBrowserNameFromBrands(input.userAgentData?.brands) ??
|
||||
parseBrowserNameFromUserAgent(input.userAgent);
|
||||
const osName =
|
||||
parseOsNameFromPlatformHint(input.userAgentData?.platform) ??
|
||||
parseOsNameFromUserAgent(input.userAgent);
|
||||
const name = browserName && osName ? `${browserName} on ${osName}` : browserName;
|
||||
|
||||
return {
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "web",
|
||||
platform: "web",
|
||||
...(name ? { name: name.slice(0, 128) } : {}),
|
||||
...(browserName ? { browserName: browserName.slice(0, 48) } : {}),
|
||||
...(osName ? { osName: osName.slice(0, 48) } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function cleanAndroidModel(
|
||||
manufacturer: string | undefined,
|
||||
model: string | undefined,
|
||||
): string | undefined {
|
||||
const cleanModel = model?.trim();
|
||||
if (!cleanModel) return undefined;
|
||||
const cleanManufacturer = manufacturer?.trim();
|
||||
if (
|
||||
!cleanManufacturer ||
|
||||
cleanModel.toLowerCase().startsWith(cleanManufacturer.toLowerCase()) ||
|
||||
cleanModel.toLowerCase().startsWith("pixel")
|
||||
) {
|
||||
return cleanModel.slice(0, 96);
|
||||
}
|
||||
const formattedManufacturer =
|
||||
cleanManufacturer === cleanManufacturer.toLowerCase()
|
||||
? `${cleanManufacturer[0]?.toUpperCase() ?? ""}${cleanManufacturer.slice(1)}`
|
||||
: cleanManufacturer;
|
||||
return `${formattedManufacturer} ${cleanModel}`.slice(0, 96);
|
||||
}
|
||||
|
||||
function resolveAndroidClientIdentity(
|
||||
input: NativeIdentityInput,
|
||||
explicitName: string | undefined,
|
||||
): AppClientIdentity {
|
||||
const constants = input.constants;
|
||||
const deviceModel = cleanAndroidModel(
|
||||
constants?.Manufacturer ?? constants?.Brand,
|
||||
constants?.Model,
|
||||
);
|
||||
const rawVersion =
|
||||
constants?.Release ?? (input.version !== undefined ? String(input.version) : undefined);
|
||||
const osVersion = normalizeNonEmpty(rawVersion, 48);
|
||||
const name = explicitName ?? deviceModel;
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
appKind: "mobile",
|
||||
platform: "android",
|
||||
osName: "Android",
|
||||
...(osVersion ? { osVersion } : {}),
|
||||
...(deviceModel ? { deviceModel } : {}),
|
||||
...(name ? { name } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resolveIosClientIdentity(
|
||||
input: NativeIdentityInput,
|
||||
explicitName: string | undefined,
|
||||
): AppClientIdentity {
|
||||
const constants = input.constants;
|
||||
const isPad = constants?.interfaceIdiom === "pad";
|
||||
const deviceModel = isPad ? "iPad" : "iPhone";
|
||||
const osName = normalizeNonEmpty(constants?.systemName, 48) ?? (isPad ? "iPadOS" : "iOS");
|
||||
const rawVersion =
|
||||
constants?.osVersion ?? (input.version !== undefined ? String(input.version) : undefined);
|
||||
const osVersion = normalizeNonEmpty(rawVersion, 48);
|
||||
const name = explicitName ?? deviceModel;
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
appKind: "mobile",
|
||||
platform: "ios",
|
||||
osName,
|
||||
...(osVersion ? { osVersion } : {}),
|
||||
deviceModel,
|
||||
...(name ? { name } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveNativeClientIdentity(input: NativeIdentityInput): AppClientIdentity {
|
||||
const explicitName = normalizeNonEmpty(input.deviceName, 128);
|
||||
if (input.os === "android") {
|
||||
return resolveAndroidClientIdentity(input, explicitName);
|
||||
}
|
||||
if (input.os === "ios") {
|
||||
return resolveIosClientIdentity(input, explicitName);
|
||||
}
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
appKind: "mobile",
|
||||
platform: "unknown",
|
||||
...(explicitName ? { name: explicitName } : {}),
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,23 +1,16 @@
|
||||
import Constants from "expo-constants";
|
||||
import { Platform } from "react-native";
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
import {
|
||||
resolveNativeClientIdentity,
|
||||
type AppClientIdentity,
|
||||
type NativePlatformConstantsInput,
|
||||
} from "./client-info-parsers";
|
||||
|
||||
function mapNativePlatform(os: string): HelloClientPlatform {
|
||||
if (os === "ios") return "ios";
|
||||
if (os === "android") return "android";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
export function resolveAppClientIdentity(): {
|
||||
clientType: "mobile" | "browser";
|
||||
clientInfo: HelloClientInfo;
|
||||
} {
|
||||
const deviceName = Constants.deviceName?.trim();
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
platform: mapNativePlatform(Platform.OS),
|
||||
...(deviceName ? { name: deviceName.slice(0, 128) } : {}),
|
||||
},
|
||||
};
|
||||
export function resolveAppClientIdentity(): AppClientIdentity {
|
||||
return resolveNativeClientIdentity({
|
||||
os: Platform.OS,
|
||||
version: Platform.Version,
|
||||
constants: Platform.constants as NativePlatformConstantsInput | undefined,
|
||||
deviceName: Constants.deviceName,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveAppClientIdentity } from "./client-info";
|
||||
import { resolveNativeClientIdentity } from "./client-info-parsers";
|
||||
|
||||
describe("resolveAppClientIdentity (Electron and Web)", () => {
|
||||
it("identifies Electron Desktop on macOS, Linux, and Windows with clean deviceName and osVersion", () => {
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: {
|
||||
platform: "darwin",
|
||||
deviceName: "MacBook Pro",
|
||||
osVersion: "15.3.1",
|
||||
browserHostLabel: "MacBook Pro · Window 1 (ABCDEF)",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "desktop",
|
||||
platform: "macos",
|
||||
name: "MacBook Pro",
|
||||
osName: "macOS",
|
||||
osVersion: "15.3.1",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: {
|
||||
platform: "linux",
|
||||
deviceName: "workstation",
|
||||
osVersion: "Ubuntu 24.04.1 LTS",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "desktop",
|
||||
platform: "linux",
|
||||
name: "workstation",
|
||||
osName: "Linux",
|
||||
osVersion: "Ubuntu 24.04.1 LTS",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: {
|
||||
platform: "win32",
|
||||
deviceName: "DEV-PC",
|
||||
osVersion: "10.0.22631",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "desktop",
|
||||
platform: "windows",
|
||||
name: "DEV-PC",
|
||||
osName: "Windows",
|
||||
osVersion: "10.0.22631",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("strips legacy Window N (HEX) suffix if older Electron preload only provides browserHostLabel", () => {
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: {
|
||||
platform: "linux",
|
||||
browserHostLabel: "devbox · Window 2 (9F0A1B)",
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "desktop",
|
||||
platform: "linux",
|
||||
name: "devbox",
|
||||
osName: "Linux",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("identifies web browsers and operating systems from userAgent and userAgentData", () => {
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: null,
|
||||
userAgent:
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "web",
|
||||
platform: "web",
|
||||
browserName: "Chrome",
|
||||
osName: "macOS",
|
||||
name: "Chrome on macOS",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: null,
|
||||
userAgent:
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "web",
|
||||
platform: "web",
|
||||
browserName: "Firefox",
|
||||
osName: "Windows",
|
||||
name: "Firefox on Windows",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: null,
|
||||
userAgent:
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15",
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "web",
|
||||
platform: "web",
|
||||
browserName: "Safari",
|
||||
osName: "macOS",
|
||||
name: "Safari on macOS",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveAppClientIdentity({
|
||||
desktop: null,
|
||||
userAgent:
|
||||
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
|
||||
userAgentData: {
|
||||
platform: "Linux",
|
||||
brands: [{ brand: "Microsoft Edge", version: "131" }],
|
||||
},
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "web",
|
||||
platform: "web",
|
||||
browserName: "Edge",
|
||||
osName: "Linux",
|
||||
name: "Edge on Linux",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveNativeClientIdentity (Android and iOS)", () => {
|
||||
it("extracts Android model, manufacturer, and release from RN Platform.constants", () => {
|
||||
expect(
|
||||
resolveNativeClientIdentity({
|
||||
os: "android",
|
||||
constants: {
|
||||
Manufacturer: "Google",
|
||||
Model: "Pixel 9 Pro",
|
||||
Release: "15",
|
||||
},
|
||||
deviceName: undefined,
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
appKind: "mobile",
|
||||
platform: "android",
|
||||
osName: "Android",
|
||||
osVersion: "15",
|
||||
deviceModel: "Pixel 9 Pro",
|
||||
name: "Pixel 9 Pro",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveNativeClientIdentity({
|
||||
os: "android",
|
||||
constants: {
|
||||
Manufacturer: "samsung",
|
||||
Model: "SM-S928B",
|
||||
Release: "14",
|
||||
},
|
||||
deviceName: "Mo's Galaxy",
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
appKind: "mobile",
|
||||
platform: "android",
|
||||
osName: "Android",
|
||||
osVersion: "14",
|
||||
deviceModel: "Samsung SM-S928B",
|
||||
name: "Mo's Galaxy",
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts iOS and iPadOS metadata from RN Platform.constants", () => {
|
||||
expect(
|
||||
resolveNativeClientIdentity({
|
||||
os: "ios",
|
||||
constants: {
|
||||
systemName: "iOS",
|
||||
osVersion: "18.3",
|
||||
interfaceIdiom: "phone",
|
||||
},
|
||||
deviceName: "iPhone",
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
appKind: "mobile",
|
||||
platform: "ios",
|
||||
osName: "iOS",
|
||||
osVersion: "18.3",
|
||||
deviceModel: "iPhone",
|
||||
name: "iPhone",
|
||||
},
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveNativeClientIdentity({
|
||||
os: "ios",
|
||||
constants: {
|
||||
systemName: "iPadOS",
|
||||
osVersion: "18.3",
|
||||
interfaceIdiom: "pad",
|
||||
},
|
||||
deviceName: undefined,
|
||||
}),
|
||||
).toEqual({
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
appKind: "mobile",
|
||||
platform: "ios",
|
||||
osName: "iPadOS",
|
||||
osVersion: "18.3",
|
||||
deviceModel: "iPad",
|
||||
name: "iPad",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,47 +1,48 @@
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
import { getIsElectron } from "@/constants/platform";
|
||||
import { getDesktopHost } from "@/desktop/host";
|
||||
import {
|
||||
resolveDesktopClientIdentity,
|
||||
resolveWebClientIdentity,
|
||||
type AppClientIdentity,
|
||||
type DesktopIdentityInput,
|
||||
type WebNavigatorUserAgentData,
|
||||
} from "./client-info-parsers";
|
||||
|
||||
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
|
||||
const normalized = raw?.toLowerCase();
|
||||
if (normalized === "darwin" || normalized === "macos") return "macos";
|
||||
if (normalized === "linux") return "linux";
|
||||
if (normalized === "win32" || normalized === "windows") return "windows";
|
||||
return "unknown";
|
||||
interface WebRuntimeEnv {
|
||||
desktop?: DesktopIdentityInput | null;
|
||||
userAgent?: string;
|
||||
userAgentData?: WebNavigatorUserAgentData;
|
||||
}
|
||||
|
||||
function parseBrowserName(userAgent: string | undefined): string | undefined {
|
||||
if (!userAgent) return undefined;
|
||||
if (/Edg\//.test(userAgent)) return "Edge";
|
||||
if (/Firefox\//.test(userAgent)) return "Firefox";
|
||||
if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) return "Chrome";
|
||||
if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) return "Safari";
|
||||
return undefined;
|
||||
function readNavigatorUserAgentData(): WebNavigatorUserAgentData | undefined {
|
||||
if (typeof navigator === "undefined") return undefined;
|
||||
const candidate = (navigator as Navigator & { userAgentData?: WebNavigatorUserAgentData })
|
||||
.userAgentData;
|
||||
return candidate && typeof candidate === "object" ? candidate : undefined;
|
||||
}
|
||||
|
||||
export function resolveAppClientIdentity(): {
|
||||
clientType: "mobile" | "browser";
|
||||
clientInfo: HelloClientInfo;
|
||||
} {
|
||||
if (getIsElectron()) {
|
||||
const desktop = getDesktopHost();
|
||||
const label = desktop?.browserHostLabel?.trim();
|
||||
return {
|
||||
clientType: "mobile",
|
||||
clientInfo: {
|
||||
platform: mapDesktopPlatform(desktop?.platform),
|
||||
...(label ? { name: label.slice(0, 128) } : {}),
|
||||
},
|
||||
};
|
||||
function resolveDesktopInput(env?: WebRuntimeEnv): DesktopIdentityInput | null {
|
||||
if (env && "desktop" in env) {
|
||||
return env.desktop ?? null;
|
||||
}
|
||||
return getIsElectron() ? getDesktopHost() : null;
|
||||
}
|
||||
|
||||
function resolveUserAgentInput(env?: WebRuntimeEnv): string | undefined {
|
||||
if (env && "userAgent" in env) {
|
||||
return env.userAgent;
|
||||
}
|
||||
return typeof navigator !== "undefined" ? navigator.userAgent : undefined;
|
||||
}
|
||||
|
||||
export function resolveAppClientIdentity(env?: WebRuntimeEnv): AppClientIdentity {
|
||||
const desktop = resolveDesktopInput(env);
|
||||
if (desktop) {
|
||||
return resolveDesktopClientIdentity(desktop);
|
||||
}
|
||||
|
||||
const browserName =
|
||||
typeof navigator !== "undefined" ? parseBrowserName(navigator.userAgent) : undefined;
|
||||
return {
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
platform: "web",
|
||||
...(browserName ? { name: browserName } : {}),
|
||||
},
|
||||
};
|
||||
return resolveWebClientIdentity({
|
||||
userAgent: resolveUserAgentInput(env),
|
||||
userAgentData: env && "userAgentData" in env ? env.userAgentData : readNavigatorUserAgentData(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -6,8 +6,6 @@ import type { TFunction } from "i18next";
|
||||
import type {
|
||||
DaemonClientsSnapshot,
|
||||
DaemonSessionSummary,
|
||||
DaemonSessionTransport,
|
||||
WSClientType,
|
||||
} from "@getpaseo/protocol/daemon-clients";
|
||||
import type { DaemonPermission } from "@getpaseo/protocol/messages";
|
||||
import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts";
|
||||
@@ -21,10 +19,19 @@ import {
|
||||
import { StatusBadge } from "@/components/ui/status-badge";
|
||||
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
|
||||
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
|
||||
import {
|
||||
formatAppDetail,
|
||||
formatAuthMethodLabel,
|
||||
formatDeviceDetail,
|
||||
formatSessionHint,
|
||||
formatSessionTitle,
|
||||
formatTransportLabel,
|
||||
} from "./device-display";
|
||||
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
|
||||
import { DaemonPasswordSheet } from "./daemon-password-sheet";
|
||||
|
||||
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
|
||||
const RELATIVE_TIME_REFRESH_MS = 60_000;
|
||||
|
||||
type StatusDotTone = "online" | "warning" | "error" | "offline";
|
||||
|
||||
@@ -51,6 +58,17 @@ const STATUS_DOTS: Record<StatusDotTone, React.ReactNode> = {
|
||||
offline: <StatusDot tone="offline" />,
|
||||
};
|
||||
|
||||
function useMinuteTick(): number {
|
||||
const [nowMs, setNowMs] = useState(() => Date.now());
|
||||
useEffect(() => {
|
||||
const timer = setInterval(() => {
|
||||
setNowMs(Date.now());
|
||||
}, RELATIVE_TIME_REFRESH_MS);
|
||||
return () => clearInterval(timer);
|
||||
}, []);
|
||||
return nowMs;
|
||||
}
|
||||
|
||||
function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[]; t: TFunction }) {
|
||||
const summary = summarizePermissions(permissions);
|
||||
let label: string;
|
||||
@@ -66,15 +84,23 @@ function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[
|
||||
return <StatusBadge label={label} variant="muted" size="xs" />;
|
||||
}
|
||||
|
||||
function PermissionPillsRow({
|
||||
function AccessDetailRow({
|
||||
permissions,
|
||||
t,
|
||||
}: {
|
||||
permissions: readonly DaemonPermission[];
|
||||
t: TFunction;
|
||||
}) {
|
||||
const summary = summarizePermissions(permissions);
|
||||
if (summary.kind === "full") {
|
||||
return (
|
||||
<SettingsRow label={t("devices.details.access")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.scopes.fullAccess")}</Text>
|
||||
</SettingsRow>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<SettingsRow label={t("devices.details.permissions")}>
|
||||
<SettingsRow label={t("devices.details.access")}>
|
||||
<View style={styles.scopePills}>
|
||||
{permissions.length > 0 ? (
|
||||
permissions.map((permission) => (
|
||||
@@ -88,9 +114,13 @@ function PermissionPillsRow({
|
||||
);
|
||||
}
|
||||
|
||||
function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFunction): string | null {
|
||||
function formatDurationLabel(
|
||||
isoTimestamp: string | null | undefined,
|
||||
nowMs: number,
|
||||
t: TFunction,
|
||||
): string | null {
|
||||
if (!isoTimestamp) return null;
|
||||
const duration = formatConnectedDuration(isoTimestamp);
|
||||
const duration = formatConnectedDuration(isoTimestamp, nowMs);
|
||||
if (!duration) return null;
|
||||
if (duration.kind === "just_now") return t("devices.time.justNow");
|
||||
if (duration.kind === "minutes") return t("devices.time.minutesAgo", { count: duration.count });
|
||||
@@ -98,77 +128,26 @@ function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFuncti
|
||||
return t("devices.time.daysAgo", { count: duration.count });
|
||||
}
|
||||
|
||||
function formatTransportLabel(
|
||||
transport: DaemonSessionTransport,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
switch (transport) {
|
||||
case "local_ipc":
|
||||
case "local":
|
||||
return t("devices.transport.local");
|
||||
case "tailscale":
|
||||
return t("devices.transport.tailscale");
|
||||
case "relay":
|
||||
return t("devices.transport.relay");
|
||||
case "hub":
|
||||
return t("devices.transport.hub");
|
||||
case "via":
|
||||
return viaHostName
|
||||
? t("devices.transport.via", { host: viaHostName })
|
||||
: t("devices.transport.viaHost");
|
||||
case "direct":
|
||||
return t("devices.transport.direct");
|
||||
}
|
||||
}
|
||||
|
||||
function formatClientPlatformLabel(
|
||||
clientType: WSClientType,
|
||||
platform: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
if (platform === "ios") return "iOS";
|
||||
if (platform === "android") return "Android";
|
||||
if (platform === "macos" || platform === "linux" || platform === "windows") {
|
||||
return t("devices.kind.desktop");
|
||||
}
|
||||
if (clientType === "browser" || platform === "web") return t("devices.kind.web");
|
||||
if (clientType === "mobile") return t("devices.kind.mobile");
|
||||
if (clientType === "hub") return t("devices.kind.hub");
|
||||
if (clientType === "cli") return "CLI";
|
||||
return "MCP";
|
||||
}
|
||||
|
||||
function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
|
||||
if (session.isCurrentSession) return t("devices.connected.thisDevice");
|
||||
if (session.name) return session.name;
|
||||
return formatClientPlatformLabel(session.clientType, session.platform, t);
|
||||
}
|
||||
|
||||
function formatSessionHint(
|
||||
session: DaemonSessionSummary,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
const transport = formatTransportLabel(session.transport, viaHostName, t);
|
||||
const platform = formatClientPlatformLabel(session.clientType, session.platform, t);
|
||||
const detail = session.appVersion ? `${platform} ${session.appVersion}` : platform;
|
||||
return detail === transport ? transport : `${transport} · ${detail}`;
|
||||
}
|
||||
|
||||
function ConnectedClientRow({
|
||||
session,
|
||||
viaHostName,
|
||||
nowMs,
|
||||
}: {
|
||||
session: DaemonSessionSummary;
|
||||
viaHostName: string | null;
|
||||
nowMs: number;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tone: StatusDotTone = session.socketCount > 0 ? "online" : "warning";
|
||||
const connectedLabel = formatDurationLabel(session.connectedAt, t);
|
||||
const isReconnecting = session.socketCount === 0;
|
||||
const tone: StatusDotTone = isReconnecting ? "warning" : "online";
|
||||
const deviceDetail = formatDeviceDetail(session);
|
||||
const appDetail = formatAppDetail(session, t);
|
||||
const connectionLabel = formatTransportLabel(session.transport, viaHostName, t);
|
||||
const authLabel = formatAuthMethodLabel(session.authMethod, t);
|
||||
const connectedLabel = formatDurationLabel(session.connectedAt, nowMs, t);
|
||||
const trailing = useMemo(
|
||||
() => <ScopePill permissions={session.permissions} t={t} />,
|
||||
[session.permissions, t],
|
||||
() => (isReconnecting ? undefined : <ScopePill permissions={session.permissions} t={t} />),
|
||||
[isReconnecting, session.permissions, t],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -176,20 +155,37 @@ function ConnectedClientRow({
|
||||
label={formatSessionTitle(session, t)}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={formatSessionHint(session, viaHostName, t)}
|
||||
summary={isReconnecting ? t("devices.status.reconnecting") : undefined}
|
||||
trailing={trailing}
|
||||
testID={`devices-client-${session.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={session.permissions} t={t} />
|
||||
{deviceDetail ? (
|
||||
<SettingsRow label={t("devices.details.device")}>
|
||||
<Text style={styles.nestedValue}>{deviceDetail}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
<SettingsRow label={t("devices.details.app")}>
|
||||
<Text style={styles.nestedValue}>{appDetail}</Text>
|
||||
</SettingsRow>
|
||||
<SettingsRow label={t("devices.details.connection")}>
|
||||
<Text style={styles.nestedValue}>{connectionLabel}</Text>
|
||||
</SettingsRow>
|
||||
{session.remoteIp ? (
|
||||
<SettingsRow label={t("devices.details.ipAddress")}>
|
||||
<Text style={styles.nestedMonoValue}>{session.remoteIp}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{authLabel ? (
|
||||
<SettingsRow label={t("devices.details.auth")}>
|
||||
<Text style={styles.nestedValue}>{authLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
<AccessDetailRow permissions={session.permissions} t={t} />
|
||||
{connectedLabel ? (
|
||||
<SettingsRow label={t("devices.details.connected")}>
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{session.socketCount === 0 ? (
|
||||
<SettingsRow label={t("devices.details.status")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
@@ -197,22 +193,25 @@ function ConnectedClientRow({
|
||||
function InboundDaemonRow({
|
||||
daemon,
|
||||
routedSessions,
|
||||
nowMs,
|
||||
}: {
|
||||
daemon: DaemonSessionSummary;
|
||||
routedSessions: readonly DaemonSessionSummary[];
|
||||
nowMs: number;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const tone: StatusDotTone = daemon.socketCount > 0 ? "online" : "warning";
|
||||
const isReconnecting = daemon.socketCount === 0;
|
||||
const tone: StatusDotTone = isReconnecting ? "warning" : "online";
|
||||
const label = daemon.name ?? t("devices.hosts.unnamed");
|
||||
const transport = formatTransportLabel(daemon.transport, null, t);
|
||||
const hintParts = [t("devices.hosts.inbound"), transport];
|
||||
if (routedSessions.length > 0) {
|
||||
hintParts.push(t("devices.hosts.routedCount", { count: routedSessions.length }));
|
||||
}
|
||||
const connectedLabel = formatDurationLabel(daemon.connectedAt, t);
|
||||
const connectedLabel = formatDurationLabel(daemon.connectedAt, nowMs, t);
|
||||
const trailing = useMemo(
|
||||
() => <ScopePill permissions={daemon.permissions} t={t} />,
|
||||
[daemon.permissions, t],
|
||||
() => (isReconnecting ? undefined : <ScopePill permissions={daemon.permissions} t={t} />),
|
||||
[daemon.permissions, isReconnecting, t],
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -220,10 +219,11 @@ function InboundDaemonRow({
|
||||
label={label}
|
||||
leading={STATUS_DOTS[tone]}
|
||||
hint={hintParts.join(" · ")}
|
||||
summary={isReconnecting ? t("devices.status.reconnecting") : undefined}
|
||||
trailing={trailing}
|
||||
testID={`devices-inbound-host-${daemon.sessionId}`}
|
||||
>
|
||||
<PermissionPillsRow permissions={daemon.permissions} t={t} />
|
||||
<AccessDetailRow permissions={daemon.permissions} t={t} />
|
||||
{routedSessions.map((routed) => (
|
||||
<SettingsRow
|
||||
key={routed.sessionId}
|
||||
@@ -233,6 +233,11 @@ function InboundDaemonRow({
|
||||
<ScopePill permissions={routed.permissions} t={t} />
|
||||
</SettingsRow>
|
||||
))}
|
||||
{daemon.remoteIp ? (
|
||||
<SettingsRow label={t("devices.details.ipAddress")}>
|
||||
<Text style={styles.nestedMonoValue}>{daemon.remoteIp}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{daemon.appVersion ? (
|
||||
<SettingsRow label={t("devices.details.version")}>
|
||||
<Text style={styles.nestedValue}>{daemon.appVersion}</Text>
|
||||
@@ -243,11 +248,6 @@ function InboundDaemonRow({
|
||||
<Text style={styles.nestedValue}>{connectedLabel}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
{daemon.socketCount === 0 ? (
|
||||
<SettingsRow label={t("devices.details.status")}>
|
||||
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
|
||||
</SettingsRow>
|
||||
) : null}
|
||||
</SettingsCollapsibleRow>
|
||||
);
|
||||
}
|
||||
@@ -281,13 +281,13 @@ function outboundHostStatusLabel(status: HostSummary["status"], t: TFunction): s
|
||||
}
|
||||
}
|
||||
|
||||
function OutboundHostRow({ host }: { host: HostSummary }) {
|
||||
function OutboundHostRow({ host, nowMs }: { host: HostSummary; nowMs: number }) {
|
||||
const { t } = useTranslation();
|
||||
const tone = outboundHostTone(host.status);
|
||||
const label = host.label ?? host.serverId ?? host.targetDescription;
|
||||
const hintParts = [t("devices.hosts.outbound"), host.targetDescription];
|
||||
const statusSummary = outboundHostStatusLabel(host.status, t);
|
||||
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, t);
|
||||
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, nowMs, t);
|
||||
const trailing = useMemo(
|
||||
() =>
|
||||
host.status === "online" && host.permissions ? (
|
||||
@@ -306,7 +306,7 @@ function OutboundHostRow({ host }: { host: HostSummary }) {
|
||||
trailing={trailing}
|
||||
testID={`devices-outbound-host-${host.registrationId}`}
|
||||
>
|
||||
{host.permissions ? <PermissionPillsRow permissions={host.permissions} t={t} /> : null}
|
||||
{host.permissions ? <AccessDetailRow permissions={host.permissions} t={t} /> : null}
|
||||
{host.error ? (
|
||||
<SettingsRow label={t("devices.details.error")}>
|
||||
<Text style={styles.nestedError}>{host.error.message}</Text>
|
||||
@@ -428,6 +428,7 @@ function ConnectedClientsCardBody({
|
||||
clientsState,
|
||||
connectedClients,
|
||||
hostNameBySessionId,
|
||||
nowMs,
|
||||
}: {
|
||||
isOnline: boolean;
|
||||
hasServerInfo: boolean;
|
||||
@@ -436,6 +437,7 @@ function ConnectedClientsCardBody({
|
||||
clientsState: ConnectedClientsLoadState;
|
||||
connectedClients: readonly DaemonSessionSummary[];
|
||||
hostNameBySessionId: ReadonlyMap<string, string | null>;
|
||||
nowMs: number;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const updateLink = useMemo(
|
||||
@@ -486,6 +488,7 @@ function ConnectedClientsCardBody({
|
||||
viaHostName={
|
||||
entry.viaSessionId ? (hostNameBySessionId.get(entry.viaSessionId) ?? null) : null
|
||||
}
|
||||
nowMs={nowMs}
|
||||
/>
|
||||
))}
|
||||
</>
|
||||
@@ -562,6 +565,7 @@ function DevicesAccessSection({
|
||||
|
||||
export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const nowMs = useMinuteTick();
|
||||
const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus;
|
||||
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
|
||||
|
||||
@@ -620,6 +624,7 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
clientsState={clientsState}
|
||||
connectedClients={connectedClients}
|
||||
hostNameBySessionId={hostNameBySessionId}
|
||||
nowMs={nowMs}
|
||||
/>
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
@@ -632,10 +637,11 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
|
||||
key={daemon.sessionId}
|
||||
daemon={daemon}
|
||||
routedSessions={routedByHostSessionId.get(daemon.sessionId) ?? EMPTY_SESSIONS}
|
||||
nowMs={nowMs}
|
||||
/>
|
||||
))}
|
||||
{outboundHosts.map((host) => (
|
||||
<OutboundHostRow key={host.registrationId} host={host} />
|
||||
<OutboundHostRow key={host.registrationId} host={host} nowMs={nowMs} />
|
||||
))}
|
||||
</SettingsCard>
|
||||
</SettingsSection>
|
||||
@@ -677,6 +683,11 @@ const styles = StyleSheet.create((theme) => ({
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
nestedMonoValue: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
fontFamily: theme.fontFamily.mono,
|
||||
color: theme.colors.foregroundMuted,
|
||||
},
|
||||
nestedError: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.statusDanger,
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TFunction } from "i18next";
|
||||
import type { DaemonSessionSummary } from "@getpaseo/protocol/daemon-clients";
|
||||
import {
|
||||
formatAppDetail,
|
||||
formatAuthMethodLabel,
|
||||
formatDeviceDetail,
|
||||
formatSessionHint,
|
||||
formatSessionTitle,
|
||||
} from "./device-display";
|
||||
|
||||
const translations: Record<string, string> = {
|
||||
"devices.connected.thisDevice": "This device",
|
||||
"devices.transport.local": "Local",
|
||||
"devices.transport.tailscale": "Tailscale",
|
||||
"devices.transport.relay": "Relay",
|
||||
"devices.transport.hub": "Hub",
|
||||
"devices.transport.direct": "Direct",
|
||||
"devices.transport.viaHost": "Via host",
|
||||
"devices.kind.desktop": "Desktop",
|
||||
"devices.kind.mobile": "Mobile",
|
||||
"devices.kind.web": "Web",
|
||||
"devices.kind.hub": "Hub",
|
||||
"devices.kind.plugin": "Plugin",
|
||||
"devices.kind.host": "Host",
|
||||
"devices.auth.localMachine": "Local machine",
|
||||
"devices.auth.password": "Password",
|
||||
"devices.auth.openAccess": "Open access",
|
||||
"devices.auth.hub": "Hub",
|
||||
};
|
||||
|
||||
const t = ((key: string, options?: { host?: string }) => {
|
||||
if (key === "devices.transport.via" && options?.host) {
|
||||
return `Via ${options.host}`;
|
||||
}
|
||||
return translations[key] ?? key;
|
||||
}) as unknown as TFunction;
|
||||
|
||||
function makeSession(overrides: Partial<DaemonSessionSummary> = {}): DaemonSessionSummary {
|
||||
return {
|
||||
sessionId: "sess_1",
|
||||
principalId: "owner",
|
||||
isCurrentSession: false,
|
||||
name: null,
|
||||
platform: null,
|
||||
clientType: "browser",
|
||||
appVersion: "0.19.0",
|
||||
transport: "local",
|
||||
permissions: ["daemon.read", "workspace.read"],
|
||||
connectedAt: "2026-12-01T10:00:00.000Z",
|
||||
socketCount: 1,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe("device-display formatting", () => {
|
||||
it("shows real machine name, This device hint, macOS version, and omits 127.0.0.1 on Local Electron", () => {
|
||||
const session = makeSession({
|
||||
isCurrentSession: true,
|
||||
name: "MacBook Pro",
|
||||
appKind: "desktop",
|
||||
platform: "macos",
|
||||
osName: "macOS",
|
||||
osVersion: "15.3.1",
|
||||
transport: "local",
|
||||
remoteIp: "127.0.0.1",
|
||||
ipSource: "direct",
|
||||
authMethod: "local_credential",
|
||||
});
|
||||
|
||||
expect(formatSessionTitle(session, t)).toBe("MacBook Pro");
|
||||
expect(formatSessionHint(session, null, t)).toBe("This device · Local · macOS 15.3");
|
||||
expect(formatDeviceDetail(session)).toBe("MacBook Pro · macOS 15.3.1");
|
||||
expect(formatAppDetail(session, t)).toBe("Desktop 0.19.0");
|
||||
expect(formatAuthMethodLabel(session.authMethod, t)).toBe("Local machine");
|
||||
});
|
||||
|
||||
it("shows observed IP and OS on Tailscale Android and omits OS repetition on Web", () => {
|
||||
const android = makeSession({
|
||||
name: "Pixel 9 Pro",
|
||||
clientType: "mobile",
|
||||
appKind: "mobile",
|
||||
platform: "android",
|
||||
osName: "Android",
|
||||
osVersion: "15",
|
||||
deviceModel: "Pixel 9 Pro",
|
||||
transport: "tailscale",
|
||||
remoteIp: "100.84.12.9",
|
||||
ipSource: "direct",
|
||||
authMethod: "password",
|
||||
});
|
||||
expect(formatSessionTitle(android, t)).toBe("Pixel 9 Pro");
|
||||
expect(formatSessionHint(android, null, t)).toBe("Tailscale · 100.84.12.9 · Android 15");
|
||||
expect(formatDeviceDetail(android)).toBe("Pixel 9 Pro · Android 15");
|
||||
expect(formatAppDetail(android, t)).toBe("Mobile 0.19.0");
|
||||
|
||||
const web = makeSession({
|
||||
isCurrentSession: true,
|
||||
name: "Chrome on macOS",
|
||||
clientType: "browser",
|
||||
appKind: "web",
|
||||
platform: "web",
|
||||
browserName: "Chrome",
|
||||
osName: "macOS",
|
||||
transport: "relay",
|
||||
remoteIp: null,
|
||||
ipSource: null,
|
||||
});
|
||||
expect(formatSessionTitle(web, t)).toBe("Chrome on macOS");
|
||||
expect(formatSessionHint(web, null, t)).toBe("This device · Relay");
|
||||
expect(formatDeviceDetail(web)).toBe("Chrome · macOS");
|
||||
expect(formatAppDetail(web, t)).toBe("Web 0.19.0");
|
||||
});
|
||||
|
||||
it("shows Linux in collapsed hint and distro name in expanded Device detail", () => {
|
||||
const linux = makeSession({
|
||||
name: "workstation",
|
||||
appKind: "desktop",
|
||||
platform: "linux",
|
||||
osName: "Linux",
|
||||
osVersion: "Ubuntu 24.04.1 LTS",
|
||||
transport: "direct",
|
||||
remoteIp: "192.168.1.42",
|
||||
ipSource: "direct",
|
||||
});
|
||||
|
||||
expect(formatSessionHint(linux, null, t)).toBe("Direct · 192.168.1.42 · Linux");
|
||||
expect(formatDeviceDetail(linux)).toBe("workstation · Ubuntu 24.04.1 LTS");
|
||||
});
|
||||
|
||||
it("falls back cleanly for unnamed legacy 0.18.2 clients and Hub", () => {
|
||||
const legacy = makeSession({
|
||||
isCurrentSession: true,
|
||||
name: null,
|
||||
clientType: "mobile",
|
||||
platform: null,
|
||||
appVersion: "0.18.2",
|
||||
transport: "relay",
|
||||
});
|
||||
expect(formatSessionTitle(legacy, t)).toBe("This device");
|
||||
expect(formatSessionHint(legacy, null, t)).toBe("Relay · Mobile 0.18.2");
|
||||
expect(formatDeviceDetail(legacy)).toBeNull();
|
||||
|
||||
const hub = makeSession({
|
||||
name: "Paseo Hub",
|
||||
clientType: "hub",
|
||||
appKind: "hub",
|
||||
appVersion: null,
|
||||
transport: "hub",
|
||||
authMethod: "hub",
|
||||
});
|
||||
expect(formatSessionTitle(hub, t)).toBe("Paseo Hub");
|
||||
expect(formatSessionHint(hub, null, t)).toBe("Hub");
|
||||
expect(formatDeviceDetail(hub)).toBeNull();
|
||||
expect(formatAppDetail(hub, t)).toBe("Hub");
|
||||
expect(formatAuthMethodLabel(hub.authMethod, t)).toBe("Hub");
|
||||
});
|
||||
|
||||
it("maps every daemon SessionAuthMethod value cleanly", () => {
|
||||
expect(formatAuthMethodLabel("local_credential", t)).toBe("Local machine");
|
||||
expect(formatAuthMethodLabel("password", t)).toBe("Password");
|
||||
expect(formatAuthMethodLabel("header_bearer", t)).toBe("Password");
|
||||
expect(formatAuthMethodLabel("unprotected", t)).toBe("Open access");
|
||||
expect(formatAuthMethodLabel("hub", t)).toBe("Hub");
|
||||
expect(formatAuthMethodLabel("plugin", t)).toBe("Plugin");
|
||||
expect(formatAuthMethodLabel(null, t)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,209 @@
|
||||
import type { TFunction } from "i18next";
|
||||
import type {
|
||||
DaemonSessionSummary,
|
||||
DaemonSessionTransport,
|
||||
} from "@getpaseo/protocol/daemon-clients";
|
||||
|
||||
function osNameFromPlatform(platform: string | null | undefined): string | null {
|
||||
switch (platform) {
|
||||
case "macos":
|
||||
return "macOS";
|
||||
case "linux":
|
||||
return "Linux";
|
||||
case "windows":
|
||||
return "Windows";
|
||||
case "ios":
|
||||
return "iOS";
|
||||
case "android":
|
||||
return "Android";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function shortenNumericVersion(version: string): string {
|
||||
const match = version.match(/^(\d+(?:\.\d+)?)/);
|
||||
return match?.[1] ?? version;
|
||||
}
|
||||
|
||||
export function formatTransportLabel(
|
||||
transport: DaemonSessionTransport,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
switch (transport) {
|
||||
case "local_ipc":
|
||||
case "local":
|
||||
return t("devices.transport.local");
|
||||
case "tailscale":
|
||||
return t("devices.transport.tailscale");
|
||||
case "relay":
|
||||
return t("devices.transport.relay");
|
||||
case "hub":
|
||||
return t("devices.transport.hub");
|
||||
case "via":
|
||||
return viaHostName
|
||||
? t("devices.transport.via", { host: viaHostName })
|
||||
: t("devices.transport.viaHost");
|
||||
case "direct":
|
||||
return t("devices.transport.direct");
|
||||
}
|
||||
}
|
||||
|
||||
export function formatAppKindLabel(
|
||||
session: Pick<DaemonSessionSummary, "appKind" | "clientType" | "platform">,
|
||||
t: TFunction,
|
||||
): string {
|
||||
switch (session.appKind) {
|
||||
case "desktop":
|
||||
return t("devices.kind.desktop");
|
||||
case "mobile":
|
||||
return t("devices.kind.mobile");
|
||||
case "web":
|
||||
return t("devices.kind.web");
|
||||
case "hub":
|
||||
return t("devices.kind.hub");
|
||||
case "cli":
|
||||
return "CLI";
|
||||
case "mcp":
|
||||
return "MCP";
|
||||
case "plugin":
|
||||
return t("devices.kind.plugin");
|
||||
case "daemon":
|
||||
return t("devices.kind.host");
|
||||
}
|
||||
|
||||
if (
|
||||
session.platform === "macos" ||
|
||||
session.platform === "linux" ||
|
||||
session.platform === "windows"
|
||||
) {
|
||||
return t("devices.kind.desktop");
|
||||
}
|
||||
if (session.platform === "ios" || session.platform === "android") {
|
||||
return t("devices.kind.mobile");
|
||||
}
|
||||
if (session.clientType === "browser" || session.platform === "web") {
|
||||
return t("devices.kind.web");
|
||||
}
|
||||
if (session.clientType === "mobile") return t("devices.kind.mobile");
|
||||
if (session.clientType === "hub") return t("devices.kind.hub");
|
||||
if (session.clientType === "cli") return "CLI";
|
||||
return "MCP";
|
||||
}
|
||||
|
||||
export function formatOsLabel(
|
||||
session: Pick<DaemonSessionSummary, "osName" | "osVersion" | "platform">,
|
||||
options: { compact: boolean },
|
||||
): string | null {
|
||||
const osName = session.osName ?? osNameFromPlatform(session.platform);
|
||||
const osVersion = session.osVersion ?? null;
|
||||
if (!osName) return osVersion;
|
||||
|
||||
if (options.compact) {
|
||||
if (
|
||||
osVersion &&
|
||||
(osName === "macOS" || osName === "iOS" || osName === "iPadOS" || osName === "Android") &&
|
||||
/^\d/.test(osVersion)
|
||||
) {
|
||||
return `${osName} ${shortenNumericVersion(osVersion)}`;
|
||||
}
|
||||
return osName;
|
||||
}
|
||||
|
||||
if (!osVersion) return osName;
|
||||
if (osName === "Linux" && !/^\d/.test(osVersion)) {
|
||||
return osVersion;
|
||||
}
|
||||
return `${osName} ${osVersion}`;
|
||||
}
|
||||
|
||||
export function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
|
||||
if (session.name) return session.name;
|
||||
if (session.isCurrentSession) return t("devices.connected.thisDevice");
|
||||
return formatAppKindLabel(session, t);
|
||||
}
|
||||
|
||||
export function formatSessionHint(
|
||||
session: DaemonSessionSummary,
|
||||
viaHostName: string | null,
|
||||
t: TFunction,
|
||||
): string {
|
||||
const title = formatSessionTitle(session, t);
|
||||
const thisDeviceLabel = t("devices.connected.thisDevice");
|
||||
const transport = formatTransportLabel(session.transport, viaHostName, t);
|
||||
const parts: string[] = [];
|
||||
|
||||
if (session.isCurrentSession && title !== thisDeviceLabel) {
|
||||
parts.push(thisDeviceLabel);
|
||||
}
|
||||
parts.push(transport);
|
||||
|
||||
if (
|
||||
session.remoteIp &&
|
||||
(session.transport === "tailscale" ||
|
||||
session.transport === "direct" ||
|
||||
session.transport === "relay")
|
||||
) {
|
||||
parts.push(session.remoteIp);
|
||||
}
|
||||
|
||||
const shortOs = formatOsLabel(session, { compact: true });
|
||||
if (shortOs && !title.toLowerCase().includes(shortOs.toLowerCase())) {
|
||||
parts.push(shortOs);
|
||||
} else if (
|
||||
!shortOs &&
|
||||
!session.name &&
|
||||
session.appVersion &&
|
||||
session.transport !== "hub" &&
|
||||
session.clientType !== "hub"
|
||||
) {
|
||||
const kind = formatAppKindLabel(session, t);
|
||||
const fallbackDetail = `${kind} ${session.appVersion}`;
|
||||
if (fallbackDetail !== title) {
|
||||
parts.push(fallbackDetail);
|
||||
}
|
||||
}
|
||||
|
||||
return parts.join(" · ");
|
||||
}
|
||||
|
||||
export function formatDeviceDetail(session: DaemonSessionSummary): string | null {
|
||||
const osDetail = formatOsLabel(session, { compact: false });
|
||||
const primary =
|
||||
session.deviceModel ??
|
||||
session.browserName ??
|
||||
(session.appKind === "desktop" ? session.name : null);
|
||||
|
||||
if (primary && osDetail) {
|
||||
if (primary.toLowerCase() === osDetail.toLowerCase()) return primary;
|
||||
return `${primary} · ${osDetail}`;
|
||||
}
|
||||
return primary ?? osDetail;
|
||||
}
|
||||
|
||||
export function formatAppDetail(session: DaemonSessionSummary, t: TFunction): string {
|
||||
const kind = formatAppKindLabel(session, t);
|
||||
return session.appVersion ? `${kind} ${session.appVersion}` : kind;
|
||||
}
|
||||
|
||||
export function formatAuthMethodLabel(
|
||||
authMethod: string | null | undefined,
|
||||
t: TFunction,
|
||||
): string | null {
|
||||
switch (authMethod) {
|
||||
case "local_credential":
|
||||
return t("devices.auth.localMachine");
|
||||
case "password":
|
||||
case "header_bearer":
|
||||
return t("devices.auth.password");
|
||||
case "unprotected":
|
||||
return t("devices.auth.openAccess");
|
||||
case "hub":
|
||||
return t("devices.auth.hub");
|
||||
case "plugin":
|
||||
return t("devices.kind.plugin");
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -2070,16 +2070,16 @@ export const ar: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "العملاء المتصلون",
|
||||
title: "الأجهزة",
|
||||
thisDevice: "هذا الجهاز",
|
||||
loading: "جارٍ تحميل العملاء المتصلين...",
|
||||
empty: "لا يوجد عملاء متصلون",
|
||||
unavailable: "تعذّر تحميل العملاء المتصلين",
|
||||
updateTitle: "حدّث هذا المضيف لعرض العملاء المتصلين",
|
||||
updateHint: "هذا المضيف لا يبلّغ عن العملاء المتصلين بعد",
|
||||
loading: "جارٍ تحميل الأجهزة...",
|
||||
empty: "لا توجد أجهزة متصلة",
|
||||
unavailable: "تعذّر تحميل الأجهزة",
|
||||
updateTitle: "حدّث هذا المضيف لعرض الأجهزة المتصلة",
|
||||
updateHint: "هذا المضيف لا يبلّغ عن الأجهزة المتصلة بعد",
|
||||
permissionTitle: "مطلوب إذن إدارة الوصول",
|
||||
permissionHint: "جلستك لا تملك إذن عرض العملاء المتصلين",
|
||||
errorTitle: "تعذّر تحميل العملاء المتصلين",
|
||||
permissionHint: "جلستك لا تملك إذن عرض الأجهزة المتصلة",
|
||||
errorTitle: "تعذّر تحميل الأجهزة",
|
||||
},
|
||||
hosts: {
|
||||
title: "المضيفون المتصلون",
|
||||
@@ -2112,8 +2112,21 @@ export const ar: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "إضافة",
|
||||
client: "عميل",
|
||||
host: "مضيف",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "الجهاز المحلي",
|
||||
password: "كلمة المرور",
|
||||
openAccess: "وصول مفتوح",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "الجهاز",
|
||||
app: "التطبيق",
|
||||
connection: "الاتصال",
|
||||
ipAddress: "عنوان IP",
|
||||
auth: "المصادقة",
|
||||
access: "الوصول",
|
||||
permissions: "الأذونات",
|
||||
connected: "متصل",
|
||||
lastSeen: "آخر اتصال",
|
||||
|
||||
@@ -2101,16 +2101,16 @@ export const en = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Connected clients",
|
||||
title: "Devices",
|
||||
thisDevice: "This device",
|
||||
loading: "Loading connected clients...",
|
||||
empty: "No connected clients",
|
||||
unavailable: "Unable to load connected clients",
|
||||
updateTitle: "Update this host to view connected clients",
|
||||
updateHint: "This host does not report connected clients yet",
|
||||
loading: "Loading devices...",
|
||||
empty: "No connected devices",
|
||||
unavailable: "Unable to load devices",
|
||||
updateTitle: "Update this host to view connected devices",
|
||||
updateHint: "This host does not report connected devices yet",
|
||||
permissionTitle: "Access management required",
|
||||
permissionHint: "Your session does not have permission to view connected clients",
|
||||
errorTitle: "Could not load connected clients",
|
||||
permissionHint: "Your session does not have permission to view connected devices",
|
||||
errorTitle: "Could not load devices",
|
||||
},
|
||||
hosts: {
|
||||
title: "Connected hosts",
|
||||
@@ -2143,8 +2143,21 @@ export const en = {
|
||||
hub: "Hub",
|
||||
plugin: "Plugin",
|
||||
client: "Client",
|
||||
host: "Host",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "Local machine",
|
||||
password: "Password",
|
||||
openAccess: "Open access",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "Device",
|
||||
app: "App",
|
||||
connection: "Connection",
|
||||
ipAddress: "IP address",
|
||||
auth: "Auth",
|
||||
access: "Access",
|
||||
permissions: "Permissions",
|
||||
connected: "Connected",
|
||||
lastSeen: "Last online",
|
||||
|
||||
@@ -2127,16 +2127,16 @@ export const es: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clientes conectados",
|
||||
title: "Dispositivos",
|
||||
thisDevice: "Este dispositivo",
|
||||
loading: "Cargando clientes conectados...",
|
||||
empty: "No hay clientes conectados",
|
||||
unavailable: "No se pudieron cargar los clientes conectados",
|
||||
updateTitle: "Actualiza este host para ver los clientes conectados",
|
||||
updateHint: "Este host todavía no informa de los clientes conectados",
|
||||
loading: "Cargando dispositivos...",
|
||||
empty: "No hay dispositivos conectados",
|
||||
unavailable: "No se pudieron cargar los dispositivos",
|
||||
updateTitle: "Actualiza este host para ver los dispositivos conectados",
|
||||
updateHint: "Este host todavía no informa de los dispositivos conectados",
|
||||
permissionTitle: "Se requiere gestión de acceso",
|
||||
permissionHint: "Tu sesión no tiene permiso para ver los clientes conectados",
|
||||
errorTitle: "No se pudieron cargar los clientes conectados",
|
||||
permissionHint: "Tu sesión no tiene permiso para ver los dispositivos conectados",
|
||||
errorTitle: "No se pudieron cargar los dispositivos",
|
||||
},
|
||||
hosts: {
|
||||
title: "Hosts conectados",
|
||||
@@ -2169,8 +2169,21 @@ export const es: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "Plugin",
|
||||
client: "Cliente",
|
||||
host: "Host",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "Equipo local",
|
||||
password: "Contraseña",
|
||||
openAccess: "Acceso abierto",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "Dispositivo",
|
||||
app: "Aplicación",
|
||||
connection: "Conexión",
|
||||
ipAddress: "Dirección IP",
|
||||
auth: "Autenticación",
|
||||
access: "Acceso",
|
||||
permissions: "Permisos",
|
||||
connected: "Conectado",
|
||||
lastSeen: "Última conexión",
|
||||
|
||||
@@ -2123,16 +2123,16 @@ export const fr: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clients connectés",
|
||||
title: "Appareils",
|
||||
thisDevice: "Cet appareil",
|
||||
loading: "Chargement des clients connectés...",
|
||||
empty: "Aucun client connecté",
|
||||
unavailable: "Impossible de charger les clients connectés",
|
||||
updateTitle: "Mettez cet hôte à jour pour voir les clients connectés",
|
||||
updateHint: "Cet hôte ne signale pas encore les clients connectés",
|
||||
loading: "Chargement des appareils...",
|
||||
empty: "Aucun appareil connecté",
|
||||
unavailable: "Impossible de charger les appareils",
|
||||
updateTitle: "Mettez cet hôte à jour pour voir les appareils connectés",
|
||||
updateHint: "Cet hôte ne signale pas encore les appareils connectés",
|
||||
permissionTitle: "Gestion des accès requise",
|
||||
permissionHint: "Votre session n’est pas autorisée à voir les clients connectés",
|
||||
errorTitle: "Impossible de charger les clients connectés",
|
||||
permissionHint: "Votre session n’est pas autorisée à voir les appareils connectés",
|
||||
errorTitle: "Impossible de charger les appareils",
|
||||
},
|
||||
hosts: {
|
||||
title: "Hôtes connectés",
|
||||
@@ -2165,8 +2165,21 @@ export const fr: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "Plugin",
|
||||
client: "Client",
|
||||
host: "Hôte",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "Machine locale",
|
||||
password: "Mot de passe",
|
||||
openAccess: "Accès ouvert",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "Appareil",
|
||||
app: "Application",
|
||||
connection: "Connexion",
|
||||
ipAddress: "Adresse IP",
|
||||
auth: "Authentification",
|
||||
access: "Accès",
|
||||
permissions: "Autorisations",
|
||||
connected: "Connecté",
|
||||
lastSeen: "Dernière connexion",
|
||||
|
||||
@@ -2093,16 +2093,16 @@ export const ja: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "接続中のクライアント",
|
||||
title: "デバイス",
|
||||
thisDevice: "このデバイス",
|
||||
loading: "接続中のクライアントを読み込み中...",
|
||||
empty: "接続中のクライアントはありません",
|
||||
unavailable: "接続中のクライアントを読み込めません",
|
||||
updateTitle: "接続中のクライアントを表示するにはこのホストを更新してください",
|
||||
updateHint: "このホストはまだ接続中のクライアントの報告に対応していません",
|
||||
loading: "デバイスを読み込み中...",
|
||||
empty: "接続中のデバイスはありません",
|
||||
unavailable: "デバイスを読み込めません",
|
||||
updateTitle: "接続中のデバイスを表示するにはこのホストを更新してください",
|
||||
updateHint: "このホストはまだ接続中のデバイスの報告に対応していません",
|
||||
permissionTitle: "アクセス管理権限が必要です",
|
||||
permissionHint: "このセッションには接続中のクライアントを表示する権限がありません",
|
||||
errorTitle: "接続中のクライアントを読み込めませんでした",
|
||||
permissionHint: "このセッションには接続中のデバイスを表示する権限がありません",
|
||||
errorTitle: "デバイスを読み込めませんでした",
|
||||
},
|
||||
hosts: {
|
||||
title: "接続されたホスト",
|
||||
@@ -2135,8 +2135,21 @@ export const ja: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "プラグイン",
|
||||
client: "クライアント",
|
||||
host: "ホスト",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "ローカルマシン",
|
||||
password: "パスワード",
|
||||
openAccess: "オープンアクセス",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "デバイス",
|
||||
app: "アプリ",
|
||||
connection: "接続",
|
||||
ipAddress: "IPアドレス",
|
||||
auth: "認証",
|
||||
access: "アクセス",
|
||||
permissions: "権限",
|
||||
connected: "接続時間",
|
||||
lastSeen: "最終オンライン",
|
||||
|
||||
@@ -2086,16 +2086,16 @@ export const ko: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "연결된 클라이언트",
|
||||
title: "기기",
|
||||
thisDevice: "이 기기",
|
||||
loading: "연결된 클라이언트를 불러오는 중...",
|
||||
empty: "연결된 클라이언트가 없습니다",
|
||||
unavailable: "연결된 클라이언트를 불러올 수 없습니다",
|
||||
updateTitle: "연결된 클라이언트를 보려면 이 호스트를 업데이트하세요",
|
||||
updateHint: "이 호스트는 아직 연결된 클라이언트 보고를 지원하지 않습니다",
|
||||
loading: "기기를 불러오는 중...",
|
||||
empty: "연결된 기기가 없습니다",
|
||||
unavailable: "기기를 불러올 수 없습니다",
|
||||
updateTitle: "연결된 기기를 보려면 이 호스트를 업데이트하세요",
|
||||
updateHint: "이 호스트는 아직 연결된 기기 보고를 지원하지 않습니다",
|
||||
permissionTitle: "접근 관리 권한이 필요합니다",
|
||||
permissionHint: "현재 세션에는 연결된 클라이언트를 볼 권한이 없습니다",
|
||||
errorTitle: "연결된 클라이언트를 불러오지 못했습니다",
|
||||
permissionHint: "현재 세션에는 연결된 기기를 볼 권한이 없습니다",
|
||||
errorTitle: "기기를 불러오지 못했습니다",
|
||||
},
|
||||
hosts: {
|
||||
title: "연결된 호스트",
|
||||
@@ -2128,8 +2128,21 @@ export const ko: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "플러그인",
|
||||
client: "클라이언트",
|
||||
host: "호스트",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "로컬 기기",
|
||||
password: "비밀번호",
|
||||
openAccess: "열린 접근",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "기기",
|
||||
app: "앱",
|
||||
connection: "연결",
|
||||
ipAddress: "IP 주소",
|
||||
auth: "인증",
|
||||
access: "접근",
|
||||
permissions: "권한",
|
||||
connected: "연결됨",
|
||||
lastSeen: "마지막 온라인",
|
||||
|
||||
@@ -2109,16 +2109,16 @@ export const ptBR: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Clientes conectados",
|
||||
title: "Dispositivos",
|
||||
thisDevice: "Este dispositivo",
|
||||
loading: "Carregando clientes conectados...",
|
||||
empty: "Nenhum cliente conectado",
|
||||
unavailable: "Não foi possível carregar os clientes conectados",
|
||||
updateTitle: "Atualize este host para ver clientes conectados",
|
||||
updateHint: "Este host ainda não informa clientes conectados",
|
||||
loading: "Carregando dispositivos...",
|
||||
empty: "Nenhum dispositivo conectado",
|
||||
unavailable: "Não foi possível carregar os dispositivos",
|
||||
updateTitle: "Atualize este host para ver dispositivos conectados",
|
||||
updateHint: "Este host ainda não informa dispositivos conectados",
|
||||
permissionTitle: "Gerenciamento de acesso necessário",
|
||||
permissionHint: "Sua sessão não tem permissão para ver clientes conectados",
|
||||
errorTitle: "Não foi possível carregar os clientes conectados",
|
||||
permissionHint: "Sua sessão não tem permissão para ver dispositivos conectados",
|
||||
errorTitle: "Não foi possível carregar os dispositivos",
|
||||
},
|
||||
hosts: {
|
||||
title: "Hosts conectados",
|
||||
@@ -2151,8 +2151,21 @@ export const ptBR: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "Plugin",
|
||||
client: "Cliente",
|
||||
host: "Host",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "Máquina local",
|
||||
password: "Senha",
|
||||
openAccess: "Acesso aberto",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "Dispositivo",
|
||||
app: "Aplicativo",
|
||||
connection: "Conexão",
|
||||
ipAddress: "Endereço IP",
|
||||
auth: "Autenticação",
|
||||
access: "Acesso",
|
||||
permissions: "Permissões",
|
||||
connected: "Conectado",
|
||||
lastSeen: "Última vez online",
|
||||
|
||||
@@ -2108,16 +2108,16 @@ export const ru: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "Подключённые клиенты",
|
||||
title: "Устройства",
|
||||
thisDevice: "Это устройство",
|
||||
loading: "Загрузка подключённых клиентов...",
|
||||
empty: "Нет подключённых клиентов",
|
||||
unavailable: "Не удалось загрузить подключённых клиентов",
|
||||
updateTitle: "Обновите этот хост, чтобы видеть подключённых клиентов",
|
||||
updateHint: "Этот хост ещё не передаёт список подключённых клиентов",
|
||||
loading: "Загрузка устройств...",
|
||||
empty: "Нет подключённых устройств",
|
||||
unavailable: "Не удалось загрузить устройства",
|
||||
updateTitle: "Обновите этот хост, чтобы видеть подключённые устройства",
|
||||
updateHint: "Этот хост ещё не передаёт список подключённых устройств",
|
||||
permissionTitle: "Требуются права управления доступом",
|
||||
permissionHint: "У текущей сессии нет прав для просмотра подключённых клиентов",
|
||||
errorTitle: "Не удалось загрузить подключённых клиентов",
|
||||
permissionHint: "У текущей сессии нет прав для просмотра подключённых устройств",
|
||||
errorTitle: "Не удалось загрузить устройства",
|
||||
},
|
||||
hosts: {
|
||||
title: "Подключённые хосты",
|
||||
@@ -2150,8 +2150,21 @@ export const ru: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "Плагин",
|
||||
client: "Клиент",
|
||||
host: "Хост",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "Локальная машина",
|
||||
password: "Пароль",
|
||||
openAccess: "Открытый доступ",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "Устройство",
|
||||
app: "Приложение",
|
||||
connection: "Подключение",
|
||||
ipAddress: "IP-адрес",
|
||||
auth: "Аутентификация",
|
||||
access: "Доступ",
|
||||
permissions: "Разрешения",
|
||||
connected: "Подключено",
|
||||
lastSeen: "Последний раз в сети",
|
||||
|
||||
@@ -2050,16 +2050,16 @@ export const zhCN: TranslationResources = {
|
||||
},
|
||||
},
|
||||
connected: {
|
||||
title: "已连接的客户端",
|
||||
title: "设备",
|
||||
thisDevice: "此设备",
|
||||
loading: "正在加载已连接的客户端...",
|
||||
empty: "没有已连接的客户端",
|
||||
unavailable: "无法加载已连接的客户端",
|
||||
updateTitle: "更新此主机以查看已连接的客户端",
|
||||
updateHint: "此主机暂不支持报告已连接的客户端",
|
||||
loading: "正在加载设备...",
|
||||
empty: "没有已连接的设备",
|
||||
unavailable: "无法加载设备",
|
||||
updateTitle: "更新此主机以查看已连接的设备",
|
||||
updateHint: "此主机暂不支持报告已连接的设备",
|
||||
permissionTitle: "需要访问管理权限",
|
||||
permissionHint: "当前会话无权查看已连接的客户端",
|
||||
errorTitle: "无法加载已连接的客户端",
|
||||
permissionHint: "当前会话无权查看已连接的设备",
|
||||
errorTitle: "无法加载设备",
|
||||
},
|
||||
hosts: {
|
||||
title: "已连接的主机",
|
||||
@@ -2092,8 +2092,21 @@ export const zhCN: TranslationResources = {
|
||||
hub: "Hub",
|
||||
plugin: "插件",
|
||||
client: "客户端",
|
||||
host: "主机",
|
||||
},
|
||||
auth: {
|
||||
localMachine: "本机",
|
||||
password: "密码",
|
||||
openAccess: "开放访问",
|
||||
hub: "Hub",
|
||||
},
|
||||
details: {
|
||||
device: "设备",
|
||||
app: "应用",
|
||||
connection: "连接",
|
||||
ipAddress: "IP 地址",
|
||||
auth: "认证",
|
||||
access: "访问权限",
|
||||
permissions: "权限",
|
||||
connected: "连接时间",
|
||||
lastSeen: "上次在线",
|
||||
|
||||
@@ -31,6 +31,7 @@ import { FileDropZone } from "@/components/file-drop/file-drop-zone";
|
||||
import { useRetainedPanelActive } from "@/components/retained-panel";
|
||||
import { RetainedChatContent } from "./retained-chat-content";
|
||||
import { Composer } from "@/composer";
|
||||
import type { ComposerInputMode } from "@/composer/input-mode";
|
||||
import { AgentCommandsProvider } from "@/agent-commands";
|
||||
import {
|
||||
useComposerEditingSession,
|
||||
@@ -74,6 +75,7 @@ import { useContainerWidthBelow } from "@/hooks/use-container-width";
|
||||
import { reconcileMissingAgentStateWithPresentAgent } from "@/panels/agent-panel-load-state";
|
||||
import { TimelineSyncStatus } from "@/timeline/sync-status";
|
||||
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
|
||||
import type { PaneHost } from "@/panels/panel-manifest";
|
||||
import { useAgentFactsLine } from "@/panels/agent-facts-line";
|
||||
import { PaneSubtitle } from "@/panels/pane-subtitle";
|
||||
import { definePanel } from "@/panels/panel-registry";
|
||||
@@ -111,6 +113,7 @@ import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
|
||||
import { buildWorkspaceTabPersistenceKey, type WorkspaceTabTarget } from "@/workspace-tabs/model";
|
||||
import { openWorkspaceChanges } from "@/workspace-tabs/open-supporting-view";
|
||||
import { useSettings } from "@/hooks/use-settings";
|
||||
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import type { PendingPermission } from "@/types/shared";
|
||||
import type { StreamItem } from "@/types/stream";
|
||||
@@ -350,13 +353,58 @@ function resolveConversationAgentId(target: ConversationTarget): string | undefi
|
||||
return target.kind === "agent" ? target.agentId.trim() || undefined : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a conversation is shown. A pane is a workspace tab or sheet; an embed is a plugin's
|
||||
* `AgentChat`, which has no tab to retarget or close and shows a composer only when asked.
|
||||
* `id` names the viewer: the tab in a pane, the embed instance otherwise.
|
||||
*/
|
||||
export type ConversationSurface =
|
||||
| { kind: "pane"; id: string; host: PaneHost }
|
||||
| {
|
||||
kind: "embed";
|
||||
id: string;
|
||||
composer: EmbeddedComposer | null;
|
||||
/** The pane or screen around the embed is the one in front. */
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
export interface EmbeddedComposer {
|
||||
/** `chat` is the agent tab's composer; `message` is a text box and Send. */
|
||||
inputMode: Extract<ComposerInputMode, "chat" | "message">;
|
||||
/** Replaces the default placeholder. */
|
||||
placeholder: string | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* An embed with a composer is where the user acts on the agent, so while it is in front it clears
|
||||
* "needs attention" without key focus. One without a composer is a preview: a plugin can show many
|
||||
* at once, and a glance is not the user handling the agent.
|
||||
*/
|
||||
function surfaceClearsAttention(surface: ConversationSurface, isPaneFocused: boolean): boolean {
|
||||
return surface.kind === "embed" ? surface.composer !== null && surface.isActive : isPaneFocused;
|
||||
}
|
||||
|
||||
/** The track's pills open tabs and sheets of the workspace, which an embed is not in. */
|
||||
function surfaceShowsTrack(surface: ConversationSurface, hasActiveComposer: boolean): boolean {
|
||||
return hasActiveComposer && surface.kind === "pane";
|
||||
}
|
||||
|
||||
function surfaceShowsComposer(surface: ConversationSurface): boolean {
|
||||
// The workspace sheet is for looking; Open as tab brings the agent back with its composer.
|
||||
return surface.kind === "pane" ? surface.host !== "sheet" : surface.composer !== null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Drafts and agents render through one chain so the timeline stays mounted when the draft's
|
||||
* first prompt creates the agent and the tab retargets. The agent gates are idle for a draft.
|
||||
*/
|
||||
export function AgentConversationPanel() {
|
||||
const { serverId, workspaceId, target, openFileInWorkspace } = usePaneContext();
|
||||
const { serverId, workspaceId, target, openFileInWorkspace, tabId, host } = usePaneContext();
|
||||
const { isInteractive } = usePaneFocus();
|
||||
const surface = useMemo<ConversationSurface>(
|
||||
() => ({ kind: "pane", id: tabId, host }),
|
||||
[host, tabId],
|
||||
);
|
||||
invariant(
|
||||
target.kind === "agent" || target.kind === "draft",
|
||||
"AgentConversationPanel requires an agent or draft target",
|
||||
@@ -368,6 +416,7 @@ export function AgentConversationPanel() {
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
target={target}
|
||||
surface={surface}
|
||||
isPaneFocused={isInteractive}
|
||||
onOpenWorkspaceFile={openFileInWorkspace}
|
||||
/>
|
||||
@@ -446,16 +495,18 @@ type AgentLookupState =
|
||||
| { tag: "not_found"; message: string }
|
||||
| { tag: "error"; message: string };
|
||||
|
||||
function AgentPanelContent({
|
||||
export function AgentPanelContent({
|
||||
serverId,
|
||||
workspaceId,
|
||||
target,
|
||||
surface,
|
||||
isPaneFocused,
|
||||
onOpenWorkspaceFile,
|
||||
}: {
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
target: ConversationTarget;
|
||||
surface: ConversationSurface;
|
||||
isPaneFocused: boolean;
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
@@ -509,6 +560,7 @@ function AgentPanelContent({
|
||||
serverId={resolvedServerId ?? serverId}
|
||||
workspaceId={workspaceId}
|
||||
target={target}
|
||||
surface={surface}
|
||||
isPaneFocused={isPaneFocused}
|
||||
client={runtimeClient}
|
||||
isConnected={runtimeIsConnected}
|
||||
@@ -522,6 +574,7 @@ function AgentPanelBody({
|
||||
serverId,
|
||||
workspaceId,
|
||||
target,
|
||||
surface,
|
||||
isPaneFocused,
|
||||
client,
|
||||
isConnected,
|
||||
@@ -531,6 +584,7 @@ function AgentPanelBody({
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
target: ConversationTarget;
|
||||
surface: ConversationSurface;
|
||||
isPaneFocused: boolean;
|
||||
client: ReturnType<typeof useHostRuntimeClient>;
|
||||
isConnected: boolean;
|
||||
@@ -663,6 +717,7 @@ function AgentPanelBody({
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
target={target}
|
||||
surface={surface}
|
||||
isPaneFocused={isPaneFocused}
|
||||
client={client}
|
||||
isConnected={isConnected}
|
||||
@@ -716,6 +771,7 @@ function ChatAgentContent({
|
||||
serverId,
|
||||
workspaceId,
|
||||
target,
|
||||
surface,
|
||||
isPaneFocused,
|
||||
client,
|
||||
isConnected,
|
||||
@@ -725,6 +781,7 @@ function ChatAgentContent({
|
||||
serverId: string;
|
||||
workspaceId: string;
|
||||
target: ConversationTarget;
|
||||
surface: ConversationSurface;
|
||||
isPaneFocused: boolean;
|
||||
client: ReturnType<typeof useHostRuntimeClient>;
|
||||
isConnected: boolean;
|
||||
@@ -732,7 +789,7 @@ function ChatAgentContent({
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { tabId } = usePaneContext();
|
||||
const tabId = surface.id;
|
||||
const agentId = resolveConversationAgentId(target);
|
||||
const isPaneVisible = useRetainedPanelActive();
|
||||
const { api: toastApi, toast: toastState, dismiss: dismissToast } = useToastHost();
|
||||
@@ -841,7 +898,7 @@ function ChatAgentContent({
|
||||
isAgentDataReady: agentHistorySyncGeneration === historySyncGeneration,
|
||||
requiresAttention: agentState.requiresAttention,
|
||||
attentionReason: agentState.attentionReason,
|
||||
isScreenFocused: isPaneFocused,
|
||||
isScreenFocused: surfaceClearsAttention(surface, isPaneFocused),
|
||||
focusRequest,
|
||||
onError: reportAttentionError,
|
||||
});
|
||||
@@ -1075,6 +1132,7 @@ function ChatAgentContent({
|
||||
workspaceId={workspaceId}
|
||||
agentId={agentId ?? tabId}
|
||||
draft={draft}
|
||||
surface={surface}
|
||||
isPaneFocused={isPaneFocused}
|
||||
isArchivingCurrentAgent={isArchivingCurrentAgent}
|
||||
agentState={agentState}
|
||||
@@ -1106,6 +1164,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
workspaceId,
|
||||
agentId,
|
||||
draft,
|
||||
surface,
|
||||
isPaneFocused,
|
||||
isArchivingCurrentAgent,
|
||||
agentState,
|
||||
@@ -1134,6 +1193,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
/** The agent's id, or the tab id while a draft has no agent yet. */
|
||||
agentId: string;
|
||||
draft: DraftConversation | null;
|
||||
surface: ConversationSurface;
|
||||
isPaneFocused: boolean;
|
||||
isArchivingCurrentAgent: boolean;
|
||||
agentState: ChatAgentSelectedState;
|
||||
@@ -1158,9 +1218,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
// The workspace sheet is for looking; Open as tab brings the agent back with its composer.
|
||||
const paneHost = usePaneContext().host;
|
||||
const showsComposer = draft !== null || paneHost !== "sheet";
|
||||
const showsComposer = draft !== null || surfaceShowsComposer(surface);
|
||||
// The dock lays out fullscreen for the same session the composer edits in.
|
||||
const composerEditingSession = useComposerEditingSession("chat");
|
||||
const isComposerFullscreen = useComposerFullscreen(composerEditingSession);
|
||||
@@ -1170,6 +1228,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
agentId,
|
||||
});
|
||||
const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent;
|
||||
const showsTrack = surfaceShowsTrack(surface, hasActiveComposer);
|
||||
const focusRestoredComposer = useStableEvent(() => {
|
||||
if (isPaneFocused && showsComposer && hasActiveComposer) {
|
||||
composerEditingSession.focus();
|
||||
@@ -1246,6 +1305,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
<AgentComposerSection
|
||||
agentId={agentId}
|
||||
serverId={serverId}
|
||||
surface={surface}
|
||||
isPaneFocused={isPaneFocused}
|
||||
isArchivingCurrentAgent={isArchivingCurrentAgent}
|
||||
isWorkspaceRestoring={isWorkspaceRestoring}
|
||||
@@ -1303,13 +1363,13 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
|
||||
hasAppliedAuthoritativeHistory={hasAppliedAuthoritativeHistory}
|
||||
isInitialHistoryLoading={isInitialHistoryLoading}
|
||||
revealInitialHistory={hasCachedHistory || showHistorySyncError}
|
||||
reservesTrack={showsTrack}
|
||||
onInitialHistoryVisibilityChange={handleInitialHistoryVisibilityChange}
|
||||
hasActiveComposer={hasActiveComposer}
|
||||
toast={toastApi}
|
||||
onOpenWorkspaceFile={onOpenWorkspaceFile}
|
||||
/>
|
||||
</RenderProfile>
|
||||
{hasActiveComposer && !draft ? (
|
||||
{showsTrack && !draft ? (
|
||||
<AgentTracks
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
@@ -1540,8 +1600,8 @@ const AgentStreamSection = memo(function AgentStreamSection({
|
||||
hasAppliedAuthoritativeHistory,
|
||||
isInitialHistoryLoading,
|
||||
revealInitialHistory,
|
||||
reservesTrack,
|
||||
onInitialHistoryVisibilityChange,
|
||||
hasActiveComposer,
|
||||
toast,
|
||||
onOpenWorkspaceFile,
|
||||
}: {
|
||||
@@ -1554,18 +1614,19 @@ const AgentStreamSection = memo(function AgentStreamSection({
|
||||
hasAppliedAuthoritativeHistory: boolean;
|
||||
isInitialHistoryLoading: boolean;
|
||||
revealInitialHistory: boolean;
|
||||
/** Whether the composer's track bar sits over the bottom of the stream. */
|
||||
reservesTrack: boolean;
|
||||
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
|
||||
hasActiveComposer: boolean;
|
||||
toast: ReturnType<typeof useToastHost>["api"];
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
// The track bar's space is reserved whenever the bar is mounted, pills or not: pills come and go
|
||||
// every turn, and the transcript must not jump with them.
|
||||
const bottomOverlayTailClearance = hasActiveComposer
|
||||
const bottomOverlayTailClearance = reservesTrack
|
||||
? resolveComposerTrackTailClearance(isCompactFormFactor)
|
||||
: 0;
|
||||
const bottomOverlayControlClearance = hasActiveComposer
|
||||
const bottomOverlayControlClearance = reservesTrack
|
||||
? resolveComposerTrackControlClearance(isCompactFormFactor)
|
||||
: 0;
|
||||
const streamItemsRaw = useAgentStreamTail(serverId, agentId);
|
||||
@@ -1699,6 +1760,7 @@ function DraftComposerSection({
|
||||
const AgentComposerSection = memo(function AgentComposerSection({
|
||||
agentId,
|
||||
serverId,
|
||||
surface,
|
||||
isPaneFocused,
|
||||
isArchivingCurrentAgent,
|
||||
isWorkspaceRestoring,
|
||||
@@ -1714,6 +1776,7 @@ const AgentComposerSection = memo(function AgentComposerSection({
|
||||
}: {
|
||||
agentId?: string;
|
||||
serverId: string;
|
||||
surface: ConversationSurface;
|
||||
isPaneFocused: boolean;
|
||||
isArchivingCurrentAgent: boolean;
|
||||
isWorkspaceRestoring: boolean;
|
||||
@@ -1743,36 +1806,28 @@ const AgentComposerSection = memo(function AgentComposerSection({
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<ActiveAgentComposer
|
||||
agentId={agentId}
|
||||
serverId={serverId}
|
||||
isPaneFocused={isPaneFocused}
|
||||
cwd={cwd}
|
||||
isSubmitLoading={isSubmitLoading}
|
||||
agentInputDraft={agentInputDraft}
|
||||
editingSession={editingSession}
|
||||
onAttentionInputFocus={onAttentionInputFocus}
|
||||
onAttentionPromptSend={onAttentionPromptSend}
|
||||
onComposerHeightChange={onComposerHeightChange}
|
||||
onMessageSent={onMessageSent}
|
||||
/>
|
||||
);
|
||||
const composer: AgentComposerProps = {
|
||||
agentId,
|
||||
serverId,
|
||||
isPaneFocused,
|
||||
cwd,
|
||||
isSubmitLoading,
|
||||
agentInputDraft,
|
||||
editingSession,
|
||||
onAttentionInputFocus,
|
||||
onAttentionPromptSend,
|
||||
onComposerHeightChange,
|
||||
onMessageSent,
|
||||
};
|
||||
if (surface.kind === "embed") {
|
||||
return surface.composer ? (
|
||||
<EmbeddedAgentComposer {...composer} options={surface.composer} />
|
||||
) : null;
|
||||
}
|
||||
return <PaneAgentComposer {...composer} />;
|
||||
});
|
||||
|
||||
function ActiveAgentComposer({
|
||||
agentId,
|
||||
serverId,
|
||||
isPaneFocused,
|
||||
cwd,
|
||||
isSubmitLoading,
|
||||
agentInputDraft,
|
||||
editingSession,
|
||||
onAttentionInputFocus,
|
||||
onAttentionPromptSend,
|
||||
onComposerHeightChange,
|
||||
onMessageSent,
|
||||
}: {
|
||||
interface AgentComposerProps {
|
||||
agentId: string;
|
||||
serverId: string;
|
||||
isPaneFocused: boolean;
|
||||
@@ -1784,12 +1839,83 @@ function ActiveAgentComposer({
|
||||
onAttentionPromptSend: () => void;
|
||||
onComposerHeightChange: (height: number) => void;
|
||||
onMessageSent: () => void;
|
||||
}) {
|
||||
}
|
||||
|
||||
/** What differs between the composer of a workspace tab and that of an embed. */
|
||||
interface AgentComposerSurfaceProps {
|
||||
workspaceId: string | null;
|
||||
onClientSlashCommand: (command: ClientSlashCommand) => Promise<void>;
|
||||
attachmentScopeKeys?: readonly string[];
|
||||
onOpenWorkspaceAttachment?: (attachment: WorkspaceComposerAttachment) => void;
|
||||
autoFocus: boolean;
|
||||
inputMode?: ComposerInputMode;
|
||||
placeholder?: string;
|
||||
}
|
||||
|
||||
function AgentComposer({
|
||||
agentId,
|
||||
serverId,
|
||||
isPaneFocused,
|
||||
cwd,
|
||||
isSubmitLoading,
|
||||
agentInputDraft,
|
||||
editingSession,
|
||||
onAttentionInputFocus,
|
||||
onAttentionPromptSend,
|
||||
onComposerHeightChange,
|
||||
onMessageSent,
|
||||
workspaceId,
|
||||
onClientSlashCommand,
|
||||
attachmentScopeKeys,
|
||||
onOpenWorkspaceAttachment,
|
||||
autoFocus,
|
||||
inputMode,
|
||||
placeholder,
|
||||
}: AgentComposerProps & AgentComposerSurfaceProps) {
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow(
|
||||
COMPACT_CONTENT_WIDTH,
|
||||
{ initialIsBelow: isCompactFormFactor },
|
||||
);
|
||||
return (
|
||||
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
|
||||
<Composer
|
||||
agentId={agentId}
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
blurOnSubmit={isNative}
|
||||
isPaneFocused={isPaneFocused}
|
||||
textSource={agentInputDraft.textSource}
|
||||
onChangeText={agentInputDraft.editText}
|
||||
textReplacement={agentInputDraft.textReplacement}
|
||||
attachments={agentInputDraft.attachments}
|
||||
attachmentScopeKeys={attachmentScopeKeys}
|
||||
onOpenWorkspaceAttachment={onOpenWorkspaceAttachment}
|
||||
onChangeAttachments={agentInputDraft.setAttachments}
|
||||
cwd={cwd}
|
||||
getDraftRevision={agentInputDraft.getRevision}
|
||||
clearDraft={agentInputDraft.clear}
|
||||
editingSession={editingSession}
|
||||
autoFocus={autoFocus}
|
||||
autoFocusKey={String(agentInputDraft.attachmentFocusRequestId)}
|
||||
isSubmitLoading={isSubmitLoading}
|
||||
onAttentionInputFocus={onAttentionInputFocus}
|
||||
onAttentionPromptSend={onAttentionPromptSend}
|
||||
onComposerHeightChange={onComposerHeightChange}
|
||||
onMessageSent={onMessageSent}
|
||||
onClientSlashCommand={onClientSlashCommand}
|
||||
inputMode={inputMode}
|
||||
placeholder={placeholder}
|
||||
isCompactLayout={isCompactComposerLayout}
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** A workspace tab's composer: `/exit` and `/clear` close or retarget the tab. */
|
||||
function PaneAgentComposer(props: AgentComposerProps) {
|
||||
const { agentId, serverId, cwd } = props;
|
||||
const isCompactFormFactor = useIsCompactFormFactor();
|
||||
const paneContext = usePaneContext();
|
||||
const openInSidePane = useSettings((settings) => settings.openInSidePane);
|
||||
const { workspaceId, tabId, retargetCurrentTab } = paneContext;
|
||||
@@ -1859,35 +1985,61 @@ function ActiveAgentComposer({
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
|
||||
<Composer
|
||||
agentId={agentId}
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
blurOnSubmit={isNative}
|
||||
isPaneFocused={isPaneFocused}
|
||||
textSource={agentInputDraft.textSource}
|
||||
onChangeText={agentInputDraft.editText}
|
||||
textReplacement={agentInputDraft.textReplacement}
|
||||
attachments={agentInputDraft.attachments}
|
||||
attachmentScopeKeys={attachmentScopeKeys}
|
||||
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
|
||||
onChangeAttachments={agentInputDraft.setAttachments}
|
||||
cwd={cwd}
|
||||
getDraftRevision={agentInputDraft.getRevision}
|
||||
clearDraft={agentInputDraft.clear}
|
||||
editingSession={editingSession}
|
||||
autoFocus
|
||||
autoFocusKey={String(agentInputDraft.attachmentFocusRequestId)}
|
||||
isSubmitLoading={isSubmitLoading}
|
||||
onAttentionInputFocus={onAttentionInputFocus}
|
||||
onAttentionPromptSend={onAttentionPromptSend}
|
||||
onComposerHeightChange={onComposerHeightChange}
|
||||
onMessageSent={onMessageSent}
|
||||
onClientSlashCommand={handleClientSlashCommand}
|
||||
isCompactLayout={isCompactComposerLayout}
|
||||
/>
|
||||
</View>
|
||||
<AgentComposer
|
||||
{...props}
|
||||
workspaceId={workspaceId}
|
||||
onClientSlashCommand={handleClientSlashCommand}
|
||||
attachmentScopeKeys={attachmentScopeKeys}
|
||||
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
|
||||
autoFocus
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The composer of an embed. It has no tab: `/clear` archives the agent and opens a fresh draft in
|
||||
* the agent's workspace, as forking to a tab does. It does not take focus on mount; the plugin's
|
||||
* screen decides where the user starts.
|
||||
*/
|
||||
function EmbeddedAgentComposer({
|
||||
options,
|
||||
...props
|
||||
}: AgentComposerProps & { options: EmbeddedComposer }) {
|
||||
const { agentId, serverId } = props;
|
||||
const workspaceId = useSessionStore(
|
||||
(state) => resolveChatAgentFromSession(state, serverId, agentId)?.workspaceId ?? null,
|
||||
);
|
||||
const { archiveAgent } = useArchiveAgent();
|
||||
const handleClientSlashCommand = useCallback(
|
||||
async (command: ClientSlashCommand) => {
|
||||
const agent = resolveChatAgentFromSession(useSessionStore.getState(), serverId, agentId);
|
||||
if (!agent) {
|
||||
throw new Error("Agent not found");
|
||||
}
|
||||
if (command.kind === "replace-agent-with-draft") {
|
||||
if (!agent.workspaceId) {
|
||||
throw new Error("This agent has no workspace to start a draft in");
|
||||
}
|
||||
navigateToWorkspace({
|
||||
serverId,
|
||||
workspaceId: agent.workspaceId,
|
||||
target: { kind: "draft", draftId: generateDraftId(), setup: buildDraftAgentSetup(agent) },
|
||||
});
|
||||
}
|
||||
await archiveAgent({ serverId, agentId });
|
||||
},
|
||||
[agentId, archiveAgent, serverId],
|
||||
);
|
||||
|
||||
return (
|
||||
<AgentComposer
|
||||
{...props}
|
||||
workspaceId={workspaceId}
|
||||
onClientSlashCommand={handleClientSlashCommand}
|
||||
autoFocus={false}
|
||||
inputMode={options.inputMode}
|
||||
placeholder={options.placeholder}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -84,3 +84,8 @@ export function usePaneFocus(): PaneFocusContextValue {
|
||||
invariant(value, "PaneFocusContext is required");
|
||||
return value;
|
||||
}
|
||||
|
||||
/** The focus of the pane around this component, or null on a screen with no panes. */
|
||||
export function useEnclosingPaneFocus(): PaneFocusContextValue | null {
|
||||
return useContext(PaneFocusContext);
|
||||
}
|
||||
|
||||
@@ -836,7 +836,8 @@ describe("evaluatePluginClientBundle", () => {
|
||||
`(function(require) {
|
||||
const shared = require("@getpaseo/plugin");
|
||||
const client = require("@getpaseo/plugin/client");
|
||||
const { ExternalLink, Loading, Markdown } = require("@getpaseo/plugin/client/ui");
|
||||
const { AgentChat, ExternalLink, Loading, Markdown } = require("@getpaseo/plugin/client/ui");
|
||||
if (typeof AgentChat !== "function") throw new Error("AgentChat");
|
||||
if (typeof Markdown !== "function") throw new Error("Markdown");
|
||||
if (typeof ExternalLink !== "function") throw new Error("ExternalLink");
|
||||
if (typeof Loading !== "function") throw new Error("Loading");
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import type { AgentChatProps } from "@getpaseo/plugin/client/ui";
|
||||
import { lazy, Suspense, useMemo } from "react";
|
||||
import type { EmbeddedComposer } from "@/agent-embed";
|
||||
import { FilePanelLoading } from "@/file-panels/loading";
|
||||
import { usePluginInstallationServerId } from "../installation-provider";
|
||||
|
||||
/**
|
||||
* The embed renders the agent tab's chain, composer included. The plugin runtime loads this
|
||||
* module with the host runtime, so a static import would put the whole chat surface in the host
|
||||
* runtime's import graph. Only the first chat of a session waits for it.
|
||||
*/
|
||||
const AgentEmbed = lazy(async () => ({ default: (await import("@/agent-embed")).AgentEmbed }));
|
||||
|
||||
const LOADING = <FilePanelLoading />;
|
||||
|
||||
export function AgentChat({ agentId, hostId, composer, testID }: AgentChatProps) {
|
||||
const installationServerId = usePluginInstallationServerId();
|
||||
const serverId = hostId ?? installationServerId;
|
||||
const hasComposer = composer !== false;
|
||||
const inputMode = composer && composer.controls === "none" ? "message" : "chat";
|
||||
const placeholder = composer ? composer.placeholder : undefined;
|
||||
const embedComposer = useMemo<EmbeddedComposer | null>(
|
||||
() => (hasComposer ? { inputMode, placeholder } : null),
|
||||
[hasComposer, inputMode, placeholder],
|
||||
);
|
||||
if (!serverId) {
|
||||
throw new Error("AgentChat needs a hostId outside a plugin surface");
|
||||
}
|
||||
|
||||
return (
|
||||
<Suspense fallback={LOADING}>
|
||||
<AgentEmbed serverId={serverId} agentId={agentId} composer={embedComposer} testID={testID} />
|
||||
</Suspense>
|
||||
);
|
||||
}
|
||||
@@ -30,3 +30,4 @@ export { useToast } from "./toast";
|
||||
export { StreamedText } from "./streamed-text";
|
||||
|
||||
export { Markdown } from "./markdown";
|
||||
export { AgentChat } from "./agent-chat";
|
||||
|
||||
@@ -27,6 +27,7 @@ import { isAgentArchiving, setAgentArchiving } from "@/hooks/use-archive-agent";
|
||||
import { queryClient } from "@/data/query-client";
|
||||
import { checkoutStatusQueryKey } from "@/git/query-keys";
|
||||
import {
|
||||
buildRoutedProbeClientConfig,
|
||||
HostRuntimeController,
|
||||
HostRuntimeStore,
|
||||
readInitialDaemonConnectionHint,
|
||||
@@ -6379,4 +6380,54 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("uses persisted clientId and resolved app client identity on routed probes with an isolated route scope", async () => {
|
||||
const cancelledScopes: string[] = [];
|
||||
const openedScopes: string[] = [];
|
||||
const origin = {
|
||||
subscribeRawMessages: () => () => undefined,
|
||||
subscribeHostFrames: () => () => undefined,
|
||||
subscribeConnectionStatus: () => () => undefined,
|
||||
openHostRoute: (_serverId: string, scopeId: string) => {
|
||||
openedScopes.push(scopeId);
|
||||
return new Promise<never>(() => undefined);
|
||||
},
|
||||
cancelHostRoute: (scopeId: string) => {
|
||||
cancelledScopes.push(scopeId);
|
||||
},
|
||||
closeHostRoute: () => undefined,
|
||||
} as unknown as DaemonClient;
|
||||
|
||||
const config = await buildRoutedProbeClientConfig({
|
||||
origin,
|
||||
serverId: "srv_routed_target",
|
||||
getClientId: async () => "cid_persisted_device",
|
||||
resolveClientIdentity: () => ({
|
||||
clientType: "browser",
|
||||
clientInfo: {
|
||||
appKind: "desktop",
|
||||
platform: "linux",
|
||||
name: "workstation",
|
||||
osName: "Linux",
|
||||
osVersion: "Ubuntu 24.04",
|
||||
},
|
||||
}),
|
||||
});
|
||||
|
||||
expect(config.clientId).toBe("cid_persisted_device");
|
||||
expect(config.clientType).toBe("browser");
|
||||
expect(config.clientInfo).toEqual({
|
||||
appKind: "desktop",
|
||||
platform: "linux",
|
||||
name: "workstation",
|
||||
osName: "Linux",
|
||||
osVersion: "Ubuntu 24.04",
|
||||
});
|
||||
|
||||
const transport = config.transportFactory!({ url: "ws://routed-host/ws" });
|
||||
transport.close();
|
||||
expect(openedScopes).toHaveLength(1);
|
||||
expect(openedScopes[0]).not.toBe("cid_persisted_device");
|
||||
expect(cancelledScopes).toEqual([openedScopes[0]]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -585,6 +585,38 @@ function probeIntervalForConnection(
|
||||
return PROBE_MAX_BACKOFF_MS;
|
||||
}
|
||||
|
||||
export async function buildRoutedProbeClientConfig(params: {
|
||||
origin: DaemonClient;
|
||||
serverId: string;
|
||||
capabilities?: DaemonClientConfig["capabilities"];
|
||||
trace?: DaemonClientConfig["trace"];
|
||||
getClientId?: () => Promise<string>;
|
||||
resolveClientIdentity?: typeof resolveAppClientIdentity;
|
||||
probeScopeId?: string;
|
||||
}): Promise<DaemonClientConfig> {
|
||||
const clientId = await (params.getClientId ?? getOrCreateClientId)();
|
||||
const probeScopeId = params.probeScopeId ?? crypto.randomUUID();
|
||||
const appIdentity = (params.resolveClientIdentity ?? resolveAppClientIdentity)();
|
||||
return {
|
||||
url: "ws://routed-host/ws",
|
||||
clientId,
|
||||
clientType: appIdentity.clientType,
|
||||
clientInfo: appIdentity.clientInfo,
|
||||
transportFactory: createHostChannelTransport(
|
||||
params.origin,
|
||||
params.serverId,
|
||||
probeScopeId,
|
||||
null,
|
||||
),
|
||||
reconnect: { enabled: false },
|
||||
logger: createHostLogger(() => params.serverId),
|
||||
appVersion: resolveAppVersion() ?? undefined,
|
||||
...(params.capabilities ? { capabilities: params.capabilities } : {}),
|
||||
...(params.trace ? { trace: params.trace } : {}),
|
||||
createPluginClientBundleStore: createHostPluginClientBundleStore,
|
||||
};
|
||||
}
|
||||
|
||||
function createDefaultDeps(
|
||||
resolveOrigin: (serverId: string) => DaemonClient | null = () => null,
|
||||
): HostRuntimeControllerDeps {
|
||||
@@ -679,20 +711,14 @@ function createDefaultDeps(
|
||||
const origin = resolveOrigin(connection.originServerId);
|
||||
if (!origin?.isConnected)
|
||||
throw new Error(`Origin host ${connection.originServerId} is unavailable`);
|
||||
const client = new DaemonClient({
|
||||
url: "ws://routed-host/ws",
|
||||
clientId: crypto.randomUUID(),
|
||||
transportFactory: createHostChannelTransport(
|
||||
const client = new DaemonClient(
|
||||
await buildRoutedProbeClientConfig({
|
||||
origin,
|
||||
host.serverId,
|
||||
crypto.randomUUID(),
|
||||
null,
|
||||
),
|
||||
reconnect: { enabled: false },
|
||||
logger: createHostLogger(() => host.serverId),
|
||||
appVersion: resolveAppVersion() ?? undefined,
|
||||
createPluginClientBundleStore: createHostPluginClientBundleStore,
|
||||
});
|
||||
serverId: host.serverId,
|
||||
capabilities: appCapabilities,
|
||||
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
|
||||
}),
|
||||
);
|
||||
try {
|
||||
await client.connect();
|
||||
return { client, serverId: host.serverId, hostname: null };
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { PairDeviceModal } from "@/devices";
|
||||
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
|
||||
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
|
||||
export function OpenProjectScreen() {
|
||||
const { t } = useTranslation();
|
||||
@@ -61,11 +60,7 @@ export function OpenProjectScreen() {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<MenuHeader borderless />
|
||||
<ScrollView
|
||||
style={styles.scroll}
|
||||
contentContainerStyle={styles.scrollContent}
|
||||
dataSet={WINDOW_CONTENT_DATASET}
|
||||
>
|
||||
<ScrollView style={styles.scroll} contentContainerStyle={styles.scrollContent}>
|
||||
<View style={styles.content}>
|
||||
<View style={styles.logo}>
|
||||
<PaseoLogo size={52} />
|
||||
|
||||
@@ -1,12 +1,4 @@
|
||||
import {
|
||||
createContext,
|
||||
useCallback,
|
||||
useContext,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
type ComponentType,
|
||||
} from "react";
|
||||
import { createContext, useCallback, useContext, useMemo, type ComponentType } from "react";
|
||||
import { View } from "react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
@@ -22,8 +14,7 @@ import {
|
||||
import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu";
|
||||
import type { PanelIconProps } from "@/panels/panel-registry";
|
||||
import { getPanelRegistration } from "@/panels/panel-registry";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
import { useViewedAgent } from "@/timeline/use-viewed-agent";
|
||||
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { WorkspacePaneContent } from "@/screens/workspace/workspace-pane-content";
|
||||
@@ -139,7 +130,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
|
||||
);
|
||||
const exit = useMemo<SheetPaneExit>(() => ({ close: onClose, opener }), [onClose, opener]);
|
||||
const isPaneFocused = isTop && host.isWorkspaceFocused;
|
||||
useViewedSheetAgent({
|
||||
useViewedAgent({
|
||||
sourceId: `${workspaceKey}:sheet:${tab.tabId}`,
|
||||
serverId: host.serverId,
|
||||
agentId: isPaneFocused && tab.target.kind === "agent" ? tab.target.agentId : null,
|
||||
@@ -199,35 +190,6 @@ function SheetFileMenu({ path, onClose }: { path: string; onClose: () => void })
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent of the sheet on top is viewed, alongside the pane under it: its timeline catches up
|
||||
* and stays live. The workspace only publishes the agents of its panes.
|
||||
*/
|
||||
function useViewedSheetAgent({
|
||||
sourceId,
|
||||
serverId,
|
||||
agentId,
|
||||
}: {
|
||||
sourceId: string;
|
||||
serverId: string;
|
||||
agentId: string | null;
|
||||
}) {
|
||||
const viewedTimelineSync = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.viewedTimelineSync ?? null,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!agentId) return;
|
||||
void getHostRuntimeStore()
|
||||
.prepareAgentTimeline(serverId, agentId)
|
||||
.catch(() => undefined);
|
||||
}, [agentId, serverId]);
|
||||
useLayoutEffect(() => {
|
||||
if (!agentId || !viewedTimelineSync) return;
|
||||
viewedTimelineSync.replaceVisibleAgentIds(sourceId, [agentId]);
|
||||
return () => viewedTimelineSync.replaceVisibleAgentIds(sourceId, []);
|
||||
}, [agentId, sourceId, viewedTimelineSync]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Leaves the sheet the calling pane is shown in, if any, on the way to `destination`. Answers
|
||||
* whether closing the sheet already lands there, so the caller navigates only when it does not.
|
||||
|
||||
@@ -106,7 +106,11 @@ export function useWorkspaceExplorerControls({
|
||||
/>
|
||||
),
|
||||
titlebarAction: (
|
||||
<View pointerEvents="box-none" style={styles.titlebarSlot}>
|
||||
<View
|
||||
pointerEvents="box-none"
|
||||
style={styles.titlebarSlot}
|
||||
dataSet={WINDOW_NO_DRAG_DATASET}
|
||||
>
|
||||
<WorkspaceExplorerToggle {...props} mobile={false} />
|
||||
</View>
|
||||
),
|
||||
|
||||
@@ -151,7 +151,7 @@ import {
|
||||
import { useDesktopBrowserNewTabRequests } from "@/desktop/browser/new-tab-requests";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
import { useWorkspaceExplorerControls } from "@/screens/workspace/workspace-explorer-toggle";
|
||||
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
|
||||
import { WindowChromeRegion } from "@/utils/desktop-window";
|
||||
import {
|
||||
resolveWorkspaceHeaderRenderState,
|
||||
type WorkspaceHeaderCheckoutState,
|
||||
@@ -3182,11 +3182,7 @@ function WorkspaceScreenContent({
|
||||
},
|
||||
};
|
||||
const compactWorkspaceHeader = renderCompactWorkspaceHeader(workspaceCompactHeaderTabs);
|
||||
// SplitContainer reserves the corner around its own compact headers; this is the column's.
|
||||
const centerColumnCompactHeader = useMemo(
|
||||
() => <WindowChromeSafeArea placement="inline">{compactWorkspaceHeader}</WindowChromeSafeArea>,
|
||||
[compactWorkspaceHeader],
|
||||
);
|
||||
const centerColumnCompactHeader = compactWorkspaceHeader;
|
||||
const fullWorkspaceActions = renderCompactWorkspaceHeader(workspaceCompactHeaderTabs, true);
|
||||
const desktopSplitContent = useMemo(() => {
|
||||
if (!canRenderDesktopPaneSplits || !workspaceLayout || !persistenceKey) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createStreamPresentation } from "@/agent-stream/presentation";
|
||||
import { DatabaseSync } from "node:sqlite";
|
||||
import { ReplicaCache } from "@/runtime/replica-cache";
|
||||
import {
|
||||
@@ -1221,6 +1222,65 @@ describe("the turn footer changes together with its messages", () => {
|
||||
owner.dispose();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ endsOffline: true, expectedPhase: "complete", expectedFooter: "settled" },
|
||||
{ endsOffline: false, expectedPhase: "streaming", expectedFooter: "running" },
|
||||
])(
|
||||
"reconciles a live reply after reconnect (turn ends offline: $endsOffline)",
|
||||
async ({ endsOffline, expectedPhase, expectedFooter }) => {
|
||||
const owner = createChat(null);
|
||||
try {
|
||||
agentIsRunning();
|
||||
await connectAndCatchUp(owner);
|
||||
owner.applyStreamEvent(AGENT_ID, {
|
||||
event: {
|
||||
type: "timeline",
|
||||
provider: "claude",
|
||||
turnId: OPEN_TURN.turnId,
|
||||
item: { type: "assistant_message", text: "Done.", messageId: "reply-1" },
|
||||
},
|
||||
seq: 5,
|
||||
epoch: "epoch-1",
|
||||
timestamp: new Date("2026-08-26T10:00:01.000Z"),
|
||||
});
|
||||
owner.flushStreamAgent(AGENT_ID);
|
||||
const session = () => useSessionStore.getState().sessions[SERVER_ID];
|
||||
const present = createStreamPresentation();
|
||||
const replyPhases = () => {
|
||||
const phases: string[] = [];
|
||||
present({
|
||||
display: "collapseToolCalls",
|
||||
expandedTurnHostIds: new Set(),
|
||||
isTurnActive: footer() === "running",
|
||||
tail: session()?.agentStreamTail.get(AGENT_ID) ?? [],
|
||||
head: session()?.agentStreamHead.get(AGENT_ID) ?? [],
|
||||
transform: ({ item: source, phase }) => {
|
||||
if (source.type === "assistant_message" && source.text === "Done.")
|
||||
phases.push(phase);
|
||||
return undefined;
|
||||
},
|
||||
});
|
||||
return phases;
|
||||
};
|
||||
expect(replyPhases()).toEqual(["streaming"]);
|
||||
|
||||
owner.setConnected(false);
|
||||
owner.setConnected(true);
|
||||
if (endsOffline) idleSnapshotArrives();
|
||||
owner.applyTimelineResponse({
|
||||
...catchUpPage({ replyThroughSeq: null }),
|
||||
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
|
||||
});
|
||||
|
||||
expect(footer()).toBe(expectedFooter);
|
||||
expect(replies()).toEqual(["Done."]);
|
||||
expect(replyPhases()).toEqual([expectedPhase]);
|
||||
} finally {
|
||||
owner.dispose();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("a turn that ended with no new messages settles when the empty catch-up lands", async () => {
|
||||
const owner = createChat("Done.");
|
||||
agentIsRunning();
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { useEffect, useLayoutEffect } from "react";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { useSessionStore } from "@/stores/session-store";
|
||||
|
||||
/**
|
||||
* Shows one agent from a viewer outside the workspace's panes, such as a sheet or a plugin's
|
||||
* embedded timeline: its timeline catches up and stays live while the viewer is mounted. Each
|
||||
* viewer is its own `sourceId`; the sync observes the union of every source, so a tab and any
|
||||
* number of viewers of the same agent share one daemon observation, and removing one viewer
|
||||
* leaves the others live.
|
||||
*/
|
||||
export function useViewedAgent({
|
||||
sourceId,
|
||||
serverId,
|
||||
agentId,
|
||||
}: {
|
||||
sourceId: string;
|
||||
serverId: string;
|
||||
agentId: string | null;
|
||||
}) {
|
||||
const viewedTimelineSync = useSessionStore(
|
||||
(state) => state.sessions[serverId]?.viewedTimelineSync ?? null,
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!agentId) return;
|
||||
void getHostRuntimeStore()
|
||||
.prepareAgentTimeline(serverId, agentId)
|
||||
.catch(() => undefined);
|
||||
}, [agentId, serverId]);
|
||||
useLayoutEffect(() => {
|
||||
if (!agentId || !viewedTimelineSync) return;
|
||||
viewedTimelineSync.replaceVisibleAgentIds(sourceId, [agentId]);
|
||||
return () => viewedTimelineSync.replaceVisibleAgentIds(sourceId, []);
|
||||
}, [agentId, sourceId, viewedTimelineSync]);
|
||||
}
|
||||
@@ -30,7 +30,7 @@ import {
|
||||
processTimelineResponse,
|
||||
} from "./session-stream-reducers";
|
||||
import { isTimelineResumeSnapshotAuthoritative } from "./timeline-sync-plan";
|
||||
import { replaceWithCanonicalStream } from "@/types/stream";
|
||||
import { flushHeadToTail, replaceWithCanonicalStream } from "@/types/stream";
|
||||
import type { TurnLivenessTransition } from "./turn-liveness";
|
||||
|
||||
export interface TimelineReplicaStorage {
|
||||
@@ -297,6 +297,33 @@ function finalizeProcessedTimeline(input: {
|
||||
if (input.result.initResolution === "resolve") resolveInitDeferred(input.initKey);
|
||||
}
|
||||
|
||||
function settleRecoveredTurn(input: {
|
||||
session: SessionState | undefined;
|
||||
payload: TimelineResponsePayload;
|
||||
result: ProcessTimelineResponseOutput;
|
||||
synchronized: boolean;
|
||||
}): ProcessTimelineResponseOutput {
|
||||
const { session, payload, result, synchronized } = input;
|
||||
if (!synchronized || result.head.length === 0) return result;
|
||||
|
||||
const agentId = payload.agentId;
|
||||
const turn = (session?.agents.get(agentId) ?? session?.agentDetails.get(agentId))?.turn;
|
||||
const heldTurn = session?.agentTimelineUnsettledTurn.get(agentId);
|
||||
if (turn?.phase !== "idle" || !heldTurn) return result;
|
||||
if (result.sideEffects.some(({ type }) => type === "catch_up")) return result;
|
||||
|
||||
// A turn end that happened offline is not a timeline row. Commit the live rows
|
||||
// from that turn if the response covers all of them.
|
||||
const covered = result.head.every(
|
||||
({ timelineCursor, turnId }) =>
|
||||
(turnId ?? null) === heldTurn.turnId &&
|
||||
timelineCursor?.epoch === payload.epoch &&
|
||||
timelineCursor.seq <= payload.window.maxSeq,
|
||||
);
|
||||
if (!covered) return result;
|
||||
return { ...result, commit: "apply", tail: flushHeadToTail(result.tail, result.head), head: [] };
|
||||
}
|
||||
|
||||
function applyAuthoritativeTimelineResponse(input: {
|
||||
serverId: string;
|
||||
payload: TimelineResponsePayload;
|
||||
@@ -333,12 +360,20 @@ function applyAuthoritativeTimelineResponse(input: {
|
||||
hasNewer: payload.hasNewer,
|
||||
error: payload.error,
|
||||
});
|
||||
commitProcessedTimeline({ serverId, payload, result, timeline, currentCursor, synchronized });
|
||||
const settledResult = settleRecoveredTurn({ session, payload, result, synchronized });
|
||||
commitProcessedTimeline({
|
||||
serverId,
|
||||
payload,
|
||||
result: settledResult,
|
||||
timeline,
|
||||
currentCursor,
|
||||
synchronized,
|
||||
});
|
||||
finalizeProcessedTimeline({
|
||||
serverId,
|
||||
agentId,
|
||||
initKey,
|
||||
result,
|
||||
result: settledResult,
|
||||
recoverGap: input.recoverGap,
|
||||
});
|
||||
return true;
|
||||
|
||||
@@ -390,4 +390,37 @@ describe("test-daemon-connection connectToDaemon", () => {
|
||||
message: "Transport error",
|
||||
});
|
||||
});
|
||||
|
||||
it("uses resolved app client identity instead of hardcoding mobile on probe-adopted connections", async () => {
|
||||
const { buildClientConfig } = await import("./test-daemon-connection");
|
||||
const { resolveDesktopClientIdentity } = await import("@/devices/client-info-parsers");
|
||||
const config = await buildClientConfig(
|
||||
{
|
||||
id: "relay:test",
|
||||
type: "relay",
|
||||
relayEndpoint: "relay.paseo.sh:443",
|
||||
daemonPublicKeyB64: "pubkey",
|
||||
},
|
||||
"srv_probe_test",
|
||||
{},
|
||||
{
|
||||
...probe.deps,
|
||||
resolveClientIdentity: () =>
|
||||
resolveDesktopClientIdentity({
|
||||
platform: "darwin",
|
||||
deviceName: "Mo-MacBook-Pro",
|
||||
osVersion: "15.3.1",
|
||||
browserHostLabel: "Mo-MacBook-Pro · Window 1 (A1B2C3)",
|
||||
}),
|
||||
},
|
||||
);
|
||||
expect(config.clientType).toBe("browser");
|
||||
expect(config.clientInfo).toMatchObject({
|
||||
appKind: "desktop",
|
||||
platform: "macos",
|
||||
name: "Mo-MacBook-Pro",
|
||||
osName: "macOS",
|
||||
osVersion: "15.3.1",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,7 @@ import { createAppWebSocketFactory } from "@/runtime/websocket-factory";
|
||||
import { createHostLogger } from "@/runtime/host-logger";
|
||||
import { getOrCreateClientId } from "./client-id";
|
||||
import { resolveAppVersion } from "./app-version";
|
||||
import { resolveAppClientIdentity } from "@/devices/client-info";
|
||||
import {
|
||||
buildDaemonWebSocketUrl,
|
||||
buildRelayWebSocketUrl,
|
||||
@@ -37,6 +38,7 @@ export interface DaemonConnectionDependencies<TClient extends DaemonProbeClient>
|
||||
createLogger: typeof createHostLogger;
|
||||
getClientId(): Promise<string>;
|
||||
resolveAppVersion(): string | null;
|
||||
resolveClientIdentity?: typeof resolveAppClientIdentity;
|
||||
createDesktopTransportFactory(): DaemonClientConfig["transportFactory"] | null;
|
||||
buildDesktopTransportUrl(input: DesktopDaemonTransportTarget): string;
|
||||
createClient(config: DaemonClientConfig): TClient;
|
||||
@@ -46,6 +48,7 @@ const defaultDaemonConnectionDependencies: DaemonConnectionDependencies<DaemonCl
|
||||
createLogger: createHostLogger,
|
||||
getClientId: getOrCreateClientId,
|
||||
resolveAppVersion,
|
||||
resolveClientIdentity: resolveAppClientIdentity,
|
||||
createDesktopTransportFactory: createDesktopDaemonTransportFactory,
|
||||
buildDesktopTransportUrl: buildDesktopDaemonTransportUrl,
|
||||
createClient: (config) => new DaemonClient(config),
|
||||
@@ -174,6 +177,7 @@ export async function buildClientConfig(
|
||||
DaemonConnectionDependencies<DaemonProbeClient>,
|
||||
| "getClientId"
|
||||
| "resolveAppVersion"
|
||||
| "resolveClientIdentity"
|
||||
| "createDesktopTransportFactory"
|
||||
| "buildDesktopTransportUrl"
|
||||
> = defaultDaemonConnectionDependencies,
|
||||
@@ -181,10 +185,12 @@ export async function buildClientConfig(
|
||||
if (connection.type === "routed")
|
||||
throw new Error("Routed host connections are resolved by HostRuntime");
|
||||
const clientId = await deps.getClientId();
|
||||
const appIdentity = (deps.resolveClientIdentity ?? resolveAppClientIdentity)();
|
||||
const desktopTransportFactory = deps.createDesktopTransportFactory();
|
||||
const base = {
|
||||
clientId,
|
||||
clientType: "mobile" as const,
|
||||
clientType: appIdentity.clientType,
|
||||
clientInfo: appIdentity.clientInfo,
|
||||
appVersion: deps.resolveAppVersion() ?? undefined,
|
||||
suppressSendErrors: true,
|
||||
webSocketFactory: createAppWebSocketFactory(),
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Portal, PortalHost } from "@gorhom/portal";
|
||||
import { StyleSheet, View } from "react-native";
|
||||
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
|
||||
import { RetainedPanelActivity } from "@/components/retained-panel";
|
||||
import { IconButtonChromeProvider } from "@/components/ui/icon-button-chrome";
|
||||
import { useWindowLayout } from "./context";
|
||||
@@ -29,6 +30,7 @@ export function WindowLayoutActions({
|
||||
<Portal hostName={HOST}>
|
||||
<View
|
||||
testID="workspace-vertical-actions"
|
||||
dataSet={WINDOW_OVERLAY_HOST_DATASET}
|
||||
style={[
|
||||
styles.bar,
|
||||
{ left: bar.x, top: bar.y, width: bar.width, height: bar.height },
|
||||
|
||||
@@ -155,3 +155,24 @@ export const Laptop = StubIcon;
|
||||
export const Network = StubIcon;
|
||||
export const PcCase = StubIcon;
|
||||
export const Waypoints = StubIcon;
|
||||
export const AlertCircle = StubIcon;
|
||||
export const ArchiveRestore = StubIcon;
|
||||
export const ArrowUpToLine = StubIcon;
|
||||
export const BookOpen = StubIcon;
|
||||
export const Boxes = StubIcon;
|
||||
export const Bug = StubIcon;
|
||||
export const ChevronUp = StubIcon;
|
||||
export const Compass = StubIcon;
|
||||
export const CornerUpLeft = StubIcon;
|
||||
export const Database = StubIcon;
|
||||
export const Feather = StubIcon;
|
||||
export const FlaskConical = StubIcon;
|
||||
export const Hammer = StubIcon;
|
||||
export const Microscope = StubIcon;
|
||||
export const Minimize2 = StubIcon;
|
||||
export const Package = StubIcon;
|
||||
export const Palette = StubIcon;
|
||||
export const Pause = StubIcon;
|
||||
export const Rocket = StubIcon;
|
||||
export const Summary = StubIcon;
|
||||
export const TestTube = StubIcon;
|
||||
|
||||
@@ -227,9 +227,6 @@ export default defineConfig({
|
||||
// Loaded by the reanimated-web-style-helpers plugin, which the dependency scan does not see.
|
||||
"react-native-web/dist/exports/StyleSheet/compiler/createReactDOMStyle",
|
||||
"react-native-web/dist/exports/StyleSheet/preprocess",
|
||||
// Dynamically imported by the excluded react-native-enriched-markdown package;
|
||||
// pre-optimizing avoids mid-suite Vite re-optimization invalidating browser imports.
|
||||
"katex",
|
||||
],
|
||||
exclude: [
|
||||
"react-native-enriched-markdown",
|
||||
|
||||
@@ -35,7 +35,7 @@ function toListItem(
|
||||
agentId: agent.id,
|
||||
agentShortId: agent.id.slice(0, 7),
|
||||
name: permission.name,
|
||||
description: permission.description ?? "-",
|
||||
description: permission.description ?? permission.title ?? "-",
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -20,6 +20,23 @@ const agent = {
|
||||
} as AgentSnapshotPayload;
|
||||
|
||||
describe("permit ls output", () => {
|
||||
it("shows a Pi select question when the request only has a title", () => {
|
||||
const question: AgentPermissionRequest = {
|
||||
id: "select-request",
|
||||
provider: "pi",
|
||||
name: "Pi select",
|
||||
kind: "question",
|
||||
title: "Allow the diagnostic echo?",
|
||||
};
|
||||
|
||||
const result = listPendingPermissions([{ ...agent, pendingPermissions: [question] }]);
|
||||
|
||||
expect(render(result, { format: "table" })).toContain("Allow the diagnostic echo?");
|
||||
expect(JSON.parse(render(result, { format: "json" }))).toMatchObject([
|
||||
{ description: "Allow the diagnostic echo?" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("emits full request ids that permit allow accepts", () => {
|
||||
const result = listPendingPermissions([agent]);
|
||||
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { hostname } from "node:os";
|
||||
import {
|
||||
createLeanHostClient,
|
||||
parseHostTarget,
|
||||
type DaemonClientCore,
|
||||
} from "@getpaseo/client/node/lean";
|
||||
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
|
||||
import {
|
||||
waitForDaemonReady,
|
||||
resolvePaseoHome,
|
||||
@@ -216,6 +218,34 @@ export function resolveDaemonCredential(
|
||||
return token ? { kind: "localCredential", token } : null;
|
||||
}
|
||||
|
||||
function mapNodePlatform(platform: NodeJS.Platform): HelloClientPlatform {
|
||||
if (platform === "darwin") return "macos";
|
||||
if (platform === "linux") return "linux";
|
||||
if (platform === "win32") return "windows";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
function mapNodeOsName(platform: NodeJS.Platform): string | undefined {
|
||||
if (platform === "darwin") return "macOS";
|
||||
if (platform === "linux") return "Linux";
|
||||
if (platform === "win32") return "Windows";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function resolveCliClientInfo(): HelloClientInfo {
|
||||
const name = hostname()
|
||||
.replace(/\.local$/i, "")
|
||||
.trim()
|
||||
.slice(0, 128);
|
||||
const osName = mapNodeOsName(process.platform);
|
||||
return {
|
||||
appKind: "cli",
|
||||
platform: mapNodePlatform(process.platform),
|
||||
...(name ? { name } : {}),
|
||||
...(osName ? { osName } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonClient> {
|
||||
const timeout = options.timeout ?? defaultConnectTimeout(options.target);
|
||||
const host =
|
||||
@@ -234,6 +264,7 @@ async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonCli
|
||||
const client = createLeanHostClient(host, {
|
||||
clientId: await getOrCreateCliClientId(home),
|
||||
clientType: "cli",
|
||||
clientInfo: resolveCliClientInfo(),
|
||||
appVersion: resolveCliVersion(),
|
||||
...(credential?.kind === "password" ? { password: credential.password } : {}),
|
||||
...(credential?.kind === "localCredential"
|
||||
|
||||
@@ -21,14 +21,15 @@ SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$SCRIPT_PATH")" && pwd)
|
||||
RESOURCES_DIR=$(CDPATH= cd -- "${SCRIPT_DIR}/.." && pwd)
|
||||
|
||||
MACOS_DIR="${RESOURCES_DIR}/../MacOS"
|
||||
MACOS_HELPER_EXECUTABLE="${RESOURCES_DIR}/../Frameworks/Paseo Helper.app/Contents/MacOS/Paseo Helper"
|
||||
MACOS_HELPER_EXECUTABLE="${RESOURCES_DIR}/../Frameworks/Paseo Helper (Plugin).app/Contents/MacOS/Paseo Helper (Plugin)"
|
||||
|
||||
# macOS CLI invocations must enter Electron through the agent Helper. Launching
|
||||
# the main APPL executable here makes later daemon supervision inherit app UI
|
||||
# lifecycle behavior.
|
||||
# macOS CLI invocations must enter Electron through the Plugin Helper: it runs
|
||||
# as an LSUIElement agent (avoiding main APPL Dock/UI lifecycle inheritance)
|
||||
# and is the only helper signed with disable-library-validation so daemon and
|
||||
# forked plugin workers can load third-party native .node addons.
|
||||
if [ -d "${MACOS_DIR}" ]; then
|
||||
if [ ! -x "${MACOS_HELPER_EXECUTABLE}" ]; then
|
||||
echo "Bundled Paseo Helper executable not found at ${MACOS_HELPER_EXECUTABLE}" >&2
|
||||
echo "Bundled Paseo Helper (Plugin) executable not found at ${MACOS_HELPER_EXECUTABLE}" >&2
|
||||
exit 1
|
||||
fi
|
||||
APP_EXECUTABLE="${MACOS_HELPER_EXECUTABLE}"
|
||||
|
||||
@@ -4,9 +4,5 @@
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
</dict>
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.allow-jit</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
|
||||
<true/>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -33,9 +33,9 @@ const CLICK_POINTS = [
|
||||
/** Static overlays and a sibling window control mirror the app shell ownership. */
|
||||
function buildFixtureHtml(appStyles) {
|
||||
const dragOverlay =
|
||||
'style="position:absolute;top:0;left:0;display:block;width:100%;height:100%;-webkit-app-region:drag"';
|
||||
const button = (id, style) =>
|
||||
`<button id="${id}" style="${style}" onclick="count('${id}')">${id}</button>`;
|
||||
'data-window-drag-region="" style="position:absolute;top:0;left:0;display:block;width:100%;height:100%;-webkit-app-region:drag"';
|
||||
const button = (id, style, attrs = "") =>
|
||||
`<button id="${id}" ${attrs} style="${style}" onclick="count('${id}')">${id}</button>`;
|
||||
return `<!doctype html><html><head><meta charset="utf-8"><style>${appStyles}</style>
|
||||
<style>html,body{margin:0;width:100%;height:100%;background:#161616;color:#ddd;font:12px -apple-system,sans-serif;user-select:none}
|
||||
.pane{position:absolute}</style></head><body>
|
||||
@@ -56,14 +56,14 @@ function buildFixtureHtml(appStyles) {
|
||||
<div class="pane" style="left:250px;top:36px;width:750px;height:28px">
|
||||
<div ${dragOverlay}></div>
|
||||
</div>
|
||||
<!-- The sidebar toggle belongs to the window, outside every drag surface subtree. -->
|
||||
${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height:24px;z-index:2")}
|
||||
<div id="focusable" tabindex="0" onclick="count('focusable')"
|
||||
<!-- Window-owned controls mounted outside drag containers opt in via data-window-no-drag. -->
|
||||
${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height:24px;z-index:2", 'data-window-no-drag=""')}
|
||||
<div id="focusable" tabindex="0" data-window-no-drag="" onclick="count('focusable')"
|
||||
style="position:absolute;left:290px;top:6px;width:60px;height:24px;z-index:2">Focusable</div>
|
||||
<div id="negative-button" role="button" tabindex="-1" onclick="count('negative-button')"
|
||||
<div id="negative-button" role="button" tabindex="-1" data-window-no-drag="" onclick="count('negative-button')"
|
||||
style="position:absolute;left:370px;top:6px;width:60px;height:24px;z-index:2">Button</div>
|
||||
<div class="pane" id="chat-root" style="left:250px;top:64px;width:750px;height:536px;overflow:clip">
|
||||
<div id="scroller" tabindex="-1" data-window-content
|
||||
<div id="scroller" tabindex="-1"
|
||||
style="width:100%;height:100%;overflow-y:auto;overflow-x:clip;outline:none">
|
||||
<div id="chat-inner" style="height:2000px;position:relative">
|
||||
<a id="chat-link" href="#" onclick="event.preventDefault();count('chat-link')" style="position:absolute;left:250px;top:160px;width:180px;height:24px">Chat link</a>
|
||||
@@ -72,10 +72,11 @@ ${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div id="paseo-browser-resident-webviews" style="position:fixed;left:0;top:0;width:100vw;height:100vh;overflow:visible;pointer-events:none;z-index:0"></div>
|
||||
<div id="overlay-root" style="position:fixed;inset:0;pointer-events:none;z-index:9999">
|
||||
${button("portal-btn", "position:fixed;left:460px;top:6px;width:60px;height:24px;pointer-events:auto")}
|
||||
</div>
|
||||
<div style="position:fixed;inset:0;pointer-events:none;z-index:9999">
|
||||
<div data-window-overlay-host="" style="position:fixed;inset:0;pointer-events:none;z-index:9999">
|
||||
${button("floating-btn", "position:fixed;left:755px;top:6px;width:60px;height:24px;pointer-events:auto")}
|
||||
</div>
|
||||
<script>
|
||||
@@ -83,6 +84,23 @@ ${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height
|
||||
window.count = (id) => { window.__clicks[id] = (window.__clicks[id] || 0) + 1; };
|
||||
window.__fixture = {
|
||||
setScroll(value) { document.getElementById("scroller").scrollTop = value; return this.snapshot(); },
|
||||
parkBrowserTab() {
|
||||
return new Promise((resolve) => {
|
||||
const host = document.getElementById("paseo-browser-resident-webviews");
|
||||
const surface = document.createElement("div");
|
||||
surface.setAttribute("data-paseo-browser-surface", "parked-tab");
|
||||
surface.setAttribute("aria-hidden", "true");
|
||||
surface.setAttribute("inert", "");
|
||||
surface.setAttribute("tabindex", "-1");
|
||||
surface.style.cssText = "position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;opacity:1;pointer-events:none;display:block;visibility:visible";
|
||||
const webview = document.createElement("webview");
|
||||
webview.setAttribute("src", "data:text/html,<h1>Parked browser tab</h1><button>Action</button>");
|
||||
webview.style.cssText = "display:inline-flex;flex:0 0 auto;width:1280px;height:800px;border:0;background:transparent;position:absolute;left:0;top:0;z-index:0";
|
||||
webview.addEventListener("dom-ready", () => resolve(true), { once: true });
|
||||
surface.appendChild(webview);
|
||||
host.appendChild(surface);
|
||||
});
|
||||
},
|
||||
placeControl(id, y) {
|
||||
const control = document.getElementById(id);
|
||||
const rect = control.getBoundingClientRect();
|
||||
@@ -147,6 +165,9 @@ async function runTitlebarDragGroup(outDir) {
|
||||
frame: false,
|
||||
show: false,
|
||||
backgroundColor: "#161616",
|
||||
webPreferences: {
|
||||
webviewTag: true,
|
||||
},
|
||||
});
|
||||
const evalPage = (code) => win.webContents.executeJavaScript(code);
|
||||
const bounds = () => {
|
||||
@@ -249,6 +270,18 @@ async function runTitlebarDragGroup(outDir) {
|
||||
});
|
||||
}
|
||||
|
||||
await evalPage("window.__fixture.parkBrowserTab()");
|
||||
await new Promise((resolve) => setTimeout(resolve, 250));
|
||||
for (const point of DRAG_POINTS) {
|
||||
await resetPosition();
|
||||
const before = bounds();
|
||||
const from = mouseAt(point);
|
||||
await runMouse(["drag", from.x, from.y, from.x + DRAG_DELTA.x, from.y + DRAG_DELTA.y]);
|
||||
const after = bounds();
|
||||
const moved = after.x - before.x === DRAG_DELTA.x && after.y - before.y === DRAG_DELTA.y;
|
||||
record(`parked-webview-${point.check}`, moved, { before, after });
|
||||
}
|
||||
|
||||
const image = await win.webContents.capturePage();
|
||||
await fsp.writeFile(path.join(outDir, "titlebar-drag.png"), image.toPNG());
|
||||
} catch (error) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user