mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-05 14:45:25 +00:00
Compare commits
9
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
765aec33e5 | ||
|
|
073743647a | ||
|
|
6b3b349c8b | ||
|
|
b1bb161133 | ||
|
|
2f1fc53cdb | ||
|
|
617ebbdb1a | ||
|
|
c174f475c8 | ||
|
|
6e5f0bd889 | ||
|
|
350a4937d9 |
+3
-3
@@ -22,11 +22,11 @@ The relay is designed to be untrusted. All traffic between your phone and daemon
|
||||
1. The daemon generates a persistent Curve25519 keypair on first run and stores it at `$PASEO_HOME/daemon-keypair.json` with mode `0600`
|
||||
2. The pairing URL (rendered as a QR code or opened directly) carries the daemon's public key in its URL fragment (`https://app.paseo.sh/#offer=...`). Fragments are not sent to the web server, so `app.paseo.sh` never sees the key.
|
||||
3. When the phone connects via the relay, it generates fresh ephemeral keys and sends an `e2ee_hello` message. The daemon will not process any application messages until this handshake completes.
|
||||
4. Updated peers run a Noise `NK` handshake (`Noise_NK_25519_ChaChaPoly_SHA256`) keyed to the daemon's static key: the `e2ee_hello` carries the first Noise message and the daemon's `e2ee_ready` carries the second. Every later frame is a counter-nonced ChaCha20-Poly1305 record. When either side predates this, the session falls back to the legacy construction: a Curve25519 ECDH shared key with XSalsa20-Poly1305 (NaCl `box`) and a random `[24-byte nonce][ciphertext]` bundle. Both modes negotiate `binaryCiphertext`: negotiated application text is carried as a base64 WebSocket text frame, while application binary is carried as a raw WebSocket binary frame. A peer that does not negotiate the capability uses base64 text frames for both kinds. [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) has the exact mapping.
|
||||
4. Updated peers run a Noise `NK` handshake (`Noise_NK_25519_ChaChaPoly_SHA256`) keyed to the daemon's static key: the `e2ee_hello` carries the first Noise message and the daemon's `e2ee_ready` carries the second. Every later frame is a counter-nonced ChaCha20-Poly1305 record. When either side predates this, the session falls back to the legacy construction: a Curve25519 ECDH shared key with XSalsa20-Poly1305 (NaCl `box`) and a random `[24-byte nonce][ciphertext]` bundle. Both modes negotiate `binaryCiphertext`. In protected mode every record then travels as a WebSocket binary frame, and an authenticated `kind` byte inside the record says whether the plaintext is text or binary. In legacy mode negotiated application text is carried as a base64 WebSocket text frame and application binary as a raw WebSocket binary frame. A peer that does not negotiate the capability uses base64 text frames for both kinds. [docs/relay-endpoint-security.md](docs/relay-endpoint-security.md) has the exact mapping.
|
||||
|
||||
The WebSocket opcode is preserved end to end after negotiation; the receiver never guesses whether authenticated plaintext is text or binary from its byte contents. The plaintext handshake remains WebSocket text and contains only public keys and capability declarations.
|
||||
After negotiation the receiver never guesses whether authenticated plaintext is text or binary from its byte contents: protected mode reads the authenticated `kind` byte and legacy mode reads the WebSocket opcode. The plaintext handshake remains WebSocket text and contains only public keys and capability declarations.
|
||||
|
||||
When both peers negotiate a frame codec (`frame_codecs`), frames of 1024 bytes or more are compressed statelessly per frame before encryption. Compression never shares dictionary state across frames, never compresses `hello` or `server_info`, and enforces the 100 MiB logical message limit as a hard decompression cap. As with any compression before encryption, compressed frame lengths remain observable to the relay.
|
||||
When both peers negotiate a frame codec (`frame_codecs`), frames of 1024 bytes or more are compressed statelessly per frame before encryption. Compression never shares dictionary state across frames and enforces the 100 MiB logical message limit as a hard decompression cap. `hello` and the `server_info` that answers it are never compressed: the client selects its codec from `server_info`, and the relay E2EE downgrade check reads `server_info` as text. Clients do not advertise codecs on loopback connections, where compression costs CPU and saves no bandwidth. As with any compression before encryption, compressed frame lengths remain observable to the relay.
|
||||
|
||||
The relay sees only: IP addresses, timing, message sizes, session IDs, and the plaintext `e2ee_hello` / `e2ee_ready` handshake frames (which contain only public keys). It cannot read message contents, forge messages, or derive encryption keys from observing the handshake.
|
||||
|
||||
|
||||
@@ -78,7 +78,14 @@ negotiate connection-scoped framing. Optional `frame_codecs` in `hello` and opti
|
||||
client's local codec list, so selection is deterministic regardless of client list order.
|
||||
Application serializers and routed envelopes use the same boundary. Handshakes (`hello`
|
||||
and `server_info`), frames below 1024 bytes, and incompressible frames keep their
|
||||
existing uncompressed representation. Older peers that omit `frame_codecs` or
|
||||
existing uncompressed representation. The daemon sends `server_info` before it applies the
|
||||
negotiated codec, because the client selects its codec from it. A routed envelope whose
|
||||
enclosed frame is already compressed is forwarded as it is.
|
||||
|
||||
A client omits `frame_codecs` when its transport reports `local` (loopback TCP, Unix
|
||||
socket, named pipe), unless the caller lists codecs explicitly in `capabilities`. Hosts
|
||||
routed through that client still use its installed codecs, so a routed host behind a
|
||||
loopback origin compresses end to end while the origin socket carries the frames as they are. Older peers that omit `frame_codecs` or
|
||||
`features.frameCodecs` exchange uncompressed frames and retain existing frame limits.
|
||||
|
||||
The reserved binary opcode `0x31` is followed by version `1`, original kind
|
||||
@@ -96,12 +103,16 @@ decodes UTF-8 only after END and decode complete. Transfers cannot interleave.
|
||||
Disconnect clears partial state and negotiation.
|
||||
|
||||
Codecs are host-supplied (`DaemonClientConfig.frameCodecs`), not sniffed in client core:
|
||||
Node entry points supply `node:zlib` (sync fast path only when work is bounded below
|
||||
256 KiB, libuv async otherwise so high-ratio inbound frames never stall the event loop),
|
||||
Node entry points supply `node:zlib` (sync up to 256 KiB: encode when the raw frame is at
|
||||
most that, decode when its input and output stay within it; libuv async past it, so high-ratio inbound
|
||||
frames never stall the event loop),
|
||||
web/Electron supplies `CompressionStream("deflate-raw")`, and native iOS/Android
|
||||
supplies the `paseo-compression` Expo module. Async codecs preserve strict FIFO order on
|
||||
both send and receive; a protocol error during async decode closes the socket via
|
||||
`onProtocolError` without delivering queued frames.
|
||||
`onProtocolError` without delivering queued frames. `close()` drops frames still decoding,
|
||||
so a client that disposes a connection never sees its stale frames. When a peer disconnects,
|
||||
the daemon awaits `flushInbound()` before `close()`, so a request the peer sent just before
|
||||
dropping applies as it would uncompressed.
|
||||
|
||||
The lower transport supplies its plaintext frame budget, including encryption
|
||||
overhead. The sender waits for drain between chunks while ordinary messages keep
|
||||
|
||||
@@ -49,5 +49,5 @@ Terminal frames share the daemon main event loop with all agent traffic. The `ev
|
||||
## Known remaining contention (follow-up candidates)
|
||||
|
||||
- A single large `agent_stream` message (e.g. a 250KB diff payload) measurably delays terminal echo (~100ms-class dips) — cost is split between daemon serialization and app-side parse/render on the shared browser main thread. See [agent-stream-performance.md](agent-stream-performance.md) for that pipeline's own budgets.
|
||||
- Relay-attached clients pay pure-JS tweetnacl encryption on the daemon main loop (`packages/relay/src/encrypted-channel.ts`). Negotiated binary application frames stay binary ciphertext and avoid base64 encode/decode; text and mixed-version traffic remain base64 WebSocket text frames.
|
||||
- Relay-attached clients pay pure-JS encryption on the daemon main loop: `@noble/ciphers` ChaCha20-Poly1305 records in protected mode (`packages/relay/src/protected-records.ts`), tweetnacl in legacy mode (`packages/relay/src/encrypted-channel.ts`). Protected peers that negotiate `binaryCiphertext` send every record as a binary frame with no base64 step. Legacy text and peers that predate `binaryCiphertext` still pay base64 encode/decode.
|
||||
- `sendToClient` re-stringifies session messages per socket; only matters for multi-socket connections.
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { deflateRawSync, inflateRawSync } from "node:zlib";
|
||||
import { deflateRawSync } from "node:zlib";
|
||||
import { expect, type Page } from "@playwright/test";
|
||||
import {
|
||||
decodeHostRouteFrame,
|
||||
@@ -33,15 +33,37 @@ interface HostAdminClient {
|
||||
|
||||
interface BrowserCompressionTraffic {
|
||||
connectedPorts: Set<string>;
|
||||
advertisedCodecs: string[][];
|
||||
/** `frame_codecs` of each hello the browser sent on its own socket; null when omitted. */
|
||||
outerHelloCodecs: Array<string[] | null>;
|
||||
/** `frame_codecs` of each hello the browser sent to a routed host through the primary. */
|
||||
routedHelloCodecs: Array<string[] | null>;
|
||||
outerEncodedFrames: number[];
|
||||
routedEncodedFrames: number[];
|
||||
}
|
||||
|
||||
interface SentHello {
|
||||
type?: string;
|
||||
capabilities?: { frame_codecs?: unknown };
|
||||
}
|
||||
|
||||
function helloCodecs(hello: SentHello): string[] | null {
|
||||
const codecs = hello.capabilities?.frame_codecs;
|
||||
return Array.isArray(codecs) ? (codecs as string[]) : null;
|
||||
}
|
||||
|
||||
function parseJson<T>(text: string): T | null {
|
||||
try {
|
||||
return JSON.parse(text) as T;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic {
|
||||
const traffic: BrowserCompressionTraffic = {
|
||||
connectedPorts: new Set(),
|
||||
advertisedCodecs: [],
|
||||
outerHelloCodecs: [],
|
||||
routedHelloCodecs: [],
|
||||
outerEncodedFrames: [],
|
||||
routedEncodedFrames: [],
|
||||
};
|
||||
@@ -52,16 +74,21 @@ function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic
|
||||
|
||||
socket.on("framesent", ({ payload }) => {
|
||||
if (typeof payload !== "string") return;
|
||||
try {
|
||||
const parsed = JSON.parse(payload) as {
|
||||
type?: string;
|
||||
capabilities?: { frame_codecs?: unknown };
|
||||
};
|
||||
if (parsed.type === "hello" && Array.isArray(parsed.capabilities?.frame_codecs)) {
|
||||
traffic.advertisedCodecs.push(parsed.capabilities.frame_codecs as string[]);
|
||||
}
|
||||
} catch {
|
||||
// non-JSON text frame
|
||||
const parsed = parseJson<
|
||||
SentHello & { message?: { type?: string; data?: unknown; binary?: unknown } }
|
||||
>(payload);
|
||||
if (parsed?.type === "hello") {
|
||||
traffic.outerHelloCodecs.push(helloCodecs(parsed));
|
||||
return;
|
||||
}
|
||||
const routed = parsed?.message;
|
||||
if (
|
||||
parsed?.type === "session" &&
|
||||
routed?.type === "hosts.route.frame.request" &&
|
||||
typeof routed.data === "string"
|
||||
) {
|
||||
const hello = parseJson<SentHello>(routed.data);
|
||||
if (hello?.type === "hello") traffic.routedHelloCodecs.push(helloCodecs(hello));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -83,13 +110,6 @@ function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic
|
||||
|
||||
if (payload[0] === 0x31 && (payload[3]! & 0x04) !== 0) {
|
||||
traffic.outerEncodedFrames.push(payload.byteLength);
|
||||
if ((payload[3]! & 0x03) === 0x03 && payload[2] === 1) {
|
||||
try {
|
||||
inspectRouted(inflateRawSync(payload.subarray(4)));
|
||||
} catch {
|
||||
// ignore non-single-frame or partial
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
inspectRouted(payload);
|
||||
@@ -99,18 +119,15 @@ function observeBrowserCompressionTraffic(page: Page): BrowserCompressionTraffic
|
||||
return traffic;
|
||||
}
|
||||
|
||||
function hasAdvertisedCodec(traffic: BrowserCompressionTraffic, codecId: string): boolean {
|
||||
for (const codecs of traffic.advertisedCodecs) {
|
||||
if (codecs.includes(codecId)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
async function waitForAdvertisedCodec(
|
||||
async function expectRoutedHelloAdvertises(
|
||||
traffic: BrowserCompressionTraffic,
|
||||
codecId: string,
|
||||
): Promise<void> {
|
||||
await expect.poll(() => hasAdvertisedCodec(traffic, codecId), { timeout: 20_000 }).toBe(true);
|
||||
await expect
|
||||
.poll(() => traffic.routedHelloCodecs.some((codecs) => codecs?.includes(codecId) === true), {
|
||||
timeout: 20_000,
|
||||
})
|
||||
.toBe(true);
|
||||
}
|
||||
|
||||
async function waitForHostOnline(client: HostAdminClient, registrationId: string): Promise<void> {
|
||||
@@ -133,6 +150,7 @@ const SERVED_PROTOCOL_FILES = new Set([
|
||||
"web-frame-codec.js",
|
||||
"frame-transport.js",
|
||||
"websocket-message-limit.js",
|
||||
"binary-frames/host-route.js",
|
||||
]);
|
||||
|
||||
async function verifyProductionWebCodecInChromium(page: Page, bombB64: string, validText: string) {
|
||||
@@ -147,7 +165,7 @@ async function verifyProductionWebCodecInChromium(page: Page, bombB64: string, v
|
||||
});
|
||||
return;
|
||||
}
|
||||
const name = path.basename(url.pathname);
|
||||
const name = url.pathname.slice(1);
|
||||
if (SERVED_PROTOCOL_FILES.has(name)) {
|
||||
const source = await readFile(path.join(PROTOCOL_DIST_DIR, name), "utf8");
|
||||
await route.fulfill({
|
||||
@@ -319,12 +337,17 @@ test.describe("Routed host frame compression in browser", () => {
|
||||
|
||||
await test.step("open the routed host workspace through the primary daemon", async () => {
|
||||
await gotoAppShell(page);
|
||||
await waitForAdvertisedCodec(traffic, "deflate-raw");
|
||||
|
||||
const routedProjectGroup = page.getByRole("group", {
|
||||
name: path.basename(secondaryWorkspace!.repoPath),
|
||||
});
|
||||
await expect(routedProjectGroup).toBeVisible({ timeout: 30_000 });
|
||||
|
||||
// The browser reaches the primary over loopback, so its own socket stays uncompressed,
|
||||
// while the routed host session negotiates deflate-raw end to end.
|
||||
expect(traffic.outerHelloCodecs.length).toBeGreaterThan(0);
|
||||
expect(new Set(traffic.outerHelloCodecs)).toEqual(new Set([null]));
|
||||
await expectRoutedHelloAdvertises(traffic, "deflate-raw");
|
||||
await routedProjectGroup.getByRole("button", { name: "main" }).click();
|
||||
await waitForTabBar(page);
|
||||
});
|
||||
@@ -342,11 +365,12 @@ test.describe("Routed host frame compression in browser", () => {
|
||||
expect(traffic.connectedPorts.has(primaryPort)).toBe(true);
|
||||
expect(traffic.connectedPorts.has(String(secondaryDaemon!.port))).toBe(false);
|
||||
|
||||
// Real deflate-raw 0x31 ENCODED frames crossed the routed host channel.
|
||||
// Real deflate-raw 0x31 ENCODED frames crossed the routed host channel, compressed once.
|
||||
expect(traffic.routedEncodedFrames.length).toBeGreaterThan(0);
|
||||
expect(Math.max(...traffic.routedEncodedFrames)).toBeLessThan(
|
||||
largeFileContent.length * 0.35,
|
||||
);
|
||||
expect(traffic.outerEncodedFrames).toEqual([]);
|
||||
});
|
||||
} finally {
|
||||
if (registrationId && primaryClient) {
|
||||
|
||||
@@ -112,24 +112,25 @@ test.describe("Settings sidebar scroll position", () => {
|
||||
await expectSettingsSidebarScrollOffset(page, 0);
|
||||
});
|
||||
|
||||
test("updates appearance without losing the detail scroll or form edits", async ({ page }) => {
|
||||
test("updates typography and normalizes font sizes in one Appearance visit", async ({ page }) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
test("shows normalized font sizes after committing out-of-range and empty values", async ({
|
||||
page,
|
||||
}) => {
|
||||
await gotoAppShell(page);
|
||||
await openSettings(page);
|
||||
await openSettingsSection(page, "appearance");
|
||||
await normalizeSettingsFontSizes(page);
|
||||
await test.step("change the syntax theme without losing the detail scroll", async () => {
|
||||
const { offset, keywordColor } = await revealSettingsSyntaxTheme(page);
|
||||
await changeSettingsSyntaxTheme(page, "Dracula");
|
||||
await expectSettingsDetailScrollOffset(page, offset);
|
||||
await expectSettingsSyntaxColorChanged(page, keywordColor);
|
||||
});
|
||||
|
||||
await test.step("apply valid font edits to Settings and the preview", async () => {
|
||||
await changeSettingsTypography(page);
|
||||
});
|
||||
|
||||
await test.step("normalize out-of-range and empty font sizes on commit", async () => {
|
||||
await normalizeSettingsFontSizes(page);
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps the sidebar context through interface font changes", async ({ page }) => {
|
||||
|
||||
@@ -212,19 +212,11 @@ async function expectAgentConsistentlyIdle(page: Page, title: string): Promise<v
|
||||
await expectTurnCopyButton(page);
|
||||
}
|
||||
|
||||
async function withViewedTimelineScenario(
|
||||
run: (scenario: ViewedTimelineScenario) => Promise<void>,
|
||||
async function openFiveMoreChats(
|
||||
page: Page,
|
||||
scenario: ViewedTimelineScenario,
|
||||
subscriptions: ReturnType<typeof observeTimelineSubscriptions>,
|
||||
) {
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
try {
|
||||
await run(scenario);
|
||||
} finally {
|
||||
await scenario.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
async function openSevenChats(page: Page, scenario: ViewedTimelineScenario) {
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const additional = [];
|
||||
for (let index = 0; index < 5; index += 1) {
|
||||
additional.push(
|
||||
@@ -238,8 +230,6 @@ async function openSevenChats(page: Page, scenario: ViewedTimelineScenario) {
|
||||
}),
|
||||
);
|
||||
}
|
||||
await openAgent(page, scenario, scenario.firstAgentId);
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
for (let index = 0; index < additional.length; index += 1) {
|
||||
await selectAgent(page, `Additional chat ${index + 1}`);
|
||||
}
|
||||
@@ -512,15 +502,6 @@ test.describe("Viewed agent timelines", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("open chats stay current after switching beyond five agents", async ({ page }) => {
|
||||
await withViewedTimelineScenario(async (scenario) => {
|
||||
await openSevenChats(page, scenario);
|
||||
await commitMessage(scenario, scenario.firstAgentId, "Current after seven open chats.");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expectCurrentChatWithoutCatchUp(page, "Current after seven open chats.");
|
||||
});
|
||||
});
|
||||
|
||||
test("a turn that finishes while hidden reopens with consistently idle chrome", async ({
|
||||
page,
|
||||
}) => {
|
||||
@@ -542,35 +523,49 @@ test.describe("Viewed agent timelines", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("a hidden retained chat stays current without rendering", async ({ page }) => {
|
||||
test("a retained chat stays current while hidden and after opening seven chats", async ({
|
||||
page,
|
||||
}) => {
|
||||
test.setTimeout(60_000);
|
||||
const subscriptions = observeTimelineSubscriptions(page);
|
||||
const scenario = await seedViewedTimelineScenario();
|
||||
try {
|
||||
await openAgent(page, scenario, scenario.firstAgentId, { recordRenders: true });
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
await composer.fill("Unsent draft survives hidden streaming");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([scenario.firstAgentId, scenario.secondAgentId]);
|
||||
const hiddenCommits = await countChatCommits(page, scenario.firstAgentId);
|
||||
expect(hiddenCommits).toBeGreaterThan(0);
|
||||
await commitMessage(
|
||||
scenario,
|
||||
scenario.firstAgentId,
|
||||
"Committed while the first chat is hidden.",
|
||||
);
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toHaveCount(0);
|
||||
expect(await countChatCommits(page, scenario.firstAgentId)).toBe(hiddenCommits);
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText("(end of synthetic stream)", { exact: true })).toBeVisible();
|
||||
await expect(composer).toHaveValue("Unsent draft survives hidden streaming");
|
||||
await composer.fill("Draft edited after returning");
|
||||
await expect(composer).toHaveValue("Draft edited after returning");
|
||||
await test.step("Keep a hidden chat current without rendering or losing its draft", async () => {
|
||||
const composer = page.getByRole("textbox", { name: "Message agent..." });
|
||||
await composer.fill("Unsent draft survives hidden streaming");
|
||||
await selectAgent(page, "Second viewed chat");
|
||||
await subscriptions.waitForSubscribedAgents([
|
||||
scenario.firstAgentId,
|
||||
scenario.secondAgentId,
|
||||
]);
|
||||
const hiddenCommits = await countChatCommits(page, scenario.firstAgentId);
|
||||
expect(hiddenCommits).toBeGreaterThan(0);
|
||||
await commitMessage(
|
||||
scenario,
|
||||
scenario.firstAgentId,
|
||||
"Committed while the first chat is hidden.",
|
||||
);
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toHaveCount(0);
|
||||
expect(await countChatCommits(page, scenario.firstAgentId)).toBe(hiddenCommits);
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expect(
|
||||
page.getByText("Committed while the first chat is hidden.", { exact: true }),
|
||||
).toBeVisible();
|
||||
await expect(page.getByText("(end of synthetic stream)", { exact: true })).toBeVisible();
|
||||
await expect(composer).toHaveValue("Unsent draft survives hidden streaming");
|
||||
await composer.fill("Draft edited after returning");
|
||||
await expect(composer).toHaveValue("Draft edited after returning");
|
||||
});
|
||||
|
||||
await test.step("Keep the first chat current after opening seven chats", async () => {
|
||||
await openFiveMoreChats(page, scenario, subscriptions);
|
||||
await commitMessage(scenario, scenario.firstAgentId, "Current after seven open chats.");
|
||||
await selectAgent(page, "First viewed chat");
|
||||
await expectCurrentChatWithoutCatchUp(page, "Current after seven open chats.");
|
||||
});
|
||||
} finally {
|
||||
await scenario.cleanup();
|
||||
}
|
||||
|
||||
@@ -20,11 +20,11 @@ import {
|
||||
getWorkspaceSelectionKey,
|
||||
orderWorkspaceSelectionsForStableRender,
|
||||
reconcileRetainedWorkspaceSelections,
|
||||
resolveWorkspaceDeckRetentionLimit,
|
||||
type RetainedWorkspaceSelection,
|
||||
resolveWorkspaceDeckEntries,
|
||||
shouldKeepWorkspaceDeckEntryMounted,
|
||||
} from "@/screens/workspace/workspace-deck-retention";
|
||||
import { workspaceDeckRetentionLimit } from "@/constants/resource-budget";
|
||||
import {
|
||||
decodeWorkspaceIdFromPathSegment,
|
||||
parseWorkspaceOpenIntent,
|
||||
@@ -35,7 +35,7 @@ import {
|
||||
stripHostWorkspaceRouteEchoSearchFromBrowserUrlAfterCommit,
|
||||
} from "@/utils/host-route-browser";
|
||||
import { prepareWorkspaceTab } from "@/utils/prepare-workspace-tab";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
|
||||
function getParamValue(value: string | string[] | undefined): string {
|
||||
@@ -167,7 +167,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: retainedSelections,
|
||||
activeSelection,
|
||||
now: reconciliationNow,
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
[activeSelection, reconciliationNow, retainedSelections],
|
||||
);
|
||||
@@ -204,7 +204,7 @@ function WorkspaceDeck() {
|
||||
currentEntries: current,
|
||||
activeSelection,
|
||||
now: Date.now(),
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative }),
|
||||
maxMountedWorkspaces: workspaceDeckRetentionLimit,
|
||||
}),
|
||||
);
|
||||
}, expirationDelay + 1);
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
} from "@/components/ui/isolated-bottom-sheet-modal";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { usesCompactBottomSheet } from "@/constants/presentation";
|
||||
import { useAggregatedAgents, type AggregatedAgent } from "@/hooks/use-aggregated-agents";
|
||||
import { useProjects } from "@/hooks/use-projects";
|
||||
import { useTimeAgo } from "@/hooks/use-time-ago";
|
||||
@@ -991,7 +992,7 @@ export function CommandCenter() {
|
||||
const bottomSheetListRef = useRef<BottomSheetFlatListMethods>(null);
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const bottomSheetInputRef = useRef<EditingTextInputHandle>(null);
|
||||
const showBottomSheet = isCompact && isNative;
|
||||
const showBottomSheet = isCompact && usesCompactBottomSheet;
|
||||
const getInputHandle = useCallback(
|
||||
() => (showBottomSheet ? bottomSheetInputRef.current : inputRef.current),
|
||||
[showBottomSheet],
|
||||
|
||||
@@ -16,6 +16,7 @@ import DraggableFlatList, {
|
||||
import type { GestureType } from "react-native-gesture-handler";
|
||||
import { useUnistyles } from "react-native-unistyles";
|
||||
import { useContentDrag } from "@/components/ui/content-drag";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { createDragHold } from "./drag-reorder/drag-hold";
|
||||
import { movedItemKey } from "./drag-reorder/native-drop";
|
||||
import type {
|
||||
@@ -52,7 +53,7 @@ export function DraggableListHandle({ testID, style, children }: DraggableListHa
|
||||
delayMs: HANDLE_HOLD_MS,
|
||||
slopPx: HANDLE_HOLD_SLOP_PX,
|
||||
onArm: () => {
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
},
|
||||
})
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Animated, StyleSheet, Text, View } from "react-native";
|
||||
import MaskedView from "@react-native-masked-view/masked-view";
|
||||
import Svg, { Defs, Rect, Stop, LinearGradient as SvgLinearGradient } from "react-native-svg";
|
||||
import { useIndicatorMotion } from "@/components/indicator-motion";
|
||||
import { supportsMaskedEffects } from "@/constants/platform";
|
||||
import { sharedIndicatorClock, useRunningClock } from "@/components/indicator-motion/clock";
|
||||
import { type LabelShimmerProps, getRowSweep, getShimmerCycle } from "./sweep";
|
||||
|
||||
@@ -60,7 +61,8 @@ export const LabelShimmer = memo(function LabelShimmer({
|
||||
measurements,
|
||||
}: LabelShimmerProps) {
|
||||
const { rowSize } = measurements;
|
||||
const measured = rowSize.width > 0 && rowSize.height > 0;
|
||||
// Without an alpha-mask compositor the band would paint as a bare white bar.
|
||||
const measured = supportsMaskedEffects && rowSize.width > 0 && rowSize.height > 0;
|
||||
const motion = useIndicatorMotion();
|
||||
// A held band stays on the clock, so it keeps its place and its pass.
|
||||
const sweeping = motion !== "resting" && measured;
|
||||
|
||||
@@ -61,8 +61,13 @@ import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { useHardwareKeyboardPresent, type KeyboardInputEvent } from "@/keyboard";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { usesDesktopPopoverSpacing } from "@/constants/presentation";
|
||||
import {
|
||||
hasSoftwareKeyboard,
|
||||
useHardwareKeyboardPresent,
|
||||
type KeyboardInputEvent,
|
||||
} from "@/keyboard";
|
||||
import {
|
||||
buildProviderQualifiedDescription,
|
||||
buildSelectedTriggerLabel,
|
||||
@@ -105,7 +110,7 @@ const DESKTOP_PROVIDER_VIEW_BASE_HEIGHT = 80;
|
||||
const DESKTOP_MODEL_ROW_HEIGHT = 40;
|
||||
|
||||
/** Fixed picker row heights so virtualized lists can mount directly at the selected row via `getItemLayout`. */
|
||||
export const MODEL_PICKER_ROW_HEIGHT = isWeb ? 36 : 44;
|
||||
export const MODEL_PICKER_ROW_HEIGHT = usesDesktopPopoverSpacing ? 36 : 44;
|
||||
export const MODEL_PICKER_HEADING_HEIGHT = 32;
|
||||
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle);
|
||||
@@ -386,7 +391,7 @@ export function useModelBrowser({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch = isWeb,
|
||||
autoFocusSearch = !hasSoftwareKeyboard,
|
||||
profiles = null,
|
||||
serverId = null,
|
||||
}: ModelBrowserInput): ModelBrowserState {
|
||||
@@ -1649,7 +1654,7 @@ function ModelSearchEmptyState() {
|
||||
// React Native Web blurs the focused input on every scroll in "on-drag" mode, including wheel
|
||||
// scrolls and the scroll that reveals an arrowed-to row. That moves focus out of search, so
|
||||
// typing stops and Enter lands on the header's Back button. Only a native keyboard needs it.
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = isNative ? "on-drag" : "none";
|
||||
const MODEL_LIST_KEYBOARD_DISMISS_MODE = hasSoftwareKeyboard ? "on-drag" : "none";
|
||||
|
||||
interface ModelBrowserKeyboardBinding {
|
||||
view: ModelBrowserView;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
import { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
|
||||
interface RenderErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
/** A caught error is cleared when any of these values change, so new content renders. */
|
||||
resetKeys: readonly unknown[];
|
||||
/** The error state shown in place of the children. `retry` renders the children again. */
|
||||
renderError(error: string, retry: () => void): ReactNode;
|
||||
onError(error: unknown, componentStack: string | null | undefined): void;
|
||||
}
|
||||
|
||||
interface RenderErrorBoundaryState {
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps a render error inside one surface. Without it the error reaches the root boundary,
|
||||
* which replaces the whole app.
|
||||
*/
|
||||
export class RenderErrorBoundary extends Component<
|
||||
RenderErrorBoundaryProps,
|
||||
RenderErrorBoundaryState
|
||||
> {
|
||||
state: RenderErrorBoundaryState = { error: null };
|
||||
|
||||
static getDerivedStateFromError(error: unknown): RenderErrorBoundaryState {
|
||||
return { error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: unknown, info: ErrorInfo): void {
|
||||
this.props.onError(error, info.componentStack);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: RenderErrorBoundaryProps): void {
|
||||
if (this.state.error !== null && resetKeysChanged(previous.resetKeys, this.props.resetKeys)) {
|
||||
this.retry();
|
||||
}
|
||||
}
|
||||
|
||||
retry = (): void => {
|
||||
this.setState({ error: null });
|
||||
};
|
||||
|
||||
render() {
|
||||
if (this.state.error !== null) return this.props.renderError(this.state.error, this.retry);
|
||||
return this.props.children;
|
||||
}
|
||||
}
|
||||
|
||||
function resetKeysChanged(previous: readonly unknown[], next: readonly unknown[]): boolean {
|
||||
return previous.length !== next.length || previous.some((key, index) => key !== next[index]);
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { startResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
|
||||
describe("startResizeHandleDrag", () => {
|
||||
it("previews pointer frames and commits only the final size", () => {
|
||||
@@ -29,3 +32,14 @@ describe("startResizeHandleDrag", () => {
|
||||
expect(commit.mock.calls[0]?.[0][1]).toBeCloseTo(0.4, 10);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveResizeHandleInteraction", () => {
|
||||
it("uses DOM pointer events only on fine-pointer web targets, gesture pan on fine-pointer non-web targets, and touch grip on touch targets", () => {
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: true })).toBe("web-pointer");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: true, isWeb: false })).toBe(
|
||||
"native-pointer",
|
||||
);
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: false })).toBe("touch");
|
||||
expect(resolveResizeHandleInteraction({ finePointer: false, isWeb: true })).toBe("touch");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -7,6 +7,24 @@ interface StartResizeHandleDragInput {
|
||||
commit: (sizes: number[]) => void;
|
||||
}
|
||||
|
||||
export type ResizeHandleInteraction = "web-pointer" | "native-pointer" | "touch";
|
||||
|
||||
/**
|
||||
* Selects how the resize bar is hit-tested and dragged: thin pointer bar with DOM events on a
|
||||
* fine-pointer web target, thin pointer bar with gesture pan on a fine-pointer non-web target, and a
|
||||
* wide touch target with a grip pill otherwise.
|
||||
*/
|
||||
export function resolveResizeHandleInteraction({
|
||||
finePointer,
|
||||
isWeb,
|
||||
}: {
|
||||
finePointer: boolean;
|
||||
isWeb: boolean;
|
||||
}): ResizeHandleInteraction {
|
||||
if (!finePointer) return "touch";
|
||||
return isWeb ? "web-pointer" : "native-pointer";
|
||||
}
|
||||
|
||||
export interface ResizeHandleDrag {
|
||||
move: (deltaRatio: number) => void;
|
||||
finish: () => void;
|
||||
|
||||
@@ -2,7 +2,12 @@ import { useCallback, useMemo, useRef, useState } from "react";
|
||||
import { View, type PointerEvent as RNPointerEvent } from "react-native";
|
||||
import { Gesture, GestureDetector } from "react-native-gesture-handler";
|
||||
import { StyleSheet, useUnistyles } from "react-native-unistyles";
|
||||
import { startResizeHandleDrag, type ResizeHandleDrag } from "@/components/resize-handle-drag";
|
||||
import {
|
||||
resolveResizeHandleInteraction,
|
||||
startResizeHandleDrag,
|
||||
type ResizeHandleDrag,
|
||||
} from "@/components/resize-handle-drag";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import {
|
||||
SIDEBAR_RESIZE_ACTIVATION_OFFSET,
|
||||
@@ -48,6 +53,7 @@ export function ResizeHandle({
|
||||
}: ResizeHandleProps) {
|
||||
const { theme } = useUnistyles();
|
||||
const { finePointer } = usePointerCapabilities();
|
||||
const interaction = resolveResizeHandleInteraction({ finePointer, isWeb });
|
||||
const pointerStatesRef = useRef(new Map<number, PointerState>());
|
||||
const touchStateRef = useRef<PointerState | null>(null);
|
||||
const cursorBeforeDragRef = useRef<string | null>(null);
|
||||
@@ -225,8 +231,12 @@ export function ResizeHandle({
|
||||
...(direction === "horizontal"
|
||||
? { left: hitAreaAlignment === "end" ? 0 : -5 }
|
||||
: { top: hitAreaAlignment === "end" ? 0 : -5 }),
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
...(isWeb
|
||||
? {
|
||||
cursor: direction === "horizontal" ? "col-resize" : "row-resize",
|
||||
touchAction: "none",
|
||||
}
|
||||
: {}),
|
||||
} as object,
|
||||
],
|
||||
[direction, hitAreaAlignment],
|
||||
@@ -254,6 +264,32 @@ export function ResizeHandle({
|
||||
[direction, highlighted, theme.colors.foreground],
|
||||
);
|
||||
|
||||
const ariaOrientation = direction === "horizontal" ? "vertical" : "horizontal";
|
||||
const separatorHitArea =
|
||||
interaction === "web-pointer" ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={ariaOrientation}
|
||||
collapsable={false}
|
||||
style={interaction === "native-pointer" ? hitAreaStyle : touchHitAreaStyle}
|
||||
onPointerEnter={interaction === "native-pointer" ? handlePointerEnter : undefined}
|
||||
onPointerLeave={interaction === "native-pointer" ? handlePointerLeave : undefined}
|
||||
>
|
||||
{interaction === "touch" ? <View pointerEvents="none" style={touchGripStyle} /> : null}
|
||||
</View>
|
||||
</GestureDetector>
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={handleStyle} testID={testID}>
|
||||
{highlighted && (
|
||||
@@ -263,27 +299,7 @@ export function ResizeHandle({
|
||||
testID={testID ? `${testID}-highlight` : undefined}
|
||||
/>
|
||||
)}
|
||||
{finePointer ? (
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
style={hitAreaStyle}
|
||||
onPointerDown={handlePointerDown}
|
||||
onPointerEnter={handlePointerEnter}
|
||||
onPointerLeave={handlePointerLeave}
|
||||
/>
|
||||
) : (
|
||||
<GestureDetector gesture={touchGesture}>
|
||||
<View
|
||||
role="separator"
|
||||
aria-orientation={direction === "horizontal" ? "vertical" : "horizontal"}
|
||||
collapsable={false}
|
||||
style={touchHitAreaStyle}
|
||||
>
|
||||
<View pointerEvents="none" style={touchGripStyle} />
|
||||
</View>
|
||||
</GestureDetector>
|
||||
)}
|
||||
{separatorHitArea}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { useCallback, useEffect, useRef } from "react";
|
||||
import type { GestureResponderEvent } from "react-native";
|
||||
import * as Haptics from "expo-haptics";
|
||||
import { isWeb as platformIsWeb } from "@/constants/platform";
|
||||
import { supportsTouchHaptics, usesTouchLongPressHold } from "@/constants/touch-timing";
|
||||
import { decideLongPressMove } from "@/utils/sidebar-gesture-arbitration";
|
||||
import type { useContextMenu } from "@/components/ui/context-menu";
|
||||
|
||||
@@ -59,7 +59,7 @@ export function useLongPressDragInteraction(input: {
|
||||
|
||||
const armTimers = useCallback(() => {
|
||||
clearTimers();
|
||||
if (platformIsWeb || !drag) {
|
||||
if (!usesTouchLongPressHold || !drag) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -86,7 +86,7 @@ export function useLongPressDragInteraction(input: {
|
||||
dragArmedRef.current = true;
|
||||
dragActivatedRef.current = true;
|
||||
didLongPressRef.current = true;
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
drag();
|
||||
}, DRAG_ARM_DELAY_MS);
|
||||
|
||||
@@ -109,7 +109,7 @@ export function useLongPressDragInteraction(input: {
|
||||
if (distance > CONTEXT_MENU_STATIONARY_SLOP_PX) {
|
||||
return;
|
||||
}
|
||||
void Haptics.selectionAsync().catch(() => {});
|
||||
if (supportsTouchHaptics) void Haptics.selectionAsync().catch(() => {});
|
||||
openContextMenuAtStartPoint();
|
||||
}, CONTEXT_MENU_DELAY_MS);
|
||||
}, [clearTimers, drag, menuController, openContextMenuAtStartPoint]);
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
} from "@getpaseo/protocol/terminal-input-mode";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { useHostRuntimeClient, useHostRuntimeIsConnected } from "@/runtime/host-runtime";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { useKeyboardShiftStyle } from "@/keyboard/shift";
|
||||
import { useAppActivelyVisible } from "@/hooks/use-app-visible";
|
||||
import { useStableEvent } from "@/hooks/use-stable-event";
|
||||
@@ -89,7 +90,6 @@ import {
|
||||
type TerminalResizeRequest,
|
||||
} from "./terminal-resize-debouncer";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { useKeyboardFocusSurface } from "@/keyboard";
|
||||
import {
|
||||
applyTerminalRendererReadyChange,
|
||||
@@ -305,7 +305,10 @@ export function TerminalPane({
|
||||
return trimmed.length > 0 ? trimmed : undefined;
|
||||
}, [settings.monoFontFamily]);
|
||||
const isMobile = useIsCompactFormFactor();
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({ isNative, isCompact: isMobile });
|
||||
const showVirtualKeyBar = shouldShowTerminalVirtualKeyBar({
|
||||
hasSoftwareKeyboard,
|
||||
isCompact: isMobile,
|
||||
});
|
||||
const [keyBarWidth, setKeyBarWidth] = useState(0);
|
||||
const virtualKeyboardRows = resolveTerminalVirtualKeyboardRows({
|
||||
isCompact: isMobile,
|
||||
@@ -316,7 +319,7 @@ export function TerminalPane({
|
||||
const swipeGesturesEnabled = isMobile;
|
||||
const { shift: keyboardShift, style: keyboardPaddingStyle } = useKeyboardShiftStyle({
|
||||
mode: "padding",
|
||||
enabled: isNative || isMobile,
|
||||
enabled: hasSoftwareKeyboard || isMobile,
|
||||
});
|
||||
const [keyboardInset, setKeyboardInset] = useState(0);
|
||||
const [isKeyboardVisible, setIsKeyboardVisible] = useState(false);
|
||||
@@ -608,7 +611,7 @@ export function TerminalPane({
|
||||
|
||||
const handleKeyboardChange = useCallback(
|
||||
(nextShift: number) => {
|
||||
setKeyboardInset(isNative || isMobile ? nextShift : 0);
|
||||
setKeyboardInset(hasSoftwareKeyboard || isMobile ? nextShift : 0);
|
||||
setIsKeyboardVisible(nextShift > 0);
|
||||
pulseKeyboardRefits();
|
||||
},
|
||||
@@ -1180,10 +1183,10 @@ export function TerminalPane({
|
||||
emulatorRef.current?.blur();
|
||||
onOpenFileExplorer();
|
||||
}, [swipeGesturesEnabled, onOpenFileExplorer]);
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ isNative });
|
||||
const showPasteAction = shouldShowTerminalPasteAction({ hasSoftwareKeyboard });
|
||||
const showFloatingCopyAction = shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection,
|
||||
isNative,
|
||||
hasSoftwareKeyboard,
|
||||
});
|
||||
const keyboardToggleIconColor = theme.colors.foregroundMuted;
|
||||
|
||||
@@ -1332,7 +1335,9 @@ export function TerminalPane({
|
||||
<View
|
||||
style={styles.keyboardRows}
|
||||
onLayout={handleKeyBarLayout}
|
||||
testID={isNative && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined}
|
||||
testID={
|
||||
hasSoftwareKeyboard && !isMobile ? "terminal-virtual-keyboard-native-wide" : undefined
|
||||
}
|
||||
>
|
||||
{virtualKeyboardRows.map((row) => (
|
||||
<View
|
||||
|
||||
@@ -21,7 +21,7 @@ import { ComposerToolbarGlyph } from "@/composer/agent-controls/glyph";
|
||||
import { resolveModelTriggerLabels } from "@/composer/agent-controls/layout";
|
||||
import type { ProviderSelectorProvider } from "@/provider-selection/provider-selection";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { readMeasuredWidth } from "@/hooks/use-container-width";
|
||||
import {
|
||||
toolbarContentSlot,
|
||||
@@ -186,7 +186,7 @@ export function CompactModelSheet({
|
||||
selectedProvider,
|
||||
selectedModel,
|
||||
isLoading,
|
||||
autoFocusSearch: isWeb && !usesBottomSheet,
|
||||
autoFocusSearch: !hasSoftwareKeyboard && !usesBottomSheet,
|
||||
profiles,
|
||||
serverId,
|
||||
});
|
||||
|
||||
@@ -61,6 +61,7 @@ import {
|
||||
toolbarSlot,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { usePanelStore, type MobilePanelView } from "@/stores/panel-store";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { usePointerCapabilities } from "@/hooks/pointer-capabilities";
|
||||
import { useShallow } from "zustand/shallow";
|
||||
import {
|
||||
@@ -254,7 +255,7 @@ function resolveKeyboardPriority(isMessageInputFocused: boolean): number {
|
||||
}
|
||||
|
||||
function resolveIsDesktopWebBreakpoint(isMobile: boolean): boolean {
|
||||
return isWeb && !isMobile;
|
||||
return !hasSoftwareKeyboard && !isMobile;
|
||||
}
|
||||
|
||||
function resolveCompactLayout(override: boolean | undefined, formFactor: boolean): boolean {
|
||||
|
||||
@@ -82,8 +82,11 @@ import { useIosHardwareKeyboardSubmit } from "@/hooks/use-ios-hardware-keyboard-
|
||||
import { formatShortcut, type ShortcutKey } from "@/utils/format-shortcut";
|
||||
import { getShortcutOs } from "@/utils/shortcut-platform";
|
||||
import type { MessageInputKeyboardActionKind } from "@/keyboard/actions";
|
||||
import { supportsConfigurableComposerSendKeys } from "@/keyboard";
|
||||
import { isImeComposingKeyboardEvent } from "@/utils/keyboard-ime";
|
||||
import { getIsElectron, isNative, isWeb } from "@/constants/platform";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { composerMinInputHeight } from "@/constants/presentation";
|
||||
import { supportsTouchHaptics } from "@/constants/touch-timing";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { useComposerKeyboardScope } from "@/composer/keyboard-scope";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
@@ -238,11 +241,9 @@ export interface MessageInputRef {
|
||||
getNativeElement?: () => HTMLElement | null;
|
||||
}
|
||||
|
||||
const MIN_INPUT_HEIGHT_MOBILE = 30;
|
||||
const MIN_INPUT_HEIGHT_DESKTOP = 46;
|
||||
const DEFAULT_MAX_INPUT_HEIGHT = 160;
|
||||
const MAX_INPUT_VIEWPORT_RATIO = 0.5;
|
||||
const MIN_INPUT_HEIGHT = isWeb ? MIN_INPUT_HEIGHT_DESKTOP : MIN_INPUT_HEIGHT_MOBILE;
|
||||
const MIN_INPUT_HEIGHT = composerMinInputHeight;
|
||||
type WebTextInputKeyPressEvent = NativeSyntheticEvent<
|
||||
TextInputKeyPressEventData & {
|
||||
metaKey?: boolean;
|
||||
@@ -1883,7 +1884,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
|
||||
const handleLongPressSend = useCallback(() => {
|
||||
if (alternateSendAction && isNative) {
|
||||
if (alternateSendAction && supportsTouchHaptics) {
|
||||
void Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Medium).catch(() => {});
|
||||
}
|
||||
handleAlternateSendAction();
|
||||
@@ -1910,12 +1911,12 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
[onSelectionChangeCallback],
|
||||
);
|
||||
|
||||
const shouldHandleWebKeyPress = isWeb;
|
||||
const shouldSubmitOnEnter = isWeb && !isCompact;
|
||||
const shouldHandleKeyPress = supportsConfigurableComposerSendKeys;
|
||||
const shouldSubmitOnEnter = supportsConfigurableComposerSendKeys && !isCompact;
|
||||
|
||||
const handleDesktopKeyPress = useCallback(
|
||||
(event: WebTextInputKeyPressEvent) => {
|
||||
if (!shouldHandleWebKeyPress) return;
|
||||
if (!shouldHandleKeyPress) return;
|
||||
handleDesktopKeyPressImpl(event, {
|
||||
onKeyPressCallback,
|
||||
input: getComposerInputSnapshot(
|
||||
@@ -1935,7 +1936,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
});
|
||||
},
|
||||
[
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
onKeyPressCallback,
|
||||
shouldSubmitOnEnter,
|
||||
sendShortcut,
|
||||
@@ -2222,14 +2223,19 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
editable={!isDictating && !isRealtimeVoiceForCurrentAgent && !disabled}
|
||||
scrollEnabled={isComposerScrollEnabled}
|
||||
autoFocus={false}
|
||||
onKeyPress={shouldHandleWebKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onKeyPress={shouldHandleKeyPress ? handleDesktopKeyPress : undefined}
|
||||
onSelectionChange={handleSelectionChange}
|
||||
onPasteImages={onPasteImages}
|
||||
onPasteError={handlePasteError}
|
||||
fullscreen={isFullscreen}
|
||||
compact={isCompact}
|
||||
onRenderedLinesChange={setRenderedLines}
|
||||
focusHintVisible={!isFullscreen && isWeb && !isInputFocused && !hasLiveText}
|
||||
focusHintVisible={
|
||||
!isFullscreen &&
|
||||
supportsConfigurableComposerSendKeys &&
|
||||
!isInputFocused &&
|
||||
!hasLiveText
|
||||
}
|
||||
focusInputKeys={focusInputKeys}
|
||||
focusHintLabel={t("composer.input.focusHint", {
|
||||
shortcut: focusInputKeys ? formatShortcut(focusInputKeys[0], getShortcutOs()) : "",
|
||||
@@ -2253,7 +2259,7 @@ export const MessageInput = forwardRef<MessageInputRef, MessageInputProps>(
|
||||
isRealtimeVoiceForCurrentAgent,
|
||||
disabled,
|
||||
isComposerScrollEnabled,
|
||||
shouldHandleWebKeyPress,
|
||||
shouldHandleKeyPress,
|
||||
handleDesktopKeyPress,
|
||||
handleSelectionChange,
|
||||
onPasteImages,
|
||||
|
||||
@@ -25,6 +25,9 @@ export const isWeb = Platform.OS === "web";
|
||||
/** iOS or Android — the JS runtime is React Native. */
|
||||
export const isNative = Platform.OS !== "web";
|
||||
|
||||
/** Platforms with an alpha-mask compositor for decorative shimmer effects. */
|
||||
export const supportsMaskedEffects = ["web", "ios", "android"].includes(Platform.OS);
|
||||
|
||||
/** Development build/runtime — true in Metro dev bundles, false in production. */
|
||||
export const isDev = Boolean((globalThis as { __DEV__?: boolean }).__DEV__);
|
||||
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolvePresentationCapabilities } from "./presentation";
|
||||
|
||||
describe("presentation capabilities per target", () => {
|
||||
it("resolves mobile and desktop presentation answers for iOS, Android, web, and Electron", () => {
|
||||
expect(resolvePresentationCapabilities({ isNative: true, isWeb: false })).toEqual({
|
||||
allowsInlineWorkspaceRename: false,
|
||||
usesCompactBottomSheet: true,
|
||||
usesDesktopPopoverSpacing: false,
|
||||
initialUiBaseFontSize: 15,
|
||||
initialContentFontSize: 16,
|
||||
usesMobileContentFontMigration: true,
|
||||
composerMinInputHeight: 30,
|
||||
});
|
||||
expect(resolvePresentationCapabilities({ isNative: false, isWeb: true })).toEqual({
|
||||
allowsInlineWorkspaceRename: true,
|
||||
usesCompactBottomSheet: false,
|
||||
usesDesktopPopoverSpacing: true,
|
||||
initialUiBaseFontSize: 14,
|
||||
initialContentFontSize: 15,
|
||||
usesMobileContentFontMigration: false,
|
||||
composerMinInputHeight: 46,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,44 @@
|
||||
import { FONT_SIZE } from "@/styles/theme";
|
||||
import { isNative, isWeb } from "./platform";
|
||||
|
||||
export interface PresentationCapabilities {
|
||||
/** Wide sidebar rows rename in place instead of opening a rename modal. */
|
||||
allowsInlineWorkspaceRename: boolean;
|
||||
/** Compact screens present bottom sheets (`SheetFlatList` / Gorhom modal) instead of dialogs. */
|
||||
usesCompactBottomSheet: boolean;
|
||||
/** Popover lists use tight desktop row padding instead of touch-sheet spacing. */
|
||||
usesDesktopPopoverSpacing: boolean;
|
||||
/** Initial UI font size (pt) when no user preference is saved. */
|
||||
initialUiBaseFontSize: number;
|
||||
/** Initial chat content font size (pt) when no user preference is saved. */
|
||||
initialContentFontSize: number;
|
||||
/** Whether legacy 15 pt persisted content size migrates up to the mobile 16 pt default. */
|
||||
usesMobileContentFontMigration: boolean;
|
||||
/** Minimum multiline composer input height (pt). */
|
||||
composerMinInputHeight: number;
|
||||
}
|
||||
|
||||
export function resolvePresentationCapabilities(input: {
|
||||
isNative: boolean;
|
||||
isWeb: boolean;
|
||||
}): PresentationCapabilities {
|
||||
return {
|
||||
allowsInlineWorkspaceRename: input.isWeb,
|
||||
usesCompactBottomSheet: input.isNative,
|
||||
usesDesktopPopoverSpacing: input.isWeb,
|
||||
initialUiBaseFontSize: input.isNative ? 15 : FONT_SIZE.base,
|
||||
initialContentFontSize: input.isNative ? 16 : FONT_SIZE.content,
|
||||
usesMobileContentFontMigration: input.isNative,
|
||||
composerMinInputHeight: input.isWeb ? 46 : 30,
|
||||
};
|
||||
}
|
||||
|
||||
const CAPABILITIES = resolvePresentationCapabilities({ isNative, isWeb });
|
||||
|
||||
export const allowsInlineWorkspaceRename = CAPABILITIES.allowsInlineWorkspaceRename;
|
||||
export const usesCompactBottomSheet = CAPABILITIES.usesCompactBottomSheet;
|
||||
export const usesDesktopPopoverSpacing = CAPABILITIES.usesDesktopPopoverSpacing;
|
||||
export const initialUiBaseFontSize = CAPABILITIES.initialUiBaseFontSize;
|
||||
export const initialContentFontSize = CAPABILITIES.initialContentFontSize;
|
||||
export const usesMobileContentFontMigration = CAPABILITIES.usesMobileContentFontMigration;
|
||||
export const composerMinInputHeight = CAPABILITIES.composerMinInputHeight;
|
||||
@@ -0,0 +1,26 @@
|
||||
// Platform-free: Playwright imports this through workspace-deck-retention in plain Node.
|
||||
|
||||
export interface SourceFileBudgets {
|
||||
readonly highlighted: number;
|
||||
readonly plain: number;
|
||||
}
|
||||
|
||||
export interface PlatformResourceBudgets {
|
||||
readonly workspaceDeckRetentionLimit: number;
|
||||
readonly sourceFileBudgets: SourceFileBudgets;
|
||||
}
|
||||
|
||||
const MOBILE_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
const WEB_RESOURCE_BUDGETS: PlatformResourceBudgets = {
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
};
|
||||
|
||||
/** Native phones use mobile memory budgets; web and Electron use desktop budgets. */
|
||||
export function resolveResourceBudgets(input: { isNative: boolean }): PlatformResourceBudgets {
|
||||
return input.isNative ? MOBILE_RESOURCE_BUDGETS : WEB_RESOURCE_BUDGETS;
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
describe("resource budget per target", () => {
|
||||
it("resolves mobile and desktop resource budget limits for iOS, Android, web, and Electron", () => {
|
||||
expect(resolveResourceBudgets({ isNative: true })).toEqual({
|
||||
workspaceDeckRetentionLimit: 1,
|
||||
sourceFileBudgets: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
});
|
||||
expect(resolveResourceBudgets({ isNative: false })).toEqual({
|
||||
workspaceDeckRetentionLimit: 10,
|
||||
sourceFileBudgets: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,7 @@
|
||||
import { isNative } from "./platform";
|
||||
import { resolveResourceBudgets } from "./resource-budget-tables";
|
||||
|
||||
const RESOURCE_BUDGETS = resolveResourceBudgets({ isNative });
|
||||
|
||||
export const workspaceDeckRetentionLimit = RESOURCE_BUDGETS.workspaceDeckRetentionLimit;
|
||||
export const sourceFileBudgets = RESOURCE_BUDGETS.sourceFileBudgets;
|
||||
@@ -0,0 +1,15 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveTouchTiming } from "./touch-timing";
|
||||
|
||||
describe("touch timing per target", () => {
|
||||
it("enables touch timing and haptics only on iOS and Android, not on web or Electron", () => {
|
||||
expect(resolveTouchTiming({ isNative: true })).toEqual({
|
||||
supportsTouchHaptics: true,
|
||||
usesTouchLongPressHold: true,
|
||||
});
|
||||
expect(resolveTouchTiming({ isNative: false })).toEqual({
|
||||
supportsTouchHaptics: false,
|
||||
usesTouchLongPressHold: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { isNative } from "./platform";
|
||||
|
||||
export interface TouchTimingCapabilities {
|
||||
/** Fire tactile `expo-haptics` feedback on touch interactions. */
|
||||
supportsTouchHaptics: boolean;
|
||||
/** Require a stationary long-press delay to arm drag or open context menus. */
|
||||
usesTouchLongPressHold: boolean;
|
||||
}
|
||||
|
||||
export function resolveTouchTiming(input: { isNative: boolean }): TouchTimingCapabilities {
|
||||
return {
|
||||
supportsTouchHaptics: input.isNative,
|
||||
usesTouchLongPressHold: input.isNative,
|
||||
};
|
||||
}
|
||||
|
||||
const TOUCH_TIMING = resolveTouchTiming({ isNative });
|
||||
|
||||
export const supportsTouchHaptics = TOUCH_TIMING.supportsTouchHaptics;
|
||||
export const usesTouchLongPressHold = TOUCH_TIMING.usesTouchLongPressHold;
|
||||
@@ -94,6 +94,18 @@ describe("desktop-daemon-transport", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports socket and pipe sessions as local and Remote SSH sessions as remote", () => {
|
||||
const transportFactory = createDesktopDaemonTransportFactory(
|
||||
createFakeLocalDaemonTransportRpc(),
|
||||
);
|
||||
const open = (target: Parameters<typeof buildDesktopDaemonTransportUrl>[0]) =>
|
||||
transportFactory!({ url: buildDesktopDaemonTransportUrl(target) });
|
||||
|
||||
expect(open({ transportType: "socket", transportPath: "/tmp/paseo.sock" }).local).toBe(true);
|
||||
expect(open({ transportType: "pipe", transportPath: "\\\\.\\pipe\\paseo" }).local).toBe(true);
|
||||
expect(open({ transportType: "ssh", host: "deploy@example.com" }).local).toBe(false);
|
||||
});
|
||||
|
||||
it.each([0, 65536])("rejects an out-of-range Remote SSH port (%s)", (sshPort) => {
|
||||
const transportFactory = createDesktopDaemonTransportFactory(
|
||||
createFakeLocalDaemonTransportRpc(),
|
||||
|
||||
@@ -168,6 +168,8 @@ export function createDesktopDaemonTransportFactory(
|
||||
})();
|
||||
|
||||
const transport: DaemonTransport = {
|
||||
// Remote SSH forwards bytes across the network; sockets and pipes stay on this machine.
|
||||
local: target.transportType !== "ssh",
|
||||
send: (data) => {
|
||||
if (!didEmitOpen) {
|
||||
return;
|
||||
|
||||
@@ -73,7 +73,7 @@ type TextFilePanelProps = BuiltinFilePanelProps & {
|
||||
*/
|
||||
export function TextFilePanel(props: TextFilePanelProps) {
|
||||
const size = props.file.size;
|
||||
const presentation = selectSourcePresentation({ size, platform: isWeb ? "web" : "native" });
|
||||
const presentation = selectSourcePresentation({ size });
|
||||
if (presentation === "unsupported") return <TooLargeTextFile size={size} />;
|
||||
if (isWeb && size <= MAX_EDITABLE_BYTES) return <EditableTextFile {...props} />;
|
||||
return <ReadonlyTextFile {...props} presentation={presentation} />;
|
||||
|
||||
@@ -11,4 +11,11 @@ describe("selectSourcePresentation", () => {
|
||||
expect(selectSourcePresentation({ platform, size: budgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
}
|
||||
|
||||
it("defaults to the target resource budget limits when no platform override is passed", () => {
|
||||
const webBudgets = SOURCE_PRESENTATION_BUDGETS.web;
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted })).toBe("highlighted");
|
||||
expect(selectSourcePresentation({ size: webBudgets.highlighted + 1 })).toBe("plain");
|
||||
expect(selectSourcePresentation({ size: webBudgets.plain + 1 })).toBe("unsupported");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { sourceFileBudgets } from "@/constants/resource-budget";
|
||||
import { resolveResourceBudgets } from "@/constants/resource-budget-tables";
|
||||
|
||||
export const SOURCE_PRESENTATION_BUDGETS = {
|
||||
web: { highlighted: 10 * 1024 * 1024, plain: 50 * 1024 * 1024 },
|
||||
native: { highlighted: 1024 * 1024, plain: 10 * 1024 * 1024 },
|
||||
web: resolveResourceBudgets({ isNative: false }).sourceFileBudgets,
|
||||
native: resolveResourceBudgets({ isNative: true }).sourceFileBudgets,
|
||||
} as const;
|
||||
|
||||
export type SourcePresentation = "highlighted" | "plain" | "unsupported";
|
||||
@@ -8,9 +11,9 @@ export type SourcePlatform = keyof typeof SOURCE_PRESENTATION_BUDGETS;
|
||||
|
||||
export function selectSourcePresentation(input: {
|
||||
size: number;
|
||||
platform: SourcePlatform;
|
||||
platform?: SourcePlatform;
|
||||
}): SourcePresentation {
|
||||
const budgets = SOURCE_PRESENTATION_BUDGETS[input.platform];
|
||||
const budgets = input.platform ? SOURCE_PRESENTATION_BUDGETS[input.platform] : sourceFileBudgets;
|
||||
if (input.size <= budgets.highlighted) return "highlighted";
|
||||
if (input.size <= budgets.plain) return "plain";
|
||||
return "unsupported";
|
||||
|
||||
@@ -23,7 +23,12 @@ import {
|
||||
isChecksHiddenByLegacyRowItem,
|
||||
type SidebarRowItems,
|
||||
} from "@/components/sidebar/display-preferences/row-items";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import {
|
||||
initialContentFontSize,
|
||||
initialUiBaseFontSize,
|
||||
resolvePresentationCapabilities,
|
||||
usesMobileContentFontMigration,
|
||||
} from "@/constants/presentation";
|
||||
import {
|
||||
DEFAULT_CONTENT_MAX_WIDTH,
|
||||
FONT_SIZE,
|
||||
@@ -60,17 +65,19 @@ export const DEFAULT_TERMINAL_SCROLLBACK_LINES = 10_000;
|
||||
export const MIN_TERMINAL_SCROLLBACK_LINES = 0;
|
||||
export const MAX_TERMINAL_SCROLLBACK_LINES = 1_000_000;
|
||||
export function defaultUiBaseFontSize(native: boolean): number {
|
||||
return native ? 15 : FONT_SIZE.base;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialUiBaseFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = defaultUiBaseFontSize(isNative);
|
||||
export const DEFAULT_UI_BASE_FONT_SIZE = initialUiBaseFontSize;
|
||||
export const MIN_UI_BASE_FONT_SIZE = 10;
|
||||
export const MAX_UI_BASE_FONT_SIZE = 21;
|
||||
export function defaultContentFontSize(native: boolean): number {
|
||||
return native ? 16 : FONT_SIZE.content;
|
||||
return resolvePresentationCapabilities({ isNative: native, isWeb: !native })
|
||||
.initialContentFontSize;
|
||||
}
|
||||
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = defaultContentFontSize(isNative);
|
||||
export const DEFAULT_CONTENT_FONT_SIZE = initialContentFontSize;
|
||||
export const MIN_CONTENT_FONT_SIZE = 10;
|
||||
export const MAX_CONTENT_FONT_SIZE = 21;
|
||||
export const DEFAULT_CODE_FONT_SIZE = 12; // == FONT_SIZE.code
|
||||
@@ -410,7 +417,9 @@ export async function loadAppSettingsFromStorage(deps: SettingsDeps): Promise<Ap
|
||||
await writeAppSettings(deps.storage, read.stored, read.settings);
|
||||
}
|
||||
const { needsWrite: _needsWrite, ...stored } = read.stored;
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, { native: isNative });
|
||||
return await migrateAppSettings(read.settings, deps.storage, stored, {
|
||||
native: usesMobileContentFontMigration,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error("[AppSettings] Failed to load settings:", error);
|
||||
throw error;
|
||||
|
||||
@@ -2435,6 +2435,9 @@ export const ar: TranslationResources = {
|
||||
archiveFinishedRetry: "إعادة المحاولة ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "تعذّر عرض هذه اللوحة",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "وكيل جديد",
|
||||
creatingAgent: "وكيل الخلق",
|
||||
|
||||
@@ -2467,6 +2467,9 @@ export const en = {
|
||||
archiveFinishedRetry: "Retry ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Unable to show this panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "New Agent",
|
||||
creatingAgent: "Creating agent",
|
||||
|
||||
@@ -2495,6 +2495,9 @@ export const es: TranslationResources = {
|
||||
archiveFinishedRetry: "Reintentar ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "No se puede mostrar este panel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nuevo agente",
|
||||
creatingAgent: "Agente creador",
|
||||
|
||||
@@ -2491,6 +2491,9 @@ export const fr: TranslationResources = {
|
||||
archiveFinishedRetry: "Réessayer ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Impossible d'afficher ce panneau",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Nouvel agent",
|
||||
creatingAgent: "Création de l’agent",
|
||||
|
||||
@@ -2461,6 +2461,9 @@ export const ja: TranslationResources = {
|
||||
archiveFinishedRetry: "再試行 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "このパネルを表示できません",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新しいエージェント",
|
||||
creatingAgent: "エージェントを作成中",
|
||||
|
||||
@@ -2452,6 +2452,9 @@ export const ko: TranslationResources = {
|
||||
archiveFinishedRetry: "다시 시도 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "이 패널을 표시할 수 없습니다",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "새 에이전트",
|
||||
creatingAgent: "에이전트 생성 중",
|
||||
|
||||
@@ -2477,6 +2477,9 @@ export const ptBR: TranslationResources = {
|
||||
archiveFinishedRetry: "Tentar novamente ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Não foi possível exibir este painel",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Novo Agente",
|
||||
creatingAgent: "Criando agente",
|
||||
|
||||
@@ -2477,6 +2477,9 @@ export const ru: TranslationResources = {
|
||||
archiveFinishedRetry: "Повторить ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "Не удалось показать эту панель",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "Новый агент",
|
||||
creatingAgent: "Создание агента",
|
||||
|
||||
@@ -2408,6 +2408,9 @@ export const zhCN: TranslationResources = {
|
||||
archiveFinishedRetry: "重试 ({{failed}}/{{total}})",
|
||||
},
|
||||
panels: {
|
||||
renderError: {
|
||||
title: "无法显示此面板",
|
||||
},
|
||||
draft: {
|
||||
newAgent: "新建 Agent",
|
||||
creatingAgent: "正在创建 Agent",
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { createHardwareKeyboardPresence } from "./internal/hardware-presence";
|
||||
import * as webConventions from "./internal/conventions.web";
|
||||
import { createWebHardwareKeyboardPresence } from "./internal/presence.web";
|
||||
import { buildEffectiveBindings } from "./keyboard-shortcuts";
|
||||
import { createKeyboardPipeline } from "./internal/pipeline";
|
||||
import { createOverlayRegistry } from "./internal/overlays";
|
||||
@@ -65,4 +67,39 @@ describe("hardware keyboard availability", () => {
|
||||
expect(actions).toEqual(["command-center.toggle"]);
|
||||
pipeline.dispose();
|
||||
});
|
||||
|
||||
it("answers keyboard presence and conventions per target", async () => {
|
||||
const nativeConventions = (await import(
|
||||
new URL("./internal/conventions.ts", import.meta.url).href
|
||||
)) as typeof webConventions & { usesDesktopBindings: boolean };
|
||||
const { hardwareKeyboardPresence: nativePresence } = (await import(
|
||||
new URL("./internal/presence.ts", import.meta.url).href
|
||||
)) as { hardwareKeyboardPresence: { getSnapshot(): boolean } };
|
||||
|
||||
expect(nativePresence.getSnapshot()).toBe(false);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: true } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(true);
|
||||
expect(
|
||||
createWebHardwareKeyboardPresence({ matches: false } as MediaQueryList, null).getSnapshot(),
|
||||
).toBe(false);
|
||||
|
||||
expect({
|
||||
usesDesktopBindings: nativeConventions.usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys: nativeConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: nativeConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
usesDesktopBindings: true,
|
||||
supportsConfigurableComposerSendKeys: false,
|
||||
hasSoftwareKeyboard: true,
|
||||
});
|
||||
|
||||
expect({
|
||||
supportsConfigurableComposerSendKeys: webConventions.supportsConfigurableComposerSendKeys,
|
||||
hasSoftwareKeyboard: webConventions.hasSoftwareKeyboard,
|
||||
}).toEqual({
|
||||
supportsConfigurableComposerSendKeys: true,
|
||||
hasSoftwareKeyboard: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -11,7 +11,11 @@ export { hasFocusedTextInput, registerFocusedTextInput } from "./internal/focuse
|
||||
export { useKeyboardFocusSurface } from "./internal/use-focus-surface";
|
||||
export { subscribeHardwareKeyboard } from "./internal/sources/hardware";
|
||||
export type { HardwareKeyboardEvent } from "./internal/sources/hardware";
|
||||
export { usesDesktopBindings, supportsConfigurableComposerSendKeys } from "./internal/conventions";
|
||||
export {
|
||||
hasSoftwareKeyboard,
|
||||
usesDesktopBindings,
|
||||
supportsConfigurableComposerSendKeys,
|
||||
} from "./internal/conventions";
|
||||
export type { BrowserKeyboardPolicy } from "./internal/sources/electron-browser";
|
||||
export { useHardwareKeyboardPresent } from "./availability";
|
||||
export { readPressModifiers } from "./internal/press-modifiers";
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
export const usesDesktopBindings = true;
|
||||
// Native composer Return retains its existing submit path in this feature.
|
||||
export const supportsConfigurableComposerSendKeys = false;
|
||||
export const hasSoftwareKeyboard = true;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { isElectronRuntime } from "@/desktop/host";
|
||||
export const usesDesktopBindings = isElectronRuntime();
|
||||
export const supportsConfigurableComposerSendKeys = true;
|
||||
export const hasSoftwareKeyboard = false;
|
||||
|
||||
@@ -28,7 +28,7 @@ import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { scheduleOnRN, scheduleOnUI } from "react-native-worklets";
|
||||
import { resolveDesktopSidebarWidth } from "@/components/desktop-sidebar-layout";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import {
|
||||
usePanelStore,
|
||||
type MobilePanelSelection,
|
||||
@@ -138,7 +138,7 @@ export function MobilePanelsProvider({ children }: { children: ReactNode }) {
|
||||
if (selection.revision !== revision || selection.target !== panel) {
|
||||
return;
|
||||
}
|
||||
if (isNative && panel !== "agent") {
|
||||
if (hasSoftwareKeyboard && panel !== "agent") {
|
||||
Keyboard.dismiss();
|
||||
}
|
||||
settledPanel.setState(panel);
|
||||
|
||||
@@ -57,7 +57,8 @@ import {
|
||||
import type { WorkspaceComposerAttachment } from "@/attachments/types";
|
||||
import { useWorkspaceAttachmentScopeKey } from "@/attachments/workspace-attachments-store";
|
||||
import { COMPACT_CONTENT_WIDTH, useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { isNative, isWeb } from "@/constants/platform";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { hasSoftwareKeyboard } from "@/keyboard";
|
||||
import { useAgentAttentionClear } from "@/hooks/use-agent-attention-clear";
|
||||
import { useAgentInputDraft, type AgentInputDraft } from "@/composer/draft/input-draft";
|
||||
import {
|
||||
@@ -1883,7 +1884,7 @@ function AgentComposer({
|
||||
agentId={agentId}
|
||||
serverId={serverId}
|
||||
workspaceId={workspaceId}
|
||||
blurOnSubmit={isNative}
|
||||
blurOnSubmit={hasSoftwareKeyboard}
|
||||
isPaneFocused={isPaneFocused}
|
||||
textSource={agentInputDraft.textSource}
|
||||
onChangeText={agentInputDraft.editText}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import React, { Component, type ErrorInfo, type ReactNode } from "react";
|
||||
import type { ReactNode } from "react";
|
||||
import { Text } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { RenderErrorBoundary } from "@/components/render-error-boundary";
|
||||
|
||||
interface SurfaceErrorBoundaryProps {
|
||||
children: ReactNode;
|
||||
@@ -10,42 +11,30 @@ interface SurfaceErrorBoundaryProps {
|
||||
renderError?(error: string): ReactNode;
|
||||
}
|
||||
|
||||
interface SurfaceErrorBoundaryState {
|
||||
error: string | null;
|
||||
export function SurfaceErrorBoundary({
|
||||
children,
|
||||
installation,
|
||||
resetKey,
|
||||
Surface,
|
||||
renderError,
|
||||
}: SurfaceErrorBoundaryProps) {
|
||||
return (
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[installation, resetKey, Surface]}
|
||||
onError={warnSurfaceRenderFailed}
|
||||
renderError={renderError ?? renderPluginFailed}
|
||||
>
|
||||
{children}
|
||||
</RenderErrorBoundary>
|
||||
);
|
||||
}
|
||||
|
||||
export class SurfaceErrorBoundary extends Component<
|
||||
SurfaceErrorBoundaryProps,
|
||||
SurfaceErrorBoundaryState
|
||||
> {
|
||||
state: SurfaceErrorBoundaryState = { error: null };
|
||||
function renderPluginFailed(error: string) {
|
||||
return <Text style={styles.errorText}>Plugin failed: {error}</Text>;
|
||||
}
|
||||
|
||||
static getDerivedStateFromError(error: unknown): SurfaceErrorBoundaryState {
|
||||
return { error: error instanceof Error ? error.message : String(error) };
|
||||
}
|
||||
|
||||
componentDidCatch(error: Error, info: ErrorInfo): void {
|
||||
console.warn("[Plugins] Surface render failed", error, info.componentStack);
|
||||
}
|
||||
|
||||
componentDidUpdate(previous: SurfaceErrorBoundaryProps): void {
|
||||
if (
|
||||
this.state.error &&
|
||||
(previous.installation !== this.props.installation ||
|
||||
previous.resetKey !== this.props.resetKey ||
|
||||
previous.Surface !== this.props.Surface)
|
||||
) {
|
||||
this.setState({ error: null });
|
||||
}
|
||||
}
|
||||
|
||||
render() {
|
||||
if (this.state.error) {
|
||||
if (this.props.renderError) return this.props.renderError(this.state.error);
|
||||
return <Text style={styles.errorText}>Plugin failed: {this.state.error}</Text>;
|
||||
}
|
||||
return this.props.children;
|
||||
}
|
||||
function warnSurfaceRenderFailed(error: unknown, componentStack: string | null | undefined): void {
|
||||
console.warn("[Plugins] Surface render failed", error, componentStack);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
|
||||
@@ -4,7 +4,6 @@ import {
|
||||
getNextWorkspaceDeckExpirationDelay,
|
||||
orderWorkspaceSelectionsForStableRender,
|
||||
reconcileRetainedWorkspaceSelections,
|
||||
resolveWorkspaceDeckRetentionLimit,
|
||||
resolveWorkspaceDeckEntries,
|
||||
shouldKeepWorkspaceDeckEntryMounted,
|
||||
WORKSPACE_DECK_INACTIVE_TTL_MS,
|
||||
@@ -30,21 +29,26 @@ function retainedWorkspaceIds(
|
||||
}
|
||||
|
||||
describe("reconcileRetainedWorkspaceSelections", () => {
|
||||
it("retains only the active workspace on native", () => {
|
||||
it("retains only the active workspace when limited to one mounted workspace", () => {
|
||||
const entries = reconcileRetainedWorkspaceSelections({
|
||||
currentEntries: [retained("A", null)],
|
||||
activeSelection: workspace("B"),
|
||||
now: 2,
|
||||
maxMountedWorkspaces: resolveWorkspaceDeckRetentionLimit({ isNative: true }),
|
||||
maxMountedWorkspaces: 1,
|
||||
});
|
||||
|
||||
expect(retainedWorkspaceIds(entries)).toEqual(["B"]);
|
||||
});
|
||||
|
||||
it("retains the desktop deck limit on web", () => {
|
||||
expect(resolveWorkspaceDeckRetentionLimit({ isNative: false })).toBe(
|
||||
WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES,
|
||||
);
|
||||
it("retains up to the configured limit when higher", () => {
|
||||
const entries = reconcileRetainedWorkspaceSelections({
|
||||
currentEntries: [retained("A", null)],
|
||||
activeSelection: workspace("B"),
|
||||
now: 2,
|
||||
maxMountedWorkspaces: WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES,
|
||||
});
|
||||
|
||||
expect(retainedWorkspaceIds(entries)).toEqual(["B", "A"]);
|
||||
});
|
||||
|
||||
it("retains inactive workspaces for ten minutes across app-wide routes", () => {
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { resolveResourceBudgets } from "../../constants/resource-budget-tables";
|
||||
import type { ActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
|
||||
export const WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES = 10;
|
||||
// Relative import: Playwright loads this file in plain Node, without the `@/` alias or react-native.
|
||||
export const WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES = resolveResourceBudgets({
|
||||
isNative: false,
|
||||
}).workspaceDeckRetentionLimit;
|
||||
export const WORKSPACE_DECK_INACTIVE_TTL_MS = 10 * 60 * 1000;
|
||||
|
||||
export interface RetainedWorkspaceSelection {
|
||||
@@ -8,10 +12,6 @@ export interface RetainedWorkspaceSelection {
|
||||
inactiveSince: number | null;
|
||||
}
|
||||
|
||||
export function resolveWorkspaceDeckRetentionLimit(input: { isNative: boolean }): number {
|
||||
return input.isNative ? 1 : WORKSPACE_DECK_MAX_MOUNTED_WORKSPACES;
|
||||
}
|
||||
|
||||
interface ReconcileRetainedWorkspaceSelectionsInput {
|
||||
currentEntries: RetainedWorkspaceSelection[];
|
||||
activeSelection: ActiveWorkspaceSelection | null;
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
import { act } from "@testing-library/react";
|
||||
import React from "react";
|
||||
import { createRoot, type Root } from "react-dom/client";
|
||||
import { Text } from "react-native";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { definePanel, registerPanel } from "@/panels/panel-registry";
|
||||
import {
|
||||
buildWorkspacePaneContentModel,
|
||||
WorkspacePaneContent,
|
||||
} from "@/screens/workspace/workspace-pane-content";
|
||||
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
|
||||
|
||||
Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });
|
||||
|
||||
let panelFails = false;
|
||||
let panelMounts = 0;
|
||||
|
||||
function TestPanel() {
|
||||
React.useEffect(() => {
|
||||
panelMounts += 1;
|
||||
}, []);
|
||||
if (panelFails) throw new Error("Panel exploded");
|
||||
return <Text>Panel content</Text>;
|
||||
}
|
||||
|
||||
// The workspace screen registers the real panels; this one stands in for each kind the tests open.
|
||||
for (const kind of ["agent", "draft"] as const) {
|
||||
registerPanel(
|
||||
definePanel(kind, {
|
||||
component: TestPanel,
|
||||
useDescriptor: () => {
|
||||
throw new Error("The test panel has no descriptor");
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const draftTab: WorkspaceTabDescriptor = {
|
||||
key: "tab-a",
|
||||
tabId: "tab-a",
|
||||
kind: "draft",
|
||||
target: { kind: "draft", draftId: "draft-a" },
|
||||
};
|
||||
const agentTab: WorkspaceTabDescriptor = {
|
||||
key: "tab-a",
|
||||
tabId: "tab-a",
|
||||
kind: "agent",
|
||||
target: { kind: "agent", agentId: "agent-a" },
|
||||
};
|
||||
|
||||
function buildContent(tab: WorkspaceTabDescriptor) {
|
||||
return buildWorkspacePaneContentModel({
|
||||
tab,
|
||||
normalizedServerId: "server-a",
|
||||
normalizedWorkspaceId: "workspace-a",
|
||||
host: "main",
|
||||
onOpenTab: vi.fn(),
|
||||
onOpenPreferredTarget: vi.fn(),
|
||||
onOpenTargetToSide: vi.fn(),
|
||||
onCloseCurrentTab: vi.fn(),
|
||||
onRetargetCurrentTab: vi.fn(),
|
||||
onSetCurrentTabState: vi.fn(),
|
||||
onOpenWorkspaceFile: vi.fn(),
|
||||
onOpenImportSheet: vi.fn(),
|
||||
});
|
||||
}
|
||||
|
||||
function byTestId(container: HTMLElement, testID: string): HTMLElement | null {
|
||||
return container.querySelector(`[data-testid="${testID}"]`);
|
||||
}
|
||||
|
||||
// Every host (explorer, split pane, compact center, sheet) mounts panels through
|
||||
// WorkspacePaneContent, so its boundary keeps a panel's render error from reaching the root screen.
|
||||
describe("WorkspacePaneContent when the panel throws while rendering", () => {
|
||||
let root: Root;
|
||||
let container: HTMLDivElement;
|
||||
|
||||
function show(tab: WorkspaceTabDescriptor) {
|
||||
act(() =>
|
||||
root.render(
|
||||
<>
|
||||
<Text>Sibling</Text>
|
||||
<WorkspacePaneContent content={buildContent(tab)} isPaneFocused isWorkspaceFocused />
|
||||
</>,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
panelFails = false;
|
||||
panelMounts = 0;
|
||||
container = document.createElement("div");
|
||||
document.body.appendChild(container);
|
||||
root = createRoot(container);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
act(() => root.unmount());
|
||||
container.remove();
|
||||
});
|
||||
|
||||
it("shows the error in place of the panel and retries on demand", () => {
|
||||
panelFails = true;
|
||||
show(agentTab);
|
||||
|
||||
expect(container.textContent).toContain("Sibling");
|
||||
expect(byTestId(container, "panel-render-error")?.textContent).toContain("Panel exploded");
|
||||
|
||||
panelFails = false;
|
||||
act(() => byTestId(container, "panel-render-error-retry")?.click());
|
||||
|
||||
expect(byTestId(container, "panel-render-error")).toBeNull();
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
expect(container.textContent).toContain("Sibling");
|
||||
});
|
||||
|
||||
it("clears the error when the tab is retargeted", () => {
|
||||
panelFails = true;
|
||||
show(draftTab);
|
||||
expect(byTestId(container, "panel-render-error")).not.toBeNull();
|
||||
|
||||
panelFails = false;
|
||||
show(agentTab);
|
||||
|
||||
expect(byTestId(container, "panel-render-error")).toBeNull();
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
});
|
||||
|
||||
it("keeps a healthy panel mounted when its tab is retargeted in place", () => {
|
||||
show(draftTab);
|
||||
show(agentTab);
|
||||
|
||||
expect(container.textContent).toContain("Panel content");
|
||||
expect(panelMounts).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,12 @@
|
||||
import { ComposerEditingScope } from "@/composer/editing-session";
|
||||
import React, { useMemo, type ComponentType } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import invariant from "tiny-invariant";
|
||||
import { RenderErrorBoundary } from "@/components/render-error-boundary";
|
||||
import { Alert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
createPaneFocusContextValue,
|
||||
PaneFocusProvider,
|
||||
@@ -87,6 +93,31 @@ export interface WorkspacePaneContentProps {
|
||||
onFocusPane?: () => void;
|
||||
}
|
||||
|
||||
function logPanelRenderError(error: unknown, componentStack: string | null | undefined): void {
|
||||
console.error("[WorkspacePanel] Render failed", error, componentStack);
|
||||
}
|
||||
|
||||
function renderPanelError(error: string, retry: () => void) {
|
||||
return <PanelRenderError error={error} onRetry={retry} />;
|
||||
}
|
||||
|
||||
function PanelRenderError({ error, onRetry }: { error: string; onRetry: () => void }) {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<View style={styles.renderError} testID="panel-render-error">
|
||||
<Alert variant="error" title={t("panels.renderError.title")} description={error}>
|
||||
<Button variant="outline" size="sm" onPress={onRetry} testID="panel-render-error-retry">
|
||||
{t("common.actions.retry")}
|
||||
</Button>
|
||||
</Alert>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Mounts one panel with its pane context. A render error stays inside the panel, so every host
|
||||
* (explorer, split pane, compact center, sheet) keeps the rest of the app alive.
|
||||
*/
|
||||
export function WorkspacePaneContent({
|
||||
content,
|
||||
isWorkspaceFocused,
|
||||
@@ -159,10 +190,22 @@ export function WorkspacePaneContent({
|
||||
tabId={paneContextValue.tabId}
|
||||
targetKey={JSON.stringify(paneContextValue.target)}
|
||||
>
|
||||
<Component key={key} />
|
||||
<RenderErrorBoundary
|
||||
resetKeys={[key, paneContextValue.target, paneContextValue.state]}
|
||||
onError={logPanelRenderError}
|
||||
renderError={renderPanelError}
|
||||
>
|
||||
<Component key={key} />
|
||||
</RenderErrorBoundary>
|
||||
</ComposerEditingScope>
|
||||
</PaneFocusProvider>
|
||||
</PaneProvider>
|
||||
</RenderProfile>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
renderError: {
|
||||
padding: theme.spacing[4],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -45,11 +45,19 @@ function controlsByType(
|
||||
}
|
||||
|
||||
describe("terminal virtual keyboard policy", () => {
|
||||
it("keeps terminal controls on wide native touch screens with either IME state", () => {
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: true, isCompact: false })).toBe(true);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: true, isCompact: true })).toBe(true);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: false, isCompact: true })).toBe(true);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ isNative: false, isCompact: false })).toBe(false);
|
||||
it("keeps terminal controls on wide software-keyboard screens and compact windows", () => {
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: true, isCompact: false })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: true, isCompact: true })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: false, isCompact: true })).toBe(
|
||||
true,
|
||||
);
|
||||
expect(shouldShowTerminalVirtualKeyBar({ hasSoftwareKeyboard: false, isCompact: false })).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("selects the same controls in narrow and wide row arrangements", () => {
|
||||
@@ -116,29 +124,29 @@ describe("terminal virtual keyboard policy", () => {
|
||||
expect(controlIds()).not.toContain("terminal-copy");
|
||||
});
|
||||
|
||||
it("shows Copy only as a native selection affordance", () => {
|
||||
it("shows Copy only as a software-keyboard selection affordance", () => {
|
||||
expect(
|
||||
shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection: false,
|
||||
isNative: true,
|
||||
hasSoftwareKeyboard: true,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection: true,
|
||||
isNative: false,
|
||||
hasSoftwareKeyboard: false,
|
||||
}),
|
||||
).toBe(false);
|
||||
expect(
|
||||
shouldShowTerminalFloatingCopyAction({
|
||||
hasSelection: true,
|
||||
isNative: true,
|
||||
hasSoftwareKeyboard: true,
|
||||
}),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("keeps Paste native-gated", () => {
|
||||
expect(shouldShowTerminalPasteAction({ isNative: true })).toBe(true);
|
||||
expect(shouldShowTerminalPasteAction({ isNative: false })).toBe(false);
|
||||
it("keeps Paste gated to software-keyboard targets", () => {
|
||||
expect(shouldShowTerminalPasteAction({ hasSoftwareKeyboard: true })).toBe(true);
|
||||
expect(shouldShowTerminalPasteAction({ hasSoftwareKeyboard: false })).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -97,10 +97,10 @@ export function resolveTerminalVirtualKeyboardRows(input: {
|
||||
}
|
||||
|
||||
export function shouldShowTerminalVirtualKeyBar(input: {
|
||||
isNative: boolean;
|
||||
hasSoftwareKeyboard: boolean;
|
||||
isCompact: boolean;
|
||||
}): boolean {
|
||||
return input.isNative || input.isCompact;
|
||||
return input.hasSoftwareKeyboard || input.isCompact;
|
||||
}
|
||||
|
||||
export function getTerminalVirtualKeyboardControlId(
|
||||
@@ -118,13 +118,13 @@ export function getTerminalVirtualKeyboardControlId(
|
||||
}
|
||||
}
|
||||
|
||||
export function shouldShowTerminalPasteAction(input: { isNative: boolean }): boolean {
|
||||
return input.isNative;
|
||||
export function shouldShowTerminalPasteAction(input: { hasSoftwareKeyboard: boolean }): boolean {
|
||||
return input.hasSoftwareKeyboard;
|
||||
}
|
||||
|
||||
export function shouldShowTerminalFloatingCopyAction(input: {
|
||||
hasSelection: boolean;
|
||||
isNative: boolean;
|
||||
hasSoftwareKeyboard: boolean;
|
||||
}): boolean {
|
||||
return input.isNative && input.hasSelection;
|
||||
return input.hasSoftwareKeyboard && input.hasSelection;
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { UnistylesRuntime } from "react-native-unistyles";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { allowsInlineWorkspaceRename } from "@/constants/presentation";
|
||||
|
||||
export type WorkspaceRenameSurface = "inline" | "modal";
|
||||
|
||||
@@ -7,11 +7,11 @@ export type WorkspaceRenameSurface = "inline" | "modal";
|
||||
* Read when a rename starts rather than subscribed to: the surface is chosen once per rename, and
|
||||
* a subscription would re-render every sidebar row on each breakpoint change.
|
||||
*
|
||||
* Native wide layouts keep the modal. Their sidebar rows are touch targets with a permanent
|
||||
* Mobile native wide layouts keep the modal. Their sidebar rows are touch targets with a permanent
|
||||
* kebab, and the iPad overlay-dismissal flows drive the modal.
|
||||
*/
|
||||
export function resolveWorkspaceRenameSurface(): WorkspaceRenameSurface {
|
||||
if (!isWeb) return "modal";
|
||||
if (!allowsInlineWorkspaceRename) return "modal";
|
||||
const breakpoint = UnistylesRuntime.breakpoint;
|
||||
return breakpoint === "lg" || breakpoint === "xl" ? "inline" : "modal";
|
||||
}
|
||||
|
||||
@@ -8863,11 +8863,8 @@ export class DaemonClientCore {
|
||||
this.deliverSessionMessage(msg);
|
||||
}
|
||||
|
||||
getAdvertisedFrameCodecs(): readonly FrameCodec[] {
|
||||
return this.advertisedFrameCodecs();
|
||||
}
|
||||
|
||||
private advertisedFrameCodecs(): readonly FrameCodec[] {
|
||||
/** Codecs this client may use on any connection, including hosts routed through it. */
|
||||
getFrameCodecs(): readonly FrameCodec[] {
|
||||
const installed = this.config.frameCodecs;
|
||||
if (!installed?.length) return [];
|
||||
const override = this.config.capabilities?.[CLIENT_CAPS.frameCodecs];
|
||||
@@ -8879,6 +8876,13 @@ export class DaemonClientCore {
|
||||
return installed;
|
||||
}
|
||||
|
||||
/** Compression costs CPU and saves no bandwidth when bytes never leave this machine. */
|
||||
private advertisedFrameCodecs(): readonly FrameCodec[] {
|
||||
const explicit = Array.isArray(this.config.capabilities?.[CLIENT_CAPS.frameCodecs]);
|
||||
if (this.transport?.local === true && !explicit) return [];
|
||||
return this.getFrameCodecs();
|
||||
}
|
||||
|
||||
private applyServerFrameNegotiation(serverInfo: ServerInfoStatusPayload): void {
|
||||
if (!this.frameTransport) return;
|
||||
this.frameTransport.enabled =
|
||||
|
||||
@@ -2,6 +2,8 @@ export interface DaemonTransport {
|
||||
/** False when the underlying socket cannot report write drain. */
|
||||
supportsDrain?: boolean;
|
||||
maxFrameBytes?: number;
|
||||
/** True when bytes never leave this machine (loopback TCP, Unix socket, named pipe). */
|
||||
local?: boolean;
|
||||
send: (data: string | Uint8Array | ArrayBuffer) => void | Promise<void>;
|
||||
close: (code?: number, reason?: string) => void;
|
||||
onMessage: (handler: (data: unknown, isBinary: boolean) => void | Promise<void>) => () => void;
|
||||
|
||||
@@ -195,6 +195,23 @@ test("native drain capability survives WebSocket and encryption wrappers", async
|
||||
expect(encrypted.supportsDrain).toBe(false);
|
||||
});
|
||||
|
||||
test("WebSocket transports report whether their bytes stay on this machine", () => {
|
||||
const factory = createWebSocketTransportFactory(() => ({ readyState: 1, send() {}, close() {} }));
|
||||
const local = (url: string) => factory({ url }).local;
|
||||
expect(local("ws://127.0.0.1:6767/ws")).toBe(true);
|
||||
expect(local("ws://localhost:6767/ws")).toBe(true);
|
||||
expect(local("ws://[::1]:6767/ws")).toBe(true);
|
||||
expect(local("ws+unix:///tmp/paseo.sock:/ws")).toBe(true);
|
||||
expect(local("ws://192.168.1.12:6767/ws")).toBe(false);
|
||||
expect(local("wss://relay.paseo.sh/ws?serverId=srv")).toBe(false);
|
||||
// A relay forwards to a daemon that may be anywhere, even when the relay itself is local.
|
||||
const encrypted = createEncryptedTransport(factory({ url: "ws://127.0.0.1:8787/ws" }), {
|
||||
daemonPublicKeyB64: "unused-key",
|
||||
logger: { warn() {} },
|
||||
});
|
||||
expect(encrypted.local).not.toBe(true);
|
||||
});
|
||||
|
||||
interface ObservedSocket {
|
||||
closeFrame: { code: number; reason: string } | null;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
WebSocketFactory,
|
||||
WebSocketLike,
|
||||
} from "./daemon-client-transport-types.js";
|
||||
import { isLocalWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints";
|
||||
import { extractRelayMessage } from "./daemon-client-transport-utils.js";
|
||||
|
||||
type GlobalWebSocketConstructor = new (
|
||||
@@ -54,6 +55,7 @@ export function createWebSocketTransportFactory(factory: WebSocketFactory): Daem
|
||||
}
|
||||
return {
|
||||
supportsDrain: factory.supportsDrain !== false,
|
||||
local: isLocalWebSocketUrl(url),
|
||||
send: (data) => {
|
||||
if (typeof ws.readyState === "number" && ws.readyState !== 1) {
|
||||
throw new Error(`WebSocket not open (readyState=${ws.readyState})`);
|
||||
|
||||
@@ -10878,6 +10878,49 @@ test("advertises host-supplied frameCodecs in hello and omits frame_codecs on ex
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
test("a local transport advertises no frame codecs unless the caller lists them explicitly", async () => {
|
||||
const { createNodeDeflateRawCodec } = await import("@getpaseo/protocol/node-frame-codec");
|
||||
const codec = createNodeDeflateRawCodec();
|
||||
const connectLocal = async (capabilities?: Record<string, unknown>) => {
|
||||
const mock = createMockTransport();
|
||||
mock.transport.local = true;
|
||||
const client = new DaemonClient({
|
||||
url: "ws://127.0.0.1:6767/ws",
|
||||
clientId: "codec-local",
|
||||
frameCodecs: [codec],
|
||||
...(capabilities ? { capabilities } : {}),
|
||||
transportFactory: () => mock.transport,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
clients.push(client);
|
||||
const connecting = client.connect();
|
||||
mock.triggerOpen({
|
||||
preserveSent: true,
|
||||
features: { binaryChunkingV1: true, frameCodecs: ["deflate-raw"] },
|
||||
});
|
||||
await connecting;
|
||||
const hello = JSON.parse(assertStr(mock.sent[0]));
|
||||
mock.sent.length = 0;
|
||||
await client.sendHostFrame("route-1", "a".repeat(4096));
|
||||
const sent = mock.sent[0];
|
||||
return {
|
||||
client,
|
||||
advertised: hello.capabilities.frame_codecs,
|
||||
compressed: sent instanceof Uint8Array && sent[0] === 0x31 && (sent[3]! & 0x04) !== 0,
|
||||
};
|
||||
};
|
||||
|
||||
const local = await connectLocal();
|
||||
expect(local.advertised).toBeUndefined();
|
||||
expect(local.compressed).toBe(false);
|
||||
// Routed hosts reached through this client still get the installed codecs.
|
||||
expect(local.client.getFrameCodecs()).toEqual([codec]);
|
||||
|
||||
const explicit = await connectLocal({ frame_codecs: ["deflate-raw"] });
|
||||
expect(explicit.advertised).toEqual(["deflate-raw"]);
|
||||
expect(explicit.compressed).toBe(true);
|
||||
});
|
||||
|
||||
test("async codec protocol error closes the client transport with 4003", async () => {
|
||||
const mock = createMockTransport();
|
||||
const closed = vi.fn();
|
||||
|
||||
@@ -204,7 +204,7 @@ export function createHostActions(
|
||||
origin.closeHostRoute(routeId);
|
||||
assertActive();
|
||||
}
|
||||
const frameCodecs = origin.getAdvertisedFrameCodecs();
|
||||
const frameCodecs = origin.getFrameCodecs();
|
||||
const client = new DaemonClient({
|
||||
url: "ws://routed-host/ws",
|
||||
clientId: scopeId,
|
||||
|
||||
@@ -33,6 +33,14 @@ test("connector retains per-attempt headers and WebSocket subprotocols", async (
|
||||
expect(request.headers.authorization).toBe("Bearer example");
|
||||
expect(socket.protocol).toBe("paseo-test");
|
||||
});
|
||||
test("connector reports a loopback daemon connection as local", async () => {
|
||||
const server = await endpoint();
|
||||
const connected = once(server.wss, "connection");
|
||||
const transport = createHostTransportFactory(server.url)({ url: server.url });
|
||||
cleanup.push(async () => transport.close());
|
||||
await connected;
|
||||
expect(transport.local).toBe(true);
|
||||
});
|
||||
test("a slow consumer cannot exceed the shared byte budget and close releases reserved bytes", async () => {
|
||||
const server = await endpoint();
|
||||
const budget = new HostTransportBudget(4 * 1024 * 1024);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { homedir } from "node:os";
|
||||
import type { Agent } from "node:http";
|
||||
import { WebSocket } from "ws";
|
||||
import {
|
||||
isLocalHostTarget,
|
||||
localListenOfHostTarget,
|
||||
parseHostTarget,
|
||||
type HostTarget,
|
||||
@@ -44,6 +45,7 @@ interface AttemptScope {
|
||||
* it exists; closing at any point runs the attempt's deferred cleanups once.
|
||||
*/
|
||||
function deferredTransport(
|
||||
{ local }: { local: boolean },
|
||||
open: (
|
||||
scope: AttemptScope,
|
||||
) => Promise<{ transport: DaemonTransport; describeError?: (error: unknown) => unknown } | null>,
|
||||
@@ -117,6 +119,7 @@ function deferredTransport(
|
||||
get maxFrameBytes() {
|
||||
return transport?.maxFrameBytes;
|
||||
},
|
||||
local,
|
||||
send(data) {
|
||||
if (closed || !transport) throw new Error("Host transport is unavailable");
|
||||
return transport.send(data);
|
||||
@@ -157,8 +160,9 @@ export function createHostTransportFactory(
|
||||
// cannot be downgraded to legacy endpoint security.
|
||||
let securityFloor: SecurityMode | undefined =
|
||||
target.kind === "socket" ? target.offer?.minimumSecurityMode : undefined;
|
||||
const local = isLocalHostTarget(target);
|
||||
return (attemptOptions) =>
|
||||
deferredTransport(async (scope) => {
|
||||
deferredTransport({ local }, async (scope) => {
|
||||
let sshTunnel: SshTunnel | null = null;
|
||||
let socketTarget: Extract<HostTarget, { kind: "socket" }>;
|
||||
if (target.kind === "ssh") {
|
||||
@@ -271,7 +275,7 @@ function createRoutedTransportFactory(
|
||||
const listen = localListenOfHostTarget(parseHostTarget(spec.via));
|
||||
const { localCredential } = options;
|
||||
return (attemptOptions: DaemonTransportAttempt) =>
|
||||
deferredTransport(async (scope) => {
|
||||
deferredTransport({ local: false }, async (scope) => {
|
||||
// The full client loads the AOT protocol validator, so only routed specs import it.
|
||||
const { createHostChannelTransport, createHostClient } = await import("./index.js");
|
||||
if (scope.closed) return null;
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
validatePort,
|
||||
validateSshHost,
|
||||
} from "@getpaseo/protocol/ssh-transport";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
|
||||
|
||||
export interface SshProxyTarget {
|
||||
host: string;
|
||||
@@ -59,7 +59,7 @@ export function buildSshSpawnEnv(
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): NodeJS.ProcessEnv {
|
||||
const env = { ...baseEnv };
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
stripLinuxDesktopRuntimeEnv(env, { platform });
|
||||
return env;
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ import { existsSync as nodeExistsSync, readdirSync as nodeReaddirSync } from "no
|
||||
import { readFile } from "node:fs/promises";
|
||||
import os from "node:os";
|
||||
import path, { posix, win32 } from "node:path";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { app, shell } from "electron";
|
||||
|
||||
import type {
|
||||
@@ -53,7 +53,7 @@ function createExternalProcessEnv(
|
||||
for (const key of RUNTIME_CONTROL_ENV_KEYS) {
|
||||
delete env[key];
|
||||
}
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
stripLinuxDesktopRuntimeEnv(env, { platform });
|
||||
for (const [key, value] of Object.entries(env)) {
|
||||
if (value === undefined) {
|
||||
delete env[key];
|
||||
|
||||
@@ -7,7 +7,7 @@ import { spawnSync as defaultSpawnSync } from "node:child_process";
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { userInfo as defaultUserInfo } from "node:os";
|
||||
import { basename } from "node:path";
|
||||
import { stripAppImageRuntimeEnv } from "@getpaseo/server/process";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "@getpaseo/server/process";
|
||||
import defaultLog from "electron-log/main";
|
||||
|
||||
const DEFAULT_RESOLVE_TIMEOUT_MS = 30_000;
|
||||
@@ -410,7 +410,7 @@ function resolveShellEnv({ deps, timeoutMs }: ResolveShellEnvInput): ResolvedShe
|
||||
delete shellEnv.PASEO_NODE_ENV;
|
||||
delete shellEnv.PASEO_DESKTOP_MANAGED;
|
||||
delete shellEnv.PASEO_SUPERVISED;
|
||||
stripAppImageRuntimeEnv(shellEnv, { platform: deps.platform });
|
||||
stripLinuxDesktopRuntimeEnv(shellEnv, { platform: deps.platform });
|
||||
|
||||
deps.logger.info("[login-shell-env] start", {
|
||||
shell,
|
||||
|
||||
@@ -201,6 +201,26 @@ function createConnectionUri(parts: ConnectionUriParts): URL {
|
||||
return url;
|
||||
}
|
||||
|
||||
const IPV4_LOOPBACK = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
||||
|
||||
/** True when a daemon WebSocket URL never leaves this machine: a loopback host or a Unix socket. */
|
||||
export function isLocalWebSocketUrl(url: string): boolean {
|
||||
let parsed: URL;
|
||||
try {
|
||||
parsed = new URL(url);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (parsed.protocol === "ws+unix:") return true;
|
||||
const host = parsed.hostname.toLowerCase().replace(/^\[|\]$/g, "");
|
||||
return (
|
||||
host === "localhost" ||
|
||||
host.endsWith(".localhost") ||
|
||||
host === "::1" ||
|
||||
IPV4_LOOPBACK.test(host)
|
||||
);
|
||||
}
|
||||
|
||||
export function normalizeLoopbackToLocalhost(endpoint: string): string {
|
||||
const { host, port, isIpv6 } = parseHostPort(endpoint);
|
||||
if (host === "127.0.0.1" || (!isIpv6 && host === "0.0.0.0")) {
|
||||
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
createNodeDeflateRawCodec,
|
||||
} from "./node-frame-codec.js";
|
||||
import { createWebDeflateRawCodec } from "./web-frame-codec.js";
|
||||
import { encodeHostRouteFrame } from "./binary-frames/host-route.js";
|
||||
|
||||
function createDelayedCodec(
|
||||
base: FrameCodec,
|
||||
@@ -33,6 +34,14 @@ function createDelayedCodec(
|
||||
};
|
||||
}
|
||||
|
||||
function encodedTextFrame(text: string): Uint8Array {
|
||||
const encoded = deflateRawSync(new TextEncoder().encode(text));
|
||||
const wire = new Uint8Array(4 + encoded.byteLength);
|
||||
wire.set([0x31, 1, 0, 0x07]);
|
||||
wire.set(encoded, 4);
|
||||
return wire;
|
||||
}
|
||||
|
||||
describe("selectFrameCodec", () => {
|
||||
it("picks the first server-preferred codec shared with the local codecs", () => {
|
||||
const deflate = createNodeDeflateRawCodec();
|
||||
@@ -195,6 +204,43 @@ describe("FrameTransport compression and framing", () => {
|
||||
expect(delivered).toEqual([randomPayload]);
|
||||
});
|
||||
|
||||
it("forwards a routed frame that already carries a compressed frame without compressing it again", async () => {
|
||||
const base = createNodeDeflateRawCodec();
|
||||
const encodedInputs: Uint8Array[] = [];
|
||||
const spyCodec: FrameCodec = {
|
||||
id: base.id,
|
||||
encode(input) {
|
||||
encodedInputs.push(input);
|
||||
return base.encode(input);
|
||||
},
|
||||
decode: (input, max) => base.decode(input, max),
|
||||
};
|
||||
const wireFrames: (string | Uint8Array)[] = [];
|
||||
const sender = new FrameTransport({
|
||||
frameBytes: 64 * 1024,
|
||||
send: (frame) => {
|
||||
wireFrames.push(frame);
|
||||
},
|
||||
deliver: () => {},
|
||||
});
|
||||
sender.enabled = true;
|
||||
sender.codec = spyCodec;
|
||||
const text = Array.from(
|
||||
{ length: 2000 },
|
||||
(_, i) => `row-${i}:${((i * 2654435761) >>> 0).toString(36)}`,
|
||||
).join("\n");
|
||||
const compressedRoute = encodeHostRouteFrame("route-1", encodedTextFrame(text));
|
||||
const rawRoute = encodeHostRouteFrame("route-1", new TextEncoder().encode(text));
|
||||
|
||||
expect(compressedRoute.byteLength).toBeGreaterThan(DEFAULT_FRAME_COMPRESSION_MIN_BYTES);
|
||||
await sender.send(compressedRoute);
|
||||
await sender.send(rawRoute);
|
||||
|
||||
expect(wireFrames[0]).toEqual(compressedRoute);
|
||||
expect(encodedInputs).toEqual([rawRoute]);
|
||||
expect((wireFrames[1] as Uint8Array)[0]).toBe(0x31);
|
||||
});
|
||||
|
||||
it("is stateless per frame (no cross-frame dictionary leakage)", async () => {
|
||||
const codec = createNodeDeflateRawCodec();
|
||||
const wireFrames: Uint8Array[] = [];
|
||||
@@ -320,6 +366,57 @@ describe("FrameTransport compression and framing", () => {
|
||||
expect(delivered).toEqual([large1, small2, large3, small4]);
|
||||
});
|
||||
|
||||
it("flushInbound waits for every received frame, and close drops frames still decoding", async () => {
|
||||
const asyncCodec = createDelayedCodec(createNodeDeflateRawCodec(), 0, 15);
|
||||
const delivered: (string | Uint8Array)[] = [];
|
||||
const receiver = new FrameTransport({
|
||||
frameBytes: 64 * 1024,
|
||||
send: () => {},
|
||||
deliver: (frame) => delivered.push(frame),
|
||||
});
|
||||
receiver.enabled = true;
|
||||
receiver.codec = asyncCodec;
|
||||
const large = "received-before-flush ".repeat(100);
|
||||
|
||||
receiver.receive(encodedTextFrame(large));
|
||||
receiver.receive("small-after-large");
|
||||
await receiver.flushInbound();
|
||||
expect(delivered).toEqual([large, "small-after-large"]);
|
||||
|
||||
// A disposed connection must not deliver stale frames after its owner moved on.
|
||||
receiver.receive(encodedTextFrame(large));
|
||||
receiver.close();
|
||||
receiver.receive("after-close");
|
||||
await receiver.flushInbound();
|
||||
expect(delivered).toEqual([large, "small-after-large"]);
|
||||
});
|
||||
|
||||
it("rejects the receive completion when deliver throws and keeps delivering later frames", async () => {
|
||||
const asyncCodec = createDelayedCodec(createNodeDeflateRawCodec(), 0, 15);
|
||||
const delivered: (string | Uint8Array)[] = [];
|
||||
const consumerError = new Error("consumer failed");
|
||||
const receiver = new FrameTransport({
|
||||
frameBytes: 64 * 1024,
|
||||
send: () => {},
|
||||
deliver: (frame) => {
|
||||
if (frame === "throws") throw consumerError;
|
||||
delivered.push(frame);
|
||||
},
|
||||
});
|
||||
receiver.enabled = true;
|
||||
receiver.codec = asyncCodec;
|
||||
const large = "queued-ahead ".repeat(100);
|
||||
|
||||
const first = receiver.receive(encodedTextFrame(large));
|
||||
const failing = receiver.receive("throws");
|
||||
const after = receiver.receive("after-failure");
|
||||
|
||||
await expect(first).resolves.toBeUndefined();
|
||||
await expect(failing).rejects.toBe(consumerError);
|
||||
await expect(after).resolves.toBeUndefined();
|
||||
expect(delivered).toEqual([large, "after-failure"]);
|
||||
});
|
||||
|
||||
it("rejects decompression bombs strictly at maxOutputBytes for both sync (Node) and async (Web) codecs", async () => {
|
||||
// 10 MiB of zeros compresses to ~10 KB
|
||||
const bombDeflated = new Uint8Array(
|
||||
@@ -439,7 +536,7 @@ describe("createNodeDeflateRawCodec sync/async threshold", () => {
|
||||
|
||||
const codec = createNodeDeflateRawCodec({ asyncThresholdBytes: 4096 });
|
||||
|
||||
// Below threshold: encode returns Uint8Array synchronously, and decode is sync only when maxOutputBytes < threshold
|
||||
// Below threshold: encode and decode return Uint8Array synchronously
|
||||
const smallRaw = new TextEncoder().encode("small-sync-payload ".repeat(100)); // ~1900 B < 4096
|
||||
const smallEncoded = codec.encode(smallRaw);
|
||||
expect(smallEncoded).toBeInstanceOf(Uint8Array);
|
||||
@@ -447,11 +544,37 @@ describe("createNodeDeflateRawCodec sync/async threshold", () => {
|
||||
expect(smallDecoded).toBeInstanceOf(Uint8Array);
|
||||
expect(smallDecoded).toEqual(smallRaw);
|
||||
|
||||
// Small compressed payload with unbounded/large maxOutputBytes (>= threshold) must decode asynchronously
|
||||
// so a small high-ratio frame cannot expand to 100 MiB on the main thread.
|
||||
const smallInputLargeCapPromise = codec.decode(smallEncoded as Uint8Array, 100 * 1024 * 1024);
|
||||
expect(smallInputLargeCapPromise).toBeInstanceOf(Promise);
|
||||
expect(await smallInputLargeCapPromise).toEqual(smallRaw);
|
||||
// Callers pass the 100 MiB message cap. Output that fits the threshold still decodes
|
||||
// synchronously; only the threshold's worth of output can be produced on the main thread.
|
||||
const smallInputLargeCap = codec.decode(smallEncoded as Uint8Array, 100 * 1024 * 1024);
|
||||
expect(smallInputLargeCap).toBeInstanceOf(Uint8Array);
|
||||
expect(smallInputLargeCap).toEqual(smallRaw);
|
||||
|
||||
// Output beyond the threshold moves to the libuv threadpool under the full cap.
|
||||
const highRatioRaw = new Uint8Array(64 * 1024);
|
||||
const highRatioEncoded = deflateRawSync(highRatioRaw);
|
||||
expect(highRatioEncoded.byteLength).toBeLessThan(4096);
|
||||
const highRatioPromise = codec.decode(highRatioEncoded, 100 * 1024 * 1024);
|
||||
expect(highRatioPromise).toBeInstanceOf(Promise);
|
||||
expect(await highRatioPromise).toEqual(highRatioRaw);
|
||||
await expect(codec.decode(highRatioEncoded, 32 * 1024)).rejects.toThrow();
|
||||
|
||||
// Input beyond the threshold also moves off the main thread, even when it inflates to
|
||||
// almost nothing: a peer can pad a valid stream with empty stored blocks.
|
||||
const emptyStoredBlock = [0x00, 0x00, 0x00, 0xff, 0xff];
|
||||
const paddedEncoded = new Uint8Array([
|
||||
...Array.from({ length: 1000 }, () => emptyStoredBlock).flat(),
|
||||
0x01,
|
||||
0x01,
|
||||
0x00,
|
||||
0xfe,
|
||||
0xff,
|
||||
0x41,
|
||||
]);
|
||||
expect(paddedEncoded.byteLength).toBeGreaterThan(4096);
|
||||
const paddedPromise = codec.decode(paddedEncoded, 100 * 1024 * 1024);
|
||||
expect(paddedPromise).toBeInstanceOf(Promise);
|
||||
expect(new TextDecoder().decode(await paddedPromise)).toBe("A");
|
||||
|
||||
// At/above threshold for encode: returns a Promise<Uint8Array>
|
||||
const largeRaw = new Uint8Array(randomBytes(8192)); // incompressible -> compressed >= 8192 >= 4096
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { HOST_ROUTE_OPCODE, decodeHostRouteFrame } from "./binary-frames/host-route.js";
|
||||
import { MAX_WEBSOCKET_MESSAGE_BYTES } from "./websocket-message-limit.js";
|
||||
|
||||
export type TransportFrame = string | Uint8Array;
|
||||
@@ -102,7 +103,8 @@ export class FrameTransport {
|
||||
if (this.closed) throw new Error("Transport closed");
|
||||
const canChunk = this.enabled && this.io.supportsDrain !== false;
|
||||
const codec = this.codec;
|
||||
const shouldEncode = codec !== undefined && byteLength >= this.minCompressBytes;
|
||||
const shouldEncode =
|
||||
codec !== undefined && byteLength >= this.minCompressBytes && !routesEncodedFrame(frame);
|
||||
const willChunkRaw = !shouldEncode && canChunk && byteLength > this.io.frameBytes;
|
||||
let needsBarrier = willChunkRaw || !this.io.supportsConcurrentWrites;
|
||||
let started = false;
|
||||
@@ -323,7 +325,10 @@ export class FrameTransport {
|
||||
});
|
||||
}
|
||||
|
||||
/** Wait for all currently queued async inbound decodes to finish. */
|
||||
/**
|
||||
* Wait until every frame received so far has been delivered. Call it before `close()` to
|
||||
* keep frames the peer sent before it went away; `close()` drops frames still decoding.
|
||||
*/
|
||||
flushInbound(): Promise<void> {
|
||||
return this.receiveQueue ?? Promise.resolve();
|
||||
}
|
||||
@@ -335,15 +340,20 @@ export class FrameTransport {
|
||||
}
|
||||
this.inboundQueuedBytes += wireBytes;
|
||||
const prev = this.receiveQueue ?? Promise.resolve();
|
||||
const next = prev
|
||||
.then(run)
|
||||
.catch(() => undefined)
|
||||
// The frame's own completion carries a deliver() failure to the caller, as a
|
||||
// synchronous receive() would throw it; the queue itself keeps going.
|
||||
const completion = prev.then(run);
|
||||
const next = completion
|
||||
.then(
|
||||
() => undefined,
|
||||
() => undefined,
|
||||
)
|
||||
.finally(() => {
|
||||
this.inboundQueuedBytes -= wireBytes;
|
||||
if (this.receiveQueue === next) this.receiveQueue = undefined;
|
||||
});
|
||||
this.receiveQueue = next;
|
||||
return next;
|
||||
return completion;
|
||||
}
|
||||
|
||||
private finalizeDecoded(decoded: Uint8Array, kind: 0 | 1): TransportFrame {
|
||||
@@ -467,6 +477,19 @@ export class FrameTransport {
|
||||
}
|
||||
}
|
||||
|
||||
/** A routed host frame whose enclosed frame its origin transport already compressed. */
|
||||
function routesEncodedFrame(frame: TransportFrame): boolean {
|
||||
if (typeof frame === "string" || frame[0] !== HOST_ROUTE_OPCODE) return false;
|
||||
const enclosed = decodeHostRouteFrame(frame)?.payload;
|
||||
return (
|
||||
enclosed !== undefined &&
|
||||
enclosed.byteLength > HEADER &&
|
||||
enclosed[0] === OPCODE &&
|
||||
enclosed[1] === VERSION &&
|
||||
(enclosed[3]! & FLAG_ENCODED) !== 0
|
||||
);
|
||||
}
|
||||
|
||||
function isPromiseLike<T>(value: T | Promise<T>): value is Promise<T> {
|
||||
return (
|
||||
typeof value === "object" &&
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, test } from "vitest";
|
||||
import { localListenOfHostTarget, parseHostTarget } from "./host-target.js";
|
||||
import { isLocalHostTarget, localListenOfHostTarget, parseHostTarget } from "./host-target.js";
|
||||
|
||||
test.each([
|
||||
["127.0.0.1:6767", "tcp://127.0.0.1:6767"],
|
||||
@@ -97,3 +97,29 @@ test.each(["ssh://box?daemonPort=7000", "relay://relay.example.test:443/srv_test
|
||||
expect(localListenOfHostTarget(parseHostTarget(connection))).toBeNull();
|
||||
},
|
||||
);
|
||||
|
||||
test("only targets whose bytes never leave this machine are local", () => {
|
||||
const local = (input: string) => isLocalHostTarget(parseHostTarget(input));
|
||||
expect(local("127.0.0.1:6767")).toBe(true);
|
||||
expect(local("6767")).toBe(true);
|
||||
expect(local("localhost:6767")).toBe(true);
|
||||
expect(local("ws://[::1]:6767/ws")).toBe(true);
|
||||
expect(local("unix:///tmp/paseo.sock")).toBe(true);
|
||||
expect(local("pipe://paseo")).toBe(true);
|
||||
expect(local("192.168.1.12:6767")).toBe(false);
|
||||
expect(local("wss://devbox.example.com/ws")).toBe(false);
|
||||
// The SSH tunnel endpoint is loopback, but the bytes cross the SSH connection.
|
||||
expect(local("ssh://devbox.example.com")).toBe(false);
|
||||
// A relay on this machine still forwards to a daemon that may be anywhere.
|
||||
const offer = {
|
||||
v: 2,
|
||||
serverId: "srv_local_relay",
|
||||
daemonPublicKeyB64: "a".repeat(44),
|
||||
relay: { endpoint: "127.0.0.1:8787" },
|
||||
};
|
||||
expect(
|
||||
local(
|
||||
`https://app.paseo.sh/#offer=${Buffer.from(JSON.stringify(offer)).toString("base64url")}`,
|
||||
),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { parseConnectionOfferFromUrl, type ConnectionOffer } from "./connection-
|
||||
import {
|
||||
buildDaemonWebSocketUrl,
|
||||
buildRelayWebSocketUrl,
|
||||
isLocalWebSocketUrl,
|
||||
normalizeHostPort,
|
||||
parseConnectionUri,
|
||||
parseRelayConnectionUri,
|
||||
@@ -54,6 +55,14 @@ export function localListenOfHostTarget(target: HostTarget): string | null {
|
||||
return `${url.hostname}:${url.port || (url.protocol === "wss:" ? 443 : 80)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the connection's bytes never leave this machine. An SSH target dials a
|
||||
* loopback tunnel, and a relay forwards elsewhere, so neither is local.
|
||||
*/
|
||||
export function isLocalHostTarget(target: HostTarget): boolean {
|
||||
return target.kind === "socket" && !target.offer && isLocalWebSocketUrl(target.url);
|
||||
}
|
||||
|
||||
function parse(input: string): HostTarget {
|
||||
if (!input) throw new Error("empty");
|
||||
if (input.startsWith("ssh://")) {
|
||||
|
||||
@@ -7,19 +7,24 @@ export const DEFAULT_NODE_ASYNC_CODEC_THRESHOLD_BYTES = 256 * 1024;
|
||||
export interface NodeDeflateRawCodecOptions {
|
||||
/** Zlib deflate compression level (1-9). Defaults to 4 (near-L6 ratio at < half L6 CPU). */
|
||||
level?: number;
|
||||
/** Payloads >= this byte count run via async `node:zlib` instead of blocking the event loop. */
|
||||
/** Raw frames larger than this run via async `node:zlib` instead of blocking the event loop. */
|
||||
asyncThresholdBytes?: number;
|
||||
}
|
||||
|
||||
function exceededOutputLimit(error: unknown): boolean {
|
||||
return (error as { code?: unknown } | null)?.code === "ERR_BUFFER_TOO_LARGE";
|
||||
}
|
||||
|
||||
function asUint8Array(buf: Buffer): Uint8Array {
|
||||
return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||
}
|
||||
|
||||
/**
|
||||
* Node.js `node:zlib` stateless per-frame deflate-raw codec with hard `maxOutputLength` cap.
|
||||
* Uses the synchronous fast path only when output work is bounded below `asyncThresholdBytes`
|
||||
* (raw input length on encode; `maxOutputBytes` cap on decode) and offloads everything else to
|
||||
* libuv worker threads so neither multi-MiB frames nor small high-ratio payloads block the event loop.
|
||||
* Main-thread work stays within `asyncThresholdBytes` of input and output: encode runs synchronously
|
||||
* when the raw input is at most that, and decode of input at most that first inflates synchronously
|
||||
* capped at the threshold. Larger frames, including small high-ratio payloads and padded streams
|
||||
* that inflate to almost nothing, finish on libuv worker threads under the full cap.
|
||||
*/
|
||||
export function createNodeDeflateRawCodec(options?: NodeDeflateRawCodecOptions): FrameCodec {
|
||||
const level = options?.level ?? 4;
|
||||
@@ -29,7 +34,7 @@ export function createNodeDeflateRawCodec(options?: NodeDeflateRawCodecOptions):
|
||||
return {
|
||||
id: FRAME_CODEC_DEFLATE_RAW,
|
||||
encode(input: Uint8Array): Uint8Array | Promise<Uint8Array> {
|
||||
if (input.byteLength < asyncThresholdBytes) {
|
||||
if (input.byteLength <= asyncThresholdBytes) {
|
||||
return asUint8Array(deflateRawSync(input, { level }));
|
||||
}
|
||||
return new Promise<Uint8Array>((resolve, reject) => {
|
||||
@@ -43,8 +48,16 @@ export function createNodeDeflateRawCodec(options?: NodeDeflateRawCodecOptions):
|
||||
if (input.byteLength === 0) {
|
||||
throw new Error("Empty deflate-raw payload");
|
||||
}
|
||||
if (maxOutputBytes < asyncThresholdBytes) {
|
||||
return asUint8Array(inflateRawSync(input, { maxOutputLength: maxOutputBytes }));
|
||||
if (input.byteLength <= asyncThresholdBytes) {
|
||||
try {
|
||||
return asUint8Array(
|
||||
inflateRawSync(input, {
|
||||
maxOutputLength: Math.min(maxOutputBytes, asyncThresholdBytes),
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
if (maxOutputBytes <= asyncThresholdBytes || !exceededOutputLimit(error)) throw error;
|
||||
}
|
||||
}
|
||||
return new Promise<Uint8Array>((resolve, reject) => {
|
||||
inflateRaw(input, { maxOutputLength: maxOutputBytes }, (err, out) => {
|
||||
|
||||
@@ -100,7 +100,7 @@
|
||||
"speech:transcribe:local": "tsx scripts/transcribe-local-wav.ts",
|
||||
"test": "npm run test:unit && npm run test:integration",
|
||||
"test:unit": "vitest run --fileParallelism --exclude \"**/*.e2e.test.ts\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/daemon-e2e/daemon-shutdown.e2e.test.ts src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/frame-compression.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap\"",
|
||||
"test:integration": "vitest run --fileParallelism --maxWorkers=3 src/server/daemon-e2e/daemon-shutdown.e2e.test.ts src/server/git-filename-diffs.e2e.test.ts src/server/daemon-e2e/checkout-diff-content.e2e.test.ts src/server/daemon-e2e/concurrent-agent-refresh.e2e.test.ts src/server/daemon-e2e/agent-archive-overlap.e2e.test.ts src/server/daemon-e2e/create-agent-mode.e2e.test.ts src/server/daemon-e2e/filesystem.e2e.test.ts src/server/daemon-e2e/file-download.e2e.test.ts src/server/daemon-e2e/frame-compression.e2e.test.ts src/server/daemon-e2e/cli-logs-follow.e2e.test.ts src/server/creation/creation.e2e.test.ts src/server/daemon-e2e/creation-status.e2e.test.ts src/server/daemon-e2e/persisted-creation-caller.e2e.test.ts src/server/daemon-e2e/terminal-workspace-sdk.e2e.test.ts src/server/daemon-e2e/terminal-worker-lifecycle.e2e.test.ts src/server/workspace-create-worktree-source.e2e.test.ts src/server/daemon-e2e/models.e2e.test.ts src/server/daemon-e2e/acp-child-exit-recovery.e2e.test.ts src/server/daemon-e2e/live-preferences.e2e.test.ts src/server/daemon-e2e/oversized-message.e2e.test.ts src/server/agent/model-catalog.e2e.test.ts src/server/plugins/plugin-paseo-api.e2e.test.ts src/server/plugins/usage-sources.e2e.test.ts src/server/plugins/lifecycle.e2e.test.ts src/server/plugins/agent-configuration.e2e.test.ts src/server/plugins/worktree-manager.e2e.test.ts src/server/connected-hosts/hosts.e2e.test.ts src/server/owned-subscriptions.e2e.test.ts && vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t \"agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap|negotiates protected endpoint security\"",
|
||||
"test:hub-cli-contract": "vitest run --maxWorkers=1 src/server/hub/hub-cli-contract.test.ts",
|
||||
"test:integration:all": "npm run test:e2e",
|
||||
"test:integration:real": "vitest run real.e2e.test.ts",
|
||||
|
||||
@@ -498,6 +498,182 @@ describe("Codex active-turn steering admission", () => {
|
||||
appServer.assertNoErrors();
|
||||
});
|
||||
|
||||
test("returns unavailable when a steered prompt mentions an enabled Codex skill inline", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("Answer briefly. /marker-skill", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
}),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when a steered prompt with attachments mentions an enabled Codex skill", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Earlier turn context",
|
||||
},
|
||||
{ type: "text", text: "Check this with /marker-skill." },
|
||||
],
|
||||
{ expectedTurnId: paseoTurnId },
|
||||
),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers normally without listing skills when the prompt only contains a file path", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
const skillListsBeforeSteer = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "skills/list").length;
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("Check /docs/api.md next", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
}),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(
|
||||
appServer.requests().filter((request) => request.method === "skills/list").length,
|
||||
).toBe(skillListsBeforeSteer);
|
||||
expect(appServer.requests().find((request) => request.method === "turn/steer")).toMatchObject(
|
||||
{
|
||||
params: {
|
||||
input: [{ type: "text", text: "Check /docs/api.md next", text_elements: [] }],
|
||||
},
|
||||
},
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not steer B when A completes while skill lookup is pending", async () => {
|
||||
const skillLookup = deferred<{ data: [] }>();
|
||||
const skillLookupEntered = deferred<void>();
|
||||
let holdSkillLookup = false;
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => {
|
||||
if (!holdSkillLookup) {
|
||||
return { data: [] };
|
||||
}
|
||||
skillLookupEntered.resolve();
|
||||
return skillLookup.promise;
|
||||
},
|
||||
"turn/steer": () => ({ turn: { id: "native-B" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
holdSkillLookup = true;
|
||||
try {
|
||||
const steer = session.steerActiveTurn!("Check /unknown-token", {
|
||||
expectedTurnId: paseoTurnId,
|
||||
clientMessageId: "steer-skill-race",
|
||||
});
|
||||
await skillLookupEntered.promise;
|
||||
appServer.completeTurn({ threadId: "thread-1" });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const startedB = await session.startTurn("second");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-B" });
|
||||
await new Promise<void>((resolve) => setImmediate(resolve));
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
skillLookup.resolve({ data: [] });
|
||||
|
||||
await expect(steer).resolves.toEqual({ status: "unavailable" });
|
||||
expect(startedB.turnId).not.toBe(paseoTurnId);
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when steering a built-in /compact command", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"turn/steer": () => ({ turn: { id: "native-A" } }),
|
||||
});
|
||||
const { session, paseoTurnId } = await startPublicSteeringSession(appServer);
|
||||
try {
|
||||
await expect(
|
||||
session.steerActiveTurn!("/compact", { expectedTurnId: paseoTurnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toEqual([]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each([
|
||||
["method unavailable", -32601, "method not found", undefined, "unavailable"],
|
||||
["no active turn", -32600, "no active turn to steer", undefined, "unavailable"],
|
||||
@@ -4114,6 +4290,326 @@ describe("Codex app-server provider", () => {
|
||||
);
|
||||
});
|
||||
|
||||
test("resolves inline, repeated, and punctuated Codex skill mentions into app-server skill input", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "second-skill",
|
||||
description: "Second skill.",
|
||||
path: "/workspace/skills/second-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn(
|
||||
"Answer briefly using /marker-skill, then /second-skill. Re-check /marker-skill!",
|
||||
);
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "skill",
|
||||
name: "second-skill",
|
||||
path: "/workspace/skills/second-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Answer briefly using $marker-skill, then $second-skill. Re-check $marker-skill!",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves Codex skill mentions in prompts carrying attachments without touching chat_history or attachment text", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "history-skill",
|
||||
description: "History skill.",
|
||||
path: "/workspace/skills/history-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous conversation mentioned /history-skill",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "/marker-skill inspect this screenshot",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: ONE_BY_ONE_PNG_BASE64,
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Snippet",
|
||||
text: "Attached note mentioning /history-skill",
|
||||
},
|
||||
]);
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
const input = (turnStart?.params as { input?: Array<Record<string, unknown>> })?.input ?? [];
|
||||
const localImage = input.find((item) => item.type === "localImage");
|
||||
try {
|
||||
expect(input).toEqual([
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Previous conversation mentioned /history-skill",
|
||||
text_elements: [],
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "$marker-skill inspect this screenshot",
|
||||
text_elements: [],
|
||||
},
|
||||
{
|
||||
type: "localImage",
|
||||
path: expect.any(String),
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: "Attached note mentioning /history-skill",
|
||||
text_elements: [],
|
||||
},
|
||||
]);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
if (typeof localImage?.path === "string") {
|
||||
rmSync(localImage.path, { force: true });
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves file paths like /docs/api.md untouched and skips skills/list when no mention candidate exists", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.connect();
|
||||
const skillListsBeforeTurn = appServer
|
||||
.requests()
|
||||
.filter((request) => request.method === "skills/list").length;
|
||||
|
||||
await session.startTurn("Check /docs/api.md before replying.");
|
||||
|
||||
expect(
|
||||
appServer.requests().filter((request) => request.method === "skills/list").length,
|
||||
).toBe(skillListsBeforeTurn);
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Check /docs/api.md before replying.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("does not resolve disabled Codex skills mentioned inline", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "disabled-skill",
|
||||
description: "Disabled skill.",
|
||||
path: "/workspace/skills/disabled-skill/SKILL.md",
|
||||
enabled: false,
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Use /disabled-skill please.");
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Use /disabled-skill please.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves Codex skill mentions in /prompts:* arguments while keeping saved template text literal", async () => {
|
||||
const codexHome = await mkdtemp(path.join(tmpdir(), "codex-custom-prompt-skill-"));
|
||||
mkdirSync(path.join(codexHome, "prompts"), { recursive: true });
|
||||
writeFileSync(
|
||||
path.join(codexHome, "prompts", "review.md"),
|
||||
"---\ndescription: Review with args\n---\n\nKeep /docs literal and review: $ARGUMENTS\n",
|
||||
"utf8",
|
||||
);
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: "/workspace/project",
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
name: "docs",
|
||||
description: "Docs skill.",
|
||||
path: "/workspace/skills/docs/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
createConfig({ cwd: "/workspace/project" }),
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
{ codexHome },
|
||||
);
|
||||
try {
|
||||
await session.startTurn("/prompts:review Use /marker-skill.");
|
||||
|
||||
const turnStart = appServer.requests().find((request) => request.method === "turn/start");
|
||||
expect(turnStart?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "skill",
|
||||
name: "marker-skill",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
text: expect.stringContaining("Keep /docs literal and review: Use $marker-skill."),
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
rmSync(codexHome, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("lists project skill commands when app-server receives the project cwd in cwds", async () => {
|
||||
const commands = await listCommandsFromFakeCodex([
|
||||
{
|
||||
|
||||
@@ -2,6 +2,13 @@ import type { ProviderOptions } from "@getpaseo/protocol/agent-types";
|
||||
import { applyProviderOptionsPatch } from "../option-controls.js";
|
||||
import { assertChangesAreLive, validateProviderOptions } from "../provider-options.js";
|
||||
import { CodexBackgroundInventory } from "./codex/background-inventory.js";
|
||||
import {
|
||||
type CodexPromptInput,
|
||||
type CodexSkillPromptBlock,
|
||||
hasCodexSkillMentionCandidate,
|
||||
resolveCodexSkillMentions,
|
||||
type ResolvedCodexSkillMentions,
|
||||
} from "./codex/skill-mentions.js";
|
||||
import {
|
||||
AgentTurnStartCanceledError,
|
||||
getAgentStreamEventTurnId,
|
||||
@@ -21,7 +28,6 @@ import {
|
||||
type AgentPermissionResponse,
|
||||
type AgentPermissionResult,
|
||||
type AgentProviderNotice,
|
||||
type AgentPromptContentBlock,
|
||||
type AgentPromptInput,
|
||||
type AgentRunOptions,
|
||||
type AgentRunResult,
|
||||
@@ -3590,12 +3596,6 @@ async function readCodexConfiguredDefaults(
|
||||
return mergeCodexConfiguredDefaults(savedConfigDefaults, configReadDefaults);
|
||||
}
|
||||
|
||||
interface CodexSkillPromptBlock {
|
||||
type: "skill";
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
function enabledCodexSkills(
|
||||
entries: unknown[],
|
||||
): Array<{ name: string; description: string; path: string }> {
|
||||
@@ -3620,8 +3620,6 @@ function enabledCodexSkills(
|
||||
return Array.from(skillsByName.values());
|
||||
}
|
||||
|
||||
type CodexPromptContentBlock = AgentPromptContentBlock | CodexSkillPromptBlock;
|
||||
type CodexPromptInput = string | CodexPromptContentBlock[];
|
||||
interface CodexTextElement {
|
||||
byteRange: {
|
||||
start: number;
|
||||
@@ -3952,6 +3950,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
name: string;
|
||||
} | null = null;
|
||||
private cachedSkills: Array<{ name: string; description: string; path: string }> | null = null;
|
||||
private pendingLiteralFollowUpPrompt: string | null = null;
|
||||
|
||||
private readonly usageSessionKey = randomUUID();
|
||||
private readonly harnessEnvironment: Record<string, string>;
|
||||
@@ -4714,12 +4713,12 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
return null;
|
||||
}
|
||||
const parsed = this.parseSlashCommandInput(prompt);
|
||||
if (!parsed) {
|
||||
if (!parsed || !parsed.commandName.startsWith("prompts:")) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
const commands = await this.listCommands();
|
||||
return commands.some((command) => command.name === parsed.commandName) ? parsed : null;
|
||||
const prompts = await listCodexCustomPrompts(this.codexHome);
|
||||
return prompts.some((command) => command.name === parsed.commandName) ? parsed : null;
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
{ err: error, commandName: parsed.commandName },
|
||||
@@ -4733,31 +4732,30 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
commandName: string,
|
||||
args?: string,
|
||||
): Promise<CodexPromptInput> {
|
||||
if (commandName.startsWith("prompts:")) {
|
||||
const promptName = commandName.slice("prompts:".length);
|
||||
const promptPath = path.join(this.codexHome, "prompts", `${promptName}.md`);
|
||||
const raw = await fs.readFile(promptPath, "utf8");
|
||||
const parsed = parseFrontMatter(raw);
|
||||
return expandCodexCustomPrompt(parsed.body, args);
|
||||
const promptName = commandName.slice("prompts:".length);
|
||||
const promptPath = path.join(this.codexHome, "prompts", `${promptName}.md`);
|
||||
const raw = await fs.readFile(promptPath, "utf8");
|
||||
const parsed = parseFrontMatter(raw);
|
||||
const resolvedArgs = args ? await this.resolveMentionedSkills(args) : null;
|
||||
const expandedArgs =
|
||||
resolvedArgs && resolvedArgs.skills.length > 0 && Array.isArray(resolvedArgs.prompt)
|
||||
? (resolvedArgs.prompt.find((block) => block.type === "text")?.text ?? args)
|
||||
: args;
|
||||
const expandedBody = expandCodexCustomPrompt(parsed.body, expandedArgs);
|
||||
if (!resolvedArgs || resolvedArgs.skills.length === 0) {
|
||||
return expandedBody;
|
||||
}
|
||||
return [...resolvedArgs.skills, { type: "text", text: expandedBody }];
|
||||
}
|
||||
|
||||
if (this.connectionState === "disconnected") {
|
||||
await this.connect();
|
||||
} else {
|
||||
await this.loadSkills();
|
||||
private async resolveMentionedSkills(
|
||||
prompt: AgentPromptInput,
|
||||
): Promise<ResolvedCodexSkillMentions> {
|
||||
if (!hasCodexSkillMentionCandidate(prompt)) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
const skill = this.cachedSkills?.find((entry) => entry.name === commandName);
|
||||
if (skill) {
|
||||
const trimmedArgs = args?.trim() ?? "";
|
||||
const text = trimmedArgs ? `$${skill.name} ${trimmedArgs}` : `$${skill.name}`;
|
||||
const input: CodexPromptContentBlock[] = [
|
||||
{ type: "skill", name: skill.name, path: skill.path },
|
||||
{ type: "text", text },
|
||||
];
|
||||
return input;
|
||||
}
|
||||
|
||||
return args ? `$${commandName} ${args}` : `$${commandName}`;
|
||||
await this.loadSkills();
|
||||
return resolveCodexSkillMentions(prompt, this.cachedSkills ?? []);
|
||||
}
|
||||
|
||||
private async buildTurnStartParams(
|
||||
@@ -4953,10 +4951,19 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
throw new Error("Codex client not initialized");
|
||||
}
|
||||
|
||||
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
|
||||
const effectivePrompt = slashCommand
|
||||
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
|
||||
: prompt;
|
||||
const isLiteralFollowUp =
|
||||
typeof prompt === "string" &&
|
||||
this.pendingLiteralFollowUpPrompt !== null &&
|
||||
prompt === this.pendingLiteralFollowUpPrompt;
|
||||
this.pendingLiteralFollowUpPrompt = null;
|
||||
|
||||
let effectivePrompt: CodexPromptInput = prompt;
|
||||
if (!isLiteralFollowUp) {
|
||||
const slashCommand = await this.resolveSlashCommandInvocation(prompt);
|
||||
effectivePrompt = slashCommand
|
||||
? await this.buildCommandPromptInput(slashCommand.commandName, slashCommand.args)
|
||||
: (await this.resolveMentionedSkills(prompt)).prompt;
|
||||
}
|
||||
|
||||
if (this.currentThreadId) {
|
||||
await this.ensureThreadLoaded();
|
||||
@@ -5012,16 +5019,44 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
async steerActiveTurn(
|
||||
private async canSteerPrompt(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
},
|
||||
): Promise<boolean> {
|
||||
if (this.tryHandleOutOfBand(prompt)) {
|
||||
return false;
|
||||
}
|
||||
if (await this.resolveSlashCommandInvocation(prompt)) {
|
||||
return false;
|
||||
}
|
||||
if (!this.matchesSteerAdmission(admission)) {
|
||||
return false;
|
||||
}
|
||||
// Codex app-server only resolves skills at turn start (turn/steer ignores skill items and
|
||||
// $skill mentions), so fall back to turn replacement whenever a steered prompt mentions a skill.
|
||||
if ((await this.resolveMentionedSkills(prompt)).skills.length > 0) {
|
||||
return false;
|
||||
}
|
||||
return this.matchesSteerAdmission(admission);
|
||||
}
|
||||
|
||||
private async resolveSteerAdmission(expectedTurnId: string): Promise<{
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
} | null> {
|
||||
const client = this.client;
|
||||
const threadId = this.currentThreadId;
|
||||
let nativeTurnId = this.currentTurnId;
|
||||
const foregroundTurnId = this.activeForegroundTurnId;
|
||||
if (!client || !threadId || foregroundTurnId !== options.expectedTurnId) {
|
||||
return { status: "unavailable" };
|
||||
if (!client || !threadId || foregroundTurnId !== expectedTurnId) {
|
||||
return null;
|
||||
}
|
||||
const pendingIdentification = this.pendingForegroundTurnIdentification;
|
||||
// The start acknowledgement precedes the notification that identifies the native
|
||||
@@ -5029,23 +5064,29 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
if (!nativeTurnId && pendingIdentification?.foregroundTurnId === foregroundTurnId) {
|
||||
nativeTurnId = await pendingIdentification.promise;
|
||||
}
|
||||
if (!nativeTurnId) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
if (await this.resolveSlashCommandInvocation(prompt)) return { status: "unavailable" };
|
||||
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
return nativeTurnId ? { client, threadId, nativeTurnId, foregroundTurnId } : null;
|
||||
}
|
||||
|
||||
private async submitTurnSteer(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
nativeTurnId: string;
|
||||
foregroundTurnId: string;
|
||||
},
|
||||
): Promise<SteerResult> {
|
||||
const input = await this.buildUserInput(prompt);
|
||||
if (!this.matchesSteerAdmission({ client, threadId, nativeTurnId, foregroundTurnId })) {
|
||||
if (!this.matchesSteerAdmission(admission)) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
try {
|
||||
const response = await client.request(
|
||||
const response = await admission.client.request(
|
||||
"turn/steer",
|
||||
{
|
||||
threadId,
|
||||
expectedTurnId: nativeTurnId,
|
||||
threadId: admission.threadId,
|
||||
expectedTurnId: admission.nativeTurnId,
|
||||
input,
|
||||
...(options.clientMessageId ? { clientUserMessageId: options.clientMessageId } : {}),
|
||||
},
|
||||
@@ -5054,7 +5095,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
const record = toObjectRecord(response);
|
||||
const turn = record ? toObjectRecord(record.turn) : null;
|
||||
const acknowledgedTurnId = nonEmptyString(record?.turnId) ?? nonEmptyString(turn?.id);
|
||||
if (acknowledgedTurnId !== nativeTurnId) {
|
||||
if (acknowledgedTurnId !== admission.nativeTurnId) {
|
||||
throw new Error("Codex returned an invalid steer acknowledgement");
|
||||
}
|
||||
if (options.clearPendingPermissions) {
|
||||
@@ -5067,6 +5108,17 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
}
|
||||
}
|
||||
|
||||
async steerActiveTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
const admission = await this.resolveSteerAdmission(options.expectedTurnId);
|
||||
if (!admission || !(await this.canSteerPrompt(prompt, admission))) {
|
||||
return { status: "unavailable" };
|
||||
}
|
||||
return this.submitTurnSteer(prompt, options, admission);
|
||||
}
|
||||
|
||||
private matchesSteerAdmission(admission: {
|
||||
client: CodexAppServerClientLike;
|
||||
threadId: string;
|
||||
@@ -5408,10 +5460,16 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
let followUpPrompt = prepared.prompt;
|
||||
const expectedTurnId = this.activeForegroundTurnId;
|
||||
if (prepared.prompt && expectedTurnId) {
|
||||
const result = await this.steerActiveTurn(prepared.prompt, {
|
||||
expectedTurnId,
|
||||
clientMessageId: randomUUID(),
|
||||
});
|
||||
// Async question answers are structured replies to the active turn, not composer slash
|
||||
// prompts, so steer them directly without composer command/skill interception.
|
||||
const admission = await this.resolveSteerAdmission(expectedTurnId);
|
||||
const result = admission
|
||||
? await this.submitTurnSteer(
|
||||
prepared.prompt,
|
||||
{ expectedTurnId, clientMessageId: randomUUID() },
|
||||
admission,
|
||||
)
|
||||
: { status: "unavailable" as const };
|
||||
if (result.status !== "accepted") {
|
||||
throw new Error("The active Codex turn changed. Retry sending your answer.");
|
||||
}
|
||||
@@ -5424,7 +5482,11 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
requestId,
|
||||
resolution: response,
|
||||
});
|
||||
return followUpPrompt ? { followUpPrompt } : undefined;
|
||||
if (followUpPrompt) {
|
||||
this.pendingLiteralFollowUpPrompt = followUpPrompt;
|
||||
return { followUpPrompt };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private handlePlanPermissionResponse(params: {
|
||||
@@ -5443,6 +5505,7 @@ export class CodexAppServerAgentSession implements AgentSession {
|
||||
|
||||
this.resolvePlanPermission(requestId, response);
|
||||
if (followUpPrompt) {
|
||||
this.pendingLiteralFollowUpPrompt = followUpPrompt;
|
||||
return { followUpPrompt };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -460,3 +460,137 @@ test("restores unanswered questions and does not reopen answered questions on du
|
||||
await resumed.session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers an async answer containing an enabled Codex skill token without failing", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: tmpdir(),
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
"turn/steer": () => ({ turnId: "native-turn" }),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Ask me a question.");
|
||||
const started = waitForNextEvent(session, "turn_started");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-turn" });
|
||||
await started;
|
||||
const shown = waitForTimelineToolCall(session, questionItem.id);
|
||||
appServer.child.stdout.write(
|
||||
JSON.stringify({
|
||||
method: "item/completed",
|
||||
params: { threadId: "thread-1", turnId: "native-turn", item: questionItem },
|
||||
}) + "\n",
|
||||
);
|
||||
await shown;
|
||||
const [permission] = session.getPendingPermissions();
|
||||
expect(permission).toBeDefined();
|
||||
|
||||
await session.respondToPermission(permission!.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { "0": "Use /marker-skill" } },
|
||||
});
|
||||
|
||||
expect(session.getPendingPermissions()).toEqual([]);
|
||||
expect(appServer.requests().filter((request) => request.method === "turn/steer")).toMatchObject(
|
||||
[
|
||||
{
|
||||
params: {
|
||||
expectedTurnId: "native-turn",
|
||||
input: [{ type: "text", text: expect.stringContaining("Use /marker-skill") }],
|
||||
},
|
||||
},
|
||||
],
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("keeps a late async answer containing an enabled Codex skill token literal on the follow-up turn", async () => {
|
||||
const appServer = createFakeCodexAppServer({
|
||||
"skills/list": () => ({
|
||||
data: [
|
||||
{
|
||||
cwd: tmpdir(),
|
||||
skills: [
|
||||
{
|
||||
name: "marker-skill",
|
||||
description: "Marker skill.",
|
||||
path: "/workspace/skills/marker-skill/SKILL.md",
|
||||
},
|
||||
],
|
||||
errors: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const session = new CodexAppServerAgentSession(
|
||||
{ provider: "codex", cwd: tmpdir(), model: "gpt-5.4", modeId: "full-access" },
|
||||
null,
|
||||
createTestLogger(),
|
||||
async () => appServer.child,
|
||||
);
|
||||
try {
|
||||
await session.startTurn("Ask me a question.");
|
||||
const started = waitForNextEvent(session, "turn_started");
|
||||
appServer.startsTurn({ threadId: "thread-1", turnId: "native-turn" });
|
||||
await started;
|
||||
const shown = waitForTimelineToolCall(session, questionItem.id);
|
||||
appServer.child.stdout.write(
|
||||
JSON.stringify({
|
||||
method: "item/completed",
|
||||
params: { threadId: "thread-1", turnId: "native-turn", item: questionItem },
|
||||
}) + "\n",
|
||||
);
|
||||
await shown;
|
||||
const completed = waitForNextEvent(session, "turn_completed");
|
||||
appServer.completeTurn({ threadId: "thread-1" });
|
||||
await completed;
|
||||
|
||||
const [permission] = session.getPendingPermissions();
|
||||
expect(permission).toBeDefined();
|
||||
const result = await session.respondToPermission(permission!.id, {
|
||||
behavior: "allow",
|
||||
updatedInput: { answers: { "0": "Show /marker-skill in the example." } },
|
||||
});
|
||||
expect(result?.followUpPrompt).toBe(
|
||||
"Answers to your questions:\n\nWhich color?\nShow /marker-skill in the example.",
|
||||
);
|
||||
|
||||
await session.startTurn(result!.followUpPrompt!);
|
||||
|
||||
const turnStarts = appServer.requests().filter((request) => request.method === "turn/start");
|
||||
expect(turnStarts[turnStarts.length - 1]?.params).toEqual(
|
||||
expect.objectContaining({
|
||||
input: [
|
||||
{
|
||||
type: "text",
|
||||
text: "Answers to your questions:\n\nWhich color?\nShow /marker-skill in the example.",
|
||||
text_elements: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
);
|
||||
appServer.assertNoErrors();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { AgentPromptContentBlock } from "../../agent-sdk-types.js";
|
||||
import {
|
||||
type CodexSkillDescriptor,
|
||||
hasCodexSkillMentionCandidate,
|
||||
resolveCodexSkillMentions,
|
||||
} from "./skill-mentions.js";
|
||||
|
||||
const SKILLS: CodexSkillDescriptor[] = [
|
||||
{ name: "marker-skill", path: "/workspace/.agents/skills/marker-skill/SKILL.md" },
|
||||
{ name: "second-skill", path: "/workspace/.agents/skills/second-skill/SKILL.md" },
|
||||
{ name: "docs", path: "/workspace/.agents/skills/docs/SKILL.md" },
|
||||
];
|
||||
|
||||
describe("hasCodexSkillMentionCandidate", () => {
|
||||
test("detects leading, inline, and punctuated slash candidates in user text", () => {
|
||||
expect(hasCodexSkillMentionCandidate("/marker-skill")).toBe(true);
|
||||
expect(hasCodexSkillMentionCandidate("Use /marker-skill.")).toBe(true);
|
||||
expect(hasCodexSkillMentionCandidate("Check /docs/api.md then /marker-skill")).toBe(true);
|
||||
expect(
|
||||
hasCodexSkillMentionCandidate([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "No candidate here",
|
||||
},
|
||||
{ type: "text", text: "Now run /marker-skill!" },
|
||||
]),
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("returns false for plain text, file paths, URLs, bare slashes, and non-user blocks", () => {
|
||||
expect(hasCodexSkillMentionCandidate("Answer briefly: what is 2+2?")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Read /docs/api.md before replying")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Read /docs/api.md.")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("See https://example.com/marker-skill")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Path foo/marker-skill")).toBe(false);
|
||||
expect(hasCodexSkillMentionCandidate("Ratio a/b and bare / or /.")).toBe(false);
|
||||
expect(
|
||||
hasCodexSkillMentionCandidate([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Prior message used /marker-skill",
|
||||
},
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Note",
|
||||
text: "Attached snippet with /marker-skill",
|
||||
},
|
||||
{
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: "AAAA",
|
||||
},
|
||||
{
|
||||
type: "github_issue",
|
||||
mimeType: "application/github-issue",
|
||||
number: 5008,
|
||||
title: "Fix /marker-skill",
|
||||
url: "https://github.com/getpaseo/paseo/issues/5008",
|
||||
},
|
||||
]),
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveCodexSkillMentions", () => {
|
||||
test("resolves leading, inline, multiple, deduplicated, and punctuated mentions", () => {
|
||||
expect(resolveCodexSkillMentions("/marker-skill Answer briefly.", SKILLS)).toEqual({
|
||||
skills: [{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path }],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "text", text: "$marker-skill Answer briefly." },
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveCodexSkillMentions(
|
||||
"Use /second-skill, then /marker-skill; finally (/second-skill or /marker-skill!).",
|
||||
SKILLS,
|
||||
),
|
||||
).toEqual({
|
||||
skills: [
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
],
|
||||
prompt: [
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{
|
||||
type: "text",
|
||||
text: "Use $second-skill, then $marker-skill; finally (/second-skill or $marker-skill!).",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
expect(
|
||||
resolveCodexSkillMentions(
|
||||
"Try /marker-skill? /second-skill: [use /docs] {and /docs}",
|
||||
SKILLS,
|
||||
),
|
||||
).toEqual({
|
||||
skills: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "docs", path: SKILLS[2]!.path },
|
||||
],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
{ type: "skill", name: "second-skill", path: SKILLS[1]!.path },
|
||||
{ type: "skill", name: "docs", path: SKILLS[2]!.path },
|
||||
{
|
||||
type: "text",
|
||||
text: "Try $marker-skill? $second-skill: [use $docs] {and $docs}",
|
||||
},
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("never corrupts file paths, extensions, suffixes, or unknown slash tokens", () => {
|
||||
const prompt =
|
||||
"Check /docs/api.md, /docs/api.md., /docs.md, /docs-extra, /docs_v2, path/docs, and /unknown.";
|
||||
const result = resolveCodexSkillMentions(prompt, SKILLS);
|
||||
expect(result).toEqual({ skills: [], prompt });
|
||||
expect(result.prompt).toBe(prompt);
|
||||
});
|
||||
|
||||
test("scans only user text blocks and leaves images, chat_history, and attachments untouched", () => {
|
||||
const chatHistory: AgentPromptContentBlock = {
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "History mentioned /docs",
|
||||
};
|
||||
const textAttachment: AgentPromptContentBlock = {
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
title: "Pasted text",
|
||||
text: "Attachment mentioned /second-skill",
|
||||
};
|
||||
const image: AgentPromptContentBlock = {
|
||||
type: "image",
|
||||
mimeType: "image/png",
|
||||
data: "AAAA",
|
||||
};
|
||||
const blocks: AgentPromptContentBlock[] = [
|
||||
chatHistory,
|
||||
{ type: "text", text: "Please run /marker-skill on /docs/api.md." },
|
||||
image,
|
||||
textAttachment,
|
||||
];
|
||||
|
||||
const result = resolveCodexSkillMentions(blocks, SKILLS);
|
||||
expect(result).toEqual({
|
||||
skills: [{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path }],
|
||||
prompt: [
|
||||
{ type: "skill", name: "marker-skill", path: SKILLS[0]!.path },
|
||||
chatHistory,
|
||||
{ type: "text", text: "Please run $marker-skill on /docs/api.md." },
|
||||
image,
|
||||
textAttachment,
|
||||
],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
import type { AgentPromptContentBlock, AgentPromptInput } from "../../agent-sdk-types.js";
|
||||
|
||||
export interface CodexSkillDescriptor {
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface CodexSkillPromptBlock {
|
||||
type: "skill";
|
||||
name: string;
|
||||
path: string;
|
||||
}
|
||||
|
||||
export type CodexPromptContentBlock = AgentPromptContentBlock | CodexSkillPromptBlock;
|
||||
export type CodexPromptInput = string | CodexPromptContentBlock[];
|
||||
|
||||
export interface ResolvedCodexSkillMentions {
|
||||
skills: CodexSkillPromptBlock[];
|
||||
prompt: CodexPromptInput;
|
||||
}
|
||||
|
||||
// Match a whitespace- or start-delimited `/token` across the full non-whitespace token so a
|
||||
// trailing path segment like `/docs/api.md` or extension like `/docs.md` never matches `/docs`.
|
||||
const SLASH_TOKEN_PATTERN = /(^|\s)\/(\S+)/g;
|
||||
const TRAILING_BOUNDARY_PUNCTUATION_PATTERN = /[.,!?;:)\]}]+$/;
|
||||
const DISALLOWED_CANDIDATE_CHARS_PATTERN = /[/"']/;
|
||||
|
||||
function isUserTextBlock(block: AgentPromptContentBlock): block is { type: "text"; text: string } {
|
||||
return block.type === "text" && !("contextKind" in block) && !("mimeType" in block);
|
||||
}
|
||||
|
||||
function parseSlashMentionToken(rawToken: string): { name: string; trailing: string } | null {
|
||||
const trailingMatch = TRAILING_BOUNDARY_PUNCTUATION_PATTERN.exec(rawToken);
|
||||
const name = trailingMatch ? rawToken.slice(0, trailingMatch.index) : rawToken;
|
||||
const trailing = trailingMatch ? trailingMatch[0] : "";
|
||||
if (name.length === 0 || DISALLOWED_CANDIDATE_CHARS_PATTERN.test(name)) {
|
||||
return null;
|
||||
}
|
||||
return { name, trailing };
|
||||
}
|
||||
|
||||
function textHasSlashMentionCandidate(text: string): boolean {
|
||||
if (!text.includes("/")) {
|
||||
return false;
|
||||
}
|
||||
for (const match of text.matchAll(SLASH_TOKEN_PATTERN)) {
|
||||
const rawToken = match[2];
|
||||
if (rawToken && parseSlashMentionToken(rawToken)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function hasCodexSkillMentionCandidate(prompt: AgentPromptInput): boolean {
|
||||
if (typeof prompt === "string") {
|
||||
return textHasSlashMentionCandidate(prompt);
|
||||
}
|
||||
return prompt.some((block) => isUserTextBlock(block) && textHasSlashMentionCandidate(block.text));
|
||||
}
|
||||
|
||||
export function resolveCodexSkillMentions(
|
||||
prompt: AgentPromptInput,
|
||||
skills: ReadonlyArray<CodexSkillDescriptor>,
|
||||
): ResolvedCodexSkillMentions {
|
||||
if (skills.length === 0 || !hasCodexSkillMentionCandidate(prompt)) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
|
||||
const skillsByName = new Map<string, CodexSkillDescriptor>();
|
||||
for (const skill of skills) {
|
||||
if (!skillsByName.has(skill.name)) {
|
||||
skillsByName.set(skill.name, skill);
|
||||
}
|
||||
}
|
||||
|
||||
const mentioned = new Map<string, CodexSkillPromptBlock>();
|
||||
const rewriteUserText = (text: string): string => {
|
||||
if (!text.includes("/")) {
|
||||
return text;
|
||||
}
|
||||
return text.replace(SLASH_TOKEN_PATTERN, (fullMatch, prefix: string, rawToken: string) => {
|
||||
const parsed = parseSlashMentionToken(rawToken);
|
||||
if (!parsed) {
|
||||
return fullMatch;
|
||||
}
|
||||
const skill = skillsByName.get(parsed.name);
|
||||
if (!skill) {
|
||||
return fullMatch;
|
||||
}
|
||||
if (!mentioned.has(skill.name)) {
|
||||
mentioned.set(skill.name, {
|
||||
type: "skill",
|
||||
name: skill.name,
|
||||
path: skill.path,
|
||||
});
|
||||
}
|
||||
return `${prefix}$${skill.name}${parsed.trailing}`;
|
||||
});
|
||||
};
|
||||
|
||||
if (typeof prompt === "string") {
|
||||
const rewrittenText = rewriteUserText(prompt);
|
||||
if (mentioned.size === 0) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
const skillBlocks = Array.from(mentioned.values());
|
||||
return {
|
||||
skills: skillBlocks,
|
||||
prompt: [...skillBlocks, { type: "text", text: rewrittenText }],
|
||||
};
|
||||
}
|
||||
|
||||
const rewrittenBlocks = prompt.map((block): AgentPromptContentBlock => {
|
||||
if (!isUserTextBlock(block)) {
|
||||
return block;
|
||||
}
|
||||
const rewrittenText = rewriteUserText(block.text);
|
||||
return rewrittenText === block.text ? block : { ...block, text: rewrittenText };
|
||||
});
|
||||
|
||||
if (mentioned.size === 0) {
|
||||
return { skills: [], prompt };
|
||||
}
|
||||
|
||||
const skillBlocks = Array.from(mentioned.values());
|
||||
return {
|
||||
skills: skillBlocks,
|
||||
prompt: [...skillBlocks, ...rewrittenBlocks],
|
||||
};
|
||||
}
|
||||
@@ -94,7 +94,7 @@ import {
|
||||
isOmpBackgroundJobKillOutput,
|
||||
ompBackgroundJobKillCommand,
|
||||
parseOmpBackgroundWorkStatus,
|
||||
} from "./background-work-extension.js";
|
||||
} from "./integration-extension.js";
|
||||
import type { OmpRuntime, OmpRuntimeSession, OmpStartSessionInput } from "./runtime.js";
|
||||
import { OmpMcpBridge, type OmpBridgedToolIdentity } from "./mcp-bridge.js";
|
||||
import type {
|
||||
|
||||
@@ -9,9 +9,9 @@ import {
|
||||
type JsonlRpcLaunch,
|
||||
} from "../jsonl-rpc-process.js";
|
||||
import {
|
||||
createOmpBackgroundWorkExtensionFile,
|
||||
type OmpBackgroundWorkExtensionFile,
|
||||
} from "./background-work-extension.js";
|
||||
createOmpIntegrationExtensionFile,
|
||||
type OmpIntegrationExtensionFile,
|
||||
} from "./integration-extension.js";
|
||||
import { establishOmpProtocol } from "./protocol-session.js";
|
||||
import {
|
||||
buildOmpLaunch,
|
||||
@@ -75,14 +75,16 @@ export class OmpCliRuntime implements OmpRuntime {
|
||||
}
|
||||
|
||||
async startSession(input: OmpStartSessionInput): Promise<OmpRuntimeSession> {
|
||||
const backgroundWorkExtension = await createOmpBackgroundWorkExtensionFile();
|
||||
const integrationExtension = await createOmpIntegrationExtensionFile(
|
||||
input.systemPrompt?.trim(),
|
||||
);
|
||||
let env: Record<string, string>;
|
||||
let process: JsonlRpcProcess;
|
||||
try {
|
||||
input.signal?.throwIfAborted();
|
||||
({ env, process } = this.spawnOmp(input, backgroundWorkExtension.path));
|
||||
({ env, process } = this.spawnOmp(input, integrationExtension.path));
|
||||
} catch (error) {
|
||||
await backgroundWorkExtension.cleanup();
|
||||
await integrationExtension.cleanup();
|
||||
throw error;
|
||||
}
|
||||
const handleAbort = () => void process.close(input.signal?.reason).catch(() => undefined);
|
||||
@@ -93,11 +95,11 @@ export class OmpCliRuntime implements OmpRuntime {
|
||||
requestTimeoutMs: this.options.requestTimeoutMs,
|
||||
});
|
||||
input.signal?.throwIfAborted();
|
||||
return new OmpCliRuntimeSession(process, this.commandsRpcName, env, backgroundWorkExtension);
|
||||
return new OmpCliRuntimeSession(process, this.commandsRpcName, env, integrationExtension);
|
||||
} catch (error) {
|
||||
const startupError = error instanceof Error ? error : new Error(String(error));
|
||||
await process.close(startupError);
|
||||
await backgroundWorkExtension.cleanup();
|
||||
await integrationExtension.cleanup();
|
||||
throw startupError;
|
||||
} finally {
|
||||
input.signal?.removeEventListener("abort", handleAbort);
|
||||
@@ -149,7 +151,7 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
private readonly process: JsonlRpcProcess,
|
||||
private readonly commandsRpcName: "get_available_commands",
|
||||
private readonly launchEnvironment: Record<string, string>,
|
||||
private readonly backgroundWorkExtension: OmpBackgroundWorkExtensionFile,
|
||||
private readonly integrationExtension: OmpIntegrationExtensionFile,
|
||||
) {
|
||||
process.onMessage((message) => {
|
||||
const event = parseOmpRuntimeEvent(message);
|
||||
@@ -334,7 +336,7 @@ class OmpCliRuntimeSession implements OmpRuntimeSession {
|
||||
try {
|
||||
await this.process.close(new Error("OMP RPC session is closed"));
|
||||
} finally {
|
||||
await this.backgroundWorkExtension.cleanup();
|
||||
await this.integrationExtension.cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+8
-8
@@ -3,11 +3,11 @@ import { pathToFileURL } from "node:url";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi, type Mock } from "vitest";
|
||||
|
||||
import {
|
||||
createOmpBackgroundWorkExtensionFile,
|
||||
createOmpIntegrationExtensionFile,
|
||||
OMP_BACKGROUND_WORK_STATUS_KEY,
|
||||
parseOmpBackgroundWorkStatus,
|
||||
type OmpBackgroundWorkExtensionFile,
|
||||
} from "./background-work-extension.js";
|
||||
type OmpIntegrationExtensionFile,
|
||||
} from "./integration-extension.js";
|
||||
|
||||
interface FakeJob {
|
||||
id: string;
|
||||
@@ -40,7 +40,7 @@ const sleepJobStatus = JSON.stringify({
|
||||
jobs: [{ id: "bg_1", type: "bash", label: "sleep 45", command: "sleep 45" }],
|
||||
});
|
||||
|
||||
let extensionFile: OmpBackgroundWorkExtensionFile | undefined;
|
||||
let extensionFile: OmpIntegrationExtensionFile | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
@@ -49,7 +49,7 @@ afterEach(async () => {
|
||||
});
|
||||
|
||||
async function installExtension(): Promise<FakeHost> {
|
||||
extensionFile = await createOmpBackgroundWorkExtensionFile();
|
||||
extensionFile = await createOmpIntegrationExtensionFile();
|
||||
// The extension path is a runtime temp file, so it can only be loaded dynamically.
|
||||
const module = (await import(pathToFileURL(extensionFile.path).href)) as ExtensionModule;
|
||||
const handlers = new Map<string, FakeHandler>();
|
||||
@@ -90,7 +90,7 @@ function publishedTexts(setStatus: Mock): string[] {
|
||||
|
||||
describe("OMP background work extension file", () => {
|
||||
test("writes a module that exports the extension function", async () => {
|
||||
const file = await createOmpBackgroundWorkExtensionFile();
|
||||
const file = await createOmpIntegrationExtensionFile();
|
||||
try {
|
||||
// The generated module lives at a runtime temp path, so it can only be loaded dynamically.
|
||||
const module = (await import(pathToFileURL(file.path).href)) as ExtensionModule;
|
||||
@@ -104,7 +104,7 @@ describe("OMP background work extension file", () => {
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"writes the module readable by its owner only",
|
||||
async () => {
|
||||
const file = await createOmpBackgroundWorkExtensionFile();
|
||||
const file = await createOmpIntegrationExtensionFile();
|
||||
try {
|
||||
expect(statSync(file.path).mode & 0o777).toBe(0o600);
|
||||
} finally {
|
||||
@@ -114,7 +114,7 @@ describe("OMP background work extension file", () => {
|
||||
);
|
||||
|
||||
test("cleanup removes the private directory", async () => {
|
||||
const file = await createOmpBackgroundWorkExtensionFile();
|
||||
const file = await createOmpIntegrationExtensionFile();
|
||||
await file.cleanup();
|
||||
expect(existsSync(file.path)).toBe(false);
|
||||
});
|
||||
+24
-7
@@ -7,7 +7,7 @@ import type { AgentBackgroundWorkInput } from "../../background-work/index.js";
|
||||
|
||||
export const OMP_BACKGROUND_WORK_STATUS_KEY = "paseo:background-work";
|
||||
|
||||
export interface OmpBackgroundWorkExtensionFile {
|
||||
export interface OmpIntegrationExtensionFile {
|
||||
path: string;
|
||||
cleanup(): Promise<void>;
|
||||
}
|
||||
@@ -29,10 +29,11 @@ const statusSchema = z.object({
|
||||
|
||||
type OmpBackgroundJob = z.infer<typeof jobSchema>;
|
||||
|
||||
const EXTENSION_SOURCE = `const STATUS_KEY = ${JSON.stringify(OMP_BACKGROUND_WORK_STATUS_KEY)};
|
||||
function renderExtension(systemPrompt: string | undefined): string {
|
||||
return `const STATUS_KEY = ${JSON.stringify(OMP_BACKGROUND_WORK_STATUS_KEY)};
|
||||
const POLL_INTERVAL_MS = 250;
|
||||
|
||||
export default function paseoBackgroundWork(pi) {
|
||||
export default function paseoIntegration(pi) {
|
||||
let ctx;
|
||||
let timer;
|
||||
let lastText;
|
||||
@@ -72,18 +73,34 @@ export default function paseoBackgroundWork(pi) {
|
||||
timer.unref?.();
|
||||
}
|
||||
|
||||
${
|
||||
systemPrompt
|
||||
? `// Let OMP discover its own APPEND_SYSTEM.md before adding Paseo's instructions.
|
||||
pi.on("before_agent_start", (event) => {
|
||||
const append = ${JSON.stringify(systemPrompt)};
|
||||
return {
|
||||
systemPrompt: Array.isArray(event.systemPrompt)
|
||||
? [...event.systemPrompt, append]
|
||||
: event.systemPrompt + "\\n\\n" + append,
|
||||
};
|
||||
});`
|
||||
: ""
|
||||
}
|
||||
pi.on("session_start", (_event, sessionCtx) => start(sessionCtx));
|
||||
pi.on("session_switch", (_event, sessionCtx) => start(sessionCtx));
|
||||
pi.on("session_shutdown", () => stop());
|
||||
}
|
||||
`;
|
||||
}
|
||||
|
||||
export async function createOmpBackgroundWorkExtensionFile(): Promise<OmpBackgroundWorkExtensionFile> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "paseo-omp-background-work-"));
|
||||
const path = join(dir, "paseo-background-work.mjs");
|
||||
export async function createOmpIntegrationExtensionFile(
|
||||
systemPrompt?: string,
|
||||
): Promise<OmpIntegrationExtensionFile> {
|
||||
const dir = await mkdtemp(join(tmpdir(), "paseo-omp-integration-"));
|
||||
const path = join(dir, "paseo-integration.mjs");
|
||||
const cleanup = () => rm(dir, { recursive: true, force: true });
|
||||
try {
|
||||
await writeFile(path, EXTENSION_SOURCE, { mode: 0o600 });
|
||||
await writeFile(path, renderExtension(systemPrompt), { mode: 0o600 });
|
||||
} catch (error) {
|
||||
await cleanup();
|
||||
throw error;
|
||||
@@ -27,7 +27,6 @@ export interface OmpRuntimeLaunch {
|
||||
modeId?: string;
|
||||
session?: string;
|
||||
noSession?: boolean;
|
||||
systemPrompt?: string;
|
||||
extraArgs?: string[];
|
||||
}
|
||||
|
||||
@@ -103,8 +102,7 @@ export function buildOmpLaunch(input: {
|
||||
const argv = [...command];
|
||||
|
||||
const protocolMode = input.session.protocolMode ?? "rpc";
|
||||
const systemPrompt = input.session.systemPrompt?.trim();
|
||||
appendOmpLaunchArgs(argv, input.session, protocolMode, systemPrompt);
|
||||
appendOmpLaunchArgs(argv, input.session, protocolMode);
|
||||
|
||||
return {
|
||||
cwd: input.session.cwd,
|
||||
@@ -123,7 +121,6 @@ export function buildOmpLaunch(input: {
|
||||
modeId: input.session.modeId,
|
||||
session: input.session.session,
|
||||
noSession: input.session.noSession,
|
||||
systemPrompt,
|
||||
extraArgs: input.session.extraArgs,
|
||||
};
|
||||
}
|
||||
@@ -132,7 +129,6 @@ function appendOmpLaunchArgs(
|
||||
argv: string[],
|
||||
session: OmpStartSessionInput,
|
||||
protocolMode: "rpc" | "rpc-ui",
|
||||
systemPrompt: string | undefined,
|
||||
): void {
|
||||
if (!hasModeFlag(argv)) {
|
||||
argv.push("--mode", protocolMode);
|
||||
@@ -151,9 +147,6 @@ function appendOmpLaunchArgs(
|
||||
} else if (session.session) {
|
||||
argv.push("--session", session.session);
|
||||
}
|
||||
if (systemPrompt) {
|
||||
argv.push("--append-system-prompt", systemPrompt);
|
||||
}
|
||||
}
|
||||
|
||||
function hasModeFlag(argv: string[]): boolean {
|
||||
|
||||
@@ -20,7 +20,7 @@ import type {
|
||||
OmpThinkingLevel,
|
||||
} from "../rpc-types.js";
|
||||
import { buildOmpLaunch } from "../runtime.js";
|
||||
import { OMP_BACKGROUND_WORK_STATUS_KEY } from "../background-work-extension.js";
|
||||
import { OMP_BACKGROUND_WORK_STATUS_KEY } from "../integration-extension.js";
|
||||
|
||||
type FakeOmpSubagentSubscriptionLevel = "off" | "progress" | "events";
|
||||
type FakeOmpSubagentStatus = "pending" | "running" | "completed" | "failed" | "aborted";
|
||||
|
||||
@@ -3258,3 +3258,345 @@ describe("OpenCode v2 rewind", () => {
|
||||
expect(stages).toEqual([expect.objectContaining({ messageID: "msg_1", files: true })]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("OpenCode v2 slash commands and skill mentions", () => {
|
||||
function createSkillHarness() {
|
||||
const harness = new V2Harness();
|
||||
const location = { directory: "/tmp/project" };
|
||||
let commandListCalls = 0;
|
||||
let skillListCalls = 0;
|
||||
harness.api.command.list = async () => {
|
||||
commandListCalls += 1;
|
||||
return {
|
||||
location,
|
||||
data: [{ name: "review", description: "Review changes", source: "command" }],
|
||||
} as unknown as Awaited<ReturnType<V2Api["command"]["list"]>>;
|
||||
};
|
||||
harness.api.skill.list = async () => {
|
||||
skillListCalls += 1;
|
||||
return {
|
||||
location,
|
||||
data: [
|
||||
{ id: "grill-with-docs", description: "Grill with docs" },
|
||||
{ id: "review-docs", description: "Review docs" },
|
||||
{ id: "docs", description: "Docs skill" },
|
||||
{ id: "mcp:check", description: "MCP skill with colon" },
|
||||
],
|
||||
} as unknown as Awaited<ReturnType<V2Api["skill"]["list"]>>;
|
||||
};
|
||||
const sentPrompts: Array<Parameters<V2Api["session"]["prompt"]>[0]> = [];
|
||||
const sentCommands: Array<Parameters<V2Api["session"]["command"]>[0]> = [];
|
||||
const sentCompacts: Array<Parameters<V2Api["session"]["compact"]>[0]> = [];
|
||||
const origPrompt = harness.prompt;
|
||||
harness.prompt = async (input, options) => {
|
||||
sentPrompts.push(input);
|
||||
await origPrompt(input, options);
|
||||
};
|
||||
harness.api.session.command = async (input) => {
|
||||
sentCommands.push(input);
|
||||
if (harness.autoComplete) harness.finishExecution();
|
||||
};
|
||||
harness.api.session.compact = async (input) => {
|
||||
sentCompacts.push(input);
|
||||
if (harness.autoComplete) harness.finishExecution();
|
||||
};
|
||||
return {
|
||||
harness,
|
||||
sentPrompts,
|
||||
sentCommands,
|
||||
sentCompacts,
|
||||
get commandListCalls() {
|
||||
return commandListCalls;
|
||||
},
|
||||
get skillListCalls() {
|
||||
return skillListCalls;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test("resolves inline skill mention on idle turn with @mention and exact offset", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("Answer briefly: what is 2+2? /grill-with-docs");
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.text).toBe("Answer briefly: what is 2+2? @grill-with-docs");
|
||||
expect(sent.skills).toEqual([
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 29, end: 45, text: "@grill-with-docs" },
|
||||
},
|
||||
]);
|
||||
expect(sent.text.slice(29, 45)).toBe("@grill-with-docs");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves leading skill with prose, standalone skill, and trailing-space-only skill", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("/grill-with-docs check the plan");
|
||||
expect(h.sentPrompts[0]).toMatchObject({
|
||||
text: "@grill-with-docs check the plan",
|
||||
skills: [
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 0, end: 16, text: "@grill-with-docs" },
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
await session.run("/grill-with-docs ");
|
||||
expect(h.sentPrompts[1]).toMatchObject({
|
||||
text: "Use the grill-with-docs skill.",
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves multiple skills, punctuation boundaries, colon IDs, and deduplicates by id", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run(
|
||||
"Use /grill-with-docs, /mcp:check. Then /review-docs! Repeat /grill-with-docs.",
|
||||
);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.text).toBe(
|
||||
"Use @grill-with-docs, @mcp:check. Then @review-docs! Repeat @grill-with-docs.",
|
||||
);
|
||||
expect(sent.skills).toEqual([
|
||||
{ id: "grill-with-docs", mention: { start: 4, end: 20, text: "@grill-with-docs" } },
|
||||
{ id: "mcp:check", mention: { start: 22, end: 32, text: "@mcp:check" } },
|
||||
{ id: "review-docs", mention: { start: 39, end: 51, text: "@review-docs" } },
|
||||
]);
|
||||
for (const skill of sent.skills ?? []) {
|
||||
expect(sent.text.slice(skill.mention!.start, skill.mention!.end)).toBe(skill.mention!.text);
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("resolves skills alongside attachments without scanning chat_history or text attachments", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run([
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous chat mentioned /review-docs",
|
||||
},
|
||||
{ type: "text", text: "/grill-with-docs inspect this image" },
|
||||
{ type: "image", mimeType: "image/png", data: "AAAA" },
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
text: "Attached note with /docs",
|
||||
},
|
||||
]);
|
||||
const sent = h.sentPrompts[0]!;
|
||||
expect(sent.files).toEqual([{ uri: "data:image/png;base64,AAAA" }]);
|
||||
expect(sent.text).toContain("Previous chat mentioned /review-docs");
|
||||
expect(sent.text).toContain("Attached note with /docs");
|
||||
expect(sent.text).toContain("@grill-with-docs inspect this image");
|
||||
expect(sent.skills).toHaveLength(1);
|
||||
const [skill] = sent.skills!;
|
||||
expect(skill?.id).toBe("grill-with-docs");
|
||||
expect(sent.text.slice(skill!.mention!.start, skill!.mention!.end)).toBe("@grill-with-docs");
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("leaves file paths untouched and skips command lookup when no slash mention candidate exists", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("Compare /docs/api.md and src/docs/index.ts with /docs.ts");
|
||||
expect(h.sentPrompts[0]?.text).toBe(
|
||||
"Compare /docs/api.md and src/docs/index.ts with /docs.ts",
|
||||
);
|
||||
expect(h.sentPrompts[0]?.skills).toBeUndefined();
|
||||
// /docs.ts is a single-segment candidate so lookup ran once; /docs/api.md alone skips lookup.
|
||||
const callsBeforePathOnly = h.skillListCalls;
|
||||
await session.run("Read /docs/api.md and packages/app/index.ts");
|
||||
expect(h.skillListCalls).toBe(callsBeforePathOnly);
|
||||
expect(h.sentPrompts[1]?.text).toBe("Read /docs/api.md and packages/app/index.ts");
|
||||
expect(h.sentPrompts[1]?.skills).toBeUndefined();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("attaches skills selected inside leading command arguments and ignores code blocks", async () => {
|
||||
const h = createSkillHarness();
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
await session.run("/review src/index.ts /docs");
|
||||
expect(h.sentCommands).toEqual([
|
||||
{
|
||||
sessionID: "session",
|
||||
name: "review",
|
||||
text: "src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 13, end: 18, text: "@docs" } }],
|
||||
},
|
||||
]);
|
||||
|
||||
const fenced = "Explain:\n```sh\nls /docs\n```";
|
||||
await session.run(fenced);
|
||||
expect(h.sentPrompts[0]?.text).toBe(fenced);
|
||||
expect(h.sentPrompts[0]?.skills).toBeUndefined();
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("steers leading and inline skills natively into a running turn", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("/grill-with-docs the plan", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(h.sentPrompts[1]).toMatchObject({
|
||||
text: "@grill-with-docs the plan",
|
||||
skills: [
|
||||
{
|
||||
id: "grill-with-docs",
|
||||
mention: { start: 0, end: 16, text: "@grill-with-docs" },
|
||||
},
|
||||
],
|
||||
delivery: "steer",
|
||||
});
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("Also apply /review-docs.", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "accepted" });
|
||||
expect(h.sentPrompts[2]).toMatchObject({
|
||||
text: "Also apply @review-docs.",
|
||||
skills: [
|
||||
{
|
||||
id: "review-docs",
|
||||
mention: { start: 11, end: 23, text: "@review-docs" },
|
||||
},
|
||||
],
|
||||
delivery: "steer",
|
||||
});
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable on steer for /compact, /summarize, and provider commands", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
await expect(
|
||||
session.steerActiveTurn!("/compact", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
await expect(
|
||||
session.steerActiveTurn!(" /summarize ", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
await expect(
|
||||
session.steerActiveTurn!("/review now", { expectedTurnId: turnId }),
|
||||
).resolves.toEqual({ status: "unavailable" });
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
expect(h.sentCommands).toHaveLength(0);
|
||||
expect(h.sentCompacts).toHaveLength(0);
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("returns unavailable when the active turn ends during async skill resolution on steer", async () => {
|
||||
const h = createSkillHarness();
|
||||
h.harness.autoComplete = false;
|
||||
let releaseSkills!: () => void;
|
||||
const origSkillList = h.harness.api.skill.list;
|
||||
h.harness.api.skill.list = async (input) => {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseSkills = resolve;
|
||||
});
|
||||
return origSkillList(input);
|
||||
};
|
||||
const client = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: h.harness.runtime,
|
||||
});
|
||||
const session = await client.createSession({ provider: "opencode", cwd: "/tmp/project" });
|
||||
try {
|
||||
let completed = false;
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_completed") completed = true;
|
||||
});
|
||||
try {
|
||||
const { turnId } = await session.startTurn("Work");
|
||||
await expect.poll(() => h.harness.prompts).toEqual(["Work"]);
|
||||
|
||||
const steering = session.steerActiveTurn!("Use /grill-with-docs", {
|
||||
expectedTurnId: turnId,
|
||||
});
|
||||
await expect.poll(() => Boolean(releaseSkills)).toBe(true);
|
||||
h.harness.finishExecution();
|
||||
await expect.poll(() => completed).toBe(true);
|
||||
releaseSkills();
|
||||
|
||||
await expect(steering).resolves.toEqual({ status: "unavailable" });
|
||||
expect(h.sentPrompts).toHaveLength(1);
|
||||
} finally {
|
||||
unsubscribe();
|
||||
}
|
||||
} finally {
|
||||
await session.close();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import type { AgentSlashCommand } from "../../../agent-sdk-types.js";
|
||||
import { prepareOpenCodePrompt } from "./prompt-input.js";
|
||||
|
||||
const COMMANDS: readonly AgentSlashCommand[] = [
|
||||
{ name: "compact", description: "Compact", argumentHint: "", kind: "command" },
|
||||
{ name: "summarize", description: "Summarize", argumentHint: "", kind: "command" },
|
||||
{ name: "review", description: "Review", argumentHint: "", kind: "command" },
|
||||
{ name: "nested/docs", description: "Nested command", argumentHint: "", kind: "command" },
|
||||
{ name: "docs", description: "Docs skill", argumentHint: "", kind: "skill" },
|
||||
{ name: "grill-with-docs", description: "Grill", argumentHint: "", kind: "skill" },
|
||||
{ name: "mcp:tool", description: "MCP skill", argumentHint: "", kind: "skill" },
|
||||
];
|
||||
|
||||
describe("prepareOpenCodePrompt", () => {
|
||||
test("recognizes compact and summarize without loading commands", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
expect(await prepareOpenCodePrompt("/compact", load)).toEqual({ kind: "compact" });
|
||||
expect(await prepareOpenCodePrompt(" /summarize now ", load)).toEqual({ kind: "compact" });
|
||||
expect(loads).toBe(0);
|
||||
});
|
||||
|
||||
test("dispatches leading non-skill slash commands with args and attachments", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
[
|
||||
{ type: "text", text: " /review src/index.ts" },
|
||||
{ type: "image", mimeType: "image/png", data: "BBBB" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "src/index.ts",
|
||||
files: [{ uri: "data:image/png;base64,BBBB" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("skips loading commands when user text has no slash mention candidate", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
expect(await prepareOpenCodePrompt("Inspect /docs/api.md and a/docs/b", load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Inspect /docs/api.md and a/docs/b",
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
});
|
||||
|
||||
test("rewrites standalone single and multiple skills to fallback prose", async () => {
|
||||
expect(await prepareOpenCodePrompt(" /grill-with-docs ", async () => COMMANDS)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use the grill-with-docs skill.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
|
||||
expect(
|
||||
await prepareOpenCodePrompt(
|
||||
"/grill-with-docs /mcp:tool /grill-with-docs",
|
||||
async () => COMMANDS,
|
||||
),
|
||||
).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use the grill-with-docs, mcp:tool skills.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }, { id: "mcp:tool" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves punctuation boundaries and rejects path or word continuations", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
"Use /docs, /mcp:tool. Keep /docs/api.md, /docs.ts, foo/docs, and /unknown.",
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Use @docs, @mcp:tool. Keep /docs/api.md, /docs.ts, foo/docs, and /unknown.",
|
||||
files: [],
|
||||
skills: [
|
||||
{ id: "docs", mention: { start: 4, end: 9, text: "@docs" } },
|
||||
{ id: "mcp:tool", mention: { start: 11, end: 20, text: "@mcp:tool" } },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
test("keeps fallback text alongside preceding chat_history attachment", async () => {
|
||||
const result = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "History with /docs",
|
||||
},
|
||||
{ type: "text", text: "/grill-with-docs " },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(result).toEqual({
|
||||
kind: "prompt",
|
||||
text: "History with /docs\nUse the grill-with-docs skill.",
|
||||
files: [],
|
||||
skills: [{ id: "grill-with-docs" }],
|
||||
});
|
||||
});
|
||||
|
||||
test("resolves skill mentions inside leading command arguments", async () => {
|
||||
const result = await prepareOpenCodePrompt("/review src/index.ts /docs", async () => COMMANDS);
|
||||
expect(result).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 13, end: 18, text: "@docs" } }],
|
||||
});
|
||||
|
||||
const skillOnlyArg = await prepareOpenCodePrompt("/review /docs", async () => COMMANDS);
|
||||
expect(skillOnlyArg).toEqual({
|
||||
kind: "command",
|
||||
name: "review",
|
||||
text: "@docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 0, end: 5, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves literal paths inside fenced code blocks and inline code spans", async () => {
|
||||
let loads = 0;
|
||||
const load = async () => {
|
||||
loads += 1;
|
||||
return COMMANDS;
|
||||
};
|
||||
|
||||
const fencedOnly = "Explain this command:\n```sh\nls /docs\n```";
|
||||
expect(await prepareOpenCodePrompt(fencedOnly, load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: fencedOnly,
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
|
||||
const inlineCodeOnly = "Run `ls /docs` or `ls`/docs";
|
||||
expect(await prepareOpenCodePrompt(inlineCodeOnly, load)).toEqual({
|
||||
kind: "prompt",
|
||||
text: inlineCodeOnly,
|
||||
files: [],
|
||||
});
|
||||
expect(loads).toBe(0);
|
||||
|
||||
const mixed = "Explain `ls /docs` and:\n```sh\nls /docs\n```\nThen use /docs.";
|
||||
const mixedResult = await prepareOpenCodePrompt(mixed, load);
|
||||
expect(mixedResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Explain `ls /docs` and:\n```sh\nls /docs\n```\nThen use @docs.",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 52, end: 57, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
|
||||
test("dispatches slash-separated subdirectory commands while keeping unmatched leading paths literal", async () => {
|
||||
expect(await prepareOpenCodePrompt("/nested/docs details /docs", async () => COMMANDS)).toEqual(
|
||||
{
|
||||
kind: "command",
|
||||
name: "nested/docs",
|
||||
text: "details @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 8, end: 13, text: "@docs" } }],
|
||||
},
|
||||
);
|
||||
|
||||
expect(await prepareOpenCodePrompt("/docs/api.md", async () => COMMANDS)).toEqual({
|
||||
kind: "prompt",
|
||||
text: "/docs/api.md",
|
||||
files: [],
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves the regular prompt path when chat history precedes /compact or a provider command", async () => {
|
||||
const compactResult = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Previous conversation transcript",
|
||||
},
|
||||
{ type: "text", text: "/compact" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(compactResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Previous conversation transcript\n/compact",
|
||||
files: [],
|
||||
});
|
||||
|
||||
const commandResult = await prepareOpenCodePrompt(
|
||||
[
|
||||
{
|
||||
type: "text",
|
||||
mimeType: "text/plain",
|
||||
contextKind: "chat_history",
|
||||
text: "Earlier conversation about README.md",
|
||||
},
|
||||
{ type: "text", text: "/review src/index.ts /docs" },
|
||||
],
|
||||
async () => COMMANDS,
|
||||
);
|
||||
expect(commandResult).toEqual({
|
||||
kind: "prompt",
|
||||
text: "Earlier conversation about README.md\n/review src/index.ts @docs",
|
||||
files: [],
|
||||
skills: [{ id: "docs", mention: { start: 58, end: 63, text: "@docs" } }],
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,430 @@
|
||||
import type { AgentPromptInput, AgentSlashCommand } from "../../../agent-sdk-types.js";
|
||||
import { renderPromptAttachmentAsText } from "../../../prompt-attachments.js";
|
||||
|
||||
export interface OpenCodeSkillMention {
|
||||
start: number;
|
||||
end: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface OpenCodeSkillAttachment {
|
||||
id: string;
|
||||
mention?: OpenCodeSkillMention;
|
||||
}
|
||||
|
||||
export type PreparedOpenCodePrompt =
|
||||
| { kind: "compact" }
|
||||
| {
|
||||
kind: "command";
|
||||
name: string;
|
||||
text: string;
|
||||
files: Array<{ uri: string }>;
|
||||
skills?: OpenCodeSkillAttachment[];
|
||||
}
|
||||
| {
|
||||
kind: "prompt";
|
||||
text: string;
|
||||
files: Array<{ uri: string }>;
|
||||
skills?: OpenCodeSkillAttachment[];
|
||||
};
|
||||
|
||||
interface PromptSegment {
|
||||
text: string;
|
||||
isUserText: boolean;
|
||||
}
|
||||
|
||||
interface TextPiece {
|
||||
text: string;
|
||||
isCode: boolean;
|
||||
precededByBoundary: boolean;
|
||||
}
|
||||
|
||||
interface MatchedSegment {
|
||||
text: string;
|
||||
hasOtherProse: boolean;
|
||||
mentions: Array<{ id: string; start: number; end: number; text: string }>;
|
||||
}
|
||||
|
||||
type RewrittenSegment = PromptSegment & { mentions?: MatchedSegment["mentions"] };
|
||||
|
||||
const LEADING_SLASH_COMMAND = /^\/([^\s]+)(?:\s+([\s\S]*))?$/;
|
||||
const SLASH_TOKEN = /(^|\s)\/([^\s]+)/g;
|
||||
const TRAILING_PUNCTUATION = /[.,!?;:)\]}]+$/;
|
||||
const OPENING_FENCE = /^ {0,3}(`{3,}|~{3,})/;
|
||||
|
||||
function splitPrompt(prompt: AgentPromptInput): {
|
||||
segments: PromptSegment[];
|
||||
files: Array<{ uri: string }>;
|
||||
} {
|
||||
if (typeof prompt === "string") {
|
||||
return { segments: [{ text: prompt, isUserText: true }], files: [] };
|
||||
}
|
||||
const segments: PromptSegment[] = [];
|
||||
const files: Array<{ uri: string }> = [];
|
||||
for (const part of prompt) {
|
||||
if (part.type === "image") {
|
||||
files.push({ uri: `data:${part.mimeType};base64,${part.data}` });
|
||||
} else if (part.type === "text") {
|
||||
segments.push({
|
||||
text: part.text,
|
||||
isUserText: !("mimeType" in part) && !("contextKind" in part),
|
||||
});
|
||||
} else {
|
||||
segments.push({ text: renderPromptAttachmentAsText(part), isUserText: false });
|
||||
}
|
||||
}
|
||||
return { segments, files };
|
||||
}
|
||||
|
||||
function joinSegments(segments: readonly PromptSegment[]): string {
|
||||
return segments.map((segment) => segment.text).join("\n");
|
||||
}
|
||||
|
||||
function findFenceClose(text: string, from: number, char: string, minLength: number): number {
|
||||
let cursor = from;
|
||||
while (cursor < text.length) {
|
||||
const newline = text.indexOf("\n", cursor);
|
||||
const lineEnd = newline === -1 ? text.length : newline;
|
||||
const line = text.slice(cursor, lineEnd).replace(/\r$/, "");
|
||||
const closeMatch = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/);
|
||||
if (closeMatch && closeMatch[1]![0] === char && closeMatch[1]!.length >= minLength) {
|
||||
return newline === -1 ? text.length : newline + 1;
|
||||
}
|
||||
if (newline === -1) return text.length;
|
||||
cursor = newline + 1;
|
||||
}
|
||||
return text.length;
|
||||
}
|
||||
|
||||
function findInlineCodeEnd(text: string, from: number, tickCount: number): number {
|
||||
let cursor = from;
|
||||
while (cursor < text.length) {
|
||||
const tick = text.indexOf("`", cursor);
|
||||
if (tick === -1) return -1;
|
||||
let runEnd = tick + 1;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd += 1;
|
||||
if (runEnd - tick === tickCount) return runEnd;
|
||||
cursor = runEnd;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
function splitProseAndCode(text: string): TextPiece[] {
|
||||
const pieces: TextPiece[] = [];
|
||||
let proseStart = 0;
|
||||
let i = 0;
|
||||
|
||||
const pushProse = (end: number) => {
|
||||
if (end <= proseStart) return;
|
||||
pieces.push({
|
||||
text: text.slice(proseStart, end),
|
||||
isCode: false,
|
||||
precededByBoundary: proseStart === 0 || /\s/.test(text[proseStart - 1]!),
|
||||
});
|
||||
};
|
||||
|
||||
while (i < text.length) {
|
||||
const atLineStart = i === 0 || text[i - 1] === "\n";
|
||||
if (atLineStart) {
|
||||
const newline = text.indexOf("\n", i);
|
||||
const lineEnd = newline === -1 ? text.length : newline;
|
||||
const opening = text.slice(i, lineEnd).match(OPENING_FENCE);
|
||||
const fence = opening?.[1];
|
||||
const infoString = opening ? text.slice(i + opening[0].length, lineEnd) : "";
|
||||
if (fence && (fence[0] !== "`" || !infoString.includes("`"))) {
|
||||
pushProse(i);
|
||||
const bodyStart = newline === -1 ? text.length : newline + 1;
|
||||
const fenceEnd = findFenceClose(text, bodyStart, fence[0]!, fence.length);
|
||||
pieces.push({ text: text.slice(i, fenceEnd), isCode: true, precededByBoundary: true });
|
||||
i = fenceEnd;
|
||||
proseStart = i;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (text[i] === "`") {
|
||||
let runEnd = i + 1;
|
||||
while (runEnd < text.length && text[runEnd] === "`") runEnd += 1;
|
||||
const closeEnd = findInlineCodeEnd(text, runEnd, runEnd - i);
|
||||
if (closeEnd !== -1) {
|
||||
pushProse(i);
|
||||
pieces.push({ text: text.slice(i, closeEnd), isCode: true, precededByBoundary: false });
|
||||
i = closeEnd;
|
||||
proseStart = i;
|
||||
continue;
|
||||
}
|
||||
i = runEnd;
|
||||
continue;
|
||||
}
|
||||
|
||||
i += 1;
|
||||
}
|
||||
|
||||
pushProse(text.length);
|
||||
return pieces;
|
||||
}
|
||||
|
||||
function hasSlashCandidate(segments: readonly PromptSegment[]): boolean {
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText || !segment.text.includes("/")) continue;
|
||||
for (const piece of splitProseAndCode(segment.text)) {
|
||||
if (piece.isCode || !piece.text.includes("/")) continue;
|
||||
SLASH_TOKEN.lastIndex = 0;
|
||||
for (
|
||||
let match = SLASH_TOKEN.exec(piece.text);
|
||||
match !== null;
|
||||
match = SLASH_TOKEN.exec(piece.text)
|
||||
) {
|
||||
if (match.index === 0 && match[1] === "" && !piece.precededByBoundary) continue;
|
||||
const rawToken = match[2] ?? "";
|
||||
// Multi-segment tokens such as `/docs/api.md` are file paths, never slash names.
|
||||
if (rawToken.includes("/")) continue;
|
||||
if (rawToken.replace(TRAILING_PUNCTUATION, "").length > 0) return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function matchSkillToken(
|
||||
rawToken: string,
|
||||
skillIds: ReadonlySet<string>,
|
||||
): { id: string; trailing: string } | null {
|
||||
if (rawToken.includes("/")) return null;
|
||||
if (skillIds.has(rawToken)) return { id: rawToken, trailing: "" };
|
||||
const stripped = rawToken.replace(TRAILING_PUNCTUATION, "");
|
||||
if (stripped.length > 0 && stripped.length < rawToken.length && skillIds.has(stripped)) {
|
||||
return { id: stripped, trailing: rawToken.slice(stripped.length) };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function rewriteUserSegment(text: string, skillIds: ReadonlySet<string>): MatchedSegment {
|
||||
let rewritten = "";
|
||||
let outsideMatches = "";
|
||||
let hasCode = false;
|
||||
const mentions: MatchedSegment["mentions"] = [];
|
||||
|
||||
for (const piece of splitProseAndCode(text)) {
|
||||
if (piece.isCode) {
|
||||
rewritten += piece.text;
|
||||
hasCode = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
let cursor = 0;
|
||||
SLASH_TOKEN.lastIndex = 0;
|
||||
for (
|
||||
let match = SLASH_TOKEN.exec(piece.text);
|
||||
match !== null;
|
||||
match = SLASH_TOKEN.exec(piece.text)
|
||||
) {
|
||||
const prefix = match[1] ?? "";
|
||||
if (match.index === 0 && prefix === "" && !piece.precededByBoundary) continue;
|
||||
const rawToken = match[2] ?? "";
|
||||
const resolved = matchSkillToken(rawToken, skillIds);
|
||||
if (!resolved) continue;
|
||||
|
||||
const tokenStart = match.index + prefix.length;
|
||||
const tokenEnd = match.index + match[0].length;
|
||||
const before = piece.text.slice(cursor, tokenStart);
|
||||
rewritten += before;
|
||||
outsideMatches += before;
|
||||
|
||||
const mentionText = `@${resolved.id}`;
|
||||
const mentionStart = rewritten.length;
|
||||
rewritten += mentionText;
|
||||
const mentionEnd = rewritten.length;
|
||||
rewritten += resolved.trailing;
|
||||
outsideMatches += resolved.trailing;
|
||||
|
||||
mentions.push({ id: resolved.id, start: mentionStart, end: mentionEnd, text: mentionText });
|
||||
cursor = tokenEnd;
|
||||
}
|
||||
|
||||
const tail = piece.text.slice(cursor);
|
||||
rewritten += tail;
|
||||
outsideMatches += tail;
|
||||
}
|
||||
|
||||
return {
|
||||
text: rewritten,
|
||||
hasOtherProse: hasCode || outsideMatches.trim().length > 0,
|
||||
mentions,
|
||||
};
|
||||
}
|
||||
|
||||
function fallbackSkillPromptText(ids: readonly string[]): string {
|
||||
if (ids.length === 1) return `Use the ${ids[0]} skill.`;
|
||||
return `Use the ${ids.join(", ")} skills.`;
|
||||
}
|
||||
|
||||
function buildFallbackSkillContent(rewrittenSegments: readonly RewrittenSegment[]): {
|
||||
text: string;
|
||||
skills: OpenCodeSkillAttachment[];
|
||||
} {
|
||||
const uniqueIds: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const segment of rewrittenSegments) {
|
||||
for (const mention of segment.mentions ?? []) {
|
||||
if (seen.has(mention.id)) continue;
|
||||
seen.add(mention.id);
|
||||
uniqueIds.push(mention.id);
|
||||
}
|
||||
}
|
||||
let fallbackInserted = false;
|
||||
const outputParts: string[] = [];
|
||||
for (const segment of rewrittenSegments) {
|
||||
if (!segment.isUserText) {
|
||||
outputParts.push(segment.text);
|
||||
} else if (!fallbackInserted) {
|
||||
outputParts.push(fallbackSkillPromptText(uniqueIds));
|
||||
fallbackInserted = true;
|
||||
}
|
||||
}
|
||||
return {
|
||||
text: outputParts.join("\n"),
|
||||
skills: uniqueIds.map((id) => ({ id })),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMentionedSkillContent(rewrittenSegments: readonly RewrittenSegment[]): {
|
||||
text: string;
|
||||
skills: OpenCodeSkillAttachment[];
|
||||
} {
|
||||
const skills: OpenCodeSkillAttachment[] = [];
|
||||
const seen = new Set<string>();
|
||||
const outputParts: string[] = [];
|
||||
let offset = 0;
|
||||
|
||||
for (const segment of rewrittenSegments) {
|
||||
if (outputParts.length > 0) offset += 1;
|
||||
for (const mention of segment.mentions ?? []) {
|
||||
if (seen.has(mention.id)) continue;
|
||||
seen.add(mention.id);
|
||||
skills.push({
|
||||
id: mention.id,
|
||||
mention: {
|
||||
start: offset + mention.start,
|
||||
end: offset + mention.end,
|
||||
text: mention.text,
|
||||
},
|
||||
});
|
||||
}
|
||||
outputParts.push(segment.text);
|
||||
offset += segment.text.length;
|
||||
}
|
||||
|
||||
return {
|
||||
text: outputParts.join("\n"),
|
||||
skills,
|
||||
};
|
||||
}
|
||||
|
||||
function resolveSkillContent(
|
||||
segments: readonly PromptSegment[],
|
||||
skillIds: ReadonlySet<string>,
|
||||
options: { allowFallback: boolean },
|
||||
): { text: string; skills?: OpenCodeSkillAttachment[] } {
|
||||
if (skillIds.size === 0) {
|
||||
return { text: joinSegments(segments) };
|
||||
}
|
||||
|
||||
const rewrittenSegments: RewrittenSegment[] = [];
|
||||
let matchedAnySkill = false;
|
||||
let hasUserProse = false;
|
||||
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText) {
|
||||
rewrittenSegments.push(segment);
|
||||
continue;
|
||||
}
|
||||
const result = rewriteUserSegment(segment.text, skillIds);
|
||||
if (result.mentions.length > 0) matchedAnySkill = true;
|
||||
if (result.hasOtherProse) hasUserProse = true;
|
||||
rewrittenSegments.push({ text: result.text, isUserText: true, mentions: result.mentions });
|
||||
}
|
||||
|
||||
if (!matchedAnySkill) {
|
||||
return { text: joinSegments(segments) };
|
||||
}
|
||||
|
||||
if (!hasUserProse && options.allowFallback) {
|
||||
return buildFallbackSkillContent(rewrittenSegments);
|
||||
}
|
||||
return buildMentionedSkillContent(rewrittenSegments);
|
||||
}
|
||||
|
||||
function stripLeadingCommandFromSegments(
|
||||
segments: readonly PromptSegment[],
|
||||
commandName: string,
|
||||
): PromptSegment[] {
|
||||
const prefixPattern = new RegExp(
|
||||
`^\\s*/${commandName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?:\\s+)?`,
|
||||
);
|
||||
const result: PromptSegment[] = [];
|
||||
let stripped = false;
|
||||
for (const segment of segments) {
|
||||
if (!segment.isUserText || stripped) {
|
||||
if (segment.text.length > 0) result.push(segment);
|
||||
continue;
|
||||
}
|
||||
if (segment.text.trim().length === 0) continue;
|
||||
const remainder = segment.text.replace(prefixPattern, "");
|
||||
stripped = true;
|
||||
if (remainder.length > 0) result.push({ text: remainder, isUserText: true });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export async function prepareOpenCodePrompt(
|
||||
prompt: AgentPromptInput,
|
||||
loadCommands: () => Promise<readonly AgentSlashCommand[]>,
|
||||
): Promise<PreparedOpenCodePrompt> {
|
||||
const { segments, files } = splitPrompt(prompt);
|
||||
const userText = segments
|
||||
.filter((segment) => segment.isUserText)
|
||||
.map((segment) => segment.text)
|
||||
.join("\n")
|
||||
.trim();
|
||||
|
||||
// Only treat a leading /command or /compact as a slash command when the message starts with
|
||||
// user text. Preceding attachments (such as chat_history) keep the regular prompt path while
|
||||
// still scanning user text blocks for skill mentions.
|
||||
const leading = segments[0]?.isUserText ? userText.match(LEADING_SLASH_COMMAND) : null;
|
||||
if (leading?.[1] === "compact" || leading?.[1] === "summarize") {
|
||||
return { kind: "compact" };
|
||||
}
|
||||
|
||||
if (!leading && !hasSlashCandidate(segments)) {
|
||||
return { kind: "prompt", text: joinSegments(segments), files };
|
||||
}
|
||||
|
||||
const available = await loadCommands();
|
||||
const skillIds = new Set(
|
||||
available.filter((item) => item.kind === "skill").map((item) => item.name),
|
||||
);
|
||||
|
||||
if (leading) {
|
||||
const selected = available.find((item) => item.name === leading[1]);
|
||||
if (selected && selected.kind !== "skill") {
|
||||
const commandSegments = stripLeadingCommandFromSegments(segments, selected.name);
|
||||
const content = resolveSkillContent(commandSegments, skillIds, { allowFallback: false });
|
||||
return {
|
||||
kind: "command",
|
||||
name: selected.name,
|
||||
text: content.text,
|
||||
files,
|
||||
...(content.skills ? { skills: content.skills } : {}),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const content = resolveSkillContent(segments, skillIds, { allowFallback: true });
|
||||
return {
|
||||
kind: "prompt",
|
||||
text: content.text,
|
||||
files,
|
||||
...(content.skills ? { skills: content.skills } : {}),
|
||||
};
|
||||
}
|
||||
@@ -14,12 +14,11 @@ import type {
|
||||
|
||||
import { toDiagnosticErrorMessage } from "../../diagnostic-utils.js";
|
||||
|
||||
import { renderPromptAttachmentAsText } from "../../../prompt-attachments.js";
|
||||
|
||||
import { usageFromV2 } from "./mapping.js";
|
||||
import { latestTurnMetrics } from "./metrics.js";
|
||||
|
||||
import { commands } from "./commands.js";
|
||||
import { prepareOpenCodePrompt } from "./prompt-input.js";
|
||||
|
||||
import type { V2Api } from "./api.js";
|
||||
|
||||
@@ -235,7 +234,6 @@ export class SessionTurns {
|
||||
await this.stopping;
|
||||
if (this.options.signal.aborted) throw new Error("OpenCode session is closed");
|
||||
if (this.turn) throw new Error("OpenCode session already has an active turn");
|
||||
const input = this.promptInput(prompt);
|
||||
let accept!: () => void;
|
||||
const submitted = new Promise<void>((resolve) => {
|
||||
accept = resolve;
|
||||
@@ -243,12 +241,12 @@ export class SessionTurns {
|
||||
const output =
|
||||
options?.outputSchema === undefined ? undefined : structuredOutput(options.outputSchema);
|
||||
const turn = this.createTurn(submitted, false, output);
|
||||
void this.submit(turn, input, accept, options);
|
||||
void this.submit(turn, prompt, accept, options);
|
||||
return { turnId: turn.id };
|
||||
}
|
||||
private async submit(
|
||||
turn: Turn,
|
||||
input: ReturnType<SessionTurns["promptInput"]>,
|
||||
prompt: AgentPromptInput,
|
||||
accept: () => void,
|
||||
options?: AgentRunOptions,
|
||||
) {
|
||||
@@ -265,7 +263,7 @@ export class SessionTurns {
|
||||
} catch {
|
||||
// Keep the cached baselineIdleTime if the pre-dispatch read fails transiently.
|
||||
}
|
||||
await this.dispatch(input, options, turn.output);
|
||||
await this.dispatch(turn, prompt, options, turn.output);
|
||||
if (this.turn !== turn) return;
|
||||
turn.accepted = true;
|
||||
this.revision += 1;
|
||||
@@ -472,65 +470,57 @@ export class SessionTurns {
|
||||
if (this.turn === turn) this.fail(new Error(toDiagnosticErrorMessage(error)));
|
||||
}
|
||||
}
|
||||
private preparePrompt(prompt: AgentPromptInput) {
|
||||
return prepareOpenCodePrompt(prompt, () => commands(this.options.client(), this.options.cwd));
|
||||
}
|
||||
private async dispatch(
|
||||
input: ReturnType<SessionTurns["promptInput"]>,
|
||||
turn: Turn,
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentRunOptions,
|
||||
output?: ReturnType<typeof structuredOutput>,
|
||||
) {
|
||||
const command = input.text.match(/^\/([^\s]+)(?:\s+([\s\S]*))?$/);
|
||||
if (command?.[1] === "compact" || command?.[1] === "summarize") {
|
||||
const prepared = await this.preparePrompt(prompt);
|
||||
if (this.turn !== turn) return;
|
||||
if (prepared.kind === "compact") {
|
||||
await this.options.client().session.compact({ sessionID: this.options.id });
|
||||
return;
|
||||
}
|
||||
const selected = command
|
||||
? (await commands(this.options.client(), this.options.cwd)).find(
|
||||
(item) => item.name === command[1],
|
||||
)
|
||||
: undefined;
|
||||
if (selected && selected.kind !== "skill") {
|
||||
if (prepared.kind === "command") {
|
||||
await this.options.client().session.command({
|
||||
sessionID: this.options.id,
|
||||
name: selected.name,
|
||||
text: command?.[2] ?? "",
|
||||
files: input.files,
|
||||
name: prepared.name,
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
await this.options.client().session.prompt({
|
||||
sessionID: this.options.id,
|
||||
...input,
|
||||
...(selected?.kind === "skill"
|
||||
? {
|
||||
skills: [{ id: selected.name }],
|
||||
text: command?.[2] ?? `Use the ${selected.name} skill.`,
|
||||
}
|
||||
: {}),
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
metadata: {
|
||||
...(options?.clientMessageId ? { paseoClientMessageId: options.clientMessageId } : {}),
|
||||
...(output ? { paseoOutputSchema: output.schema } : {}),
|
||||
},
|
||||
});
|
||||
}
|
||||
private promptInput(prompt: AgentPromptInput) {
|
||||
if (typeof prompt === "string") return { text: prompt, files: [] };
|
||||
const text: string[] = [];
|
||||
const files: Array<{ uri: string }> = [];
|
||||
for (const part of prompt) {
|
||||
if (part.type === "text") text.push(part.text);
|
||||
else if (part.type === "image")
|
||||
files.push({ uri: `data:${part.mimeType};base64,${part.data}` });
|
||||
else text.push(renderPromptAttachmentAsText(part));
|
||||
}
|
||||
return { text: text.join("\n"), files };
|
||||
}
|
||||
async steerActiveTurn(
|
||||
prompt: AgentPromptInput,
|
||||
options: SteerActiveTurnOptions,
|
||||
): Promise<SteerResult> {
|
||||
if (this.turn?.id !== options.expectedTurnId || this.stopping) return { status: "unavailable" };
|
||||
const prepared = await this.preparePrompt(prompt);
|
||||
// Commands (including compact/summarize) cannot be steered into a running turn; let
|
||||
// AgentManager replace the turn so dispatch() executes them. Skills steer natively.
|
||||
if (prepared.kind !== "prompt") return { status: "unavailable" };
|
||||
if (this.turn?.id !== options.expectedTurnId || this.stopping) return { status: "unavailable" };
|
||||
await this.options.client().session.prompt({
|
||||
sessionID: this.options.id,
|
||||
...this.promptInput(prompt),
|
||||
text: prepared.text,
|
||||
files: prepared.files,
|
||||
...(prepared.skills ? { skills: prepared.skills } : {}),
|
||||
delivery: "steer",
|
||||
metadata: options.clientMessageId
|
||||
? { paseoClientMessageId: options.clientMessageId }
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
import { daemonLaunchEnvironment } from "./config-environment.js";
|
||||
|
||||
describe("daemonLaunchEnvironment AppImage sanitization", () => {
|
||||
describe("daemonLaunchEnvironment", () => {
|
||||
const appDir = "/tmp/.mount_Paseo-abcdef";
|
||||
|
||||
test("strips AppImage runtime variables in both managed and deployment modes", () => {
|
||||
@@ -47,6 +47,40 @@ describe("daemonLaunchEnvironment AppImage sanitization", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["Paseo.desktop", "paseo-desktop.desktop"])(
|
||||
"keeps the desktop identity %s out of a Linux managed daemon",
|
||||
(identity) => {
|
||||
const inputEnv = {
|
||||
CHROME_DESKTOP: identity,
|
||||
PASEO_DESKTOP_SANDBOX_REASON: "user namespaces available",
|
||||
PATH: "/usr/bin",
|
||||
};
|
||||
const result = daemonLaunchEnvironment({
|
||||
env: inputEnv,
|
||||
home: "/home/user/.paseo",
|
||||
mode: "managed",
|
||||
desktopManaged: true,
|
||||
platform: "linux",
|
||||
});
|
||||
|
||||
expect(result.CHROME_DESKTOP).toBeUndefined();
|
||||
expect(result.PASEO_DESKTOP_SANDBOX_REASON).toBeUndefined();
|
||||
expect(result.PATH).toBe("/usr/bin");
|
||||
expect(result.PASEO_DESKTOP_MANAGED).toBe("1");
|
||||
expect(inputEnv.CHROME_DESKTOP).toBe(identity);
|
||||
},
|
||||
);
|
||||
|
||||
test("preserves an unrelated Chromium desktop identity", () => {
|
||||
const result = daemonLaunchEnvironment({
|
||||
env: { CHROME_DESKTOP: "chromium.desktop" },
|
||||
home: "/home/user/.paseo",
|
||||
mode: "deployment",
|
||||
platform: "linux",
|
||||
});
|
||||
expect(result.CHROME_DESKTOP).toBe("chromium.desktop");
|
||||
});
|
||||
|
||||
test("preserves user ARGV0 without APPIMAGE or APPDIR", () => {
|
||||
const result = daemonLaunchEnvironment({
|
||||
env: {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { stripAppImageRuntimeEnv } from "./paseo-env.js";
|
||||
import { stripLinuxDesktopRuntimeEnv } from "./paseo-env.js";
|
||||
|
||||
// Daemon configuration inputs. General provider credentials and executable/runtime
|
||||
// controls remain available to managed launches and their agent processes.
|
||||
@@ -90,7 +90,7 @@ export function daemonLaunchEnvironment(input: {
|
||||
}
|
||||
delete env.PASEO_HOST;
|
||||
delete env.PASEO_DESKTOP_MANAGED;
|
||||
stripAppImageRuntimeEnv(env, { platform: input.platform });
|
||||
stripLinuxDesktopRuntimeEnv(env, { platform: input.platform });
|
||||
env.PASEO_HOME = input.home;
|
||||
if (input.desktopManaged) env.PASEO_DESKTOP_MANAGED = "1";
|
||||
return env;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { once } from "node:events";
|
||||
import { readFile, writeFile } from "node:fs/promises";
|
||||
import type { Socket } from "node:net";
|
||||
import { writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { deflateRawSync } from "node:zlib";
|
||||
@@ -10,7 +11,11 @@ import { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { createHostChannelTransport } from "@getpaseo/client/node";
|
||||
import { ConnectionOfferSchema } from "@getpaseo/protocol/connection-offer";
|
||||
import { buildRelayWebSocketUrl } from "@getpaseo/protocol/daemon-endpoints";
|
||||
import { FRAME_CODEC_DEFLATE_RAW, type FrameCodec } from "@getpaseo/protocol/frame-transport";
|
||||
import {
|
||||
DEFAULT_FRAME_COMPRESSION_MIN_BYTES,
|
||||
FRAME_CODEC_DEFLATE_RAW,
|
||||
type FrameCodec,
|
||||
} from "@getpaseo/protocol/frame-transport";
|
||||
import { createNodeDeflateRawCodec } from "@getpaseo/protocol/node-frame-codec";
|
||||
import { createWebDeflateRawCodec } from "@getpaseo/protocol/web-frame-codec";
|
||||
import { describe, expect, test } from "vitest";
|
||||
@@ -104,11 +109,76 @@ function createMeteredWebSocketFactory(): {
|
||||
return { webSocketFactory, stats };
|
||||
}
|
||||
|
||||
/**
|
||||
* Deterministic TypeScript-shaped text. It compresses like real source code (about 0.27 with
|
||||
* deflate-raw) without depending on files in this repo, which change and differ in line endings.
|
||||
*/
|
||||
function sourceFixture(chars: number, seed = 1): string {
|
||||
let state = seed >>> 0;
|
||||
const next = () => {
|
||||
state = (Math.imul(state, 1103515245) + 12345) >>> 0;
|
||||
return state >>> 8;
|
||||
};
|
||||
const words = [
|
||||
"const",
|
||||
"return",
|
||||
"await",
|
||||
"transport",
|
||||
"frame",
|
||||
"codec",
|
||||
"message",
|
||||
"session",
|
||||
"if",
|
||||
"export",
|
||||
"function",
|
||||
"client",
|
||||
"daemon",
|
||||
"bytes",
|
||||
"payload",
|
||||
"encode",
|
||||
"decode",
|
||||
"error",
|
||||
"handler",
|
||||
"queue",
|
||||
"=",
|
||||
"(",
|
||||
")",
|
||||
"{",
|
||||
"}",
|
||||
"=>",
|
||||
];
|
||||
const lines: string[] = [];
|
||||
let length = 0;
|
||||
while (length < chars) {
|
||||
const tokens: string[] = [];
|
||||
const count = 3 + (next() % 8);
|
||||
for (let i = 0; i < count; i++) {
|
||||
const word = words[next() % words.length]!;
|
||||
tokens.push(next() % 4 === 0 ? `${word}${next() % 1000}` : word);
|
||||
}
|
||||
const line = `${" ".repeat(next() % 4)}${tokens.join(" ")};`;
|
||||
lines.push(line);
|
||||
length += line.length + 1;
|
||||
}
|
||||
return lines.join("\n").slice(0, chars);
|
||||
}
|
||||
|
||||
function diffMarker(lineIndex: number): string {
|
||||
if (lineIndex % 7 === 0) return "+";
|
||||
if (lineIndex % 11 === 0) return "-";
|
||||
return " ";
|
||||
}
|
||||
|
||||
/** Wire frames that a codec compressed (FrameTransport opcode 0x31 with the ENCODED flag). */
|
||||
function isEncodedFrame(frame: { opcode: number | null; flags: number | null }): boolean {
|
||||
return frame.opcode === 0x31 && ((frame.flags ?? 0) & 0x04) !== 0;
|
||||
}
|
||||
|
||||
const nodeMajor = Number((process.versions.node ?? "0").split(".")[0] ?? "0");
|
||||
const shouldRunRelayE2e = process.env.FORCE_RELAY_E2E === "1" || nodeMajor < 25;
|
||||
|
||||
describe("FrameTransport deflate-raw E2E", () => {
|
||||
test("negotiates deflate-raw with Node and Web codecs, leaves hello/server_info/small frames uncompressed, and interoperates with legacy clients", async () => {
|
||||
test("negotiates deflate-raw with Node and Web codecs, leaves hello/server_info/small frames uncompressed, skips loopback by default, and interoperates with legacy clients", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const clients: DaemonClient[] = [];
|
||||
try {
|
||||
@@ -126,25 +196,26 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
return setup.createAgent({ provider: "claude", cwd: daemon.staticDir });
|
||||
})();
|
||||
|
||||
// Populate agent timeline with real unique Paseo source code
|
||||
const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const sourceText = await readFile(
|
||||
path.resolve(serverRoot, "src/server/websocket-server.ts"),
|
||||
"utf8",
|
||||
);
|
||||
const slice = sourceText.slice(0, 60_000);
|
||||
const slice = sourceFixture(60_000);
|
||||
await daemon.daemon.agentManager.appendTimelineItem(agent.id, {
|
||||
type: "assistant_message",
|
||||
text: slice,
|
||||
});
|
||||
|
||||
const runWith = async (label: string, frameCodecs?: readonly FrameCodec[]) => {
|
||||
// Loopback connections advertise codecs only when the caller lists them explicitly.
|
||||
const advertise = { frame_codecs: [FRAME_CODEC_DEFLATE_RAW] };
|
||||
const runWith = async (
|
||||
label: string,
|
||||
frameCodecs?: readonly FrameCodec[],
|
||||
capabilities?: typeof advertise,
|
||||
) => {
|
||||
const metered = createMeteredWebSocketFactory();
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
clientId: `e2e-${label}`,
|
||||
webSocketFactory: metered.webSocketFactory,
|
||||
...(frameCodecs ? { frameCodecs } : {}),
|
||||
...(capabilities ? { capabilities } : {}),
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
clients.push(client);
|
||||
@@ -168,9 +239,7 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
);
|
||||
expect(matched).toBeDefined();
|
||||
const timelineInboundBytes = metered.stats.totalInboundBytes;
|
||||
const usedCompressedFrame = metered.stats.inboundFrames.some(
|
||||
(f) => f.isBinary && f.opcode === 0x31 && f.flags === 0x07,
|
||||
);
|
||||
const usedCompressedFrame = metered.stats.inboundFrames.some(isEncodedFrame);
|
||||
|
||||
// Incompressible random binary upload must fall through uncompressed
|
||||
metered.stats.reset();
|
||||
@@ -182,24 +251,24 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
});
|
||||
expect(upload.error).toBeNull();
|
||||
expect(upload.file?.size).toBe(randomBuf.byteLength);
|
||||
const compressedRandomUpload = metered.stats.outboundFrames.some(
|
||||
(f) => f.isBinary && f.opcode === 0x31 && ((f.flags ?? 0) & 0x04) !== 0,
|
||||
);
|
||||
const compressedRandomUpload = metered.stats.outboundFrames.some(isEncodedFrame);
|
||||
|
||||
return { timelineInboundBytes, usedCompressedFrame, compressedRandomUpload };
|
||||
};
|
||||
|
||||
const legacy = await runWith("legacy", undefined);
|
||||
const nodeRes = await runWith("node", [createNodeDeflateRawCodec()]);
|
||||
const webRes = await runWith("web", [webCodec!]);
|
||||
const loopback = await runWith("loopback", [createNodeDeflateRawCodec()]);
|
||||
const nodeRes = await runWith("node", [createNodeDeflateRawCodec()], advertise);
|
||||
const webRes = await runWith("web", [webCodec!], advertise);
|
||||
|
||||
expect(legacy.usedCompressedFrame).toBe(false);
|
||||
expect(loopback.usedCompressedFrame).toBe(false);
|
||||
expect(nodeRes.usedCompressedFrame).toBe(true);
|
||||
expect(webRes.usedCompressedFrame).toBe(true);
|
||||
|
||||
// Both Node and Web codecs must cut real wire bytes by > 65%
|
||||
expect(nodeRes.timelineInboundBytes).toBeLessThan(legacy.timelineInboundBytes * 0.35);
|
||||
expect(webRes.timelineInboundBytes).toBeLessThan(legacy.timelineInboundBytes * 0.35);
|
||||
// Both Node and Web codecs must cut wire bytes to < 35% of the raw timeline text
|
||||
expect(nodeRes.timelineInboundBytes).toBeLessThan(slice.length * 0.35);
|
||||
expect(webRes.timelineInboundBytes).toBeLessThan(slice.length * 0.35);
|
||||
|
||||
// Random upload must NOT be sent with ENCODED flag
|
||||
expect(nodeRes.compressedRandomUpload).toBe(false);
|
||||
@@ -210,6 +279,106 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("answers a hello that advertises a codec with server_info as plain text, even when server_info is large enough to compress", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const socket = new WebSocket(`ws://127.0.0.1:${daemon.port}/ws`);
|
||||
try {
|
||||
await once(socket, "open");
|
||||
const reply = once(socket, "message");
|
||||
socket.send(
|
||||
JSON.stringify({
|
||||
type: "hello",
|
||||
clientId: "server-info-plain-text",
|
||||
clientType: "cli",
|
||||
protocolVersion: 1,
|
||||
capabilities: { binary_chunking_v1: true, frame_codecs: [FRAME_CODEC_DEFLATE_RAW] },
|
||||
}),
|
||||
);
|
||||
const [data, isBinary] = (await reply) as [Buffer, boolean];
|
||||
|
||||
// The client selects its codec from server_info, and the relay E2EE downgrade check reads
|
||||
// server_info as text, so it must arrive before the negotiated codec applies.
|
||||
expect(isBinary).toBe(false);
|
||||
expect(data.byteLength).toBeGreaterThanOrEqual(DEFAULT_FRAME_COMPRESSION_MIN_BYTES);
|
||||
expect(JSON.parse(data.toString("utf8"))).toMatchObject({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "status",
|
||||
payload: { status: "server_info", features: { frameCodecs: [FRAME_CODEC_DEFLATE_RAW] } },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
socket.terminate();
|
||||
await daemon.close();
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test("applies compressed requests the daemon received before the client dropped the connection", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
try {
|
||||
const setup = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
clientId: "abrupt-setup",
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
await setup.connect();
|
||||
const agent = await setup.createAgent({ provider: "claude", cwd: daemon.staticDir });
|
||||
await setup.close();
|
||||
|
||||
const attempts = 20;
|
||||
for (let attempt = 0; attempt < attempts; attempt++) {
|
||||
let requestWritten!: () => void;
|
||||
const written = new Promise<void>((resolve) => {
|
||||
requestWritten = resolve;
|
||||
});
|
||||
let connected = false;
|
||||
// A socket error (here, a frame with reserved bits set) reaches the daemon as error
|
||||
// followed by close; a terminated connection reaches it as close alone.
|
||||
const dropWithError = attempt % 4 >= 2;
|
||||
const client = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${daemon.port}/ws`,
|
||||
clientId: `abrupt-${attempt}`,
|
||||
frameCodecs: [createNodeDeflateRawCodec()],
|
||||
capabilities: { frame_codecs: [FRAME_CODEC_DEFLATE_RAW] },
|
||||
webSocketFactory: (url: string) => {
|
||||
const socket = new WebSocket(url);
|
||||
const send = socket.send.bind(socket);
|
||||
socket.send = ((data: Parameters<WebSocket["send"]>[0], ...rest: unknown[]) => {
|
||||
(send as (...args: unknown[]) => void)(data, ...rest);
|
||||
if (!connected) return;
|
||||
// Process exit, app kill, or a dropped TCP connection right after the write.
|
||||
if (dropWithError) {
|
||||
const raw = (socket as unknown as { _socket: Socket })._socket;
|
||||
raw.write(Buffer.from([0xf1, 0x80, 0, 0, 0, 0]));
|
||||
} else socket.terminate();
|
||||
requestWritten();
|
||||
}) as WebSocket["send"];
|
||||
return socket;
|
||||
},
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
await client.connect();
|
||||
connected = true;
|
||||
// ~1.5 KB crosses the compression threshold and decodes on the event loop;
|
||||
// 300 KB decodes on the libuv threadpool and finishes after the socket closed.
|
||||
const labelBytes = attempt % 2 === 0 ? 1_500 : 300_000;
|
||||
void client
|
||||
.updateAgent(agent.id, { labels: { [`attempt-${attempt}`]: "x".repeat(labelBytes) } })
|
||||
.catch(() => undefined);
|
||||
await written;
|
||||
await client.close();
|
||||
}
|
||||
|
||||
const appliedAttempts = () =>
|
||||
Object.keys(daemon.daemon.agentManager.getAgent(agent.id)?.labels ?? {}).filter((key) =>
|
||||
key.startsWith("attempt-"),
|
||||
).length;
|
||||
await expect.poll(appliedAttempts, { timeout: 10_000 }).toBe(attempts);
|
||||
} finally {
|
||||
await daemon.close();
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("daemon rejects a decompression bomb with close code 1002 while staying healthy for other clients", async () => {
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
let healthy: DaemonClient | undefined;
|
||||
@@ -266,35 +435,43 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
if (!address || typeof address === "string") throw new Error("Missing server address");
|
||||
|
||||
const closeCodes: number[] = [];
|
||||
const sendBombAfterHello = (ws: WebSocket) => {
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "server_info",
|
||||
serverId: "malicious-srv",
|
||||
hostname: "malicious",
|
||||
version: "0.19.1",
|
||||
features: {
|
||||
binaryChunkingV1: true,
|
||||
frameCodecs: [FRAME_CODEC_DEFLATE_RAW],
|
||||
},
|
||||
const advertised: unknown[] = [];
|
||||
const serverInfo = (hostname: string) =>
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
message: {
|
||||
type: "status",
|
||||
payload: {
|
||||
status: "server_info",
|
||||
serverId: "malicious-srv",
|
||||
hostname,
|
||||
version: "0.19.1",
|
||||
features: {
|
||||
binaryChunkingV1: true,
|
||||
frameCodecs: [FRAME_CODEC_DEFLATE_RAW],
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
// Send 110 MiB zero-filled zip bomb (~110 KB on wire)
|
||||
const bomb = deflateRawSync(Buffer.alloc(110 * 1024 * 1024), { level: 9 });
|
||||
const wire = new Uint8Array(4 + bomb.byteLength);
|
||||
},
|
||||
});
|
||||
const encodedText = (text: string, raw = Buffer.from(text, "utf8")) => {
|
||||
const body = deflateRawSync(raw, { level: 9 });
|
||||
const wire = new Uint8Array(4 + body.byteLength);
|
||||
wire.set([0x31, 1, 0, 0x07]);
|
||||
wire.set(bomb, 4);
|
||||
ws.send(wire);
|
||||
wire.set(body, 4);
|
||||
return wire;
|
||||
};
|
||||
// A valid compressed frame proves the codec negotiated before the bomb tests its limit.
|
||||
const validHostname = `compressed-${"x".repeat(4096)}`;
|
||||
const sendBombAfterHello = (ws: WebSocket, hello: Buffer) => {
|
||||
advertised.push(JSON.parse(hello.toString("utf8")).capabilities?.frame_codecs);
|
||||
ws.send(serverInfo("malicious"));
|
||||
ws.send(encodedText(serverInfo(validHostname)));
|
||||
// 110 MiB zero-filled zip bomb (~110 KB on wire)
|
||||
ws.send(encodedText("", Buffer.alloc(110 * 1024 * 1024)));
|
||||
};
|
||||
const handleConnection = (ws: WebSocket) => {
|
||||
ws.on("close", (code) => closeCodes.push(code));
|
||||
ws.once("message", () => sendBombAfterHello(ws));
|
||||
ws.once("message", (data: Buffer) => sendBombAfterHello(ws, data));
|
||||
};
|
||||
wss.on("connection", handleConnection);
|
||||
|
||||
@@ -304,11 +481,21 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
url: `ws://127.0.0.1:${address.port}`,
|
||||
clientId: "victim-client",
|
||||
frameCodecs: [webCodec!],
|
||||
// Loopback connections advertise codecs only when the caller lists them.
|
||||
capabilities: { frame_codecs: [FRAME_CODEC_DEFLATE_RAW] },
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
const hostnames: string[] = [];
|
||||
client.subscribeRawMessages((message) => {
|
||||
if (message.type === "status" && message.payload.status === "server_info") {
|
||||
hostnames.push(String(message.payload.hostname));
|
||||
}
|
||||
});
|
||||
try {
|
||||
await client.connect();
|
||||
await expect.poll(() => closeCodes[0], { timeout: 10_000 }).toBe(4003);
|
||||
expect(advertised).toEqual([[FRAME_CODEC_DEFLATE_RAW]]);
|
||||
expect(hostnames).toContain(validHostname);
|
||||
} finally {
|
||||
await client.close();
|
||||
await new Promise<void>((resolve) => wss.close(() => resolve()));
|
||||
@@ -316,7 +503,7 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
}, 30_000);
|
||||
|
||||
(shouldRunRelayE2e ? test : test.skip)(
|
||||
"measures real wire bytes and latency over local E2EE relay (ProtectedChannel Noise_NK) on real Paseo workloads",
|
||||
"measures real wire bytes and latency over local E2EE relay (ProtectedChannel Noise_NK) on Paseo-shaped workloads",
|
||||
async () => {
|
||||
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../../../..");
|
||||
const relayDir = path.resolve(repoRoot, "packages/relay");
|
||||
@@ -398,42 +585,13 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
role: "client",
|
||||
});
|
||||
|
||||
const tsFiles = [
|
||||
"packages/protocol/src/frame-transport.ts",
|
||||
"packages/protocol/src/client-capabilities.ts",
|
||||
"packages/relay/src/secure-channel.ts",
|
||||
"packages/relay/src/protected-records.ts",
|
||||
"packages/client/src/daemon-client-websocket-transport.ts",
|
||||
"packages/client/src/daemon-client-relay-e2ee-transport.ts",
|
||||
"packages/server/src/server/websocket/encrypted-relay-socket.ts",
|
||||
"packages/server/src/server/websocket/physical-socket.ts",
|
||||
];
|
||||
const tsContents = await Promise.all(
|
||||
tsFiles.map((f) => readFile(path.resolve(repoRoot, f), "utf8")),
|
||||
);
|
||||
const syntheticDiffChunks: string[] = [];
|
||||
for (let i = 0; i < tsFiles.length; i++) {
|
||||
const lines = tsContents[i]!.split("\n");
|
||||
syntheticDiffChunks.push(
|
||||
`diff --git a/${tsFiles[i]} b/${tsFiles[i]}\n--- a/${tsFiles[i]}\n+++ b/${tsFiles[i]}\n@@ -1,${lines.length} +1,${lines.length} @@\n`,
|
||||
);
|
||||
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
|
||||
let prefix = " ";
|
||||
if (lineIndex % 7 === 0) prefix = "+";
|
||||
else if (lineIndex % 11 === 0) prefix = "-";
|
||||
syntheticDiffChunks.push(`${prefix}${lines[lineIndex]}\n`);
|
||||
}
|
||||
}
|
||||
const gitDiffText = syntheticDiffChunks.join("").repeat(4).slice(0, 220_000);
|
||||
const largeFileContent = await readFile(
|
||||
path.resolve(repoRoot, "packages/client/src/daemon-client-core.ts"),
|
||||
"utf8",
|
||||
);
|
||||
await writeFile(
|
||||
path.join(daemon.staticDir, "daemon-client-core.ts"),
|
||||
largeFileContent,
|
||||
"utf8",
|
||||
);
|
||||
const timelineTexts = Array.from({ length: 8 }, (_, i) => sourceFixture(24_000, i + 1));
|
||||
const gitDiffText = sourceFixture(220_000, 99)
|
||||
.split("\n")
|
||||
.map((line, i) => `${diffMarker(i)}${line}`)
|
||||
.join("\n");
|
||||
const largeFileContent = sourceFixture(311_000, 7);
|
||||
await writeFile(path.join(daemon.staticDir, "large-file.ts"), largeFileContent, "utf8");
|
||||
const base64Image = randomBytes(150 * 1024).toString("base64");
|
||||
const randomUploadBytes = new Uint8Array(randomBytes(200 * 1024));
|
||||
|
||||
@@ -448,12 +606,11 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
cwd: daemon.staticDir,
|
||||
});
|
||||
let expectedTimelineChars = 0;
|
||||
for (let i = 0; i < tsContents.length; i++) {
|
||||
const text = `// File: ${tsFiles[i]}\n${tsContents[i]}`;
|
||||
expectedTimelineChars += text.length;
|
||||
for (let i = 0; i < timelineTexts.length; i++) {
|
||||
expectedTimelineChars += timelineTexts[i]!.length;
|
||||
await daemon.daemon.agentManager.appendTimelineItem(timelineAgent.id, {
|
||||
type: i % 2 === 0 ? "user_message" : "assistant_message",
|
||||
text,
|
||||
text: timelineTexts[i]!,
|
||||
});
|
||||
}
|
||||
const diffAgent = await seedClient.createAgent({
|
||||
@@ -524,7 +681,7 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
|
||||
const rows: Measurement[] = [];
|
||||
rows.push(
|
||||
await measure("Timeline sync (8 real TS files)", async () => {
|
||||
await measure("Timeline sync (8 x 24 KB source text)", async () => {
|
||||
const res = await client.fetchAgentTimeline(timelineAgent.id, {
|
||||
projection: "canonical",
|
||||
});
|
||||
@@ -532,7 +689,7 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
}),
|
||||
);
|
||||
rows.push(
|
||||
await measure("Real git diff (220 KB in timeline)", async () => {
|
||||
await measure("Git diff (220 KB in timeline)", async () => {
|
||||
const res = await client.fetchAgentTimeline(diffAgent.id, {
|
||||
projection: "canonical",
|
||||
});
|
||||
@@ -540,8 +697,8 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
}),
|
||||
);
|
||||
rows.push(
|
||||
await measure("File read (311 KB TS file via binary stream)", async () => {
|
||||
const res = await client.readFile(daemon.staticDir, "daemon-client-core.ts");
|
||||
await measure("File read (311 KB source file via binary stream)", async () => {
|
||||
const res = await client.readFile(daemon.staticDir, "large-file.ts");
|
||||
expect(res.bytes.byteLength).toBe(Buffer.byteLength(largeFileContent, "utf8"));
|
||||
}),
|
||||
);
|
||||
@@ -596,13 +753,15 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
);
|
||||
}
|
||||
|
||||
// Assert >70% wire reduction on timeline, diff, and file read; >35% on base64 PNG; ~0% delta on random binary and pings
|
||||
expect(nodeRes[0]!.bytes).toBeLessThan(baseline[0]!.bytes * 0.3);
|
||||
expect(nodeRes[1]!.bytes).toBeLessThan(baseline[1]!.bytes * 0.25);
|
||||
expect(nodeRes[2]!.bytes).toBeLessThan(baseline[2]!.bytes * 0.25);
|
||||
expect(nodeRes[3]!.bytes).toBeLessThan(baseline[3]!.bytes * 0.65);
|
||||
expect(webRes[0]!.bytes).toBeLessThan(baseline[0]!.bytes * 0.3);
|
||||
expect(webRes[1]!.bytes).toBeLessThan(baseline[1]!.bytes * 0.25);
|
||||
// Compressed wire bytes are measured against the raw payload, so a change to how the
|
||||
// uncompressed path frames bytes cannot move the bar. Source text compresses to ~0.27.
|
||||
for (const res of [nodeRes, webRes]) {
|
||||
expect(res[0]!.bytes).toBeLessThan(expectedTimelineChars * 0.35);
|
||||
expect(res[1]!.bytes).toBeLessThan(gitDiffText.length * 0.35);
|
||||
expect(res[2]!.bytes).toBeLessThan(largeFileContent.length * 0.35);
|
||||
// Base64 carries 6 bits per byte, so deflate saves about a quarter of it.
|
||||
expect(res[3]!.bytes).toBeLessThan(base64Image.length * 0.8);
|
||||
}
|
||||
// Incompressible random upload should not expand (< 1% overhead)
|
||||
expect(nodeRes[4]!.bytes).toBeLessThanOrEqual(baseline[4]!.bytes * 1.01);
|
||||
// Small frames (ping/pong) must stay uncompressed (within requestId/timestamp variance)
|
||||
@@ -638,21 +797,21 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
provider: "claude",
|
||||
cwd: targetDaemon.staticDir,
|
||||
});
|
||||
const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
|
||||
const largeText = (
|
||||
await readFile(path.resolve(serverRoot, "src/server/websocket-server.ts"), "utf8")
|
||||
).slice(0, 48_000);
|
||||
const largeText = sourceFixture(48_000);
|
||||
await targetDaemon.daemon.agentManager.appendTimelineItem(targetAgent.id, {
|
||||
type: "assistant_message",
|
||||
text: largeText,
|
||||
});
|
||||
await writeFile(path.join(targetDaemon.staticDir, "routed-sample.ts"), largeText, "utf8");
|
||||
|
||||
// Register target daemon on origin daemon and wait for the host link to come online
|
||||
// Register target daemon on origin daemon and wait for the host link to come online.
|
||||
// The origin session is loopback, so it carries routed frames without compressing them.
|
||||
const originWire = createMeteredWebSocketFactory();
|
||||
const originClient = new DaemonClient({
|
||||
url: `ws://127.0.0.1:${originDaemon.port}/ws`,
|
||||
clientId: "routed-origin-client",
|
||||
frameCodecs: [webCodec!],
|
||||
webSocketFactory: originWire.webSocketFactory,
|
||||
reconnect: { enabled: false },
|
||||
});
|
||||
clients.push(originClient);
|
||||
@@ -721,6 +880,9 @@ describe("FrameTransport deflate-raw E2E", () => {
|
||||
// Confirm real inner 0x31 ENCODED frames traversed the routed host channel and saved > 65%
|
||||
expect(routedEncodedInbound.length).toBeGreaterThanOrEqual(2);
|
||||
expect(Math.max(...routedEncodedInbound)).toBeLessThan(largeText.length * 0.35);
|
||||
// The loopback origin socket carries those frames as they are, compressed once end to end.
|
||||
expect(originWire.stats.inboundFrames.some(isEncodedFrame)).toBe(false);
|
||||
expect(originWire.stats.outboundFrames.some(isEncodedFrame)).toBe(false);
|
||||
|
||||
// Verify createPaseoApi(originClient).hosts.client(serverId) inherits origin's frameCodecs
|
||||
const sdkEncodedInbound: number[] = [];
|
||||
|
||||
@@ -159,17 +159,25 @@ function sseChunk(delta: Record<string, unknown>, finishReason: string | null):
|
||||
* An OpenAI-compatible model that calls OMP's `ask` tool once with `html`, then
|
||||
* replies with the tool's result so the test can read what OMP received.
|
||||
*/
|
||||
async function startScriptedAskModel(html: string): Promise<ScriptedModel> {
|
||||
async function startScriptedModel(options: {
|
||||
askHtml?: string;
|
||||
onSystemPrompt?: (text: string) => void;
|
||||
}): Promise<ScriptedModel> {
|
||||
const server: Server = createServer((request, response) => {
|
||||
void readBody(request).then((body) => {
|
||||
const payload = JSON.parse(body || "{}") as {
|
||||
tools?: Array<{ function?: { name?: string } }>;
|
||||
messages?: Array<{ role?: string; content?: unknown }>;
|
||||
};
|
||||
const systemPrompt = payload.messages
|
||||
?.filter((message) => message.role === "system")
|
||||
.map((message) => message.content)
|
||||
.join("\n");
|
||||
options.onSystemPrompt?.(systemPrompt ?? "");
|
||||
const toolMessage = payload.messages?.find((message) => message.role === "tool");
|
||||
const offersAsk = payload.tools?.some((tool) => tool.function?.name === "ask") ?? false;
|
||||
response.writeHead(200, { "content-type": "text/event-stream" });
|
||||
if (!toolMessage && offersAsk) {
|
||||
if (options.askHtml !== undefined && !toolMessage && offersAsk) {
|
||||
response.write(
|
||||
sseChunk(
|
||||
{
|
||||
@@ -179,7 +187,7 @@ async function startScriptedAskModel(html: string): Promise<ScriptedModel> {
|
||||
index: 0,
|
||||
id: "call_ask_1",
|
||||
type: "function",
|
||||
function: { name: "ask", arguments: JSON.stringify({ html }) },
|
||||
function: { name: "ask", arguments: JSON.stringify({ html: options.askHtml }) },
|
||||
},
|
||||
],
|
||||
},
|
||||
@@ -382,6 +390,41 @@ async function contextWindowUsedTokens(client: DaemonClient, agentId: string) {
|
||||
}
|
||||
|
||||
describe("daemon E2E (real OMP)", () => {
|
||||
test(
|
||||
"appends Paseo instructions to the discovered OMP workspace prompt",
|
||||
async () => {
|
||||
const prompts: string[] = [];
|
||||
const model = await startScriptedModel({ onSystemPrompt: (text) => prompts.push(text) });
|
||||
try {
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl }),
|
||||
});
|
||||
try {
|
||||
const configDir = path.join(harness.cwd, ".omp");
|
||||
mkdirSync(configDir);
|
||||
writeFileSync(path.join(configDir, "APPEND_SYSTEM.md"), "OMP_WORKSPACE_PROMPT");
|
||||
const agent = await harness.client.createAgent({
|
||||
cwd: harness.cwd,
|
||||
title: "system prompts",
|
||||
provider: "omp",
|
||||
model: "offline/offline-1",
|
||||
systemPrompt: "PASEO_APPEND_PROMPT",
|
||||
});
|
||||
await harness.client.sendMessage(agent.id, "Say hi.");
|
||||
const finish = await harness.client.waitForFinish(agent.id, TIMEOUT_MS);
|
||||
expect(finish.status).toBe("idle");
|
||||
expect(prompts).toEqual([expect.stringContaining("PASEO_APPEND_PROMPT")]);
|
||||
expect(prompts[0]?.includes("OMP_WORKSPACE_PROMPT")).toBe(true);
|
||||
} finally {
|
||||
await closeHarness(harness);
|
||||
}
|
||||
} finally {
|
||||
await model.close();
|
||||
}
|
||||
},
|
||||
TIMEOUT_MS,
|
||||
);
|
||||
|
||||
test(
|
||||
"an idle out-of-band follow-up starts a turn",
|
||||
async () => {
|
||||
@@ -552,7 +595,7 @@ describe("daemon E2E (real OMP)", () => {
|
||||
"an OMP 19.1+ HTML ask form is answered from the question card",
|
||||
async (context) => {
|
||||
await skipUnlessOmpSendsForms(context);
|
||||
const model = await startScriptedAskModel(COLOR_FORM);
|
||||
const model = await startScriptedModel({ askHtml: COLOR_FORM });
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl }),
|
||||
});
|
||||
@@ -592,7 +635,7 @@ describe("daemon E2E (real OMP)", () => {
|
||||
"an OMP 19.1+ HTML ask that times out in OMP closes its question card",
|
||||
async (context) => {
|
||||
await skipUnlessOmpSendsForms(context);
|
||||
const model = await startScriptedAskModel(COLOR_FORM);
|
||||
const model = await startScriptedModel({ askHtml: COLOR_FORM });
|
||||
const harness = await createHarness({
|
||||
ompHome: createOfflineOmpHome({ baseUrl: model.baseUrl, askTimeoutSeconds: 2 }),
|
||||
});
|
||||
|
||||
@@ -66,6 +66,15 @@ describe("paseo env contract", () => {
|
||||
expect(env.PATH).toBe("/custom/bin");
|
||||
});
|
||||
|
||||
test.runIf(process.platform === "linux")("strips Paseo desktop metadata after overlays", () => {
|
||||
const env = createExternalProcessEnv(baseEnv, {
|
||||
CHROME_DESKTOP: "Paseo.desktop",
|
||||
PASEO_DESKTOP_SANDBOX_REASON: "user namespaces available",
|
||||
});
|
||||
expect(env.CHROME_DESKTOP).toBeUndefined();
|
||||
expect(env.PASEO_DESKTOP_SANDBOX_REASON).toBeUndefined();
|
||||
});
|
||||
|
||||
test("applies non-control overlays to external process env", () => {
|
||||
const env = createExternalProcessEnv(baseEnv, { PATH: "/custom/bin" }, { CUSTOM: "value" });
|
||||
|
||||
|
||||
@@ -89,6 +89,21 @@ export function stripAppImageRuntimeEnv(
|
||||
}
|
||||
}
|
||||
|
||||
/** Keep Linux launcher metadata in the desktop process that owns it. */
|
||||
export function stripLinuxDesktopRuntimeEnv(
|
||||
env: ProcessEnvRecord,
|
||||
options?: { platform?: NodeJS.Platform },
|
||||
): void {
|
||||
const platform = options?.platform ?? process.platform;
|
||||
if (platform !== "linux") return;
|
||||
|
||||
if (env.CHROME_DESKTOP === "Paseo.desktop" || env.CHROME_DESKTOP === "paseo-desktop.desktop") {
|
||||
delete env.CHROME_DESKTOP;
|
||||
}
|
||||
delete env.PASEO_DESKTOP_SANDBOX_REASON;
|
||||
stripAppImageRuntimeEnv(env, { platform });
|
||||
}
|
||||
|
||||
function buildInternalProcessEnv<T extends ProcessEnvRecord>(baseEnv: T): T {
|
||||
return { ...baseEnv };
|
||||
}
|
||||
@@ -101,7 +116,7 @@ function buildExternalProcessEnv(
|
||||
for (const key of RUNTIME_CONTROL_ENV_KEYS) {
|
||||
delete sanitized[key];
|
||||
}
|
||||
stripAppImageRuntimeEnv(sanitized);
|
||||
stripLinuxDesktopRuntimeEnv(sanitized);
|
||||
for (const [key, value] of Object.entries(sanitized)) {
|
||||
if (value === undefined) {
|
||||
delete sanitized[key];
|
||||
|
||||
@@ -212,6 +212,12 @@ export interface SessionAdmission {
|
||||
hubExecutionAgents?: HubExecutionAgents;
|
||||
}
|
||||
|
||||
interface SocketDetachDetails {
|
||||
code?: number;
|
||||
reason?: unknown;
|
||||
error?: Error;
|
||||
}
|
||||
|
||||
interface PendingConnection {
|
||||
connectionLogger: pino.Logger;
|
||||
helloTimeout: ReturnType<typeof setTimeout> | null;
|
||||
@@ -1582,7 +1588,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
connection: SessionConnection,
|
||||
hello: WSHelloMessage,
|
||||
): void {
|
||||
// The peer learns our support from this ordinary response before receiving chunks or encoded frames.
|
||||
// server_info goes out before chunking or a codec applies, as a plain text frame. The client
|
||||
// learns our support from it, so it cannot decode an encoded server_info, and the relay E2EE
|
||||
// downgrade check reads it as text. frame-compression.e2e.test.ts guards this.
|
||||
this.sendToClient(ws, this.createServerInfoMessage(connection));
|
||||
const transport = this.frameSocket(ws);
|
||||
transport.enabled = hello.capabilities?.[CLIENT_CAPS.binaryChunkingV1] === true;
|
||||
@@ -2941,10 +2949,9 @@ export class VoiceAssistantWebSocketServer {
|
||||
|
||||
ws.on("close", async (...args: unknown[]) => {
|
||||
if (this.handedOffTunnelSockets.has(ws)) return;
|
||||
this.frameSockets.get(ws)?.close();
|
||||
const code = args[0];
|
||||
const reason = args[1];
|
||||
await this.detachSocket(ws, {
|
||||
await this.releaseSocket(ws, {
|
||||
code: typeof code === "number" ? code : undefined,
|
||||
reason,
|
||||
});
|
||||
@@ -2958,10 +2965,22 @@ export class VoiceAssistantWebSocketServer {
|
||||
const pending = this.pendingConnections.get(ws);
|
||||
const log = active?.connectionLogger ?? pending?.connectionLogger ?? this.logger;
|
||||
log.error({ err }, "Client error");
|
||||
await this.detachSocket(ws, { error: err });
|
||||
await this.releaseSocket(ws, { error: err });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Socket teardown after error or close. Frames the peer sent before the socket failed still
|
||||
* apply, as they do uncompressed, so the session stays attached until they are delivered.
|
||||
* Responses to them stop at the closed socket.
|
||||
*/
|
||||
private async releaseSocket(ws: WebSocketLike, details: SocketDetachDetails): Promise<void> {
|
||||
const transport = this.frameSockets.get(ws);
|
||||
await transport?.flushInbound();
|
||||
transport?.close();
|
||||
await this.detachSocket(ws, details);
|
||||
}
|
||||
|
||||
public resolveVoiceSpeakHandler(callerAgentId: string): VoiceSpeakHandler | null {
|
||||
return this.voiceSpeakHandlers.get(callerAgentId) ?? null;
|
||||
}
|
||||
@@ -2970,14 +2989,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
return this.voiceCallerContexts.get(callerAgentId) ?? null;
|
||||
}
|
||||
|
||||
private async detachSocket(
|
||||
ws: WebSocketLike,
|
||||
details: {
|
||||
code?: number;
|
||||
reason?: unknown;
|
||||
error?: Error;
|
||||
},
|
||||
): Promise<void> {
|
||||
private async detachSocket(ws: WebSocketLike, details: SocketDetachDetails): Promise<void> {
|
||||
this.hostLinks.get(ws)?.close();
|
||||
this.hostLinks.delete(ws);
|
||||
|
||||
|
||||
@@ -7,10 +7,11 @@ import {
|
||||
import {
|
||||
createExternalCommandProcessEnv,
|
||||
stripAppImageRuntimeEnv,
|
||||
stripLinuxDesktopRuntimeEnv,
|
||||
type ProcessEnvRecord,
|
||||
} from "../server/paseo-env.js";
|
||||
|
||||
export { stripAppImageRuntimeEnv };
|
||||
export { stripAppImageRuntimeEnv, stripLinuxDesktopRuntimeEnv };
|
||||
|
||||
interface ExternalEnvOptions {
|
||||
baseEnv?: ProcessEnvRecord;
|
||||
|
||||
@@ -717,7 +717,7 @@ test("Windows units and integration run independently with complete routed cover
|
||||
assert.doesNotMatch(invocations[0], / -t /);
|
||||
assert.equal(
|
||||
invocations[1],
|
||||
'vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t "agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap"',
|
||||
'vitest run --fileParallelism --maxWorkers=3 src/server/agent/providers/omp/history.e2e.test.ts src/server/daemon-e2e/git-operations.e2e.test.ts src/server/session.create-agent-worktree-autoarchive.e2e.test.ts src/server/agent/providers/opencode-bridge.local.e2e.test.ts src/server/daemon-e2e/relay-transport.e2e.test.ts src/server/agent/agent-mcp.e2e.test.ts src/server/plugins/agent-tools.e2e.test.ts -t "agent MCP protocol negotiation|merges into|creates a worktree and auto-archives both|versioned runtime|oversized attachments|connected hosts|password-protected daemon refuses|replays selected OMP history|changes the launch wrap|negotiates protected endpoint security"',
|
||||
);
|
||||
const serverConfig = readFileSync(new URL("packages/server/vitest.config.ts", repoRoot), "utf8");
|
||||
assert.doesNotMatch(serverConfig, /maxWorkers:\s*1\b/);
|
||||
|
||||
Reference in New Issue
Block a user