Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]andluke 8cd4cf96e9 Name the bare Git fixture explicitly
Co-authored-by: luke <luopeihuan@gmail.com>
2026-12-04 05:12:09 +00:00
paseo-bot[bot] b78548a87a Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-clone 2026-12-04 04:42:55 +00:00
Mohamed Boudra b947c229c6 fix(usage): keep local usage when Claude or Codex carries harmless flags (#11963)
* fix(usage): keep local usage when Claude or Codex carries harmless flags

PR #11154 treated any non-empty launch.args on stock claude or codex as an isolated wrapper launch, hiding local usage cards whenever users configured extra flags such as --chrome (regression reported in #11529).

- Extract a shared isWrapperLaunch helper in @getpaseo/plugin/server/usage and replace the three duplicate copies across provider-env.ts, claude-usage-source, and codex-usage-source.
- Keep renamed wrapper binaries isolated while only isolating stock binaries when args before -- include account/settings/provider-switching flags verified against claude --help (--settings, --setting-sources, --bare) or codex --help / codex app-server --help (-c, --config, -p, --profile, --oss, --local-provider, --remote, --remote-auth-token-env, --startup-sign-out).

Closes #11529

* refactor(usage): accept named input in isWrapperLaunch and test flag parity
2026-12-04 11:36:27 +07:00
Mohamed Boudra 2e3d9b375a feat(devices): fix client identity, expose daemon-observed IP, and polish Devices rows (#11902)
* feat(devices): fix client identity, expose daemon-observed IP, and polish Devices rows

Slice 1 of device identification and IP visibility:

- Extend HelloClientInfoSchema and DaemonSessionSummarySchema with additive optional fields (appKind, osName, osVersion, deviceModel, browserName, deviceKey, remoteIp, ipSource, authMethod).
- Pass clean --paseo-device-name and --paseo-os-version from desktop main into sandboxed preload and emit rich clientInfo across Electron, Web, Android, iOS, CLI, and connected hosts.
- Call resolveAppClientIdentity() in buildClientConfig() and routed probes (with persisted clientId) so probe-adopted Electron and Web sessions no longer report as Mobile.
- Sanitize client-claimed display strings, normalize daemon-observed direct/Tailscale/local remote IPs (stripping ::ffff:, omitting local_ipc/via/relay/hub), record authMethod, and add Electron User-Agent fallback for legacy direct clients.
- Polish Devices rows to show real device names, This device/transport/IP/OS hints, Reconnecting summary, monospace IP address, and plain Full access instead of a 9-pill dump across all 9 locales.

* fix(devices): isolate routed probe scopeId, avoid global window mutation in test, and tag COMPAT shims

* chore(protocol): drop COMPAT tag from permanent HelloClientInfo fields

* fix(devices): align authMethod display labels and test with daemon password auth

* chore(devices): remove duplicate authMethod assignment and dead auth label cases

* chore(devices): include added version in legacyBrowserHostLabel COMPAT tag
2026-12-04 11:34:53 +07:00
Mohamed Boudra 9cb4726c30 fix(finish-subscriptions): exclude finish-notice-only turns and queues from pending work (#11969)
* fix(finish-subscriptions): exclude finish-notice-only turns and queues from pending work

* fix(finish-subscriptions): clean retained turn history and test patterns
2026-12-04 11:34:29 +07:00
Mohamed Boudra 1544282593 Isolate oversized ACP stdout lines to the affected chat (#11894)
* fix(acp): bound ACP stdout lines and plugin IPC payloads at 64 MiB

Share the 64 MiB ProviderLineReader and createBoundedNdJsonStream helper in @getpaseo/protocol so both the direct server ACP reader and the plugin ACP reader fail only the affected request or session on oversized stdout lines instead of buffering unbounded payloads.

Add an iterative 64 MiB byte guard in the plugin worker before process.send/structuredClone so oversized plugin events or RPC payloads cannot crash the daemon worker in v8::ValueDeserializer, and preserve inline session.runtime_failed errors during prompt submission instead of retrying them as stale sessions.

Fixes #11580

* fix(acp): walk containers lazily, count DAG references, and skip non-object stdout

Use cursor/iterator frames in exceedsIpcByteLimit so huge sparse arrays fail before copying entries, count shared DAG references before jsonTransportValue stringifies plugin events, and log/ignore non-object JSON stdout lines in createLoggedNdJsonStream instead of ending the transport.

* fix(acp): race ACP requests only on stream limit and close on read errors

Do not race connection.closed ahead of processError in ACPAgentSession.runACPRequest so early startup exits preserve their stderr diagnostic, and close the readable stream instead of erroring it when closeOnStreamLimit is enabled so @agentclientprotocol/sdk 0.17.1 does not leak unhandled AbortError rejections.

* fix(plugins): send request.failed before closing oversized session open

Deliver request.failed over IPC before calling closeFailedSession on an oversized session.opened reply so inline session.closed events cannot mask the IPC size limit error.

* refactor(acp): drop plugin IPC object walker and keep stdout bounds

Keep only the 64 MiB byte-bounded NDJSON line reader at provider stdout boundaries and revert the plugin IPC payload size walker.
2026-12-04 11:34:22 +07:00
61d2ad1585 feat(plugin): embed an agent's conversation in plugin UI with AgentChat (#9602)
* feat(plugin): render an agent's timeline in plugin surfaces with AgentTimeline

Squash of getpaseo/paseo#9602 (feat/plugin-agent-timeline at fd29216a0) onto main.

Plugins can show an agent's timeline inside their own screens, panels and modals with
`AgentTimeline` from `@getpaseo/plugin/client/ui`. It renders the agent tab's own chain, so
plugin timeline items, history paging, streaming, permissions and the loading, catch-up, error
and archived states match the tab.

Discussion: https://github.com/getpaseo/paseo/discussions/9589

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* feat(plugin): reshape the embed into AgentChat

Rename the embed to AgentChat. Timeline stays free for a future
data-driven display component with no agent.

- API: <AgentChat agentId hostId? composer?: false | { controls?: "all" | "none", placeholder? } testID? />.
  Per-control maps and composer items are left out; both can be added
  later as optional fields.
- The composer reuses the ComposerInputMode table with a new "message"
  mode (no attachments, voice, autocomplete, controls, usage or client
  commands) instead of a parallel controls-scope context.
- Embed focus follows the workspace pane rule: the embed the user last
  pressed owns the composer keys, while its pane or screen is in front.
  This removes the focus-owner, Portal wrapper and oxlint rule.
- Pane and embed share one AgentComposer, so the embed keeps draft
  revisions and submit loading.
- Example, reference (en, zh-CN), docs and the paseo-plugin skill use
  the new name.

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): give each AgentChat its own composer editing session

Inside a workspace plugin panel, every embed resolved the panel's one
editing session. Fullscreen in one embed expanded all of them, and
command hints and focus restore went to whichever composer attached
last. Each embed now edits in a session of its own, keyed by agent the
way a pane's session follows its target.

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(plugin): say what AgentChat's controls "none" does with draft files

The chat edits the agent's own draft, shared with its tab. "none" removes
every way to add files; files already in the draft show, can be removed,
and are sent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(app): keep pasted forge links as text in a composer without attachments

AgentChat's controls "none" composer still turned a pasted pull request
URL of the agent's repository into an attachment. Forge auto-attach now
follows the input mode, so a mode without attachments sends links as
written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(app): stub the lucide icons the agent panel imports

AgentChat's lazy import puts the agent panel in the browser test graph.
Its icons were missing from the lucide stub, so Vite's dependency scan
failed, pre-bundling was skipped, and mid-run reoptimization broke
module imports in seven browser suites.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Tom Gringauz <17593920+tomgrin10@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-04 11:16:14 +07:00
Mohamed Boudra 512f21ba64 Allow native plugin addons on macOS via Plugin Helper entitlements (#11958)
* fix(desktop): scope macOS disable-library-validation to Plugin Helper

Packaged macOS builds run with Hardened Runtime enabled and no
disable-library-validation entitlement, so community plugins that load
third-party native .node addons fail under dlopen.

Scope com.apple.security.cs.disable-library-validation and
com.apple.security.cs.allow-unsigned-executable-memory exclusively to
Paseo Helper (Plugin).app via a custom electron-builder mac.sign hook
while keeping Paseo.app (which holds com.apple.security.device.audio-input)
and the generic, GPU, and Renderer helpers strictly library-validated.
Route packaged macOS ELECTRON_RUN_AS_NODE launches (desktop daemon and
bundled CLI shim) through Paseo Helper (Plugin).app so the daemon and its
forked plugin workers inherit the Plugin Helper entitlements without Dock
icon or UI lifecycle side effects.

* refactor(desktop): keep electron-builder entitlements defaults in mac-sign hook

* test(desktop): use POSIX bundle paths in macOS signing test

* test(desktop): verify macOS helper entitlements and ad-hoc dlopen in packaged smoke

* test(desktop): assert Hardened Runtime flag and handle SIP-disabled macOS CI runners

* test(desktop): require exit 0 for SIP-disabled generic Helper smoke branch
2026-12-04 11:16:08 +07:00
paseo-bot[bot] 646b65e617 fix(app): complete finished replies after reconnect (#11970)
A missed turn-end event leaves the last reply in the live transcript. When catch-up accounts for those rows and the held turn is idle, commit them to history so timeline plugins receive the completed reply.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 04:12:48 +00:00
Ryan大然andMohamed Boudra 302afe1104 Scope window no-drag regions to drag surfaces and overlays (#11830)
* Keep scrolled sidebar, Files and Changes rows from cutting the titlebar

Electron computes the window drag area from app-region boxes without
clipping them to scroll viewports. Rows scrolled out of the sidebar
workspace list, the Files tree and filter results, and the Changes diff
still sat under the titlebar as no-drag boxes, so the blank titlebar
above them stopped moving the window.

These viewports are now window content, like the chat timeline and
sidebar nav rows: they emit no app regions, and their controls keep
normal DOM hit testing.

Fixes #11680

* Scope window no-drag regions to drag surfaces and overlays

The global interactive/tabindex no-drag rule in public/index.html caused
any unexempt scrolled viewport (#11680) and any parked resident browser
webview surface (tabindex=-1 inherited into its 1280x800 webview and
shadow iframe, #11844) to emit unclipped no-drag rectangles over the
titlebar, eventually freezing window movement during normal use.

Invert the rule so controls emit -webkit-app-region: no-drag only when
they can overlap a drag surface: inside TitlebarDragRegion containers,
inline drag surfaces, overlays/modals (#overlay-root, [role=dialog],
[aria-modal=true], [data-window-overlay-host]), or explicit window-owned
chrome controls ([data-window-no-drag]). Remove the per-viewport
data-window-content opt-out markers, and move WindowChromeSafeArea and
TitlebarDragRegion into CompactHeader so narrow desktop layouts remain
draggable (#9797).

Closes #11680
Closes #11844
Closes #9797

* Move desktop titlebar drag E2E spec to packages/desktop/e2e

---------

Co-authored-by: Mohamed Boudra <boudra.moha@gmail.com>
2026-12-04 10:53:53 +07:00
paseo-bot[bot] b14f61ce27 test(claude): keep the event stream check focused on stale turn output (#11959)
Session totals follow the result, and a background child can update its original tool card after the launching turn ends. Keep rejecting new output under the ended turn ID.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 03:42:52 +00:00
6b808bc67b Preserve literal paths in the commit file list (#11480)
* Preserve literal paths in the commit file list

* Build literal rename path fixtures from Git trees

* Keep signed commits in machine-readable Git history

Apply the regression reported at https://github.com/getpaseo/paseo/pull/11480#issuecomment-7338842841.

Co-authored-by: jamescordrey-ops <335786770+jamescordrey-ops@users.noreply.github.com>

---------

Co-authored-by: Shane Su <26364206+suniceman@users.noreply.github.com>
Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: Shane Su <shane.su@maiscrm.com>
Co-authored-by: jamescordrey-ops <335786770+jamescordrey-ops@users.noreply.github.com>
2026-12-04 10:08:36 +07:00
paseo-bot[bot] 624c26aa91 fix(cli): show permission questions in permit ls (#11954)
Pi sends the question as the request title. Use that title when the request lacks a description so CLI users can read the prompt before responding.

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
2026-12-04 02:12:50 +00:00
lukeandRoundRedDot 5dee36e9ae refactor(server): use named Git checkout arguments
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:40:04 +08:00
lukeandRoundRedDot 8af3380124 Merge remote-tracking branch 'origin/main' into fix/plugin-blobless-auth-review
# Conflicts:
#	packages/server/src/server/plugins/managed-source.posix.test.ts

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:23:54 +08:00
lukeandRoundRedDot a14826c8fd fix(server): preserve credentials during filtered plugin checkout
Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 17:20:52 +08:00
lukeandRoundRedDot f00b32dbe6 perf(server): clone Git plugin sources without history blobs
- Use blobless clone filter when fetching Git plugin sources to improve install performance
- Add POSIX test verification for blobless git operations

Co-authored-by: RoundRedDot <roundreddot@gmail.com>
2026-11-11 09:22:00 +08:00
137 changed files with 8199 additions and 1027 deletions
+8 -5
View File
@@ -232,9 +232,11 @@ at-least-once wakeup, without turn attribution or exactly-once delivery.
A turn end is not always a settled child. A child can end its turn with work that will start its next
turn by itself: a running turn, queued messages, a pending provider wake-up
(`AgentSession.hasPendingWakeup`: Claude background tasks, task notifications, and one-shot
wake-ups), or the child's own outstanding finish subscriptions as a caller. Heartbeats, recurring
crons, change-request watches, and other daemon background items never count: they are external
triggers, not work the caller is waiting for.
wake-ups), or the child's own outstanding finish subscriptions as a caller. Queued finish notices
(`agent-notification`) and turns started only by finish notices do not count as pending work
unless a real prompt is batched into or steered into the turn. Heartbeats, recurring crons,
change-request watches, and other daemon background items never count: they are external triggers,
not work the caller is waiting for.
Every turn end reports `finished` at once, unless the child already sent an agent message to its
caller during that turn and started no further tool work afterwards. In that case the child's
@@ -243,8 +245,9 @@ ends silently, and a watch with pending work keeps following silently until a la
the work drains. Starting another non-reporting tool call or a new turn clears that mark (plain text output after the
message does not), and errors, permission requests, cancellations, and closes are never suppressed. When work is still
pending on an unreported turn end, the notice names it and the subscription follows the child: each
later turn end reports `finished` again, and the child settling with nothing pending sends a final
`finished` and removes the subscription, even when the work drains without another turn. Reporting
later turn end reports `finished` again, except that a turn started only by finish notices while
already following keeps following without another interim notice; the child settling with nothing
pending still sends the final `finished` and removes the subscription, even when the work drains without another turn. Reporting
at once keeps a long-lived task, such as a dev server, from leaving the caller without the child's
reply. Following is what lets the caller hear the reply a background task wakes up later
([#6346](https://github.com/getpaseo/paseo/issues/6346)). A work change that leaves work pending
+10
View File
@@ -445,6 +445,16 @@ workspace only. Location controls hosting, not context. An agent panel target ke
when moved between hosts. Explorer configuration can create workspace-context panels and remove
existing agent-context instances, but it cannot create an agent panel without an agent-aware command.
`AgentChat` renders the agent tab's own chain (`AgentPanelContent` in
`packages/app/src/panels/agent-panel.tsx`) through `packages/app/src/agent-embed`. The chain takes
a `ConversationSurface` instead of reading the pane: a pane has a tab to retarget and a pill track,
an embed has neither, so its composer handles `/clear` by opening the agent's workspace and the
track is never mounted. The embed publishes itself as a viewer with `useViewedAgent`, the hook the
workspace sheet uses, so the tab and every embed of one agent share the sync's single observation.
`controls: "none"` is the composer's `message` input mode (`composer/input-mode.ts`). Key focus
follows the pane rule: the embed the user last pressed owns Escape and send, while its pane or
screen is in front.
Command Center callbacks use the selected host's existing `PaseoApi` for normal Paseo operations.
They use typed plugin RPC only for plugin-specific backend work. Surface and panel navigation
belongs to the app; plugins do not receive Expo Router or workspace-layout store access.
@@ -51,16 +51,18 @@ test("lists connected clients with scopes and navigates Pair a device → Relay
});
try {
await openDevicesPage(page, daemon);
await expectConnectedClientRow(page, "This device", "Full access");
await expandConnectedClientRow(page, "This device");
await expect(
page
.getByTestId("devices-connected-clients-card")
.getByText("access.manage", { exact: true }),
).toBeVisible();
await expectConnectedClientRow(page, /^Chrome on /, "Full access");
await expandConnectedClientRow(page, /^Chrome on /);
const card = page.getByTestId("devices-connected-clients-card");
await expect(card.getByText("IP address", { exact: true })).toBeVisible();
await expect(card.getByText("127.0.0.1", { exact: true })).toBeVisible();
await expect(card.getByText("access.manage", { exact: true })).toHaveCount(0);
await viewer.connect();
await expectConnectedClientRow(page, "Test Phone", "Read-only");
await expandConnectedClientRow(page, "Test Phone");
await expect(card.getByText("daemon.read", { exact: true })).toBeVisible();
await expect(card.getByText("workspace.read", { exact: true })).toBeVisible();
await openPairDeviceModal(page);
await expectPairingOffer(page);
@@ -0,0 +1,349 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import path from "node:path";
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openCommandCenter } from "../support/helpers/command-center";
import {
openAgentRoute,
seedMockAgentWorkspace,
type MockAgentWorkspace,
} from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { pluginRequirements } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-focus-e2e";
const SCREEN_TITLE = "Embeds";
const PHONE = { width: 390, height: 844 };
interface EmbedComposer {
controls?: "all" | "none";
}
/**
* A screen with one `AgentChat` per agent under a header of its own, plus a client slash command
* that a full composer runs and a `controls: "none"` composer sends as text. A button opens the
* first agent's chat in a plugin modal too, and a workspace panel shows the same chats side by side.
*/
function pluginSource(input: { agentIds: string[]; composer: EmbedComposer }): string {
return `import { useCallback } from "react";
import { Pressable, Text, View } from "react-native";
import { AgentChat, Modal, SidebarRow } from "@getpaseo/plugin/client/ui";
import { useState } from "react";
const AGENT_IDS = ${JSON.stringify(input.agentIds)};
const COMPOSER = ${JSON.stringify(input.composer)};
function Embeds() {
const [modalOpen, setModalOpen] = useState(false);
return (
<View style={{ flex: 1 }}>
<Text testID="plugin-header" style={{ padding: 8 }}>Embedded agents</Text>
<Pressable accessibilityRole="button" onPress={() => setModalOpen(true)}>
<Text>Open in modal</Text>
</Pressable>
<Modal title="Agent in a modal" open={modalOpen} onOpenChange={setModalOpen}>
<Modal.Content scrollable={false}>
<AgentChat agentId={AGENT_IDS[0]} composer={COMPOSER} testID="modal-embed" />
</Modal.Content>
</Modal>
<View style={{ flex: 1, flexDirection: "row" }}>
{AGENT_IDS.map((agentId) => (
<View key={agentId} style={{ flex: 1, minWidth: 0 }}>
<AgentChat agentId={agentId} composer={COMPOSER} testID={"embed-" + agentId} />
</View>
))}
</View>
</View>
);
}
function Board() {
return (
<View style={{ flex: 1, flexDirection: "row" }}>
{AGENT_IDS.map((agentId) => (
<View key={agentId} style={{ flex: 1, minWidth: 0 }}>
<AgentChat agentId={agentId} composer={COMPOSER} testID={"panel-embed-" + agentId} />
</View>
))}
</View>
);
}
function EmbedsItem({ currentScreen, openScreen }) {
const open = useCallback(() => openScreen({ screenId: "main" }), [openScreen]);
return <SidebarRow icon="Bot" active={currentScreen?.screenId === "main"} onPress={open} />;
}
export default function contribute(plugin) {
plugin.addScreen({ id: "main", title: "${SCREEN_TITLE}", Component: Embeds });
plugin.addSidebarHeaderItem({ id: "main", title: "${SCREEN_TITLE}", Component: EmbedsItem });
plugin.addWorkspacePanel({ id: "board", title: "Board", icon: "Bot", context: "workspace", Component: Board });
plugin.addCommandCenterItem({
id: "board",
title: "Open embeds board",
icon: "Bot",
context: "workspace",
onSelect({ openPanel }) {
openPanel("board");
},
});
plugin.addSlashCommand({
name: "stamp",
context: "agent",
description: "Stamp the agent",
argumentHint: "",
onSubmit() {},
});
return () => {};
}`;
}
interface Scenario {
agents: MockAgentWorkspace[];
embed(agentId: string): ReturnType<Page["getByTestId"]>;
}
async function withEmbeds(
page: Page,
input: { agents: { title: string; model: string; prompt: string }[]; composer: EmbedComposer },
run: (scenario: Scenario) => Promise<void>,
): Promise<void> {
const agents: MockAgentWorkspace[] = [];
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
const directory = await mkdtemp(path.join(tmpdir(), "paseo-agent-chat-focus-"));
try {
for (const agent of input.agents) {
agents.push(
await seedMockAgentWorkspace({
repoPrefix: "agent-chat-focus-",
title: agent.title,
model: agent.model,
initialPrompt: agent.prompt,
}),
);
}
await writeFile(
path.join(directory, "paseo-plugin.json"),
JSON.stringify({ id: PLUGIN_ID, requirements: pluginRequirements }),
);
await writeFile(
path.join(directory, "index.client.tsx"),
pluginSource({ agentIds: agents.map((agent) => agent.agentId), composer: input.composer }),
);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(directory);
await gotoAppShell(page);
await page.getByRole("button", { name: SCREEN_TITLE, exact: true }).click();
const embed = (agentId: string) => page.getByTestId(`embed-${agentId}`);
for (const agent of agents) {
await expect(embed(agent.agentId).getByTestId("user-message").first()).toBeVisible({
timeout: 30_000,
});
}
await run({ agents, embed });
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close().catch(() => undefined);
await rm(directory, { recursive: true, force: true });
for (const agent of agents) await agent.cleanup();
}
}
async function agentStatus(agent: MockAgentWorkspace): Promise<string | null> {
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
return fetched?.agent.status ?? null;
}
/** Clicks land on text, not on a field, so Escape routes as the interrupt shortcut. */
async function expectEscapeInterruptsOnlyTheFocusedEmbed(
page: Page,
input: { left: MockAgentWorkspace; right: MockAgentWorkspace; embed: Scenario["embed"] },
): Promise<void> {
const { left, right, embed } = input;
await test.step("Escape after a click outside the embeds interrupts neither", async () => {
await page.getByTestId("plugin-header").click();
await page.keyboard.press("Escape");
});
await test.step("Escape after a click in the left embed interrupts only it", async () => {
await embed(left.agentId).getByTestId("user-message").first().click();
await page.keyboard.press("Escape");
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("idle");
// Interrupts go out in order, so a stray one from the first Escape has landed by now.
expect(await agentStatus(right)).toBe("running");
});
await test.step("Escape after a click in the right embed interrupts it", async () => {
await embed(right.agentId).getByTestId("user-message").first().click();
await page.keyboard.press("Escape");
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("idle");
});
}
test('controls: "none" sends a plugin slash command to the agent as typed', async ({ page }) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
await withEmbeds(
page,
{
agents: [{ title: "Slash agent", model: "e2e-fast-stream", prompt: "Say hello." }],
composer: { controls: "none" },
},
async ({ agents: [agent], embed }) => {
await agent.client.waitForFinish(agent.agentId, 30_000);
const box = embed(agent.agentId).getByRole("textbox", { name: "Message agent..." });
await box.fill("/stamp the invoices");
await box.press("Enter");
await expect(embed(agent.agentId).getByTestId("user-message").last()).toContainText(
"/stamp the invoices",
);
},
);
});
test("Escape interrupts only the embed that has focus", async ({ page }) => {
test.setTimeout(240_000);
await page.setViewportSize({ width: 1440, height: 900 });
await withEmbeds(
page,
{
agents: [
{ title: "Left agent", model: "one-minute-stream", prompt: "Keep running left." },
{ title: "Right agent", model: "one-minute-stream", prompt: "Keep running right." },
],
composer: { controls: "none" },
},
async ({ agents: [left, right], embed }) => {
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("running");
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("running");
await expectEscapeInterruptsOnlyTheFocusedEmbed(page, { left, right, embed });
},
);
});
test("a phone-width plugin modal shows an agent's chat", async ({ page }) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
await withEmbeds(
page,
{
agents: [{ title: "Modal agent", model: "e2e-fast-stream", prompt: "Say hello." }],
composer: { controls: "none" },
},
async () => {
// At phone width the modal is a bottom sheet whose body renders under the app's root
// portal host, outside the plugin screen's React tree.
await page.setViewportSize(PHONE);
await page.getByRole("button", { name: "Open in modal", exact: true }).click();
await expect(page.getByText("Agent in a modal", { exact: true })).toBeVisible();
const modalEmbed = page.getByTestId("modal-embed");
await expect(modalEmbed.getByTestId("user-message").first()).toContainText("Say hello.", {
timeout: 30_000,
});
await expect(modalEmbed.getByRole("textbox", { name: "Message agent..." })).toBeVisible();
},
);
});
/** Picks the embed's current mode again from its picker, which draws at the overlay root. */
async function pickCurrentMode(page: Page, embed: ReturnType<Page["getByTestId"]>): Promise<void> {
const trigger = embed.getByRole("button", { name: /^Select agent mode \(/ });
const label = /^Select agent mode \((.+)\)$/.exec(
(await trigger.getAttribute("aria-label")) ?? "",
)?.[1];
expect(label).toBeTruthy();
await trigger.click();
const popup = page.getByTestId("combobox-desktop-container").last();
await expect(popup).toBeVisible({ timeout: 10_000 });
await popup.getByRole("button", { name: label, exact: true }).click();
await expect(page.getByTestId("combobox-desktop-container")).toHaveCount(0);
}
test("a full-composer embed applies a slash suggestion picked with the pointer", async ({
page,
}) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
await withEmbeds(
page,
{
agents: [{ title: "Suggestion agent", model: "e2e-fast-stream", prompt: "Say hello." }],
composer: {},
},
async ({ agents: [agent], embed }) => {
await agent.client.waitForFinish(agent.agentId, 30_000);
const box = embed(agent.agentId).getByRole("textbox", { name: "Message agent..." });
await box.click();
await box.pressSequentially("/sta");
// The list draws in the floating-panel portal, outside the embed's own nodes.
const suggestion = page
.getByTestId("composer-autocomplete-popover")
.getByText("/stamp", { exact: true });
await expect(suggestion).toBeVisible({ timeout: 30_000 });
await suggestion.click();
await expect(box).toHaveValue(/^\/stamp\s*$/);
},
);
});
test("a portaled mode picker keeps its embed focused for Escape", async ({ page }) => {
test.setTimeout(240_000);
await page.setViewportSize({ width: 1440, height: 900 });
await withEmbeds(
page,
{
agents: [
{ title: "Left agent", model: "one-minute-stream", prompt: "Keep running left." },
{ title: "Right agent", model: "one-minute-stream", prompt: "Keep running right." },
],
composer: {},
},
async ({ agents: [left, right], embed }) => {
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("running");
await expect.poll(() => agentStatus(right), { timeout: 15_000 }).toBe("running");
await pickCurrentMode(page, embed(left.agentId));
await page.keyboard.press("Escape");
await expect.poll(() => agentStatus(left), { timeout: 15_000 }).toBe("idle");
expect(await agentStatus(right)).toBe("running");
},
);
});
test("embeds in one workspace panel keep their own composers", async ({ page }) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1440, height: 900 });
await withEmbeds(
page,
{
agents: [
{ title: "Left agent", model: "e2e-fast-stream", prompt: "Say hello left." },
{ title: "Right agent", model: "e2e-fast-stream", prompt: "Say hello right." },
],
composer: {},
},
async ({ agents: [left, right] }) => {
await openAgentRoute(page, left);
const commands = await openCommandCenter(page);
await commands.getByTestId("command-center-input").fill("Open embeds board");
await commands.getByRole("button", { name: "Open embeds board", exact: true }).click();
const leftEmbed = page.getByTestId(`panel-embed-${left.agentId}`);
const rightEmbed = page.getByTestId(`panel-embed-${right.agentId}`);
await expect(leftEmbed.getByTestId("user-message").first()).toBeVisible({ timeout: 30_000 });
await expect(rightEmbed.getByTestId("user-message").first()).toBeVisible({ timeout: 30_000 });
// The fullscreen control shows on a phone once the draft runs past two lines.
await page.setViewportSize(PHONE);
await leftEmbed
.getByRole("textbox", { name: "Message agent..." })
.fill("First line\nSecond line\nThird line\nFourth line");
await leftEmbed.getByRole("button", { name: "Fullscreen", exact: true }).click();
await expect(leftEmbed.getByTestId("composer-fullscreen")).toBeVisible();
await expect(rightEmbed.getByTestId("composer-fullscreen")).toHaveCount(0);
},
);
});
@@ -0,0 +1,118 @@
import { expect, test, type Page } from "../support/fixtures";
import { gotoAppShell } from "../support/helpers/app";
import { openAgentRoute, seedMockAgentWorkspace } from "../support/helpers/mock-agent";
import { connectNewWorkspaceDaemonClient } from "../support/helpers/new-workspace";
import { copyPluginExample } from "../support/helpers/plugin-fixture";
const PLUGIN_ID = "agent-chat-example";
const AGENT_TITLE = "Billing retries";
const FIRST_PROMPT = "Summarize the billing retry failures.";
function embed(page: Page) {
return page.getByTestId("example-agent-chat");
}
async function openAgentInEmbed(page: Page): Promise<void> {
await gotoAppShell(page);
await page.getByRole("button", { name: "Agents", exact: true }).click();
await page
.getByTestId("example-agent-list")
.getByRole("button", { name: AGENT_TITLE, exact: true })
.click();
}
async function sendFromEmbed(page: Page, text: string): Promise<void> {
const box = embed(page).getByRole("textbox", { name: "Message agent..." });
await box.fill(text);
await box.press("Enter");
}
test.describe("AgentChat", () => {
test("a plugin screen embeds an agent's chat with the composer it chose", async ({
page,
context,
}) => {
test.setTimeout(180_000);
await page.setViewportSize({ width: 1280, height: 800 });
const agent = await seedMockAgentWorkspace({
repoPrefix: "plugin-agent-chat-",
title: AGENT_TITLE,
initialPrompt: FIRST_PROMPT,
});
const client = await connectNewWorkspaceDaemonClient({ ownProjects: false });
const previous = await client.getDaemonConfig();
const example = await copyPluginExample("agent-chat");
try {
await agent.client.waitForFinish(agent.agentId, 30_000);
await client.patchDaemonConfig({ pluginsEnabled: true });
await client.installDirectoryPlugin(example.directory);
await openAgentInEmbed(page);
await test.step("controls: none is a message box and Send", async () => {
await expect(embed(page).getByTestId("user-message")).toContainText(FIRST_PROMPT);
await expect(embed(page).getByTestId("assistant-message").first()).toBeVisible();
await expect(
embed(page).getByRole("textbox", { name: "Message agent..." }),
).toHaveAttribute("placeholder", "Message this agent");
await expect(embed(page).getByTestId("agent-controls-toolbar")).toHaveCount(0);
await expect(embed(page).getByTestId("message-input-attach-button")).toHaveCount(0);
await expect(embed(page).getByTestId("context-window-meter")).toHaveCount(0);
const choices = await page.getByTestId("example-composer-choices").boundingBox();
const chat = await embed(page).boundingBox();
expect(chat!.y).toBeGreaterThanOrEqual(choices!.y + choices!.height);
});
await test.step("a message sent from the embed streams into it", async () => {
await sendFromEmbed(page, "Check the invoice PDFs next.");
await expect(embed(page).getByTestId("user-message").last()).toContainText(
"Check the invoice PDFs next.",
);
await agent.client.waitForFinish(agent.agentId, 30_000);
});
await test.step("slash text in the simple box reaches the agent as typed", async () => {
await sendFromEmbed(page, "/exit");
await expect(embed(page).getByTestId("user-message").last()).toContainText("/exit");
await agent.client.waitForFinish(agent.agentId, 30_000);
const fetched = await agent.client.fetchAgent({ agentId: agent.agentId });
expect(fetched?.agent.archivedAt ?? null).toBeNull();
});
await test.step("the full composer is the agent tab's", async () => {
await page.getByRole("button", { name: "Full", exact: true }).click();
await expect(embed(page).getByTestId("agent-controls-toolbar")).toBeVisible();
await expect(embed(page).getByTestId("message-input-attach-button")).toBeVisible();
await expect(embed(page).getByTestId("context-window-meter")).toBeVisible();
});
await test.step("composer={false} shows the conversation without a composer", async () => {
await page.getByRole("button", { name: "No composer", exact: true }).click();
await expect(embed(page).getByTestId("user-message").first()).toContainText(FIRST_PROMPT);
await expect(embed(page).getByRole("textbox", { name: "Message agent..." })).toHaveCount(0);
});
await test.step("the agent's tab and the embed stay live together", async () => {
await page.getByRole("button", { name: "Simple", exact: true }).click();
const tab = await context.newPage();
await openAgentRoute(tab, { workspaceId: agent.workspaceId, agentId: agent.agentId });
const tabBox = tab.getByRole("textbox", { name: "Message agent..." }).first();
await tabBox.fill("Sent from the tab.");
await tabBox.press("Enter");
await expect(embed(page).getByTestId("user-message").last()).toContainText(
"Sent from the tab.",
);
await sendFromEmbed(page, "Sent from the embed.");
await expect(tab.getByTestId("user-message").last()).toContainText("Sent from the embed.");
await tab.close();
});
} finally {
await client.removePlugin(PLUGIN_ID).catch(() => undefined);
await client
.patchDaemonConfig({ pluginsEnabled: previous.config.pluginsEnabled ?? false })
.catch(() => undefined);
await client.close().catch(() => undefined);
await example.cleanup();
await agent.cleanup();
}
});
});
@@ -76,19 +76,21 @@ export async function openDevicesPage(page: Page, daemon: PairingHost): Promise<
export async function expectConnectedClientRow(
page: Page,
title: string,
title: string | RegExp,
scopeLabel: string,
): Promise<void> {
const card = page.getByTestId("devices-connected-clients-card");
const row = card.getByRole("button", { name: title, exact: true });
const row = card.getByRole("button", { name: title, exact: typeof title === "string" });
await expect(row).toBeVisible();
await expect(card.getByText(scopeLabel, { exact: true }).first()).toBeVisible();
}
export async function expandConnectedClientRow(page: Page, title: string): Promise<void> {
export async function expandConnectedClientRow(page: Page, title: string | RegExp): Promise<void> {
const card = page.getByTestId("devices-connected-clients-card");
await card.getByRole("button", { name: title, exact: true }).click();
await expect(card.getByText("Permissions", { exact: true })).toBeVisible();
const toggle = card.getByRole("button", { name: title, exact: typeof title === "string" });
await toggle.click();
await expect(toggle).toHaveAttribute("aria-expanded", "true");
await expect(card.getByText("Access", { exact: true }).first()).toBeVisible();
}
export async function returnFromRelayToWaysToConnect(page: Page): Promise<void> {
@@ -188,7 +188,12 @@ export interface SeedDaemonClient {
archiveAgent(agentId: string): Promise<{ archivedAt: string }>;
refreshAgent(agentId: string): Promise<unknown>;
fetchAgent(options: { agentId: string }): Promise<{
agent: { id: string; archivedAt?: string | null; pendingPermissions: Array<{ id: string }> };
agent: {
id: string;
status: string;
archivedAt?: string | null;
pendingPermissions: Array<{ id: string }>;
};
} | null>;
getLastServerInfoMessage(): {
features?: {
+51 -25
View File
@@ -51,35 +51,61 @@
}
</style>
<style>
button,
a,
input,
textarea,
select,
[role="button"],
[role="link"],
[role="textbox"],
[role="combobox"],
[role="tab"],
[role="switch"],
[role="checkbox"],
[role="slider"],
[role="menuitem"],
[tabindex],
/* Only interactive controls that can overlap a window drag surface
emit -webkit-app-region: no-drag. Controls in ordinary window content
rely on normal DOM hit testing so scrolled viewports and parked
browser webviews never emit unclipped no-drag boxes over the titlebar. */
:is(
[data-window-drag-region] ~ *,
[style*="-webkit-app-region: drag"],
[style*="-webkit-app-region:drag"],
#overlay-root,
[data-window-overlay-host],
[role="dialog"],
[aria-modal="true"]
)
:is(
button,
a,
input,
textarea,
select,
[role="button"],
[role="link"],
[role="textbox"],
[role="combobox"],
[role="tab"],
[role="switch"],
[role="checkbox"],
[role="slider"],
[role="menuitem"],
[tabindex],
[contenteditable="true"]
),
[data-window-drag-region]
~ :is(
button,
a,
input,
textarea,
select,
[role="button"],
[role="link"],
[role="textbox"],
[role="combobox"],
[role="tab"],
[role="switch"],
[role="checkbox"],
[role="slider"],
[role="menuitem"],
[tabindex],
[contenteditable="true"]
),
[data-window-no-drag],
[contenteditable="true"] {
[data-window-no-drag] * {
-webkit-app-region: no-drag !important;
}
/* Electron does not clip app-region rectangles to scroll viewports.
Content-only viewports emit no window regions, including from their
controls. Visible controls here use normal DOM hit testing.
Use initial: Blink parses the explicit value none as no-drag. */
[data-window-content],
[data-window-content] * {
-webkit-app-region: initial !important;
}
/* Suppress the browser's default focus outline — it appears on mouse
clicks and looks out of place against our themed surfaces. Keep a
themed ring for keyboard users via :focus-visible. The ring is the active
@@ -0,0 +1,17 @@
import { useCallback, useMemo } from "react";
import type { View, ViewProps } from "react-native";
import type { RefObject } from "react";
/**
* Native: a touch that starts in the embed claims it, as a touch claims a workspace pane. The
* capture handler declines the responder, so the touch still reaches what was pressed.
*/
export function useClaimFocusProps(
claim: () => void,
): Pick<ViewProps, "onStartShouldSetResponderCapture"> & { ref?: RefObject<View | null> } {
const handleTouch = useCallback(() => {
claim();
return false;
}, [claim]);
return useMemo(() => ({ onStartShouldSetResponderCapture: handleTouch }), [handleTouch]);
}
@@ -0,0 +1,24 @@
import { useEffect, useMemo, useRef, type RefObject } from "react";
import type { View, ViewProps } from "react-native";
/**
* Web: a pointer press or focus move in the embed's DOM claims it, as one claims a workspace pane
* (`split-container`). Pickers and menus the embed opens draw outside its DOM, so pressing them
* leaves the claim where it is.
*/
export function useClaimFocusProps(
claim: () => void,
): Pick<ViewProps, "onStartShouldSetResponderCapture"> & { ref?: RefObject<View | null> } {
const ref = useRef<View | null>(null);
useEffect(() => {
const node: unknown = ref.current;
if (!(node instanceof HTMLElement)) return undefined;
node.addEventListener("pointerdown", claim, true);
node.addEventListener("focusin", claim, true);
return () => {
node.removeEventListener("pointerdown", claim, true);
node.removeEventListener("focusin", claim, true);
};
}, [claim]);
return useMemo(() => ({ ref }), []);
}
+62
View File
@@ -0,0 +1,62 @@
import { useCallback, useContext, useEffect, useSyncExternalStore } from "react";
import { NavigationContext } from "expo-router/react-navigation";
import { useEnclosingPaneFocus } from "@/panels/pane-context";
/**
* Which embed owns the composer's key handlers (Escape interrupts, send, mode cycling). Embeds
* follow the workspace's pane rule: the embed the user last pressed or focused owns them until
* the user presses another embed. A press elsewhere, such as in the plugin's own UI or in a
* picker the embed opened, leaves the owner as it is.
*/
let focusedEmbedId: string | null = null;
const listeners = new Set<() => void>();
function subscribe(listener: () => void): () => void {
listeners.add(listener);
return () => listeners.delete(listener);
}
function setFocusedEmbed(next: string | null): void {
if (focusedEmbedId === next) return;
focusedEmbedId = next;
for (const listener of listeners) listener();
}
/** The embed's key focus, and the claim its root calls on a press or focus move inside it. */
export function useEmbedFocus(embedId: string): { isFocused: boolean; claim: () => void } {
const read = useCallback(() => focusedEmbedId === embedId, [embedId]);
const isFocused = useSyncExternalStore(subscribe, read, read);
const claim = useCallback(() => setFocusedEmbed(embedId), [embedId]);
useEffect(
() => () => {
if (focusedEmbedId === embedId) setFocusedEmbed(null);
},
[embedId],
);
return { isFocused, claim };
}
/**
* Whether the surface around the embed is the one the user is on: the pane it sits in, or else
* the screen. A plugin screen stays mounted under the next one, and its embeds must not keep the
* keys there. Outside any screen (a modal at the app root) the surface counts as shown.
*/
export function useEmbedSurfaceActive(): boolean {
const pane = useEnclosingPaneFocus();
const navigation = useContext(NavigationContext);
const subscribeToRoute = useCallback(
(listener: () => void) => {
if (!navigation) return () => {};
const removeFocus = navigation.addListener("focus", listener);
const removeBlur = navigation.addListener("blur", listener);
return () => {
removeFocus();
removeBlur();
};
},
[navigation],
);
const readRoute = useCallback(() => navigation?.isFocused() ?? true, [navigation]);
const isRouteFocused = useSyncExternalStore(subscribeToRoute, readRoute, readRoute);
return pane ? pane.isInteractive : isRouteFocused;
}
+85
View File
@@ -0,0 +1,85 @@
import { useId, useMemo } from "react";
import { View } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { LocalComposerEditingScope } from "@/composer/editing-session";
import {
AgentPanelContent,
type ConversationSurface,
type EmbeddedComposer,
} from "@/panels/agent-panel";
import { createPaneFocusContextValue, PaneFocusProvider } from "@/panels/pane-context";
import { RetainedChatContent } from "@/panels/retained-chat-content";
import { useSessionStore } from "@/stores/session-store";
import { useViewedAgent } from "@/timeline/use-viewed-agent";
import { useClaimFocusProps } from "./claim-focus";
import { useEmbedFocus, useEmbedSurfaceActive } from "./focus";
export type { EmbeddedComposer } from "@/panels/agent-panel";
export interface AgentEmbedProps {
serverId: string;
agentId: string;
/** `null` shows the conversation without a composer. */
composer: EmbeddedComposer | null;
testID?: string;
}
/**
* An agent's conversation outside the workspace: the agent tab's own chain, with its loading,
* catch-up, error and archived states, and no tab chrome.
*
* The embed is a viewer like the workspace sheet, so the agent's timeline stays live while it is
* mounted and shares the tab's observation when the agent is also open in a tab.
*
* Several embeds can share a screen. Like workspace panes, the one the user last pressed owns the
* composer's key handlers, and only while its pane or screen is the one in front. Each embed edits
* in its own composer session, even inside a workspace panel that has one of its own.
*/
export function AgentEmbed({ serverId, agentId, composer, testID }: AgentEmbedProps) {
const viewerId = `embed:${useId()}`;
useViewedAgent({ sourceId: viewerId, serverId, agentId });
const isSurfaceActive = useEmbedSurfaceActive();
const { isFocused, claim } = useEmbedFocus(viewerId);
const claimProps = useClaimFocusProps(claim);
const isPaneFocused = composer !== null && isSurfaceActive && isFocused;
const surface = useMemo<ConversationSurface>(
() => ({ kind: "embed", id: viewerId, composer, isActive: isSurfaceActive }),
[composer, isSurfaceActive, viewerId],
);
const focus = useMemo(
() => createPaneFocusContextValue({ isWorkspaceFocused: isSurfaceActive, isPaneFocused }),
[isPaneFocused, isSurfaceActive],
);
const target = useMemo(() => ({ kind: "agent" as const, agentId }), [agentId]);
const workspaceId = useSessionStore((state) => {
const session = state.sessions[serverId];
return (
session?.agents.get(agentId)?.workspaceId ??
session?.agentDetails.get(agentId)?.workspaceId ??
""
);
});
return (
<View {...claimProps} style={styles.root} testID={testID}>
<PaneFocusProvider value={focus}>
{/* Keyed like a pane's session, which follows its target. */}
<LocalComposerEditingScope key={agentId}>
<RetainedChatContent>
<AgentPanelContent
serverId={serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isPaneFocused}
/>
</RetainedChatContent>
</LocalComposerEditingScope>
</PaneFocusProvider>
</View>
);
}
const styles = StyleSheet.create({
root: { flex: 1, minHeight: 0 },
});
@@ -1702,7 +1702,7 @@ function WebStreamViewport(props: StreamRenderInput & { isMobileBreakpoint: bool
!liveAuxiliary;
return (
<div style={viewportStyle} data-window-content>
<div style={viewportStyle}>
<div
ref={handleScrollContainerRef}
// Let clicks focus the feed for browser keyboard scrolling without adding a Tab stop.
+2
View File
@@ -54,6 +54,7 @@ import { AppearanceStyleBoundary } from "@/components/appearance-style-boundary"
import { LeftSidebar } from "@/components/left-sidebar";
import { WindowSidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import { DesktopWindowControls } from "@/components/desktop/window-controls";
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
import { SidebarModelProvider } from "@/components/sidebar/sidebar-model";
import { WorkspacePinShortcutHandler } from "@/components/workspace-pin-shortcut-handler";
import { WorkspaceArchiveShortcutHandler } from "@/components/workspace-archive-shortcut-handler";
@@ -606,6 +607,7 @@ function CompactSidebarHost({
return (
<View
collapsable={false}
dataSet={visible ? WINDOW_OVERLAY_HOST_DATASET : undefined}
style={[
layoutStyles.compactSidebarHost,
{ opacity: visible ? 1 : 0 },
@@ -10,23 +10,23 @@ import { isNative } from "@/constants/platform";
* - titlebarpart.css:249-260 → top-edge resizer, no-drag, 4px
*
* VS Code's drag region is a static DOM element — no z-index, no pointer-events,
* no state, no event listeners. Interactive elements get no-drag from their own
* CSS (global backstop in index.html). The drag region never re-renders.
* no state, no event listeners. Interactive controls only receive no-drag when
* they sit inside a drag container, an overlay/modal host, or an explicit
* window-owned chrome slot (see public/index.html). Controls in ordinary window
* content emit no app regions and use normal DOM hit testing, so scrolled
* viewports and parked browser webviews cannot subtract unclipped rects from
* the titlebar.
*
* The resizer is Windows/Linux only (titlebarpart.css:249 scopes to .windows/.linux).
* On macOS, Electron handles edge resize natively.
*/
/**
* Marks a scroll viewport as window content: it and its descendants emit no window
* regions, because Electron does not clip app-region rects to scroll viewports.
* See the `[data-window-content]` rule in public/index.html.
*/
export const WINDOW_CONTENT_DATASET = { "window-content": "" };
/** Reserves a clickable area for a control mounted outside the titlebar rail. */
/** Reserves a clickable area for a window-owned control mounted outside a drag container. */
export const WINDOW_NO_DRAG_DATASET = { "window-no-drag": "" };
/** Marks an in-app overlay/portal host whose interactive controls can float over the titlebar. */
export const WINDOW_OVERLAY_HOST_DATASET = { "window-overlay-host": "" };
export const titlebarDragSurfaceStyle: React.CSSProperties = {
cursor: "default",
// @ts-expect-error — WebkitAppRegion is not in CSSProperties
@@ -64,7 +64,7 @@ export function TitlebarDragRegion() {
return (
<>
{/* Drag overlay — VS Code .titlebar-drag-region (titlebarpart.css:57-64) */}
<div style={DRAG_OVERLAY_STYLE} />
<div data-window-drag-region="" style={DRAG_OVERLAY_STYLE} />
{/* Top-edge resizer — VS Code .resizer (titlebarpart.css:249-256) */}
<div style={TOP_RESIZER_STYLE} />
</>
@@ -12,6 +12,7 @@ import {
getDesktopWindowControlsPresentation,
type DesktopWindowControlsPresentation,
} from "@/desktop/window-chrome-presentation";
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
import { useCustomDesktopWindowControls } from "@/utils/desktop-window";
import type { Theme } from "@/styles/theme";
@@ -143,6 +144,7 @@ export function DesktopWindowControls() {
return (
<View
dataSet={WINDOW_NO_DRAG_DATASET}
style={[styles.controls, { height: presentation.controlHeight }]}
testID="desktop-window-controls"
>
@@ -2,6 +2,7 @@ import { createContext, useContext, useCallback, useState, useId, type ReactNode
import { View, type LayoutChangeEvent } from "react-native";
import { StyleSheet } from "react-native-unistyles";
import { Portal, PortalHost } from "@gorhom/portal";
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { EdgeFade } from "@/components/ui/edge-fade";
@@ -74,7 +75,11 @@ export function FloatingHeaderLayout({ header, floating, children }: FloatingHea
</View>
</View>
) : null}
<View style={styles.statusOverlay} pointerEvents="box-none">
<View
style={styles.statusOverlay}
dataSet={WINDOW_OVERLAY_HOST_DATASET}
pointerEvents="box-none"
>
<PortalHost name={overlayHostName} />
</View>
</View>
@@ -5,6 +5,7 @@ import { router } from "expo-router";
import { ArrowLeft } from "lucide-react-native";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
import { SidebarMenuToggle } from "@/components/headers/sidebar-menu-toggle";
import {
@@ -17,6 +18,7 @@ import {
HEADER_INNER_HEIGHT_MOBILE,
HEADER_TOP_PADDING_MOBILE,
} from "@/constants/layout";
import { WindowChromeSafeArea } from "@/utils/desktop-window";
import type { ShortcutKey } from "@/utils/format-shortcut";
import { useTopBand } from "@/window-layout";
@@ -75,27 +77,30 @@ export function CompactHeader({
return (
<IconButtonChromeProvider value="header-island">
<View style={rootStyle}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
<WindowChromeSafeArea placement="inline" style={styles.chromeContainer}>
<TitlebarDragRegion />
<View style={rootStyle}>
<View
style={[
usesTitlebarHeight ? styles.titlebarRow : styles.row,
inDesktopTitlebar && styles.desktopTitlebarDividerSpace,
]}
>
<View style={styles.island}>
{navigation === "menu" ? <SidebarMenuToggle /> : <BackButton onBack={onBack} />}
</View>
<View style={styles.titleGroup}>
<CompactHeaderTitle
loading={loading}
title={title}
titleTestID={titleTestID}
subtitle={subtitle}
/>
</View>
{actions ? <View style={styles.island}>{actions}</View> : null}
</View>
<View style={styles.titleGroup}>
<CompactHeaderTitle
loading={loading}
title={title}
titleTestID={titleTestID}
subtitle={subtitle}
/>
</View>
{actions ? <View style={styles.island}>{actions}</View> : null}
</View>
</View>
</WindowChromeSafeArea>
</IconButtonChromeProvider>
);
}
@@ -154,6 +159,9 @@ function BackButton({ onBack }: { onBack?: () => void }) {
}
const styles = StyleSheet.create((theme) => ({
chromeContainer: {
position: "relative",
},
root: {
paddingHorizontal: theme.spacing[3],
},
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import { View, type StyleProp, type ViewStyle } from "react-native";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
import { PanelLeft } from "lucide-react-native";
import { WINDOW_NO_DRAG_DATASET } from "@/components/desktop/titlebar-drag-region";
import { HeaderToggleButton, headerIconSlotStyle } from "./header-toggle-button";
import { selectIsAgentListOpen, usePanelStore } from "@/stores/panel-store";
import { useIsCompactFormFactor } from "@/constants/layout";
@@ -50,10 +51,12 @@ function SidebarMenuToggleButton({
tooltipSide = "right",
testID = "menu-button",
nativeID = "menu-button",
dataSet,
}: Omit<SidebarMenuToggleProps, "style"> & {
isMobile: boolean;
extraMutedIdleIcon?: boolean;
resolvedStyle: StyleProp<ViewStyle>;
dataSet?: Record<string, string>;
}) {
const { t } = useTranslation();
const isOpen = usePanelStore((state) => selectIsAgentListOpen(state, { isCompact: isMobile }));
@@ -77,6 +80,7 @@ function SidebarMenuToggleButton({
tooltipSide={tooltipSide}
testID={testID}
nativeID={nativeID}
dataSet={dataSet}
style={resolvedStyle}
accessible
accessibilityRole="button"
@@ -128,6 +132,7 @@ export function WindowSidebarMenuToggle({ style, ...props }: SidebarMenuTogglePr
{...props}
isMobile={false}
extraMutedIdleIcon
dataSet={WINDOW_NO_DRAG_DATASET}
resolvedStyle={resolvedStyle}
/>
);
+3 -12
View File
@@ -37,10 +37,7 @@ import Animated, { runOnJS, useAnimatedStyle, useSharedValue } from "react-nativ
import { scheduleOnRN } from "react-native-worklets";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { StyleSheet, useUnistyles } from "react-native-unistyles";
import {
TitlebarDragRegion,
WINDOW_CONTENT_DATASET,
} from "@/components/desktop/titlebar-drag-region";
import { TitlebarDragRegion } from "@/components/desktop/titlebar-drag-region";
import { SidebarCloseButton } from "@/components/headers/sidebar-close-button";
import {
resolveDesktopSidebarInsetLeft,
@@ -698,15 +695,13 @@ function MobileSidebar({
interface SidebarNavScrollProps {
closeGestureRef: RefObject<GestureType | undefined>;
/** Web only: the viewport emits no window regions (see WINDOW_CONTENT_DATASET). */
windowContent?: boolean;
children: ReactNode;
}
// The capped, scrolling nav block shared by the mobile and desktop sidebars, with the
// divider below it. The divider is a sibling because Unistyles does not patch the
// gesture-handler ScrollView.
function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarNavScrollProps) {
function SidebarNavScroll({ closeGestureRef, children }: SidebarNavScrollProps) {
return (
<>
{platformIsNative ? (
@@ -723,7 +718,6 @@ function SidebarNavScroll({ closeGestureRef, windowContent, children }: SidebarN
</GHScrollView>
) : (
<ScrollView
dataSet={windowContent ? WINDOW_CONTENT_DATASET : undefined}
style={styles.navScroll}
showsVerticalScrollIndicator={false}
alwaysBounceVertical={false}
@@ -899,11 +893,8 @@ function DesktopSidebar({
</View>
) : null}
</View>
{/* The drag overlay stays above this viewport: Electron does not clip
app-region rects to scroll viewports, so a scrolled-out row would
still claim its no-drag rect. */}
{hasNavRows ? (
<SidebarNavScroll closeGestureRef={closeGestureRef} windowContent>
<SidebarNavScroll closeGestureRef={closeGestureRef}>
<SidebarNavRows style={styles.sidebarHeaderGroup} onBeforeNavigate={closeSidebar} />
</SidebarNavScroll>
) : null}
@@ -252,13 +252,7 @@ export function SplitContainer({
const renderRoot = useMemo(() => wrapRootPaneForStableMount(splitRoot.root), [splitRoot.root]);
const panesShareWorkspaceHeader = hasMultipleVisiblePanes(splitRoot.root);
const sharedCompactHeader = useMemo(
() =>
panesShareWorkspaceHeader ? (
<WindowChromeSafeArea placement="inline">
<TitlebarDragRegion />
{renderCompactHeader(null)}
</WindowChromeSafeArea>
) : null,
() => (panesShareWorkspaceHeader ? renderCompactHeader(null) : null),
[panesShareWorkspaceHeader, renderCompactHeader],
);
return (
@@ -800,16 +794,13 @@ const SplitPaneView = memo(function SplitPaneView({
});
const compactHeader = useMemo(
() =>
ownsWorkspaceHeader ? (
<WindowChromeSafeArea placement="inline">
<TitlebarDragRegion />
{renderCompactHeader({
ownsWorkspaceHeader
? renderCompactHeader({
tabs: paneTabs,
activeTabKey: activeTabDescriptor?.key ?? "",
actions: compactHeaderActions,
})}
</WindowChromeSafeArea>
) : null,
})
: null,
[
ownsWorkspaceHeader,
renderCompactHeader,
@@ -8,6 +8,7 @@ import {
} from "react";
import { StyleSheet, View } from "react-native";
import { PortalHost } from "@gorhom/portal";
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
import {
createFloatingPanelHosts,
type FloatingPanelHostRect,
@@ -57,7 +58,13 @@ export function FloatingPanelPortalHost({
}, [name]);
return (
<View ref={hostRef} collapsable={false} pointerEvents="box-none" style={styles.host}>
<View
ref={hostRef}
collapsable={false}
dataSet={WINDOW_OVERLAY_HOST_DATASET}
pointerEvents="box-none"
style={styles.host}
>
<PortalHost name={name} />
</View>
);
@@ -185,6 +185,13 @@ export function ComposerEditingScope({
const scope = useMemo(() => ({ tabId, targetKey }), [tabId, targetKey]);
return <ScopeContext.Provider value={scope}>{children}</ScopeContext.Provider>;
}
/**
* Composers inside edit in sessions of their own, apart from the workspace tab around them: a
* plugin's `AgentChat` in a panel must not share the panel's fullscreen, caret or command target.
*/
export function LocalComposerEditingScope({ children }: { children: ReactNode }) {
return <ScopeContext.Provider value={null}>{children}</ScopeContext.Provider>;
}
export function useComposerEditingSession(
purpose: ComposerInputMode,
provided?: ComposerEditingSession,
@@ -80,6 +80,7 @@ interface SearchCall {
}
interface HarnessInput {
enabled?: boolean;
initialAttachments?: UserComposerAttachment[];
initialCwd?: string;
initialText?: string;
@@ -137,6 +138,7 @@ function useHarness(client: ForgeSearchClient, input: HarnessInput = {}) {
input.initialAttachments ?? [],
);
const autoAttach = useComposerForgeAutoAttach({
enabled: input.enabled ?? true,
text,
remoteUrl: input.remote ?? remoteUrl,
attachments,
@@ -190,6 +192,27 @@ describe("useComposerForgeAutoAttach", () => {
vi.useRealTimers();
});
it("leaves pasted links as text in a composer that takes no attachments", async () => {
vi.useFakeTimers();
const client = createSearchClient([pr101]);
const onChangeRequestDetected = vi.fn();
const { result } = renderHook(
() => useHarness(client, { enabled: false, onChangeRequestDetected }),
{ wrapper: createWrapper() },
);
act(() => {
result.current.setText("Please review https://github.com/acme/paseo/pull/101");
});
expect(result.current.isResolving).toBe(false);
await flushDebounce();
expect(result.current.attachments).toEqual([]);
expect(onChangeRequestDetected).not.toHaveBeenCalled();
expect(client.calls).toEqual([]);
vi.useRealTimers();
});
it("adds a matching pasted GitLab MR URL as a composer attachment", async () => {
vi.useFakeTimers();
const client = createSearchClient([gitlabMr73]);
+14 -9
View File
@@ -19,6 +19,8 @@ import { forgeItemKey } from "./attachments/forge-item-key";
const AUTO_ATTACH_DEBOUNCE_MS = 300;
interface ComposerForgeAutoAttachInput {
/** Whether links in the text become attachments: off for a composer that takes none. */
enabled: boolean;
text: string;
remoteUrl: string | null | undefined;
attachments: UserComposerAttachment[];
@@ -164,6 +166,11 @@ export function useComposerForgeAutoAttach(
);
}
/** The forge links in the text that auto-attach would act on. */
function linkedForgeRefs(params: ComposerForgeAutoAttachInput): ForgeRef[] {
return params.enabled ? extractForgeRefs(params.text, params.remoteUrl) : [];
}
function getLookupCandidateKey(
params: ComposerForgeAutoAttachInput,
removedRefKeys: ReadonlySet<string>,
@@ -175,7 +182,7 @@ function getLookupCandidateRefs(
params: ComposerForgeAutoAttachInput,
removedRefKeys: ReadonlySet<string>,
): ForgeRef[] {
return extractForgeRefs(params.text, params.remoteUrl).filter((ref) => {
return linkedForgeRefs(params).filter((ref) => {
const key = forgeRefKey(ref);
return !removedRefKeys.has(key) && !hasForgeAttachment(params.attachments, ref);
});
@@ -196,7 +203,7 @@ function getLookupRelevanceKey(
params: ComposerForgeAutoAttachInput,
removedRefKeys: ReadonlySet<string>,
): string {
return extractForgeRefs(params.text, params.remoteUrl)
return linkedForgeRefs(params)
.map(forgeRefKey)
.filter((key) => !removedRefKeys.has(key))
.sort()
@@ -204,7 +211,7 @@ function getLookupRelevanceKey(
}
function getPresentChangeRequestKey(params: ComposerForgeAutoAttachInput): string {
return extractForgeRefs(params.text, params.remoteUrl)
return linkedForgeRefs(params)
.filter((ref) => ref.kind === "change_request")
.map(forgeRefKey)
.sort()
@@ -248,7 +255,7 @@ function suppressRefsCarriedAcrossTargets({
previousTargetRef.current = { serverId: params.serverId, cwd: params.cwd };
if (!targetChanged) return;
for (const ref of extractForgeRefs(params.text, params.remoteUrl)) {
for (const ref of linkedForgeRefs(params)) {
removedRefKeys.add(forgeRefKey(ref));
}
}
@@ -261,7 +268,7 @@ function notifyNewChangeRequestRefs({
presentChangeRequestKeysRef: RefObject<Set<string>>;
}): void {
const currentKeys = new Set(
extractForgeRefs(params.text, params.remoteUrl)
linkedForgeRefs(params)
.filter((ref) => ref.kind === "change_request")
.map(forgeRefKey),
);
@@ -449,7 +456,7 @@ function refsReadyForLookup({
return [];
}
return extractForgeRefs(params.text, params.remoteUrl).filter((ref) => {
return linkedForgeRefs(params).filter((ref) => {
const key = forgeRefKey(ref);
return (
!removedRefKeys.has(key) &&
@@ -489,9 +496,7 @@ async function fetchForgeRefSearch({
}
function isRefStillPresent(ref: ForgeRef, params: ComposerForgeAutoAttachInput): boolean {
return extractForgeRefs(params.text, params.remoteUrl).some(
(candidate) => forgeRefKey(candidate) === forgeRefKey(ref),
);
return linkedForgeRefs(params).some((candidate) => forgeRefKey(candidate) === forgeRefKey(ref));
}
function isSameLookupTarget(
+44 -48
View File
@@ -123,7 +123,10 @@ import { useShortcutKeys } from "@/hooks/use-shortcut-keys";
import { AutocompletePopover } from "@/components/ui/autocomplete-popover";
import type { AutocompleteOption } from "@/components/ui/autocomplete";
import { useAgentAutocomplete } from "@/hooks/use-agent-autocomplete";
import { usePluginClientSlashCommands } from "@/plugins/client-slash-commands";
import {
type PluginClientSlashCommand,
usePluginClientSlashCommands,
} from "@/plugins/client-slash-commands";
import {
executePluginClientSlashCommand,
resolvePluginClientSlashCommand,
@@ -226,6 +229,7 @@ type AttachmentListUpdater =
| ((prev: UserComposerAttachment[]) => UserComposerAttachment[]);
const EMPTY_ATTACHMENT_SCOPE_KEYS: readonly string[] = [];
const NO_PLUGIN_CLIENT_SLASH_COMMANDS: PluginClientSlashCommand[] = [];
function noop() {}
const noopCallback = () => {};
@@ -1402,6 +1406,8 @@ function ComposerContentImpl({
const [isForgeResolving, setIsForgeResolving] = useState(false);
const forgeConfiguration = useMemo(
() => ({
// A mode without attachments sends text as written, so links stay text.
enabled: mode.showAttachments,
remoteUrl: resolveCheckoutRemoteUrl(checkoutStatusQuery.status),
attachments,
client,
@@ -1414,6 +1420,7 @@ function ComposerContentImpl({
onChangeRequestAdded: onForgeChangeRequestAutoAttach,
}),
[
mode.showAttachments,
checkoutStatusQuery.status,
attachments,
client,
@@ -1456,11 +1463,16 @@ function ComposerContentImpl({
onChangeAttachments: setSelectedAttachments,
anchorRef: attachButtonRef,
});
const pluginClientSlashCommands = usePluginClientSlashCommands({
const installedPluginClientSlashCommands = usePluginClientSlashCommands({
serverId,
workspaceId,
agentId,
});
// One switch for every client-side command, built-in or plugin, on the send and queue paths.
const handlesClientCommands = mode.runsClientCommands;
const pluginClientSlashCommands = handlesClientCommands
? installedPluginClientSlashCommands
: NO_PLUGIN_CLIENT_SLASH_COMMANDS;
const isComposerLocked = resolveIsComposerLocked(submitBehavior, isSubmitLoading);
const keyboardHandlerIdRef = useRef(
`message-input:${serverId}:${agentId}:${Math.random().toString(36).slice(2)}`,
@@ -1569,6 +1581,7 @@ function ComposerContentImpl({
const runClientSlashCommand = useCallback(
(command: ClientSlashCommand): boolean => {
if (!handlesClientCommands) return false;
if (command.execution !== "immediate" || !onClientSlashCommand) {
return false;
}
@@ -1595,6 +1608,7 @@ function ComposerContentImpl({
[
blurOnSubmit,
clearDraft,
handlesClientCommands,
onClientSlashCommand,
resetSuppression,
setSelectedAttachments,
@@ -1631,6 +1645,22 @@ function ComposerContentImpl({
[blurOnSubmit, clearDraft, replaceUserInput, resetSuppression, setSelectedAttachments, t],
);
/** Runs `text` as a client command when it is one; false sends it to the agent. */
const runComposerClientCommand = useCallback(
(text: string, hasAttachments: boolean): boolean => {
const clientSlashCommand = resolveClientSlashCommand({ text, hasAttachments });
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) return true;
const pluginSlashCommand = resolvePluginClientSlashCommand({
text,
commands: pluginClientSlashCommands,
});
if (!pluginSlashCommand) return false;
runPluginClientSlashCommand(pluginSlashCommand, hasAttachments);
return true;
},
[pluginClientSlashCommands, runClientSlashCommand, runPluginClientSlashCommand],
);
const { pickImages } = useImageAttachmentPicker();
const { pickFiles } = useFilePicker();
const agentIdRef = useRef(agentId);
@@ -1923,21 +1953,7 @@ function ComposerContentImpl({
const handleSubmit = useCallback(
(payload: MessagePayload) => {
const outgoingAttachments = buildOutgoingAttachments(attachments);
const clientSlashCommand = resolveClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
});
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) {
return;
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (runComposerClientCommand(payload.text, outgoingAttachments.length > 0)) return;
if (blurOnSubmit) {
messageInputRef.current?.blur();
@@ -1948,9 +1964,7 @@ function ComposerContentImpl({
attachments,
blurOnSubmit,
buildOutgoingAttachments,
runClientSlashCommand,
pluginClientSlashCommands,
runPluginClientSlashCommand,
runComposerClientCommand,
sendMessageWithContent,
],
);
@@ -2191,31 +2205,10 @@ function ComposerContentImpl({
const handleQueue = useCallback(
(payload: MessagePayload) => {
const outgoingAttachments = buildOutgoingAttachments(attachments);
const clientSlashCommand = resolveClientSlashCommand({
text: payload.text,
hasAttachments: outgoingAttachments.length > 0,
});
if (clientSlashCommand && runClientSlashCommand(clientSlashCommand)) {
return;
}
const pluginSlashCommand = resolvePluginClientSlashCommand({
text: payload.text,
commands: pluginClientSlashCommands,
});
if (pluginSlashCommand) {
runPluginClientSlashCommand(pluginSlashCommand, outgoingAttachments.length > 0);
return;
}
if (runComposerClientCommand(payload.text, outgoingAttachments.length > 0)) return;
void sendMessageWithContent(payload.text, outgoingAttachments);
},
[
attachments,
buildOutgoingAttachments,
pluginClientSlashCommands,
runClientSlashCommand,
runPluginClientSlashCommand,
sendMessageWithContent,
],
[attachments, buildOutgoingAttachments, runComposerClientCommand, sendMessageWithContent],
);
// An open autocomplete owns the arrows; otherwise they may recall sent messages.
@@ -2305,9 +2298,10 @@ function ComposerContentImpl({
],
);
const showsUsage = mode.showUsage;
const beforeVoiceContent = useMemo(
() =>
hasAgent ? (
hasAgent && showsUsage ? (
<View style={styles.contextWindowMeterSlot}>
<ContextWindowMeter
serverId={serverId}
@@ -2322,6 +2316,7 @@ function ComposerContentImpl({
) : null,
[
hasAgent,
showsUsage,
serverId,
agentId,
agentState.contextWindowMaxTokens,
@@ -2615,7 +2610,8 @@ function ComposerContentImpl({
onGenericFiles: handleGenericFilesDropped,
onWorkspaceFile: handleWorkspaceFileDropped,
},
{ disabled: isSubmitLoadingVisible },
// A mode without attachments refuses files by any route, not only the button.
{ disabled: isSubmitLoadingVisible || !mode.showAttachments },
);
// Focusing the composer on a touch screen raises the on-screen keyboard over the conversation.
@@ -2713,9 +2709,9 @@ function ComposerContentImpl({
cwd={cwd}
attachmentMenuItems={attachmentMenuItems}
onAttachButtonRef={handleAttachButtonRef}
onAddImages={addImages}
onPasteFiles={handlePasteFiles}
onPasteImages={handleNativePasteImages}
onAddImages={mode.showAttachments ? addImages : undefined}
onPasteFiles={mode.showAttachments ? handlePasteFiles : undefined}
onPasteImages={mode.showAttachments ? handleNativePasteImages : undefined}
client={client}
isReadyForDictation={isDictationReady}
placeholder={messagePlaceholder}
+25 -3
View File
@@ -1,13 +1,16 @@
/**
* What a composer is being used for. `Composer` and `MessageInput` are one
* component with two jobs, not two components: a terminal prompt still wants
* component with several jobs, not several components: a terminal prompt still wants
* the same bordered surface, grow-on-newline, submit button, focus handling,
* and keyboard shift that a chat message gets.
*
* `message` is a chat composer reduced to a text box and Send: what the user types
* reaches the agent as written, with nothing the app interprets on the way.
*
* Callers pick a mode and nothing else. What a mode implies lives here, so the
* two presentations cannot drift apart one prop at a time.
* presentations cannot drift apart one prop at a time.
*/
export type ComposerInputMode = "chat" | "terminal";
export type ComposerInputMode = "chat" | "message" | "terminal";
export interface ComposerInputModePresentation {
/** Attachments, dictation/voice, slash-and-@ autocomplete, and the model/mode
@@ -16,6 +19,11 @@ export interface ComposerInputModePresentation {
showVoice: boolean;
showAutocomplete: boolean;
showAgentControls: boolean;
/** The context window and cost meter beside Send. */
showUsage: boolean;
/** Client slash commands, built-in (`/exit`, `/clear`) and plugin, run in the
* app instead of being sent. */
runsClientCommands: boolean;
/** Argv is read character by character, so it gets the terminal's own font. */
isMonospace: boolean;
/** i18n key for the text input's accessible name. */
@@ -28,6 +36,18 @@ const PRESENTATION_BY_MODE: Record<ComposerInputMode, ComposerInputModePresentat
showVoice: true,
showAutocomplete: true,
showAgentControls: true,
showUsage: true,
runsClientCommands: true,
isMonospace: false,
accessibilityLabelKey: "composer.input.accessibilityLabel",
},
message: {
showAttachments: false,
showVoice: false,
showAutocomplete: false,
showAgentControls: false,
showUsage: false,
runsClientCommands: false,
isMonospace: false,
accessibilityLabelKey: "composer.input.accessibilityLabel",
},
@@ -36,6 +56,8 @@ const PRESENTATION_BY_MODE: Record<ComposerInputMode, ComposerInputModePresentat
showVoice: false,
showAutocomplete: false,
showAgentControls: false,
showUsage: false,
runsClientCommands: true,
isMonospace: true,
accessibilityLabelKey: "composer.input.terminalAccessibilityLabel",
},
+2
View File
@@ -257,6 +257,8 @@ export interface DesktopInvokeBridge {
export interface DesktopHostBridge {
platform?: string;
deviceName?: string;
osVersion?: string;
windowChromeMode?: string;
browserHostLabel?: string;
browserHostInstanceId?: string;
@@ -0,0 +1,249 @@
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
export interface AppClientIdentity {
clientType: "mobile" | "browser";
clientInfo: HelloClientInfo;
}
export interface DesktopIdentityInput {
platform?: string;
deviceName?: string;
osVersion?: string;
browserHostLabel?: string;
}
export interface WebNavigatorUserAgentData {
platform?: string;
brands?: ReadonlyArray<{ brand: string; version?: string }>;
}
export interface WebIdentityInput {
userAgent?: string;
userAgentData?: WebNavigatorUserAgentData;
}
export interface NativePlatformConstantsInput {
Model?: string;
Manufacturer?: string;
Brand?: string;
Release?: string;
systemName?: string;
osVersion?: string;
interfaceIdiom?: string;
}
export interface NativeIdentityInput {
os: string;
version?: string | number;
constants?: NativePlatformConstantsInput;
deviceName?: string | null;
}
const LEGACY_WINDOW_SUFFIX_PATTERN = /\s*·\s*Window\s+\d+(?:\s*\([0-9A-Fa-f]+\))?$/;
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
const normalized = raw?.toLowerCase();
if (normalized === "darwin" || normalized === "macos") return "macos";
if (normalized === "linux") return "linux";
if (normalized === "win32" || normalized === "windows") return "windows";
return "unknown";
}
function osNameForDesktopPlatform(platform: HelloClientPlatform): string | undefined {
if (platform === "macos") return "macOS";
if (platform === "linux") return "Linux";
if (platform === "windows") return "Windows";
return undefined;
}
function normalizeNonEmpty(
value: string | null | undefined,
maxLength: number,
): string | undefined {
const trimmed = value?.trim();
return trimmed ? trimmed.slice(0, maxLength) : undefined;
}
function cleanDesktopName(desktop: DesktopIdentityInput): string | undefined {
const explicit = normalizeNonEmpty(desktop.deviceName, 128);
if (explicit) return explicit;
// COMPAT(legacyBrowserHostLabel): added in v0.19.x, strip window suffix from older Electron preloads without --paseo-device-name; remove after 2027-06-15.
const stripped = desktop.browserHostLabel?.replace(LEGACY_WINDOW_SUFFIX_PATTERN, "").trim();
return stripped ? stripped.slice(0, 128) : undefined;
}
export function resolveDesktopClientIdentity(desktop: DesktopIdentityInput): AppClientIdentity {
const platform = mapDesktopPlatform(desktop.platform);
const osName = osNameForDesktopPlatform(platform);
const name = cleanDesktopName(desktop);
const osVersion = normalizeNonEmpty(desktop.osVersion, 48);
return {
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform,
...(name ? { name } : {}),
...(osName ? { osName } : {}),
...(osVersion ? { osVersion } : {}),
},
};
}
function parseBrowserNameFromBrands(
brands: ReadonlyArray<{ brand: string; version?: string }> | undefined,
): string | undefined {
if (!brands || brands.length === 0) return undefined;
const names = brands.map((entry) => entry.brand);
if (names.some((brand) => /Microsoft Edge/i.test(brand))) return "Edge";
if (names.some((brand) => /Opera/i.test(brand))) return "Opera";
if (names.some((brand) => /Brave/i.test(brand))) return "Brave";
if (names.some((brand) => /Google Chrome/i.test(brand))) return "Chrome";
if (names.some((brand) => /Chromium/i.test(brand))) return "Chrome";
return undefined;
}
function parseBrowserNameFromUserAgent(userAgent: string | undefined): string | undefined {
if (!userAgent) return undefined;
if (/Edg(?:A|iOS)?\//.test(userAgent)) return "Edge";
if (/OPR\//.test(userAgent)) return "Opera";
if (/(?:Firefox|FxiOS)\//.test(userAgent)) return "Firefox";
if (/(?:Chrome|CriOS)\//.test(userAgent) && !/Edg(?:A|iOS)?\//.test(userAgent)) return "Chrome";
if (/Safari\//.test(userAgent) && !/(?:Chrome|CriOS)\//.test(userAgent)) return "Safari";
return undefined;
}
function parseOsNameFromPlatformHint(platform: string | undefined): string | undefined {
if (!platform) return undefined;
const normalized = platform.trim().toLowerCase();
if (normalized === "macos" || normalized === "mac os" || normalized === "macintel")
return "macOS";
if (normalized === "windows" || normalized === "win32") return "Windows";
if (normalized === "linux") return "Linux";
if (normalized === "android") return "Android";
if (normalized === "ios") return "iOS";
if (normalized === "chrome os" || normalized === "chromeos") return "ChromeOS";
return undefined;
}
function parseOsNameFromUserAgent(userAgent: string | undefined): string | undefined {
if (!userAgent) return undefined;
if (/iPhone|iPad|iPod/.test(userAgent)) return "iOS";
if (/Android/.test(userAgent)) return "Android";
if (/CrOS/.test(userAgent)) return "ChromeOS";
if (/Windows NT|Win64|WOW64/.test(userAgent)) return "Windows";
if (/Macintosh|Mac OS X/.test(userAgent)) return "macOS";
if (/Linux|X11/.test(userAgent)) return "Linux";
return undefined;
}
export function resolveWebClientIdentity(input: WebIdentityInput): AppClientIdentity {
const browserName =
parseBrowserNameFromBrands(input.userAgentData?.brands) ??
parseBrowserNameFromUserAgent(input.userAgent);
const osName =
parseOsNameFromPlatformHint(input.userAgentData?.platform) ??
parseOsNameFromUserAgent(input.userAgent);
const name = browserName && osName ? `${browserName} on ${osName}` : browserName;
return {
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
...(name ? { name: name.slice(0, 128) } : {}),
...(browserName ? { browserName: browserName.slice(0, 48) } : {}),
...(osName ? { osName: osName.slice(0, 48) } : {}),
},
};
}
function cleanAndroidModel(
manufacturer: string | undefined,
model: string | undefined,
): string | undefined {
const cleanModel = model?.trim();
if (!cleanModel) return undefined;
const cleanManufacturer = manufacturer?.trim();
if (
!cleanManufacturer ||
cleanModel.toLowerCase().startsWith(cleanManufacturer.toLowerCase()) ||
cleanModel.toLowerCase().startsWith("pixel")
) {
return cleanModel.slice(0, 96);
}
const formattedManufacturer =
cleanManufacturer === cleanManufacturer.toLowerCase()
? `${cleanManufacturer[0]?.toUpperCase() ?? ""}${cleanManufacturer.slice(1)}`
: cleanManufacturer;
return `${formattedManufacturer} ${cleanModel}`.slice(0, 96);
}
function resolveAndroidClientIdentity(
input: NativeIdentityInput,
explicitName: string | undefined,
): AppClientIdentity {
const constants = input.constants;
const deviceModel = cleanAndroidModel(
constants?.Manufacturer ?? constants?.Brand,
constants?.Model,
);
const rawVersion =
constants?.Release ?? (input.version !== undefined ? String(input.version) : undefined);
const osVersion = normalizeNonEmpty(rawVersion, 48);
const name = explicitName ?? deviceModel;
return {
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "android",
osName: "Android",
...(osVersion ? { osVersion } : {}),
...(deviceModel ? { deviceModel } : {}),
...(name ? { name } : {}),
},
};
}
function resolveIosClientIdentity(
input: NativeIdentityInput,
explicitName: string | undefined,
): AppClientIdentity {
const constants = input.constants;
const isPad = constants?.interfaceIdiom === "pad";
const deviceModel = isPad ? "iPad" : "iPhone";
const osName = normalizeNonEmpty(constants?.systemName, 48) ?? (isPad ? "iPadOS" : "iOS");
const rawVersion =
constants?.osVersion ?? (input.version !== undefined ? String(input.version) : undefined);
const osVersion = normalizeNonEmpty(rawVersion, 48);
const name = explicitName ?? deviceModel;
return {
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "ios",
osName,
...(osVersion ? { osVersion } : {}),
deviceModel,
...(name ? { name } : {}),
},
};
}
export function resolveNativeClientIdentity(input: NativeIdentityInput): AppClientIdentity {
const explicitName = normalizeNonEmpty(input.deviceName, 128);
if (input.os === "android") {
return resolveAndroidClientIdentity(input, explicitName);
}
if (input.os === "ios") {
return resolveIosClientIdentity(input, explicitName);
}
return {
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "unknown",
...(explicitName ? { name: explicitName } : {}),
},
};
}
+12 -19
View File
@@ -1,23 +1,16 @@
import Constants from "expo-constants";
import { Platform } from "react-native";
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
import {
resolveNativeClientIdentity,
type AppClientIdentity,
type NativePlatformConstantsInput,
} from "./client-info-parsers";
function mapNativePlatform(os: string): HelloClientPlatform {
if (os === "ios") return "ios";
if (os === "android") return "android";
return "unknown";
}
export function resolveAppClientIdentity(): {
clientType: "mobile" | "browser";
clientInfo: HelloClientInfo;
} {
const deviceName = Constants.deviceName?.trim();
return {
clientType: "mobile",
clientInfo: {
platform: mapNativePlatform(Platform.OS),
...(deviceName ? { name: deviceName.slice(0, 128) } : {}),
},
};
export function resolveAppClientIdentity(): AppClientIdentity {
return resolveNativeClientIdentity({
os: Platform.OS,
version: Platform.Version,
constants: Platform.constants as NativePlatformConstantsInput | undefined,
deviceName: Constants.deviceName,
});
}
@@ -0,0 +1,252 @@
import { describe, expect, it } from "vitest";
import { resolveAppClientIdentity } from "./client-info";
import { resolveNativeClientIdentity } from "./client-info-parsers";
describe("resolveAppClientIdentity (Electron and Web)", () => {
it("identifies Electron Desktop on macOS, Linux, and Windows with clean deviceName and osVersion", () => {
expect(
resolveAppClientIdentity({
desktop: {
platform: "darwin",
deviceName: "MacBook Pro",
osVersion: "15.3.1",
browserHostLabel: "MacBook Pro · Window 1 (ABCDEF)",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "macos",
name: "MacBook Pro",
osName: "macOS",
osVersion: "15.3.1",
},
});
expect(
resolveAppClientIdentity({
desktop: {
platform: "linux",
deviceName: "workstation",
osVersion: "Ubuntu 24.04.1 LTS",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "linux",
name: "workstation",
osName: "Linux",
osVersion: "Ubuntu 24.04.1 LTS",
},
});
expect(
resolveAppClientIdentity({
desktop: {
platform: "win32",
deviceName: "DEV-PC",
osVersion: "10.0.22631",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "windows",
name: "DEV-PC",
osName: "Windows",
osVersion: "10.0.22631",
},
});
});
it("strips legacy Window N (HEX) suffix if older Electron preload only provides browserHostLabel", () => {
expect(
resolveAppClientIdentity({
desktop: {
platform: "linux",
browserHostLabel: "devbox · Window 2 (9F0A1B)",
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "linux",
name: "devbox",
osName: "Linux",
},
});
});
it("identifies web browsers and operating systems from userAgent and userAgentData", () => {
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Chrome",
osName: "macOS",
name: "Chrome on macOS",
},
});
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:133.0) Gecko/20100101 Firefox/133.0",
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Firefox",
osName: "Windows",
name: "Firefox on Windows",
},
});
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.2 Safari/605.1.15",
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Safari",
osName: "macOS",
name: "Safari on macOS",
},
});
expect(
resolveAppClientIdentity({
desktop: null,
userAgent:
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36 Edg/131.0.0.0",
userAgentData: {
platform: "Linux",
brands: [{ brand: "Microsoft Edge", version: "131" }],
},
}),
).toEqual({
clientType: "browser",
clientInfo: {
appKind: "web",
platform: "web",
browserName: "Edge",
osName: "Linux",
name: "Edge on Linux",
},
});
});
});
describe("resolveNativeClientIdentity (Android and iOS)", () => {
it("extracts Android model, manufacturer, and release from RN Platform.constants", () => {
expect(
resolveNativeClientIdentity({
os: "android",
constants: {
Manufacturer: "Google",
Model: "Pixel 9 Pro",
Release: "15",
},
deviceName: undefined,
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "android",
osName: "Android",
osVersion: "15",
deviceModel: "Pixel 9 Pro",
name: "Pixel 9 Pro",
},
});
expect(
resolveNativeClientIdentity({
os: "android",
constants: {
Manufacturer: "samsung",
Model: "SM-S928B",
Release: "14",
},
deviceName: "Mo's Galaxy",
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "android",
osName: "Android",
osVersion: "14",
deviceModel: "Samsung SM-S928B",
name: "Mo's Galaxy",
},
});
});
it("extracts iOS and iPadOS metadata from RN Platform.constants", () => {
expect(
resolveNativeClientIdentity({
os: "ios",
constants: {
systemName: "iOS",
osVersion: "18.3",
interfaceIdiom: "phone",
},
deviceName: "iPhone",
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "ios",
osName: "iOS",
osVersion: "18.3",
deviceModel: "iPhone",
name: "iPhone",
},
});
expect(
resolveNativeClientIdentity({
os: "ios",
constants: {
systemName: "iPadOS",
osVersion: "18.3",
interfaceIdiom: "pad",
},
deviceName: undefined,
}),
).toEqual({
clientType: "mobile",
clientInfo: {
appKind: "mobile",
platform: "ios",
osName: "iPadOS",
osVersion: "18.3",
deviceModel: "iPad",
name: "iPad",
},
});
});
});
+38 -37
View File
@@ -1,47 +1,48 @@
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
import { getIsElectron } from "@/constants/platform";
import { getDesktopHost } from "@/desktop/host";
import {
resolveDesktopClientIdentity,
resolveWebClientIdentity,
type AppClientIdentity,
type DesktopIdentityInput,
type WebNavigatorUserAgentData,
} from "./client-info-parsers";
function mapDesktopPlatform(raw: string | undefined): HelloClientPlatform {
const normalized = raw?.toLowerCase();
if (normalized === "darwin" || normalized === "macos") return "macos";
if (normalized === "linux") return "linux";
if (normalized === "win32" || normalized === "windows") return "windows";
return "unknown";
interface WebRuntimeEnv {
desktop?: DesktopIdentityInput | null;
userAgent?: string;
userAgentData?: WebNavigatorUserAgentData;
}
function parseBrowserName(userAgent: string | undefined): string | undefined {
if (!userAgent) return undefined;
if (/Edg\//.test(userAgent)) return "Edge";
if (/Firefox\//.test(userAgent)) return "Firefox";
if (/Chrome\//.test(userAgent) && !/Edg\//.test(userAgent)) return "Chrome";
if (/Safari\//.test(userAgent) && !/Chrome\//.test(userAgent)) return "Safari";
return undefined;
function readNavigatorUserAgentData(): WebNavigatorUserAgentData | undefined {
if (typeof navigator === "undefined") return undefined;
const candidate = (navigator as Navigator & { userAgentData?: WebNavigatorUserAgentData })
.userAgentData;
return candidate && typeof candidate === "object" ? candidate : undefined;
}
export function resolveAppClientIdentity(): {
clientType: "mobile" | "browser";
clientInfo: HelloClientInfo;
} {
if (getIsElectron()) {
const desktop = getDesktopHost();
const label = desktop?.browserHostLabel?.trim();
return {
clientType: "mobile",
clientInfo: {
platform: mapDesktopPlatform(desktop?.platform),
...(label ? { name: label.slice(0, 128) } : {}),
},
};
function resolveDesktopInput(env?: WebRuntimeEnv): DesktopIdentityInput | null {
if (env && "desktop" in env) {
return env.desktop ?? null;
}
return getIsElectron() ? getDesktopHost() : null;
}
function resolveUserAgentInput(env?: WebRuntimeEnv): string | undefined {
if (env && "userAgent" in env) {
return env.userAgent;
}
return typeof navigator !== "undefined" ? navigator.userAgent : undefined;
}
export function resolveAppClientIdentity(env?: WebRuntimeEnv): AppClientIdentity {
const desktop = resolveDesktopInput(env);
if (desktop) {
return resolveDesktopClientIdentity(desktop);
}
const browserName =
typeof navigator !== "undefined" ? parseBrowserName(navigator.userAgent) : undefined;
return {
clientType: "browser",
clientInfo: {
platform: "web",
...(browserName ? { name: browserName } : {}),
},
};
return resolveWebClientIdentity({
userAgent: resolveUserAgentInput(env),
userAgentData: env && "userAgentData" in env ? env.userAgentData : readNavigatorUserAgentData(),
});
}
@@ -6,8 +6,6 @@ import type { TFunction } from "i18next";
import type {
DaemonClientsSnapshot,
DaemonSessionSummary,
DaemonSessionTransport,
WSClientType,
} from "@getpaseo/protocol/daemon-clients";
import type { DaemonPermission } from "@getpaseo/protocol/messages";
import type { HostDirectory, HostSummary } from "@getpaseo/protocol/hosts";
@@ -21,10 +19,19 @@ import {
import { StatusBadge } from "@/components/ui/status-badge";
import { useHostRuntimeClient, useHostRuntimeSnapshot } from "@/runtime/host-runtime";
import { useSessionStore, type DaemonServerInfo } from "@/stores/session-store";
import {
formatAppDetail,
formatAuthMethodLabel,
formatDeviceDetail,
formatSessionHint,
formatSessionTitle,
formatTransportLabel,
} from "./device-display";
import { formatConnectedDuration, summarizePermissions } from "./scope-summary";
import { DaemonPasswordSheet } from "./daemon-password-sheet";
const UPDATES_DOCS_URL = "https://paseo.sh/docs/updates";
const RELATIVE_TIME_REFRESH_MS = 60_000;
type StatusDotTone = "online" | "warning" | "error" | "offline";
@@ -51,6 +58,17 @@ const STATUS_DOTS: Record<StatusDotTone, React.ReactNode> = {
offline: <StatusDot tone="offline" />,
};
function useMinuteTick(): number {
const [nowMs, setNowMs] = useState(() => Date.now());
useEffect(() => {
const timer = setInterval(() => {
setNowMs(Date.now());
}, RELATIVE_TIME_REFRESH_MS);
return () => clearInterval(timer);
}, []);
return nowMs;
}
function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[]; t: TFunction }) {
const summary = summarizePermissions(permissions);
let label: string;
@@ -66,15 +84,23 @@ function ScopePill({ permissions, t }: { permissions: readonly DaemonPermission[
return <StatusBadge label={label} variant="muted" size="xs" />;
}
function PermissionPillsRow({
function AccessDetailRow({
permissions,
t,
}: {
permissions: readonly DaemonPermission[];
t: TFunction;
}) {
const summary = summarizePermissions(permissions);
if (summary.kind === "full") {
return (
<SettingsRow label={t("devices.details.access")}>
<Text style={styles.nestedValue}>{t("devices.scopes.fullAccess")}</Text>
</SettingsRow>
);
}
return (
<SettingsRow label={t("devices.details.permissions")}>
<SettingsRow label={t("devices.details.access")}>
<View style={styles.scopePills}>
{permissions.length > 0 ? (
permissions.map((permission) => (
@@ -88,9 +114,13 @@ function PermissionPillsRow({
);
}
function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFunction): string | null {
function formatDurationLabel(
isoTimestamp: string | null | undefined,
nowMs: number,
t: TFunction,
): string | null {
if (!isoTimestamp) return null;
const duration = formatConnectedDuration(isoTimestamp);
const duration = formatConnectedDuration(isoTimestamp, nowMs);
if (!duration) return null;
if (duration.kind === "just_now") return t("devices.time.justNow");
if (duration.kind === "minutes") return t("devices.time.minutesAgo", { count: duration.count });
@@ -98,77 +128,26 @@ function formatDurationLabel(isoTimestamp: string | null | undefined, t: TFuncti
return t("devices.time.daysAgo", { count: duration.count });
}
function formatTransportLabel(
transport: DaemonSessionTransport,
viaHostName: string | null,
t: TFunction,
): string {
switch (transport) {
case "local_ipc":
case "local":
return t("devices.transport.local");
case "tailscale":
return t("devices.transport.tailscale");
case "relay":
return t("devices.transport.relay");
case "hub":
return t("devices.transport.hub");
case "via":
return viaHostName
? t("devices.transport.via", { host: viaHostName })
: t("devices.transport.viaHost");
case "direct":
return t("devices.transport.direct");
}
}
function formatClientPlatformLabel(
clientType: WSClientType,
platform: string | null,
t: TFunction,
): string {
if (platform === "ios") return "iOS";
if (platform === "android") return "Android";
if (platform === "macos" || platform === "linux" || platform === "windows") {
return t("devices.kind.desktop");
}
if (clientType === "browser" || platform === "web") return t("devices.kind.web");
if (clientType === "mobile") return t("devices.kind.mobile");
if (clientType === "hub") return t("devices.kind.hub");
if (clientType === "cli") return "CLI";
return "MCP";
}
function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
if (session.isCurrentSession) return t("devices.connected.thisDevice");
if (session.name) return session.name;
return formatClientPlatformLabel(session.clientType, session.platform, t);
}
function formatSessionHint(
session: DaemonSessionSummary,
viaHostName: string | null,
t: TFunction,
): string {
const transport = formatTransportLabel(session.transport, viaHostName, t);
const platform = formatClientPlatformLabel(session.clientType, session.platform, t);
const detail = session.appVersion ? `${platform} ${session.appVersion}` : platform;
return detail === transport ? transport : `${transport} · ${detail}`;
}
function ConnectedClientRow({
session,
viaHostName,
nowMs,
}: {
session: DaemonSessionSummary;
viaHostName: string | null;
nowMs: number;
}) {
const { t } = useTranslation();
const tone: StatusDotTone = session.socketCount > 0 ? "online" : "warning";
const connectedLabel = formatDurationLabel(session.connectedAt, t);
const isReconnecting = session.socketCount === 0;
const tone: StatusDotTone = isReconnecting ? "warning" : "online";
const deviceDetail = formatDeviceDetail(session);
const appDetail = formatAppDetail(session, t);
const connectionLabel = formatTransportLabel(session.transport, viaHostName, t);
const authLabel = formatAuthMethodLabel(session.authMethod, t);
const connectedLabel = formatDurationLabel(session.connectedAt, nowMs, t);
const trailing = useMemo(
() => <ScopePill permissions={session.permissions} t={t} />,
[session.permissions, t],
() => (isReconnecting ? undefined : <ScopePill permissions={session.permissions} t={t} />),
[isReconnecting, session.permissions, t],
);
return (
@@ -176,20 +155,37 @@ function ConnectedClientRow({
label={formatSessionTitle(session, t)}
leading={STATUS_DOTS[tone]}
hint={formatSessionHint(session, viaHostName, t)}
summary={isReconnecting ? t("devices.status.reconnecting") : undefined}
trailing={trailing}
testID={`devices-client-${session.sessionId}`}
>
<PermissionPillsRow permissions={session.permissions} t={t} />
{deviceDetail ? (
<SettingsRow label={t("devices.details.device")}>
<Text style={styles.nestedValue}>{deviceDetail}</Text>
</SettingsRow>
) : null}
<SettingsRow label={t("devices.details.app")}>
<Text style={styles.nestedValue}>{appDetail}</Text>
</SettingsRow>
<SettingsRow label={t("devices.details.connection")}>
<Text style={styles.nestedValue}>{connectionLabel}</Text>
</SettingsRow>
{session.remoteIp ? (
<SettingsRow label={t("devices.details.ipAddress")}>
<Text style={styles.nestedMonoValue}>{session.remoteIp}</Text>
</SettingsRow>
) : null}
{authLabel ? (
<SettingsRow label={t("devices.details.auth")}>
<Text style={styles.nestedValue}>{authLabel}</Text>
</SettingsRow>
) : null}
<AccessDetailRow permissions={session.permissions} t={t} />
{connectedLabel ? (
<SettingsRow label={t("devices.details.connected")}>
<Text style={styles.nestedValue}>{connectedLabel}</Text>
</SettingsRow>
) : null}
{session.socketCount === 0 ? (
<SettingsRow label={t("devices.details.status")}>
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
</SettingsRow>
) : null}
</SettingsCollapsibleRow>
);
}
@@ -197,22 +193,25 @@ function ConnectedClientRow({
function InboundDaemonRow({
daemon,
routedSessions,
nowMs,
}: {
daemon: DaemonSessionSummary;
routedSessions: readonly DaemonSessionSummary[];
nowMs: number;
}) {
const { t } = useTranslation();
const tone: StatusDotTone = daemon.socketCount > 0 ? "online" : "warning";
const isReconnecting = daemon.socketCount === 0;
const tone: StatusDotTone = isReconnecting ? "warning" : "online";
const label = daemon.name ?? t("devices.hosts.unnamed");
const transport = formatTransportLabel(daemon.transport, null, t);
const hintParts = [t("devices.hosts.inbound"), transport];
if (routedSessions.length > 0) {
hintParts.push(t("devices.hosts.routedCount", { count: routedSessions.length }));
}
const connectedLabel = formatDurationLabel(daemon.connectedAt, t);
const connectedLabel = formatDurationLabel(daemon.connectedAt, nowMs, t);
const trailing = useMemo(
() => <ScopePill permissions={daemon.permissions} t={t} />,
[daemon.permissions, t],
() => (isReconnecting ? undefined : <ScopePill permissions={daemon.permissions} t={t} />),
[daemon.permissions, isReconnecting, t],
);
return (
@@ -220,10 +219,11 @@ function InboundDaemonRow({
label={label}
leading={STATUS_DOTS[tone]}
hint={hintParts.join(" · ")}
summary={isReconnecting ? t("devices.status.reconnecting") : undefined}
trailing={trailing}
testID={`devices-inbound-host-${daemon.sessionId}`}
>
<PermissionPillsRow permissions={daemon.permissions} t={t} />
<AccessDetailRow permissions={daemon.permissions} t={t} />
{routedSessions.map((routed) => (
<SettingsRow
key={routed.sessionId}
@@ -233,6 +233,11 @@ function InboundDaemonRow({
<ScopePill permissions={routed.permissions} t={t} />
</SettingsRow>
))}
{daemon.remoteIp ? (
<SettingsRow label={t("devices.details.ipAddress")}>
<Text style={styles.nestedMonoValue}>{daemon.remoteIp}</Text>
</SettingsRow>
) : null}
{daemon.appVersion ? (
<SettingsRow label={t("devices.details.version")}>
<Text style={styles.nestedValue}>{daemon.appVersion}</Text>
@@ -243,11 +248,6 @@ function InboundDaemonRow({
<Text style={styles.nestedValue}>{connectedLabel}</Text>
</SettingsRow>
) : null}
{daemon.socketCount === 0 ? (
<SettingsRow label={t("devices.details.status")}>
<Text style={styles.nestedValue}>{t("devices.status.reconnecting")}</Text>
</SettingsRow>
) : null}
</SettingsCollapsibleRow>
);
}
@@ -281,13 +281,13 @@ function outboundHostStatusLabel(status: HostSummary["status"], t: TFunction): s
}
}
function OutboundHostRow({ host }: { host: HostSummary }) {
function OutboundHostRow({ host, nowMs }: { host: HostSummary; nowMs: number }) {
const { t } = useTranslation();
const tone = outboundHostTone(host.status);
const label = host.label ?? host.serverId ?? host.targetDescription;
const hintParts = [t("devices.hosts.outbound"), host.targetDescription];
const statusSummary = outboundHostStatusLabel(host.status, t);
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, t);
const connectedLabel = formatDurationLabel(host.connectedAt ?? host.lastOnlineAt, nowMs, t);
const trailing = useMemo(
() =>
host.status === "online" && host.permissions ? (
@@ -306,7 +306,7 @@ function OutboundHostRow({ host }: { host: HostSummary }) {
trailing={trailing}
testID={`devices-outbound-host-${host.registrationId}`}
>
{host.permissions ? <PermissionPillsRow permissions={host.permissions} t={t} /> : null}
{host.permissions ? <AccessDetailRow permissions={host.permissions} t={t} /> : null}
{host.error ? (
<SettingsRow label={t("devices.details.error")}>
<Text style={styles.nestedError}>{host.error.message}</Text>
@@ -428,6 +428,7 @@ function ConnectedClientsCardBody({
clientsState,
connectedClients,
hostNameBySessionId,
nowMs,
}: {
isOnline: boolean;
hasServerInfo: boolean;
@@ -436,6 +437,7 @@ function ConnectedClientsCardBody({
clientsState: ConnectedClientsLoadState;
connectedClients: readonly DaemonSessionSummary[];
hostNameBySessionId: ReadonlyMap<string, string | null>;
nowMs: number;
}) {
const { t } = useTranslation();
const updateLink = useMemo(
@@ -486,6 +488,7 @@ function ConnectedClientsCardBody({
viaHostName={
entry.viaSessionId ? (hostNameBySessionId.get(entry.viaSessionId) ?? null) : null
}
nowMs={nowMs}
/>
))}
</>
@@ -562,6 +565,7 @@ function DevicesAccessSection({
export function ConnectedDevicesView({ serverId }: { serverId: string }) {
const { t } = useTranslation();
const nowMs = useMinuteTick();
const connectionStatus = useHostRuntimeSnapshot(serverId)?.connectionStatus;
const serverInfo = useSessionStore((state) => state.sessions[serverId]?.serverInfo ?? null);
@@ -620,6 +624,7 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
clientsState={clientsState}
connectedClients={connectedClients}
hostNameBySessionId={hostNameBySessionId}
nowMs={nowMs}
/>
</SettingsCard>
</SettingsSection>
@@ -632,10 +637,11 @@ export function ConnectedDevicesView({ serverId }: { serverId: string }) {
key={daemon.sessionId}
daemon={daemon}
routedSessions={routedByHostSessionId.get(daemon.sessionId) ?? EMPTY_SESSIONS}
nowMs={nowMs}
/>
))}
{outboundHosts.map((host) => (
<OutboundHostRow key={host.registrationId} host={host} />
<OutboundHostRow key={host.registrationId} host={host} nowMs={nowMs} />
))}
</SettingsCard>
</SettingsSection>
@@ -677,6 +683,11 @@ const styles = StyleSheet.create((theme) => ({
fontSize: theme.fontSize.sm,
color: theme.colors.foregroundMuted,
},
nestedMonoValue: {
fontSize: theme.fontSize.sm,
fontFamily: theme.fontFamily.mono,
color: theme.colors.foregroundMuted,
},
nestedError: {
fontSize: theme.fontSize.sm,
color: theme.colors.statusDanger,
@@ -0,0 +1,168 @@
import { describe, expect, it } from "vitest";
import type { TFunction } from "i18next";
import type { DaemonSessionSummary } from "@getpaseo/protocol/daemon-clients";
import {
formatAppDetail,
formatAuthMethodLabel,
formatDeviceDetail,
formatSessionHint,
formatSessionTitle,
} from "./device-display";
const translations: Record<string, string> = {
"devices.connected.thisDevice": "This device",
"devices.transport.local": "Local",
"devices.transport.tailscale": "Tailscale",
"devices.transport.relay": "Relay",
"devices.transport.hub": "Hub",
"devices.transport.direct": "Direct",
"devices.transport.viaHost": "Via host",
"devices.kind.desktop": "Desktop",
"devices.kind.mobile": "Mobile",
"devices.kind.web": "Web",
"devices.kind.hub": "Hub",
"devices.kind.plugin": "Plugin",
"devices.kind.host": "Host",
"devices.auth.localMachine": "Local machine",
"devices.auth.password": "Password",
"devices.auth.openAccess": "Open access",
"devices.auth.hub": "Hub",
};
const t = ((key: string, options?: { host?: string }) => {
if (key === "devices.transport.via" && options?.host) {
return `Via ${options.host}`;
}
return translations[key] ?? key;
}) as unknown as TFunction;
function makeSession(overrides: Partial<DaemonSessionSummary> = {}): DaemonSessionSummary {
return {
sessionId: "sess_1",
principalId: "owner",
isCurrentSession: false,
name: null,
platform: null,
clientType: "browser",
appVersion: "0.19.0",
transport: "local",
permissions: ["daemon.read", "workspace.read"],
connectedAt: "2026-12-01T10:00:00.000Z",
socketCount: 1,
...overrides,
};
}
describe("device-display formatting", () => {
it("shows real machine name, This device hint, macOS version, and omits 127.0.0.1 on Local Electron", () => {
const session = makeSession({
isCurrentSession: true,
name: "MacBook Pro",
appKind: "desktop",
platform: "macos",
osName: "macOS",
osVersion: "15.3.1",
transport: "local",
remoteIp: "127.0.0.1",
ipSource: "direct",
authMethod: "local_credential",
});
expect(formatSessionTitle(session, t)).toBe("MacBook Pro");
expect(formatSessionHint(session, null, t)).toBe("This device · Local · macOS 15.3");
expect(formatDeviceDetail(session)).toBe("MacBook Pro · macOS 15.3.1");
expect(formatAppDetail(session, t)).toBe("Desktop 0.19.0");
expect(formatAuthMethodLabel(session.authMethod, t)).toBe("Local machine");
});
it("shows observed IP and OS on Tailscale Android and omits OS repetition on Web", () => {
const android = makeSession({
name: "Pixel 9 Pro",
clientType: "mobile",
appKind: "mobile",
platform: "android",
osName: "Android",
osVersion: "15",
deviceModel: "Pixel 9 Pro",
transport: "tailscale",
remoteIp: "100.84.12.9",
ipSource: "direct",
authMethod: "password",
});
expect(formatSessionTitle(android, t)).toBe("Pixel 9 Pro");
expect(formatSessionHint(android, null, t)).toBe("Tailscale · 100.84.12.9 · Android 15");
expect(formatDeviceDetail(android)).toBe("Pixel 9 Pro · Android 15");
expect(formatAppDetail(android, t)).toBe("Mobile 0.19.0");
const web = makeSession({
isCurrentSession: true,
name: "Chrome on macOS",
clientType: "browser",
appKind: "web",
platform: "web",
browserName: "Chrome",
osName: "macOS",
transport: "relay",
remoteIp: null,
ipSource: null,
});
expect(formatSessionTitle(web, t)).toBe("Chrome on macOS");
expect(formatSessionHint(web, null, t)).toBe("This device · Relay");
expect(formatDeviceDetail(web)).toBe("Chrome · macOS");
expect(formatAppDetail(web, t)).toBe("Web 0.19.0");
});
it("shows Linux in collapsed hint and distro name in expanded Device detail", () => {
const linux = makeSession({
name: "workstation",
appKind: "desktop",
platform: "linux",
osName: "Linux",
osVersion: "Ubuntu 24.04.1 LTS",
transport: "direct",
remoteIp: "192.168.1.42",
ipSource: "direct",
});
expect(formatSessionHint(linux, null, t)).toBe("Direct · 192.168.1.42 · Linux");
expect(formatDeviceDetail(linux)).toBe("workstation · Ubuntu 24.04.1 LTS");
});
it("falls back cleanly for unnamed legacy 0.18.2 clients and Hub", () => {
const legacy = makeSession({
isCurrentSession: true,
name: null,
clientType: "mobile",
platform: null,
appVersion: "0.18.2",
transport: "relay",
});
expect(formatSessionTitle(legacy, t)).toBe("This device");
expect(formatSessionHint(legacy, null, t)).toBe("Relay · Mobile 0.18.2");
expect(formatDeviceDetail(legacy)).toBeNull();
const hub = makeSession({
name: "Paseo Hub",
clientType: "hub",
appKind: "hub",
appVersion: null,
transport: "hub",
authMethod: "hub",
});
expect(formatSessionTitle(hub, t)).toBe("Paseo Hub");
expect(formatSessionHint(hub, null, t)).toBe("Hub");
expect(formatDeviceDetail(hub)).toBeNull();
expect(formatAppDetail(hub, t)).toBe("Hub");
expect(formatAuthMethodLabel(hub.authMethod, t)).toBe("Hub");
});
it("maps every daemon SessionAuthMethod value cleanly", () => {
expect(formatAuthMethodLabel("local_credential", t)).toBe("Local machine");
expect(formatAuthMethodLabel("password", t)).toBe("Password");
expect(formatAuthMethodLabel("header_bearer", t)).toBe("Password");
expect(formatAuthMethodLabel("unprotected", t)).toBe("Open access");
expect(formatAuthMethodLabel("hub", t)).toBe("Hub");
expect(formatAuthMethodLabel("plugin", t)).toBe("Plugin");
expect(formatAuthMethodLabel(null, t)).toBeNull();
});
});
+209
View File
@@ -0,0 +1,209 @@
import type { TFunction } from "i18next";
import type {
DaemonSessionSummary,
DaemonSessionTransport,
} from "@getpaseo/protocol/daemon-clients";
function osNameFromPlatform(platform: string | null | undefined): string | null {
switch (platform) {
case "macos":
return "macOS";
case "linux":
return "Linux";
case "windows":
return "Windows";
case "ios":
return "iOS";
case "android":
return "Android";
default:
return null;
}
}
function shortenNumericVersion(version: string): string {
const match = version.match(/^(\d+(?:\.\d+)?)/);
return match?.[1] ?? version;
}
export function formatTransportLabel(
transport: DaemonSessionTransport,
viaHostName: string | null,
t: TFunction,
): string {
switch (transport) {
case "local_ipc":
case "local":
return t("devices.transport.local");
case "tailscale":
return t("devices.transport.tailscale");
case "relay":
return t("devices.transport.relay");
case "hub":
return t("devices.transport.hub");
case "via":
return viaHostName
? t("devices.transport.via", { host: viaHostName })
: t("devices.transport.viaHost");
case "direct":
return t("devices.transport.direct");
}
}
export function formatAppKindLabel(
session: Pick<DaemonSessionSummary, "appKind" | "clientType" | "platform">,
t: TFunction,
): string {
switch (session.appKind) {
case "desktop":
return t("devices.kind.desktop");
case "mobile":
return t("devices.kind.mobile");
case "web":
return t("devices.kind.web");
case "hub":
return t("devices.kind.hub");
case "cli":
return "CLI";
case "mcp":
return "MCP";
case "plugin":
return t("devices.kind.plugin");
case "daemon":
return t("devices.kind.host");
}
if (
session.platform === "macos" ||
session.platform === "linux" ||
session.platform === "windows"
) {
return t("devices.kind.desktop");
}
if (session.platform === "ios" || session.platform === "android") {
return t("devices.kind.mobile");
}
if (session.clientType === "browser" || session.platform === "web") {
return t("devices.kind.web");
}
if (session.clientType === "mobile") return t("devices.kind.mobile");
if (session.clientType === "hub") return t("devices.kind.hub");
if (session.clientType === "cli") return "CLI";
return "MCP";
}
export function formatOsLabel(
session: Pick<DaemonSessionSummary, "osName" | "osVersion" | "platform">,
options: { compact: boolean },
): string | null {
const osName = session.osName ?? osNameFromPlatform(session.platform);
const osVersion = session.osVersion ?? null;
if (!osName) return osVersion;
if (options.compact) {
if (
osVersion &&
(osName === "macOS" || osName === "iOS" || osName === "iPadOS" || osName === "Android") &&
/^\d/.test(osVersion)
) {
return `${osName} ${shortenNumericVersion(osVersion)}`;
}
return osName;
}
if (!osVersion) return osName;
if (osName === "Linux" && !/^\d/.test(osVersion)) {
return osVersion;
}
return `${osName} ${osVersion}`;
}
export function formatSessionTitle(session: DaemonSessionSummary, t: TFunction): string {
if (session.name) return session.name;
if (session.isCurrentSession) return t("devices.connected.thisDevice");
return formatAppKindLabel(session, t);
}
export function formatSessionHint(
session: DaemonSessionSummary,
viaHostName: string | null,
t: TFunction,
): string {
const title = formatSessionTitle(session, t);
const thisDeviceLabel = t("devices.connected.thisDevice");
const transport = formatTransportLabel(session.transport, viaHostName, t);
const parts: string[] = [];
if (session.isCurrentSession && title !== thisDeviceLabel) {
parts.push(thisDeviceLabel);
}
parts.push(transport);
if (
session.remoteIp &&
(session.transport === "tailscale" ||
session.transport === "direct" ||
session.transport === "relay")
) {
parts.push(session.remoteIp);
}
const shortOs = formatOsLabel(session, { compact: true });
if (shortOs && !title.toLowerCase().includes(shortOs.toLowerCase())) {
parts.push(shortOs);
} else if (
!shortOs &&
!session.name &&
session.appVersion &&
session.transport !== "hub" &&
session.clientType !== "hub"
) {
const kind = formatAppKindLabel(session, t);
const fallbackDetail = `${kind} ${session.appVersion}`;
if (fallbackDetail !== title) {
parts.push(fallbackDetail);
}
}
return parts.join(" · ");
}
export function formatDeviceDetail(session: DaemonSessionSummary): string | null {
const osDetail = formatOsLabel(session, { compact: false });
const primary =
session.deviceModel ??
session.browserName ??
(session.appKind === "desktop" ? session.name : null);
if (primary && osDetail) {
if (primary.toLowerCase() === osDetail.toLowerCase()) return primary;
return `${primary} · ${osDetail}`;
}
return primary ?? osDetail;
}
export function formatAppDetail(session: DaemonSessionSummary, t: TFunction): string {
const kind = formatAppKindLabel(session, t);
return session.appVersion ? `${kind} ${session.appVersion}` : kind;
}
export function formatAuthMethodLabel(
authMethod: string | null | undefined,
t: TFunction,
): string | null {
switch (authMethod) {
case "local_credential":
return t("devices.auth.localMachine");
case "password":
case "header_bearer":
return t("devices.auth.password");
case "unprotected":
return t("devices.auth.openAccess");
case "hub":
return t("devices.auth.hub");
case "plugin":
return t("devices.kind.plugin");
default:
return null;
}
}
+21 -8
View File
@@ -2070,16 +2070,16 @@ export const ar: TranslationResources = {
},
},
connected: {
title: "العملاء المتصلون",
title: "الأجهزة",
thisDevice: "هذا الجهاز",
loading: "جارٍ تحميل العملاء المتصلين...",
empty: "لا يوجد عملاء متصلون",
unavailable: "تعذّر تحميل العملاء المتصلين",
updateTitle: "حدّث هذا المضيف لعرض العملاء المتصلين",
updateHint: "هذا المضيف لا يبلّغ عن العملاء المتصلين بعد",
loading: "جارٍ تحميل الأجهزة...",
empty: "لا توجد أجهزة متصلة",
unavailable: "تعذّر تحميل الأجهزة",
updateTitle: "حدّث هذا المضيف لعرض الأجهزة المتصلة",
updateHint: "هذا المضيف لا يبلّغ عن الأجهزة المتصلة بعد",
permissionTitle: "مطلوب إذن إدارة الوصول",
permissionHint: "جلستك لا تملك إذن عرض العملاء المتصلين",
errorTitle: "تعذّر تحميل العملاء المتصلين",
permissionHint: "جلستك لا تملك إذن عرض الأجهزة المتصلة",
errorTitle: "تعذّر تحميل الأجهزة",
},
hosts: {
title: "المضيفون المتصلون",
@@ -2112,8 +2112,21 @@ export const ar: TranslationResources = {
hub: "Hub",
plugin: "إضافة",
client: "عميل",
host: "مضيف",
},
auth: {
localMachine: "الجهاز المحلي",
password: "كلمة المرور",
openAccess: "وصول مفتوح",
hub: "Hub",
},
details: {
device: "الجهاز",
app: "التطبيق",
connection: "الاتصال",
ipAddress: "عنوان IP",
auth: "المصادقة",
access: "الوصول",
permissions: "الأذونات",
connected: "متصل",
lastSeen: "آخر اتصال",
+21 -8
View File
@@ -2101,16 +2101,16 @@ export const en = {
},
},
connected: {
title: "Connected clients",
title: "Devices",
thisDevice: "This device",
loading: "Loading connected clients...",
empty: "No connected clients",
unavailable: "Unable to load connected clients",
updateTitle: "Update this host to view connected clients",
updateHint: "This host does not report connected clients yet",
loading: "Loading devices...",
empty: "No connected devices",
unavailable: "Unable to load devices",
updateTitle: "Update this host to view connected devices",
updateHint: "This host does not report connected devices yet",
permissionTitle: "Access management required",
permissionHint: "Your session does not have permission to view connected clients",
errorTitle: "Could not load connected clients",
permissionHint: "Your session does not have permission to view connected devices",
errorTitle: "Could not load devices",
},
hosts: {
title: "Connected hosts",
@@ -2143,8 +2143,21 @@ export const en = {
hub: "Hub",
plugin: "Plugin",
client: "Client",
host: "Host",
},
auth: {
localMachine: "Local machine",
password: "Password",
openAccess: "Open access",
hub: "Hub",
},
details: {
device: "Device",
app: "App",
connection: "Connection",
ipAddress: "IP address",
auth: "Auth",
access: "Access",
permissions: "Permissions",
connected: "Connected",
lastSeen: "Last online",
+21 -8
View File
@@ -2127,16 +2127,16 @@ export const es: TranslationResources = {
},
},
connected: {
title: "Clientes conectados",
title: "Dispositivos",
thisDevice: "Este dispositivo",
loading: "Cargando clientes conectados...",
empty: "No hay clientes conectados",
unavailable: "No se pudieron cargar los clientes conectados",
updateTitle: "Actualiza este host para ver los clientes conectados",
updateHint: "Este host todavía no informa de los clientes conectados",
loading: "Cargando dispositivos...",
empty: "No hay dispositivos conectados",
unavailable: "No se pudieron cargar los dispositivos",
updateTitle: "Actualiza este host para ver los dispositivos conectados",
updateHint: "Este host todavía no informa de los dispositivos conectados",
permissionTitle: "Se requiere gestión de acceso",
permissionHint: "Tu sesión no tiene permiso para ver los clientes conectados",
errorTitle: "No se pudieron cargar los clientes conectados",
permissionHint: "Tu sesión no tiene permiso para ver los dispositivos conectados",
errorTitle: "No se pudieron cargar los dispositivos",
},
hosts: {
title: "Hosts conectados",
@@ -2169,8 +2169,21 @@ export const es: TranslationResources = {
hub: "Hub",
plugin: "Plugin",
client: "Cliente",
host: "Host",
},
auth: {
localMachine: "Equipo local",
password: "Contraseña",
openAccess: "Acceso abierto",
hub: "Hub",
},
details: {
device: "Dispositivo",
app: "Aplicación",
connection: "Conexión",
ipAddress: "Dirección IP",
auth: "Autenticación",
access: "Acceso",
permissions: "Permisos",
connected: "Conectado",
lastSeen: "Última conexión",
+21 -8
View File
@@ -2123,16 +2123,16 @@ export const fr: TranslationResources = {
},
},
connected: {
title: "Clients connectés",
title: "Appareils",
thisDevice: "Cet appareil",
loading: "Chargement des clients connectés...",
empty: "Aucun client connecté",
unavailable: "Impossible de charger les clients connectés",
updateTitle: "Mettez cet hôte à jour pour voir les clients connectés",
updateHint: "Cet hôte ne signale pas encore les clients connectés",
loading: "Chargement des appareils...",
empty: "Aucun appareil connecté",
unavailable: "Impossible de charger les appareils",
updateTitle: "Mettez cet hôte à jour pour voir les appareils connectés",
updateHint: "Cet hôte ne signale pas encore les appareils connectés",
permissionTitle: "Gestion des accès requise",
permissionHint: "Votre session n’est pas autorisée à voir les clients connectés",
errorTitle: "Impossible de charger les clients connectés",
permissionHint: "Votre session n’est pas autorisée à voir les appareils connectés",
errorTitle: "Impossible de charger les appareils",
},
hosts: {
title: "Hôtes connectés",
@@ -2165,8 +2165,21 @@ export const fr: TranslationResources = {
hub: "Hub",
plugin: "Plugin",
client: "Client",
host: "Hôte",
},
auth: {
localMachine: "Machine locale",
password: "Mot de passe",
openAccess: "Accès ouvert",
hub: "Hub",
},
details: {
device: "Appareil",
app: "Application",
connection: "Connexion",
ipAddress: "Adresse IP",
auth: "Authentification",
access: "Accès",
permissions: "Autorisations",
connected: "Connecté",
lastSeen: "Dernière connexion",
+21 -8
View File
@@ -2093,16 +2093,16 @@ export const ja: TranslationResources = {
},
},
connected: {
title: "接続中のクライアント",
title: "デバイス",
thisDevice: "このデバイス",
loading: "接続中のクライアントを読み込み中...",
empty: "接続中のクライアントはありません",
unavailable: "接続中のクライアントを読み込めません",
updateTitle: "接続中のクライアントを表示するにはこのホストを更新してください",
updateHint: "このホストはまだ接続中のクライアントの報告に対応していません",
loading: "デバイスを読み込み中...",
empty: "接続中のデバイスはありません",
unavailable: "デバイスを読み込めません",
updateTitle: "接続中のデバイスを表示するにはこのホストを更新してください",
updateHint: "このホストはまだ接続中のデバイスの報告に対応していません",
permissionTitle: "アクセス管理権限が必要です",
permissionHint: "このセッションには接続中のクライアントを表示する権限がありません",
errorTitle: "接続中のクライアントを読み込めませんでした",
permissionHint: "このセッションには接続中のデバイスを表示する権限がありません",
errorTitle: "デバイスを読み込めませんでした",
},
hosts: {
title: "接続されたホスト",
@@ -2135,8 +2135,21 @@ export const ja: TranslationResources = {
hub: "Hub",
plugin: "プラグイン",
client: "クライアント",
host: "ホスト",
},
auth: {
localMachine: "ローカルマシン",
password: "パスワード",
openAccess: "オープンアクセス",
hub: "Hub",
},
details: {
device: "デバイス",
app: "アプリ",
connection: "接続",
ipAddress: "IPアドレス",
auth: "認証",
access: "アクセス",
permissions: "権限",
connected: "接続時間",
lastSeen: "最終オンライン",
+21 -8
View File
@@ -2086,16 +2086,16 @@ export const ko: TranslationResources = {
},
},
connected: {
title: "연결된 클라이언트",
title: "기기",
thisDevice: "이 기기",
loading: "연결된 클라이언트를 불러오는 중...",
empty: "연결된 클라이언트가 없습니다",
unavailable: "연결된 클라이언트를 불러올 수 없습니다",
updateTitle: "연결된 클라이언트를 보려면 이 호스트를 업데이트하세요",
updateHint: "이 호스트는 아직 연결된 클라이언트 보고를 지원하지 않습니다",
loading: "기기를 불러오는 중...",
empty: "연결된 기기가 없습니다",
unavailable: "기기를 불러올 수 없습니다",
updateTitle: "연결된 기기를 보려면 이 호스트를 업데이트하세요",
updateHint: "이 호스트는 아직 연결된 기기 보고를 지원하지 않습니다",
permissionTitle: "접근 관리 권한이 필요합니다",
permissionHint: "현재 세션에는 연결된 클라이언트를 볼 권한이 없습니다",
errorTitle: "연결된 클라이언트를 불러오지 못했습니다",
permissionHint: "현재 세션에는 연결된 기기를 볼 권한이 없습니다",
errorTitle: "기기를 불러오지 못했습니다",
},
hosts: {
title: "연결된 호스트",
@@ -2128,8 +2128,21 @@ export const ko: TranslationResources = {
hub: "Hub",
plugin: "플러그인",
client: "클라이언트",
host: "호스트",
},
auth: {
localMachine: "로컬 기기",
password: "비밀번호",
openAccess: "열린 접근",
hub: "Hub",
},
details: {
device: "기기",
app: "앱",
connection: "연결",
ipAddress: "IP 주소",
auth: "인증",
access: "접근",
permissions: "권한",
connected: "연결됨",
lastSeen: "마지막 온라인",
+21 -8
View File
@@ -2109,16 +2109,16 @@ export const ptBR: TranslationResources = {
},
},
connected: {
title: "Clientes conectados",
title: "Dispositivos",
thisDevice: "Este dispositivo",
loading: "Carregando clientes conectados...",
empty: "Nenhum cliente conectado",
unavailable: "Não foi possível carregar os clientes conectados",
updateTitle: "Atualize este host para ver clientes conectados",
updateHint: "Este host ainda não informa clientes conectados",
loading: "Carregando dispositivos...",
empty: "Nenhum dispositivo conectado",
unavailable: "Não foi possível carregar os dispositivos",
updateTitle: "Atualize este host para ver dispositivos conectados",
updateHint: "Este host ainda não informa dispositivos conectados",
permissionTitle: "Gerenciamento de acesso necessário",
permissionHint: "Sua sessão não tem permissão para ver clientes conectados",
errorTitle: "Não foi possível carregar os clientes conectados",
permissionHint: "Sua sessão não tem permissão para ver dispositivos conectados",
errorTitle: "Não foi possível carregar os dispositivos",
},
hosts: {
title: "Hosts conectados",
@@ -2151,8 +2151,21 @@ export const ptBR: TranslationResources = {
hub: "Hub",
plugin: "Plugin",
client: "Cliente",
host: "Host",
},
auth: {
localMachine: "Máquina local",
password: "Senha",
openAccess: "Acesso aberto",
hub: "Hub",
},
details: {
device: "Dispositivo",
app: "Aplicativo",
connection: "Conexão",
ipAddress: "Endereço IP",
auth: "Autenticação",
access: "Acesso",
permissions: "Permissões",
connected: "Conectado",
lastSeen: "Última vez online",
+21 -8
View File
@@ -2108,16 +2108,16 @@ export const ru: TranslationResources = {
},
},
connected: {
title: "Подключённые клиенты",
title: "Устройства",
thisDevice: "Это устройство",
loading: "Загрузка подключённых клиентов...",
empty: "Нет подключённых клиентов",
unavailable: "Не удалось загрузить подключённых клиентов",
updateTitle: "Обновите этот хост, чтобы видеть подключённых клиентов",
updateHint: "Этот хост ещё не передаёт список подключённых клиентов",
loading: "Загрузка устройств...",
empty: "Нет подключённых устройств",
unavailable: "Не удалось загрузить устройства",
updateTitle: "Обновите этот хост, чтобы видеть подключённые устройства",
updateHint: "Этот хост ещё не передаёт список подключённых устройств",
permissionTitle: "Требуются права управления доступом",
permissionHint: "У текущей сессии нет прав для просмотра подключённых клиентов",
errorTitle: "Не удалось загрузить подключённых клиентов",
permissionHint: "У текущей сессии нет прав для просмотра подключённых устройств",
errorTitle: "Не удалось загрузить устройства",
},
hosts: {
title: "Подключённые хосты",
@@ -2150,8 +2150,21 @@ export const ru: TranslationResources = {
hub: "Hub",
plugin: "Плагин",
client: "Клиент",
host: "Хост",
},
auth: {
localMachine: "Локальная машина",
password: "Пароль",
openAccess: "Открытый доступ",
hub: "Hub",
},
details: {
device: "Устройство",
app: "Приложение",
connection: "Подключение",
ipAddress: "IP-адрес",
auth: "Аутентификация",
access: "Доступ",
permissions: "Разрешения",
connected: "Подключено",
lastSeen: "Последний раз в сети",
+21 -8
View File
@@ -2050,16 +2050,16 @@ export const zhCN: TranslationResources = {
},
},
connected: {
title: "已连接的客户端",
title: "设备",
thisDevice: "此设备",
loading: "正在加载已连接的客户端...",
empty: "没有已连接的客户端",
unavailable: "无法加载已连接的客户端",
updateTitle: "更新此主机以查看已连接的客户端",
updateHint: "此主机暂不支持报告已连接的客户端",
loading: "正在加载设备...",
empty: "没有已连接的设备",
unavailable: "无法加载设备",
updateTitle: "更新此主机以查看已连接的设备",
updateHint: "此主机暂不支持报告已连接的设备",
permissionTitle: "需要访问管理权限",
permissionHint: "当前会话无权查看已连接的客户端",
errorTitle: "无法加载已连接的客户端",
permissionHint: "当前会话无权查看已连接的设备",
errorTitle: "无法加载设备",
},
hosts: {
title: "已连接的主机",
@@ -2092,8 +2092,21 @@ export const zhCN: TranslationResources = {
hub: "Hub",
plugin: "插件",
client: "客户端",
host: "主机",
},
auth: {
localMachine: "本机",
password: "密码",
openAccess: "开放访问",
hub: "Hub",
},
details: {
device: "设备",
app: "应用",
connection: "连接",
ipAddress: "IP 地址",
auth: "认证",
access: "访问权限",
permissions: "权限",
connected: "连接时间",
lastSeen: "上次在线",
+223 -71
View File
@@ -31,6 +31,7 @@ import { FileDropZone } from "@/components/file-drop/file-drop-zone";
import { useRetainedPanelActive } from "@/components/retained-panel";
import { RetainedChatContent } from "./retained-chat-content";
import { Composer } from "@/composer";
import type { ComposerInputMode } from "@/composer/input-mode";
import { AgentCommandsProvider } from "@/agent-commands";
import {
useComposerEditingSession,
@@ -74,6 +75,7 @@ import { useContainerWidthBelow } from "@/hooks/use-container-width";
import { reconcileMissingAgentStateWithPresentAgent } from "@/panels/agent-panel-load-state";
import { TimelineSyncStatus } from "@/timeline/sync-status";
import { usePaneContext, usePaneFocus } from "@/panels/pane-context";
import type { PaneHost } from "@/panels/panel-manifest";
import { useAgentFactsLine } from "@/panels/agent-facts-line";
import { PaneSubtitle } from "@/panels/pane-subtitle";
import { definePanel } from "@/panels/panel-registry";
@@ -111,6 +113,7 @@ import { useWorkspaceLayoutStore } from "@/stores/workspace-layout-store";
import { buildWorkspaceTabPersistenceKey, type WorkspaceTabTarget } from "@/workspace-tabs/model";
import { openWorkspaceChanges } from "@/workspace-tabs/open-supporting-view";
import { useSettings } from "@/hooks/use-settings";
import { navigateToWorkspace } from "@/stores/navigation-active-workspace-store";
import type { Theme } from "@/styles/theme";
import type { PendingPermission } from "@/types/shared";
import type { StreamItem } from "@/types/stream";
@@ -350,13 +353,58 @@ function resolveConversationAgentId(target: ConversationTarget): string | undefi
return target.kind === "agent" ? target.agentId.trim() || undefined : undefined;
}
/**
* Where a conversation is shown. A pane is a workspace tab or sheet; an embed is a plugin's
* `AgentChat`, which has no tab to retarget or close and shows a composer only when asked.
* `id` names the viewer: the tab in a pane, the embed instance otherwise.
*/
export type ConversationSurface =
| { kind: "pane"; id: string; host: PaneHost }
| {
kind: "embed";
id: string;
composer: EmbeddedComposer | null;
/** The pane or screen around the embed is the one in front. */
isActive: boolean;
};
export interface EmbeddedComposer {
/** `chat` is the agent tab's composer; `message` is a text box and Send. */
inputMode: Extract<ComposerInputMode, "chat" | "message">;
/** Replaces the default placeholder. */
placeholder: string | undefined;
}
/**
* An embed with a composer is where the user acts on the agent, so while it is in front it clears
* "needs attention" without key focus. One without a composer is a preview: a plugin can show many
* at once, and a glance is not the user handling the agent.
*/
function surfaceClearsAttention(surface: ConversationSurface, isPaneFocused: boolean): boolean {
return surface.kind === "embed" ? surface.composer !== null && surface.isActive : isPaneFocused;
}
/** The track's pills open tabs and sheets of the workspace, which an embed is not in. */
function surfaceShowsTrack(surface: ConversationSurface, hasActiveComposer: boolean): boolean {
return hasActiveComposer && surface.kind === "pane";
}
function surfaceShowsComposer(surface: ConversationSurface): boolean {
// The workspace sheet is for looking; Open as tab brings the agent back with its composer.
return surface.kind === "pane" ? surface.host !== "sheet" : surface.composer !== null;
}
/**
* Drafts and agents render through one chain so the timeline stays mounted when the draft's
* first prompt creates the agent and the tab retargets. The agent gates are idle for a draft.
*/
export function AgentConversationPanel() {
const { serverId, workspaceId, target, openFileInWorkspace } = usePaneContext();
const { serverId, workspaceId, target, openFileInWorkspace, tabId, host } = usePaneContext();
const { isInteractive } = usePaneFocus();
const surface = useMemo<ConversationSurface>(
() => ({ kind: "pane", id: tabId, host }),
[host, tabId],
);
invariant(
target.kind === "agent" || target.kind === "draft",
"AgentConversationPanel requires an agent or draft target",
@@ -368,6 +416,7 @@ export function AgentConversationPanel() {
serverId={serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isInteractive}
onOpenWorkspaceFile={openFileInWorkspace}
/>
@@ -446,16 +495,18 @@ type AgentLookupState =
| { tag: "not_found"; message: string }
| { tag: "error"; message: string };
function AgentPanelContent({
export function AgentPanelContent({
serverId,
workspaceId,
target,
surface,
isPaneFocused,
onOpenWorkspaceFile,
}: {
serverId: string;
workspaceId: string;
target: ConversationTarget;
surface: ConversationSurface;
isPaneFocused: boolean;
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
@@ -509,6 +560,7 @@ function AgentPanelContent({
serverId={resolvedServerId ?? serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isPaneFocused}
client={runtimeClient}
isConnected={runtimeIsConnected}
@@ -522,6 +574,7 @@ function AgentPanelBody({
serverId,
workspaceId,
target,
surface,
isPaneFocused,
client,
isConnected,
@@ -531,6 +584,7 @@ function AgentPanelBody({
serverId: string;
workspaceId: string;
target: ConversationTarget;
surface: ConversationSurface;
isPaneFocused: boolean;
client: ReturnType<typeof useHostRuntimeClient>;
isConnected: boolean;
@@ -663,6 +717,7 @@ function AgentPanelBody({
serverId={serverId}
workspaceId={workspaceId}
target={target}
surface={surface}
isPaneFocused={isPaneFocused}
client={client}
isConnected={isConnected}
@@ -716,6 +771,7 @@ function ChatAgentContent({
serverId,
workspaceId,
target,
surface,
isPaneFocused,
client,
isConnected,
@@ -725,6 +781,7 @@ function ChatAgentContent({
serverId: string;
workspaceId: string;
target: ConversationTarget;
surface: ConversationSurface;
isPaneFocused: boolean;
client: ReturnType<typeof useHostRuntimeClient>;
isConnected: boolean;
@@ -732,7 +789,7 @@ function ChatAgentContent({
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
const { tabId } = usePaneContext();
const tabId = surface.id;
const agentId = resolveConversationAgentId(target);
const isPaneVisible = useRetainedPanelActive();
const { api: toastApi, toast: toastState, dismiss: dismissToast } = useToastHost();
@@ -841,7 +898,7 @@ function ChatAgentContent({
isAgentDataReady: agentHistorySyncGeneration === historySyncGeneration,
requiresAttention: agentState.requiresAttention,
attentionReason: agentState.attentionReason,
isScreenFocused: isPaneFocused,
isScreenFocused: surfaceClearsAttention(surface, isPaneFocused),
focusRequest,
onError: reportAttentionError,
});
@@ -1075,6 +1132,7 @@ function ChatAgentContent({
workspaceId={workspaceId}
agentId={agentId ?? tabId}
draft={draft}
surface={surface}
isPaneFocused={isPaneFocused}
isArchivingCurrentAgent={isArchivingCurrentAgent}
agentState={agentState}
@@ -1106,6 +1164,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
workspaceId,
agentId,
draft,
surface,
isPaneFocused,
isArchivingCurrentAgent,
agentState,
@@ -1134,6 +1193,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
/** The agent's id, or the tab id while a draft has no agent yet. */
agentId: string;
draft: DraftConversation | null;
surface: ConversationSurface;
isPaneFocused: boolean;
isArchivingCurrentAgent: boolean;
agentState: ChatAgentSelectedState;
@@ -1158,9 +1218,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const { t } = useTranslation();
// The workspace sheet is for looking; Open as tab brings the agent back with its composer.
const paneHost = usePaneContext().host;
const showsComposer = draft !== null || paneHost !== "sheet";
const showsComposer = draft !== null || surfaceShowsComposer(surface);
// The dock lays out fullscreen for the same session the composer edits in.
const composerEditingSession = useComposerEditingSession("chat");
const isComposerFullscreen = useComposerFullscreen(composerEditingSession);
@@ -1170,6 +1228,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
agentId,
});
const hasActiveComposer = !agentState.archivedAt && !isArchivingCurrentAgent;
const showsTrack = surfaceShowsTrack(surface, hasActiveComposer);
const focusRestoredComposer = useStableEvent(() => {
if (isPaneFocused && showsComposer && hasActiveComposer) {
composerEditingSession.focus();
@@ -1246,6 +1305,7 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
<AgentComposerSection
agentId={agentId}
serverId={serverId}
surface={surface}
isPaneFocused={isPaneFocused}
isArchivingCurrentAgent={isArchivingCurrentAgent}
isWorkspaceRestoring={isWorkspaceRestoring}
@@ -1303,13 +1363,13 @@ const ChatAgentReadyContent = memo(function ChatAgentReadyContent({
hasAppliedAuthoritativeHistory={hasAppliedAuthoritativeHistory}
isInitialHistoryLoading={isInitialHistoryLoading}
revealInitialHistory={hasCachedHistory || showHistorySyncError}
reservesTrack={showsTrack}
onInitialHistoryVisibilityChange={handleInitialHistoryVisibilityChange}
hasActiveComposer={hasActiveComposer}
toast={toastApi}
onOpenWorkspaceFile={onOpenWorkspaceFile}
/>
</RenderProfile>
{hasActiveComposer && !draft ? (
{showsTrack && !draft ? (
<AgentTracks
serverId={serverId}
workspaceId={workspaceId}
@@ -1540,8 +1600,8 @@ const AgentStreamSection = memo(function AgentStreamSection({
hasAppliedAuthoritativeHistory,
isInitialHistoryLoading,
revealInitialHistory,
reservesTrack,
onInitialHistoryVisibilityChange,
hasActiveComposer,
toast,
onOpenWorkspaceFile,
}: {
@@ -1554,18 +1614,19 @@ const AgentStreamSection = memo(function AgentStreamSection({
hasAppliedAuthoritativeHistory: boolean;
isInitialHistoryLoading: boolean;
revealInitialHistory: boolean;
/** Whether the composer's track bar sits over the bottom of the stream. */
reservesTrack: boolean;
onInitialHistoryVisibilityChange?: (visible: boolean) => void;
hasActiveComposer: boolean;
toast: ReturnType<typeof useToastHost>["api"];
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
}) {
const isCompactFormFactor = useIsCompactFormFactor();
// The track bar's space is reserved whenever the bar is mounted, pills or not: pills come and go
// every turn, and the transcript must not jump with them.
const bottomOverlayTailClearance = hasActiveComposer
const bottomOverlayTailClearance = reservesTrack
? resolveComposerTrackTailClearance(isCompactFormFactor)
: 0;
const bottomOverlayControlClearance = hasActiveComposer
const bottomOverlayControlClearance = reservesTrack
? resolveComposerTrackControlClearance(isCompactFormFactor)
: 0;
const streamItemsRaw = useAgentStreamTail(serverId, agentId);
@@ -1699,6 +1760,7 @@ function DraftComposerSection({
const AgentComposerSection = memo(function AgentComposerSection({
agentId,
serverId,
surface,
isPaneFocused,
isArchivingCurrentAgent,
isWorkspaceRestoring,
@@ -1714,6 +1776,7 @@ const AgentComposerSection = memo(function AgentComposerSection({
}: {
agentId?: string;
serverId: string;
surface: ConversationSurface;
isPaneFocused: boolean;
isArchivingCurrentAgent: boolean;
isWorkspaceRestoring: boolean;
@@ -1743,36 +1806,28 @@ const AgentComposerSection = memo(function AgentComposerSection({
return null;
}
return (
<ActiveAgentComposer
agentId={agentId}
serverId={serverId}
isPaneFocused={isPaneFocused}
cwd={cwd}
isSubmitLoading={isSubmitLoading}
agentInputDraft={agentInputDraft}
editingSession={editingSession}
onAttentionInputFocus={onAttentionInputFocus}
onAttentionPromptSend={onAttentionPromptSend}
onComposerHeightChange={onComposerHeightChange}
onMessageSent={onMessageSent}
/>
);
const composer: AgentComposerProps = {
agentId,
serverId,
isPaneFocused,
cwd,
isSubmitLoading,
agentInputDraft,
editingSession,
onAttentionInputFocus,
onAttentionPromptSend,
onComposerHeightChange,
onMessageSent,
};
if (surface.kind === "embed") {
return surface.composer ? (
<EmbeddedAgentComposer {...composer} options={surface.composer} />
) : null;
}
return <PaneAgentComposer {...composer} />;
});
function ActiveAgentComposer({
agentId,
serverId,
isPaneFocused,
cwd,
isSubmitLoading,
agentInputDraft,
editingSession,
onAttentionInputFocus,
onAttentionPromptSend,
onComposerHeightChange,
onMessageSent,
}: {
interface AgentComposerProps {
agentId: string;
serverId: string;
isPaneFocused: boolean;
@@ -1784,12 +1839,83 @@ function ActiveAgentComposer({
onAttentionPromptSend: () => void;
onComposerHeightChange: (height: number) => void;
onMessageSent: () => void;
}) {
}
/** What differs between the composer of a workspace tab and that of an embed. */
interface AgentComposerSurfaceProps {
workspaceId: string | null;
onClientSlashCommand: (command: ClientSlashCommand) => Promise<void>;
attachmentScopeKeys?: readonly string[];
onOpenWorkspaceAttachment?: (attachment: WorkspaceComposerAttachment) => void;
autoFocus: boolean;
inputMode?: ComposerInputMode;
placeholder?: string;
}
function AgentComposer({
agentId,
serverId,
isPaneFocused,
cwd,
isSubmitLoading,
agentInputDraft,
editingSession,
onAttentionInputFocus,
onAttentionPromptSend,
onComposerHeightChange,
onMessageSent,
workspaceId,
onClientSlashCommand,
attachmentScopeKeys,
onOpenWorkspaceAttachment,
autoFocus,
inputMode,
placeholder,
}: AgentComposerProps & AgentComposerSurfaceProps) {
const isCompactFormFactor = useIsCompactFormFactor();
const { onLayout: onInputAreaLayout, isBelow: isCompactComposerLayout } = useContainerWidthBelow(
COMPACT_CONTENT_WIDTH,
{ initialIsBelow: isCompactFormFactor },
);
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
<Composer
agentId={agentId}
serverId={serverId}
workspaceId={workspaceId}
blurOnSubmit={isNative}
isPaneFocused={isPaneFocused}
textSource={agentInputDraft.textSource}
onChangeText={agentInputDraft.editText}
textReplacement={agentInputDraft.textReplacement}
attachments={agentInputDraft.attachments}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={onOpenWorkspaceAttachment}
onChangeAttachments={agentInputDraft.setAttachments}
cwd={cwd}
getDraftRevision={agentInputDraft.getRevision}
clearDraft={agentInputDraft.clear}
editingSession={editingSession}
autoFocus={autoFocus}
autoFocusKey={String(agentInputDraft.attachmentFocusRequestId)}
isSubmitLoading={isSubmitLoading}
onAttentionInputFocus={onAttentionInputFocus}
onAttentionPromptSend={onAttentionPromptSend}
onComposerHeightChange={onComposerHeightChange}
onMessageSent={onMessageSent}
onClientSlashCommand={onClientSlashCommand}
inputMode={inputMode}
placeholder={placeholder}
isCompactLayout={isCompactComposerLayout}
/>
</View>
);
}
/** A workspace tab's composer: `/exit` and `/clear` close or retarget the tab. */
function PaneAgentComposer(props: AgentComposerProps) {
const { agentId, serverId, cwd } = props;
const isCompactFormFactor = useIsCompactFormFactor();
const paneContext = usePaneContext();
const openInSidePane = useSettings((settings) => settings.openInSidePane);
const { workspaceId, tabId, retargetCurrentTab } = paneContext;
@@ -1859,35 +1985,61 @@ function ActiveAgentComposer({
);
return (
<View style={animatedStaticStyles.inputAreaWrapper} onLayout={onInputAreaLayout}>
<Composer
agentId={agentId}
serverId={serverId}
workspaceId={workspaceId}
blurOnSubmit={isNative}
isPaneFocused={isPaneFocused}
textSource={agentInputDraft.textSource}
onChangeText={agentInputDraft.editText}
textReplacement={agentInputDraft.textReplacement}
attachments={agentInputDraft.attachments}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
onChangeAttachments={agentInputDraft.setAttachments}
cwd={cwd}
getDraftRevision={agentInputDraft.getRevision}
clearDraft={agentInputDraft.clear}
editingSession={editingSession}
autoFocus
autoFocusKey={String(agentInputDraft.attachmentFocusRequestId)}
isSubmitLoading={isSubmitLoading}
onAttentionInputFocus={onAttentionInputFocus}
onAttentionPromptSend={onAttentionPromptSend}
onComposerHeightChange={onComposerHeightChange}
onMessageSent={onMessageSent}
onClientSlashCommand={handleClientSlashCommand}
isCompactLayout={isCompactComposerLayout}
/>
</View>
<AgentComposer
{...props}
workspaceId={workspaceId}
onClientSlashCommand={handleClientSlashCommand}
attachmentScopeKeys={attachmentScopeKeys}
onOpenWorkspaceAttachment={handleOpenWorkspaceAttachment}
autoFocus
/>
);
}
/**
* The composer of an embed. It has no tab: `/clear` archives the agent and opens a fresh draft in
* the agent's workspace, as forking to a tab does. It does not take focus on mount; the plugin's
* screen decides where the user starts.
*/
function EmbeddedAgentComposer({
options,
...props
}: AgentComposerProps & { options: EmbeddedComposer }) {
const { agentId, serverId } = props;
const workspaceId = useSessionStore(
(state) => resolveChatAgentFromSession(state, serverId, agentId)?.workspaceId ?? null,
);
const { archiveAgent } = useArchiveAgent();
const handleClientSlashCommand = useCallback(
async (command: ClientSlashCommand) => {
const agent = resolveChatAgentFromSession(useSessionStore.getState(), serverId, agentId);
if (!agent) {
throw new Error("Agent not found");
}
if (command.kind === "replace-agent-with-draft") {
if (!agent.workspaceId) {
throw new Error("This agent has no workspace to start a draft in");
}
navigateToWorkspace({
serverId,
workspaceId: agent.workspaceId,
target: { kind: "draft", draftId: generateDraftId(), setup: buildDraftAgentSetup(agent) },
});
}
await archiveAgent({ serverId, agentId });
},
[agentId, archiveAgent, serverId],
);
return (
<AgentComposer
{...props}
workspaceId={workspaceId}
onClientSlashCommand={handleClientSlashCommand}
autoFocus={false}
inputMode={options.inputMode}
placeholder={options.placeholder}
/>
);
}
+5
View File
@@ -84,3 +84,8 @@ export function usePaneFocus(): PaneFocusContextValue {
invariant(value, "PaneFocusContext is required");
return value;
}
/** The focus of the pane around this component, or null on a screen with no panes. */
export function useEnclosingPaneFocus(): PaneFocusContextValue | null {
return useContext(PaneFocusContext);
}
+2 -1
View File
@@ -836,7 +836,8 @@ describe("evaluatePluginClientBundle", () => {
`(function(require) {
const shared = require("@getpaseo/plugin");
const client = require("@getpaseo/plugin/client");
const { ExternalLink, Loading, Markdown } = require("@getpaseo/plugin/client/ui");
const { AgentChat, ExternalLink, Loading, Markdown } = require("@getpaseo/plugin/client/ui");
if (typeof AgentChat !== "function") throw new Error("AgentChat");
if (typeof Markdown !== "function") throw new Error("Markdown");
if (typeof ExternalLink !== "function") throw new Error("ExternalLink");
if (typeof Loading !== "function") throw new Error("Loading");
@@ -0,0 +1,35 @@
import type { AgentChatProps } from "@getpaseo/plugin/client/ui";
import { lazy, Suspense, useMemo } from "react";
import type { EmbeddedComposer } from "@/agent-embed";
import { FilePanelLoading } from "@/file-panels/loading";
import { usePluginInstallationServerId } from "../installation-provider";
/**
* The embed renders the agent tab's chain, composer included. The plugin runtime loads this
* module with the host runtime, so a static import would put the whole chat surface in the host
* runtime's import graph. Only the first chat of a session waits for it.
*/
const AgentEmbed = lazy(async () => ({ default: (await import("@/agent-embed")).AgentEmbed }));
const LOADING = <FilePanelLoading />;
export function AgentChat({ agentId, hostId, composer, testID }: AgentChatProps) {
const installationServerId = usePluginInstallationServerId();
const serverId = hostId ?? installationServerId;
const hasComposer = composer !== false;
const inputMode = composer && composer.controls === "none" ? "message" : "chat";
const placeholder = composer ? composer.placeholder : undefined;
const embedComposer = useMemo<EmbeddedComposer | null>(
() => (hasComposer ? { inputMode, placeholder } : null),
[hasComposer, inputMode, placeholder],
);
if (!serverId) {
throw new Error("AgentChat needs a hostId outside a plugin surface");
}
return (
<Suspense fallback={LOADING}>
<AgentEmbed serverId={serverId} agentId={agentId} composer={embedComposer} testID={testID} />
</Suspense>
);
}
@@ -30,3 +30,4 @@ export { useToast } from "./toast";
export { StreamedText } from "./streamed-text";
export { Markdown } from "./markdown";
export { AgentChat } from "./agent-chat";
@@ -27,6 +27,7 @@ import { isAgentArchiving, setAgentArchiving } from "@/hooks/use-archive-agent";
import { queryClient } from "@/data/query-client";
import { checkoutStatusQueryKey } from "@/git/query-keys";
import {
buildRoutedProbeClientConfig,
HostRuntimeController,
HostRuntimeStore,
readInitialDaemonConnectionHint,
@@ -6379,4 +6380,54 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
store.syncHosts([]);
});
it("uses persisted clientId and resolved app client identity on routed probes with an isolated route scope", async () => {
const cancelledScopes: string[] = [];
const openedScopes: string[] = [];
const origin = {
subscribeRawMessages: () => () => undefined,
subscribeHostFrames: () => () => undefined,
subscribeConnectionStatus: () => () => undefined,
openHostRoute: (_serverId: string, scopeId: string) => {
openedScopes.push(scopeId);
return new Promise<never>(() => undefined);
},
cancelHostRoute: (scopeId: string) => {
cancelledScopes.push(scopeId);
},
closeHostRoute: () => undefined,
} as unknown as DaemonClient;
const config = await buildRoutedProbeClientConfig({
origin,
serverId: "srv_routed_target",
getClientId: async () => "cid_persisted_device",
resolveClientIdentity: () => ({
clientType: "browser",
clientInfo: {
appKind: "desktop",
platform: "linux",
name: "workstation",
osName: "Linux",
osVersion: "Ubuntu 24.04",
},
}),
});
expect(config.clientId).toBe("cid_persisted_device");
expect(config.clientType).toBe("browser");
expect(config.clientInfo).toEqual({
appKind: "desktop",
platform: "linux",
name: "workstation",
osName: "Linux",
osVersion: "Ubuntu 24.04",
});
const transport = config.transportFactory!({ url: "ws://routed-host/ws" });
transport.close();
expect(openedScopes).toHaveLength(1);
expect(openedScopes[0]).not.toBe("cid_persisted_device");
expect(cancelledScopes).toEqual([openedScopes[0]]);
});
});
+39 -13
View File
@@ -585,6 +585,38 @@ function probeIntervalForConnection(
return PROBE_MAX_BACKOFF_MS;
}
export async function buildRoutedProbeClientConfig(params: {
origin: DaemonClient;
serverId: string;
capabilities?: DaemonClientConfig["capabilities"];
trace?: DaemonClientConfig["trace"];
getClientId?: () => Promise<string>;
resolveClientIdentity?: typeof resolveAppClientIdentity;
probeScopeId?: string;
}): Promise<DaemonClientConfig> {
const clientId = await (params.getClientId ?? getOrCreateClientId)();
const probeScopeId = params.probeScopeId ?? crypto.randomUUID();
const appIdentity = (params.resolveClientIdentity ?? resolveAppClientIdentity)();
return {
url: "ws://routed-host/ws",
clientId,
clientType: appIdentity.clientType,
clientInfo: appIdentity.clientInfo,
transportFactory: createHostChannelTransport(
params.origin,
params.serverId,
probeScopeId,
null,
),
reconnect: { enabled: false },
logger: createHostLogger(() => params.serverId),
appVersion: resolveAppVersion() ?? undefined,
...(params.capabilities ? { capabilities: params.capabilities } : {}),
...(params.trace ? { trace: params.trace } : {}),
createPluginClientBundleStore: createHostPluginClientBundleStore,
};
}
function createDefaultDeps(
resolveOrigin: (serverId: string) => DaemonClient | null = () => null,
): HostRuntimeControllerDeps {
@@ -679,20 +711,14 @@ function createDefaultDeps(
const origin = resolveOrigin(connection.originServerId);
if (!origin?.isConnected)
throw new Error(`Origin host ${connection.originServerId} is unavailable`);
const client = new DaemonClient({
url: "ws://routed-host/ws",
clientId: crypto.randomUUID(),
transportFactory: createHostChannelTransport(
const client = new DaemonClient(
await buildRoutedProbeClientConfig({
origin,
host.serverId,
crypto.randomUUID(),
null,
),
reconnect: { enabled: false },
logger: createHostLogger(() => host.serverId),
appVersion: resolveAppVersion() ?? undefined,
createPluginClientBundleStore: createHostPluginClientBundleStore,
});
serverId: host.serverId,
capabilities: appCapabilities,
trace: createPerformanceTrace({ host: host.serverId, connection: connection.id }),
}),
);
try {
await client.connect();
return { client, serverId: host.serverId, hostname: null };
@@ -21,7 +21,6 @@ import {
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
import { PairDeviceModal } from "@/devices";
import { buildSettingsHostSectionRoute } from "@/utils/host-routes";
import { WINDOW_CONTENT_DATASET } from "@/components/desktop/titlebar-drag-region";
export function OpenProjectScreen() {
const { t } = useTranslation();
@@ -61,11 +60,7 @@ export function OpenProjectScreen() {
return (
<View style={styles.container}>
<MenuHeader borderless />
<ScrollView
style={styles.scroll}
contentContainerStyle={styles.scrollContent}
dataSet={WINDOW_CONTENT_DATASET}
>
<ScrollView style={styles.scroll} contentContainerStyle={styles.scrollContent}>
<View style={styles.content}>
<View style={styles.logo}>
<PaseoLogo size={52} />
@@ -1,12 +1,4 @@
import {
createContext,
useCallback,
useContext,
useEffect,
useLayoutEffect,
useMemo,
type ComponentType,
} from "react";
import { createContext, useCallback, useContext, useMemo, type ComponentType } from "react";
import { View } from "react-native";
import { useTranslation } from "react-i18next";
import { StyleSheet, withUnistyles } from "react-native-unistyles";
@@ -22,8 +14,7 @@ import {
import { DropdownMenu, DropdownMenuContent } from "@/components/ui/dropdown-menu";
import type { PanelIconProps } from "@/panels/panel-registry";
import { getPanelRegistration } from "@/panels/panel-registry";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
import { useViewedAgent } from "@/timeline/use-viewed-agent";
import { useWorkspaceDirectory } from "@/stores/session-store-hooks";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import { WorkspacePaneContent } from "@/screens/workspace/workspace-pane-content";
@@ -139,7 +130,7 @@ export function SheetPane({ sheet, onClose, onBack, opener = null, isTop }: Shee
);
const exit = useMemo<SheetPaneExit>(() => ({ close: onClose, opener }), [onClose, opener]);
const isPaneFocused = isTop && host.isWorkspaceFocused;
useViewedSheetAgent({
useViewedAgent({
sourceId: `${workspaceKey}:sheet:${tab.tabId}`,
serverId: host.serverId,
agentId: isPaneFocused && tab.target.kind === "agent" ? tab.target.agentId : null,
@@ -199,35 +190,6 @@ function SheetFileMenu({ path, onClose }: { path: string; onClose: () => void })
);
}
/**
* The agent of the sheet on top is viewed, alongside the pane under it: its timeline catches up
* and stays live. The workspace only publishes the agents of its panes.
*/
function useViewedSheetAgent({
sourceId,
serverId,
agentId,
}: {
sourceId: string;
serverId: string;
agentId: string | null;
}) {
const viewedTimelineSync = useSessionStore(
(state) => state.sessions[serverId]?.viewedTimelineSync ?? null,
);
useEffect(() => {
if (!agentId) return;
void getHostRuntimeStore()
.prepareAgentTimeline(serverId, agentId)
.catch(() => undefined);
}, [agentId, serverId]);
useLayoutEffect(() => {
if (!agentId || !viewedTimelineSync) return;
viewedTimelineSync.replaceVisibleAgentIds(sourceId, [agentId]);
return () => viewedTimelineSync.replaceVisibleAgentIds(sourceId, []);
}, [agentId, sourceId, viewedTimelineSync]);
}
/**
* Leaves the sheet the calling pane is shown in, if any, on the way to `destination`. Answers
* whether closing the sheet already lands there, so the caller navigates only when it does not.
@@ -106,7 +106,11 @@ export function useWorkspaceExplorerControls({
/>
),
titlebarAction: (
<View pointerEvents="box-none" style={styles.titlebarSlot}>
<View
pointerEvents="box-none"
style={styles.titlebarSlot}
dataSet={WINDOW_NO_DRAG_DATASET}
>
<WorkspaceExplorerToggle {...props} mobile={false} />
</View>
),
@@ -151,7 +151,7 @@ import {
import { useDesktopBrowserNewTabRequests } from "@/desktop/browser/new-tab-requests";
import type { WorkspaceTabDescriptor } from "@/screens/workspace/workspace-tabs-types";
import { useWorkspaceExplorerControls } from "@/screens/workspace/workspace-explorer-toggle";
import { WindowChromeRegion, WindowChromeSafeArea } from "@/utils/desktop-window";
import { WindowChromeRegion } from "@/utils/desktop-window";
import {
resolveWorkspaceHeaderRenderState,
type WorkspaceHeaderCheckoutState,
@@ -3182,11 +3182,7 @@ function WorkspaceScreenContent({
},
};
const compactWorkspaceHeader = renderCompactWorkspaceHeader(workspaceCompactHeaderTabs);
// SplitContainer reserves the corner around its own compact headers; this is the column's.
const centerColumnCompactHeader = useMemo(
() => <WindowChromeSafeArea placement="inline">{compactWorkspaceHeader}</WindowChromeSafeArea>,
[compactWorkspaceHeader],
);
const centerColumnCompactHeader = compactWorkspaceHeader;
const fullWorkspaceActions = renderCompactWorkspaceHeader(workspaceCompactHeaderTabs, true);
const desktopSplitContent = useMemo(() => {
if (!canRenderDesktopPaneSplits || !workspaceLayout || !persistenceKey) {
+60
View File
@@ -1,3 +1,4 @@
import { createStreamPresentation } from "@/agent-stream/presentation";
import { DatabaseSync } from "node:sqlite";
import { ReplicaCache } from "@/runtime/replica-cache";
import {
@@ -1221,6 +1222,65 @@ describe("the turn footer changes together with its messages", () => {
owner.dispose();
});
it.each([
{ endsOffline: true, expectedPhase: "complete", expectedFooter: "settled" },
{ endsOffline: false, expectedPhase: "streaming", expectedFooter: "running" },
])(
"reconciles a live reply after reconnect (turn ends offline: $endsOffline)",
async ({ endsOffline, expectedPhase, expectedFooter }) => {
const owner = createChat(null);
try {
agentIsRunning();
await connectAndCatchUp(owner);
owner.applyStreamEvent(AGENT_ID, {
event: {
type: "timeline",
provider: "claude",
turnId: OPEN_TURN.turnId,
item: { type: "assistant_message", text: "Done.", messageId: "reply-1" },
},
seq: 5,
epoch: "epoch-1",
timestamp: new Date("2026-08-26T10:00:01.000Z"),
});
owner.flushStreamAgent(AGENT_ID);
const session = () => useSessionStore.getState().sessions[SERVER_ID];
const present = createStreamPresentation();
const replyPhases = () => {
const phases: string[] = [];
present({
display: "collapseToolCalls",
expandedTurnHostIds: new Set(),
isTurnActive: footer() === "running",
tail: session()?.agentStreamTail.get(AGENT_ID) ?? [],
head: session()?.agentStreamHead.get(AGENT_ID) ?? [],
transform: ({ item: source, phase }) => {
if (source.type === "assistant_message" && source.text === "Done.")
phases.push(phase);
return undefined;
},
});
return phases;
};
expect(replyPhases()).toEqual(["streaming"]);
owner.setConnected(false);
owner.setConnected(true);
if (endsOffline) idleSnapshotArrives();
owner.applyTimelineResponse({
...catchUpPage({ replyThroughSeq: null }),
window: { minSeq: 1, maxSeq: 5, nextSeq: 6 },
});
expect(footer()).toBe(expectedFooter);
expect(replies()).toEqual(["Done."]);
expect(replyPhases()).toEqual([expectedPhase]);
} finally {
owner.dispose();
}
},
);
it("a turn that ended with no new messages settles when the empty catch-up lands", async () => {
const owner = createChat("Done.");
agentIsRunning();
@@ -0,0 +1,35 @@
import { useEffect, useLayoutEffect } from "react";
import { getHostRuntimeStore } from "@/runtime/host-runtime";
import { useSessionStore } from "@/stores/session-store";
/**
* Shows one agent from a viewer outside the workspace's panes, such as a sheet or a plugin's
* embedded timeline: its timeline catches up and stays live while the viewer is mounted. Each
* viewer is its own `sourceId`; the sync observes the union of every source, so a tab and any
* number of viewers of the same agent share one daemon observation, and removing one viewer
* leaves the others live.
*/
export function useViewedAgent({
sourceId,
serverId,
agentId,
}: {
sourceId: string;
serverId: string;
agentId: string | null;
}) {
const viewedTimelineSync = useSessionStore(
(state) => state.sessions[serverId]?.viewedTimelineSync ?? null,
);
useEffect(() => {
if (!agentId) return;
void getHostRuntimeStore()
.prepareAgentTimeline(serverId, agentId)
.catch(() => undefined);
}, [agentId, serverId]);
useLayoutEffect(() => {
if (!agentId || !viewedTimelineSync) return;
viewedTimelineSync.replaceVisibleAgentIds(sourceId, [agentId]);
return () => viewedTimelineSync.replaceVisibleAgentIds(sourceId, []);
}, [agentId, sourceId, viewedTimelineSync]);
}
@@ -30,7 +30,7 @@ import {
processTimelineResponse,
} from "./session-stream-reducers";
import { isTimelineResumeSnapshotAuthoritative } from "./timeline-sync-plan";
import { replaceWithCanonicalStream } from "@/types/stream";
import { flushHeadToTail, replaceWithCanonicalStream } from "@/types/stream";
import type { TurnLivenessTransition } from "./turn-liveness";
export interface TimelineReplicaStorage {
@@ -297,6 +297,33 @@ function finalizeProcessedTimeline(input: {
if (input.result.initResolution === "resolve") resolveInitDeferred(input.initKey);
}
function settleRecoveredTurn(input: {
session: SessionState | undefined;
payload: TimelineResponsePayload;
result: ProcessTimelineResponseOutput;
synchronized: boolean;
}): ProcessTimelineResponseOutput {
const { session, payload, result, synchronized } = input;
if (!synchronized || result.head.length === 0) return result;
const agentId = payload.agentId;
const turn = (session?.agents.get(agentId) ?? session?.agentDetails.get(agentId))?.turn;
const heldTurn = session?.agentTimelineUnsettledTurn.get(agentId);
if (turn?.phase !== "idle" || !heldTurn) return result;
if (result.sideEffects.some(({ type }) => type === "catch_up")) return result;
// A turn end that happened offline is not a timeline row. Commit the live rows
// from that turn if the response covers all of them.
const covered = result.head.every(
({ timelineCursor, turnId }) =>
(turnId ?? null) === heldTurn.turnId &&
timelineCursor?.epoch === payload.epoch &&
timelineCursor.seq <= payload.window.maxSeq,
);
if (!covered) return result;
return { ...result, commit: "apply", tail: flushHeadToTail(result.tail, result.head), head: [] };
}
function applyAuthoritativeTimelineResponse(input: {
serverId: string;
payload: TimelineResponsePayload;
@@ -333,12 +360,20 @@ function applyAuthoritativeTimelineResponse(input: {
hasNewer: payload.hasNewer,
error: payload.error,
});
commitProcessedTimeline({ serverId, payload, result, timeline, currentCursor, synchronized });
const settledResult = settleRecoveredTurn({ session, payload, result, synchronized });
commitProcessedTimeline({
serverId,
payload,
result: settledResult,
timeline,
currentCursor,
synchronized,
});
finalizeProcessedTimeline({
serverId,
agentId,
initKey,
result,
result: settledResult,
recoverGap: input.recoverGap,
});
return true;
@@ -390,4 +390,37 @@ describe("test-daemon-connection connectToDaemon", () => {
message: "Transport error",
});
});
it("uses resolved app client identity instead of hardcoding mobile on probe-adopted connections", async () => {
const { buildClientConfig } = await import("./test-daemon-connection");
const { resolveDesktopClientIdentity } = await import("@/devices/client-info-parsers");
const config = await buildClientConfig(
{
id: "relay:test",
type: "relay",
relayEndpoint: "relay.paseo.sh:443",
daemonPublicKeyB64: "pubkey",
},
"srv_probe_test",
{},
{
...probe.deps,
resolveClientIdentity: () =>
resolveDesktopClientIdentity({
platform: "darwin",
deviceName: "Mo-MacBook-Pro",
osVersion: "15.3.1",
browserHostLabel: "Mo-MacBook-Pro · Window 1 (A1B2C3)",
}),
},
);
expect(config.clientType).toBe("browser");
expect(config.clientInfo).toMatchObject({
appKind: "desktop",
platform: "macos",
name: "Mo-MacBook-Pro",
osName: "macOS",
osVersion: "15.3.1",
});
});
});
@@ -13,6 +13,7 @@ import { createAppWebSocketFactory } from "@/runtime/websocket-factory";
import { createHostLogger } from "@/runtime/host-logger";
import { getOrCreateClientId } from "./client-id";
import { resolveAppVersion } from "./app-version";
import { resolveAppClientIdentity } from "@/devices/client-info";
import {
buildDaemonWebSocketUrl,
buildRelayWebSocketUrl,
@@ -37,6 +38,7 @@ export interface DaemonConnectionDependencies<TClient extends DaemonProbeClient>
createLogger: typeof createHostLogger;
getClientId(): Promise<string>;
resolveAppVersion(): string | null;
resolveClientIdentity?: typeof resolveAppClientIdentity;
createDesktopTransportFactory(): DaemonClientConfig["transportFactory"] | null;
buildDesktopTransportUrl(input: DesktopDaemonTransportTarget): string;
createClient(config: DaemonClientConfig): TClient;
@@ -46,6 +48,7 @@ const defaultDaemonConnectionDependencies: DaemonConnectionDependencies<DaemonCl
createLogger: createHostLogger,
getClientId: getOrCreateClientId,
resolveAppVersion,
resolveClientIdentity: resolveAppClientIdentity,
createDesktopTransportFactory: createDesktopDaemonTransportFactory,
buildDesktopTransportUrl: buildDesktopDaemonTransportUrl,
createClient: (config) => new DaemonClient(config),
@@ -174,6 +177,7 @@ export async function buildClientConfig(
DaemonConnectionDependencies<DaemonProbeClient>,
| "getClientId"
| "resolveAppVersion"
| "resolveClientIdentity"
| "createDesktopTransportFactory"
| "buildDesktopTransportUrl"
> = defaultDaemonConnectionDependencies,
@@ -181,10 +185,12 @@ export async function buildClientConfig(
if (connection.type === "routed")
throw new Error("Routed host connections are resolved by HostRuntime");
const clientId = await deps.getClientId();
const appIdentity = (deps.resolveClientIdentity ?? resolveAppClientIdentity)();
const desktopTransportFactory = deps.createDesktopTransportFactory();
const base = {
clientId,
clientType: "mobile" as const,
clientType: appIdentity.clientType,
clientInfo: appIdentity.clientInfo,
appVersion: deps.resolveAppVersion() ?? undefined,
suppressSendErrors: true,
webSocketFactory: createAppWebSocketFactory(),
@@ -1,6 +1,7 @@
import type { ReactNode } from "react";
import { Portal, PortalHost } from "@gorhom/portal";
import { StyleSheet, View } from "react-native";
import { WINDOW_OVERLAY_HOST_DATASET } from "@/components/desktop/titlebar-drag-region";
import { RetainedPanelActivity } from "@/components/retained-panel";
import { IconButtonChromeProvider } from "@/components/ui/icon-button-chrome";
import { useWindowLayout } from "./context";
@@ -29,6 +30,7 @@ export function WindowLayoutActions({
<Portal hostName={HOST}>
<View
testID="workspace-vertical-actions"
dataSet={WINDOW_OVERLAY_HOST_DATASET}
style={[
styles.bar,
{ left: bar.x, top: bar.y, width: bar.width, height: bar.height },
@@ -155,3 +155,24 @@ export const Laptop = StubIcon;
export const Network = StubIcon;
export const PcCase = StubIcon;
export const Waypoints = StubIcon;
export const AlertCircle = StubIcon;
export const ArchiveRestore = StubIcon;
export const ArrowUpToLine = StubIcon;
export const BookOpen = StubIcon;
export const Boxes = StubIcon;
export const Bug = StubIcon;
export const ChevronUp = StubIcon;
export const Compass = StubIcon;
export const CornerUpLeft = StubIcon;
export const Database = StubIcon;
export const Feather = StubIcon;
export const FlaskConical = StubIcon;
export const Hammer = StubIcon;
export const Microscope = StubIcon;
export const Minimize2 = StubIcon;
export const Package = StubIcon;
export const Palette = StubIcon;
export const Pause = StubIcon;
export const Rocket = StubIcon;
export const Summary = StubIcon;
export const TestTube = StubIcon;
+1 -1
View File
@@ -35,7 +35,7 @@ function toListItem(
agentId: agent.id,
agentShortId: agent.id.slice(0, 7),
name: permission.name,
description: permission.description ?? "-",
description: permission.description ?? permission.title ?? "-",
};
}
@@ -20,6 +20,23 @@ const agent = {
} as AgentSnapshotPayload;
describe("permit ls output", () => {
it("shows a Pi select question when the request only has a title", () => {
const question: AgentPermissionRequest = {
id: "select-request",
provider: "pi",
name: "Pi select",
kind: "question",
title: "Allow the diagnostic echo?",
};
const result = listPendingPermissions([{ ...agent, pendingPermissions: [question] }]);
expect(render(result, { format: "table" })).toContain("Allow the diagnostic echo?");
expect(JSON.parse(render(result, { format: "json" }))).toMatchObject([
{ description: "Allow the diagnostic echo?" },
]);
});
it("emits full request ids that permit allow accepts", () => {
const result = listPendingPermissions([agent]);
+31
View File
@@ -1,8 +1,10 @@
import { hostname } from "node:os";
import {
createLeanHostClient,
parseHostTarget,
type DaemonClientCore,
} from "@getpaseo/client/node/lean";
import type { HelloClientInfo, HelloClientPlatform } from "@getpaseo/protocol/daemon-clients";
import {
waitForDaemonReady,
resolvePaseoHome,
@@ -216,6 +218,34 @@ export function resolveDaemonCredential(
return token ? { kind: "localCredential", token } : null;
}
function mapNodePlatform(platform: NodeJS.Platform): HelloClientPlatform {
if (platform === "darwin") return "macos";
if (platform === "linux") return "linux";
if (platform === "win32") return "windows";
return "unknown";
}
function mapNodeOsName(platform: NodeJS.Platform): string | undefined {
if (platform === "darwin") return "macOS";
if (platform === "linux") return "Linux";
if (platform === "win32") return "Windows";
return undefined;
}
function resolveCliClientInfo(): HelloClientInfo {
const name = hostname()
.replace(/\.local$/i, "")
.trim()
.slice(0, 128);
const osName = mapNodeOsName(process.platform);
return {
appKind: "cli",
platform: mapNodePlatform(process.platform),
...(name ? { name } : {}),
...(osName ? { osName } : {}),
};
}
async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonClient> {
const timeout = options.timeout ?? defaultConnectTimeout(options.target);
const host =
@@ -234,6 +264,7 @@ async function connectSelectedDaemon(options: ConnectOptions): Promise<DaemonCli
const client = createLeanHostClient(host, {
clientId: await getOrCreateCliClientId(home),
clientType: "cli",
clientInfo: resolveCliClientInfo(),
appVersion: resolveCliVersion(),
...(credential?.kind === "password" ? { password: credential.password } : {}),
...(credential?.kind === "localCredential"
+6 -5
View File
@@ -21,14 +21,15 @@ SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$SCRIPT_PATH")" && pwd)
RESOURCES_DIR=$(CDPATH= cd -- "${SCRIPT_DIR}/.." && pwd)
MACOS_DIR="${RESOURCES_DIR}/../MacOS"
MACOS_HELPER_EXECUTABLE="${RESOURCES_DIR}/../Frameworks/Paseo Helper.app/Contents/MacOS/Paseo Helper"
MACOS_HELPER_EXECUTABLE="${RESOURCES_DIR}/../Frameworks/Paseo Helper (Plugin).app/Contents/MacOS/Paseo Helper (Plugin)"
# macOS CLI invocations must enter Electron through the agent Helper. Launching
# the main APPL executable here makes later daemon supervision inherit app UI
# lifecycle behavior.
# macOS CLI invocations must enter Electron through the Plugin Helper: it runs
# as an LSUIElement agent (avoiding main APPL Dock/UI lifecycle inheritance)
# and is the only helper signed with disable-library-validation so daemon and
# forked plugin workers can load third-party native .node addons.
if [ -d "${MACOS_DIR}" ]; then
if [ ! -x "${MACOS_HELPER_EXECUTABLE}" ]; then
echo "Bundled Paseo Helper executable not found at ${MACOS_HELPER_EXECUTABLE}" >&2
echo "Bundled Paseo Helper (Plugin) executable not found at ${MACOS_HELPER_EXECUTABLE}" >&2
exit 1
fi
APP_EXECUTABLE="${MACOS_HELPER_EXECUTABLE}"
@@ -4,9 +4,5 @@
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.device.audio-input</key>
<true/>
</dict>
</plist>
@@ -4,8 +4,6 @@
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.device.audio-input</key>
<true/>
</dict>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.allow-jit</key>
<true/>
<key>com.apple.security.cs.allow-unsigned-executable-memory</key>
<true/>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
</dict>
</plist>
@@ -33,9 +33,9 @@ const CLICK_POINTS = [
/** Static overlays and a sibling window control mirror the app shell ownership. */
function buildFixtureHtml(appStyles) {
const dragOverlay =
'style="position:absolute;top:0;left:0;display:block;width:100%;height:100%;-webkit-app-region:drag"';
const button = (id, style) =>
`<button id="${id}" style="${style}" onclick="count('${id}')">${id}</button>`;
'data-window-drag-region="" style="position:absolute;top:0;left:0;display:block;width:100%;height:100%;-webkit-app-region:drag"';
const button = (id, style, attrs = "") =>
`<button id="${id}" ${attrs} style="${style}" onclick="count('${id}')">${id}</button>`;
return `<!doctype html><html><head><meta charset="utf-8"><style>${appStyles}</style>
<style>html,body{margin:0;width:100%;height:100%;background:#161616;color:#ddd;font:12px -apple-system,sans-serif;user-select:none}
.pane{position:absolute}</style></head><body>
@@ -56,14 +56,14 @@ function buildFixtureHtml(appStyles) {
<div class="pane" style="left:250px;top:36px;width:750px;height:28px">
<div ${dragOverlay}></div>
</div>
<!-- The sidebar toggle belongs to the window, outside every drag surface subtree. -->
${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height:24px;z-index:2")}
<div id="focusable" tabindex="0" onclick="count('focusable')"
<!-- Window-owned controls mounted outside drag containers opt in via data-window-no-drag. -->
${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height:24px;z-index:2", 'data-window-no-drag=""')}
<div id="focusable" tabindex="0" data-window-no-drag="" onclick="count('focusable')"
style="position:absolute;left:290px;top:6px;width:60px;height:24px;z-index:2">Focusable</div>
<div id="negative-button" role="button" tabindex="-1" onclick="count('negative-button')"
<div id="negative-button" role="button" tabindex="-1" data-window-no-drag="" onclick="count('negative-button')"
style="position:absolute;left:370px;top:6px;width:60px;height:24px;z-index:2">Button</div>
<div class="pane" id="chat-root" style="left:250px;top:64px;width:750px;height:536px;overflow:clip">
<div id="scroller" tabindex="-1" data-window-content
<div id="scroller" tabindex="-1"
style="width:100%;height:100%;overflow-y:auto;overflow-x:clip;outline:none">
<div id="chat-inner" style="height:2000px;position:relative">
<a id="chat-link" href="#" onclick="event.preventDefault();count('chat-link')" style="position:absolute;left:250px;top:160px;width:180px;height:24px">Chat link</a>
@@ -72,10 +72,11 @@ ${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height
</div>
</div>
</div>
<div id="paseo-browser-resident-webviews" style="position:fixed;left:0;top:0;width:100vw;height:100vh;overflow:visible;pointer-events:none;z-index:0"></div>
<div id="overlay-root" style="position:fixed;inset:0;pointer-events:none;z-index:9999">
${button("portal-btn", "position:fixed;left:460px;top:6px;width:60px;height:24px;pointer-events:auto")}
</div>
<div style="position:fixed;inset:0;pointer-events:none;z-index:9999">
<div data-window-overlay-host="" style="position:fixed;inset:0;pointer-events:none;z-index:9999">
${button("floating-btn", "position:fixed;left:755px;top:6px;width:60px;height:24px;pointer-events:auto")}
</div>
<script>
@@ -83,6 +84,23 @@ ${button("window-toggle", "position:absolute;left:10px;top:6px;width:60px;height
window.count = (id) => { window.__clicks[id] = (window.__clicks[id] || 0) + 1; };
window.__fixture = {
setScroll(value) { document.getElementById("scroller").scrollTop = value; return this.snapshot(); },
parkBrowserTab() {
return new Promise((resolve) => {
const host = document.getElementById("paseo-browser-resident-webviews");
const surface = document.createElement("div");
surface.setAttribute("data-paseo-browser-surface", "parked-tab");
surface.setAttribute("aria-hidden", "true");
surface.setAttribute("inert", "");
surface.setAttribute("tabindex", "-1");
surface.style.cssText = "position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;opacity:1;pointer-events:none;display:block;visibility:visible";
const webview = document.createElement("webview");
webview.setAttribute("src", "data:text/html,<h1>Parked browser tab</h1><button>Action</button>");
webview.style.cssText = "display:inline-flex;flex:0 0 auto;width:1280px;height:800px;border:0;background:transparent;position:absolute;left:0;top:0;z-index:0";
webview.addEventListener("dom-ready", () => resolve(true), { once: true });
surface.appendChild(webview);
host.appendChild(surface);
});
},
placeControl(id, y) {
const control = document.getElementById(id);
const rect = control.getBoundingClientRect();
@@ -147,6 +165,9 @@ async function runTitlebarDragGroup(outDir) {
frame: false,
show: false,
backgroundColor: "#161616",
webPreferences: {
webviewTag: true,
},
});
const evalPage = (code) => win.webContents.executeJavaScript(code);
const bounds = () => {
@@ -249,6 +270,18 @@ async function runTitlebarDragGroup(outDir) {
});
}
await evalPage("window.__fixture.parkBrowserTab()");
await new Promise((resolve) => setTimeout(resolve, 250));
for (const point of DRAG_POINTS) {
await resetPosition();
const before = bounds();
const from = mouseAt(point);
await runMouse(["drag", from.x, from.y, from.x + DRAG_DELTA.x, from.y + DRAG_DELTA.y]);
const after = bounds();
const moved = after.x - before.x === DRAG_DELTA.x && after.y - before.y === DRAG_DELTA.y;
record(`parked-webview-${point.check}`, moved, { before, after });
}
const image = await win.webContents.capturePage();
await fsp.writeFile(path.join(outDir, "titlebar-drag.png"), image.toPNG());
} catch (error) {
+17
View File
@@ -1184,6 +1184,23 @@ async function runRegression({
{ id: browserId, webContentsId: firstGuest.webContentsId },
{ timeout: timeoutMs },
);
const parkedAppRegions = await page.evaluate((id) => {
const surface = document.querySelector(`[data-paseo-browser-surface="${id}"]`);
const webview = document.querySelector(`[data-paseo-browser-id="${id}"]`);
const shadowIframe = webview?.shadowRoot?.querySelector("iframe") ?? null;
return [surface, webview, shadowIframe]
.filter((node) => node instanceof Element)
.map((node) => ({
tag: node.tagName,
appRegion: getComputedStyle(node).getPropertyValue("-webkit-app-region"),
}))
.filter((entry) => entry.appRegion !== "none");
}, browserId);
if (parkedAppRegions.length > 0) {
failures.push(
`parked browser webview must emit no window app-regions: ${JSON.stringify(parkedAppRegions)}`,
);
}
try {
await callBrowserTool(client, "browser_screenshot", { browserId });
} catch (error) {
+286 -3
View File
@@ -95,6 +95,19 @@ function getMacMainExecutablePath(appPath) {
return path.join(appPath, "Contents", "MacOS", EXECUTABLE_NAME);
}
function getMacHelperBundlePath(appPath, suffix = "") {
return path.join(appPath, "Contents", "Frameworks", `${EXECUTABLE_NAME} Helper${suffix}.app`);
}
function getMacHelperExecutablePath(appPath, suffix = "") {
return path.join(
getMacHelperBundlePath(appPath, suffix),
"Contents",
"MacOS",
`${EXECUTABLE_NAME} Helper${suffix}`,
);
}
function getLaunchCommand(executablePath, args) {
if (process.platform !== "linux") {
return {
@@ -275,9 +288,266 @@ function listDarwinTextExecutables(pid) {
.map((line) => line.slice(1));
}
function assertDarwinProcessDoesNotUseMainAppExecutable({ appPath, pid, label }) {
function parsePlistTrueKeys(xml) {
const keys = [];
const pattern = /<key>([^<]+)<\/key>\s*<(true|false)\/>/g;
for (const match of xml.matchAll(pattern)) {
if (match[2] === "true") {
keys.push(match[1]);
}
}
return keys.sort();
}
function readDarwinBundleEntitlements(bundlePath, runSync = spawnSync) {
const result = runSync("codesign", ["-d", "--entitlements", ":-", bundlePath], {
encoding: "utf8",
timeout: 15_000,
});
if (result.error) {
throw result.error;
}
if (result.status !== 0) {
throw new Error(
`codesign -d --entitlements failed for ${bundlePath} (code ${result.status}): ${
result.stderr?.trim() || result.stdout?.trim() || "<empty>"
}`,
);
}
return parsePlistTrueKeys(result.stdout ?? "");
}
function findBundledDarwinPtyAddon(appPath, arch = process.arch) {
const unpackedRoot = path.join(appPath, "Contents", "Resources", "app.asar.unpacked");
const expectedSuffix = path.join("node-pty", "prebuilds", `darwin-${arch}`, "pty.node");
const directCandidates = [
path.join(unpackedRoot, "node_modules", expectedSuffix),
path.join(unpackedRoot, "node_modules", "@getpaseo", "server", "node_modules", expectedSuffix),
];
for (const candidate of directCandidates) {
if (fs.existsSync(candidate)) {
return candidate;
}
}
if (fs.existsSync(unpackedRoot)) {
for (const entry of fs.readdirSync(unpackedRoot, { withFileTypes: true, recursive: true })) {
if (!entry.isFile() || entry.name !== "pty.node") {
continue;
}
const fullPath = path.join(entry.parentPath || entry.path, entry.name);
if (fullPath.endsWith(expectedSuffix)) {
return fullPath;
}
}
}
throw new Error(`Bundled darwin-${arch} pty.node not found under ${unpackedRoot}`);
}
const DARWIN_TCC_ENTITLEMENT_PATTERN =
/^com\.apple\.security\.(device|personal-information|automation)\./;
const DARWIN_HARDENED_RUNTIME_FLAG_PATTERN = /flags=0x[0-9a-f]+\([^)]*\bruntime\b[^)]*\)/i;
const DARWIN_LIBRARY_VALIDATION_ERROR_PATTERN =
/not valid for use in process|different Team IDs|mapping process and mapped file|library validation|code signature/i;
function assertDarwinHardenedRuntimeFlag(bundlePath, label, runSync) {
const result = runSyncChecked(runSync, "codesign", ["-d", "-v", bundlePath], {
encoding: "utf8",
timeout: 15_000,
});
const output = `${result.stderr ?? ""}\n${result.stdout ?? ""}`.trim();
if (result.status !== 0 || !DARWIN_HARDENED_RUNTIME_FLAG_PATTERN.test(output)) {
throw new Error(
`Expected Hardened Runtime flag on ${label} (${bundlePath}), got code ${result.status}.\nOutput:\n${
output || "<empty>"
}`,
);
}
}
function readDarwinSipStatus(runSync) {
const result = runSync("csrutil", ["status"], {
encoding: "utf8",
timeout: 10_000,
});
if (result.error) {
return { enabled: true, raw: `<csrutil error: ${result.error.message}>` };
}
const raw = `${result.stdout ?? ""}\n${result.stderr ?? ""}`.trim();
const disabled = /System Integrity Protection status:\s*disabled/i.test(raw);
return { enabled: !disabled, raw: raw || `<exit ${result.status}>` };
}
function assertDarwinBundleEntitlements(appPath, { runSync, log }) {
const expectedBundles = [
{
label: `${EXECUTABLE_NAME}.app`,
bundlePath: appPath,
expectedKeys: ["com.apple.security.cs.allow-jit", "com.apple.security.device.audio-input"],
},
{
label: `${EXECUTABLE_NAME} Helper.app`,
bundlePath: getMacHelperBundlePath(appPath, ""),
expectedKeys: ["com.apple.security.cs.allow-jit"],
},
{
label: `${EXECUTABLE_NAME} Helper (GPU).app`,
bundlePath: getMacHelperBundlePath(appPath, " (GPU)"),
expectedKeys: ["com.apple.security.cs.allow-jit"],
},
{
label: `${EXECUTABLE_NAME} Helper (Renderer).app`,
bundlePath: getMacHelperBundlePath(appPath, " (Renderer)"),
expectedKeys: ["com.apple.security.cs.allow-jit"],
},
{
label: `${EXECUTABLE_NAME} Helper (Plugin).app`,
bundlePath: getMacHelperBundlePath(appPath, " (Plugin)"),
expectedKeys: [
"com.apple.security.cs.allow-jit",
"com.apple.security.cs.allow-unsigned-executable-memory",
"com.apple.security.cs.disable-library-validation",
],
},
];
for (const { label, bundlePath, expectedKeys } of expectedBundles) {
assertDarwinHardenedRuntimeFlag(bundlePath, label, runSync);
const actualKeys = readDarwinBundleEntitlements(bundlePath, runSync);
log(`Packaged desktop smoke: entitlements for ${label}: ${actualKeys.join(", ") || "<none>"}`);
assert.deepEqual(
actualKeys,
expectedKeys,
`Unexpected macOS entitlements on ${label} (${bundlePath})`,
);
if (label === `${EXECUTABLE_NAME} Helper (Plugin).app`) {
const forbiddenTccKey = actualKeys.find((key) => DARWIN_TCC_ENTITLEMENT_PATTERN.test(key));
if (forbiddenTccKey) {
throw new Error(`${label} must not carry macOS TCC entitlement ${forbiddenTccKey}`);
}
}
}
}
function runSyncChecked(runSync, command, args, options) {
const result = runSync(command, args, options);
if (result.error) {
throw result.error;
}
return result;
}
function assertDarwinAdhocAddonLibraryValidation(appPath, { runSync, arch, log, findAddon }) {
const pluginHelperExecutable = getMacHelperExecutablePath(appPath, " (Plugin)");
const genericHelperExecutable = getMacHelperExecutablePath(appPath, "");
assertExecutable(pluginHelperExecutable, "Packaged Plugin Helper executable");
assertExecutable(genericHelperExecutable, "Packaged generic Helper executable");
const bundledPtyAddon = findAddon(appPath, arch);
const addonTempDir = createTempDir("paseo-smoke-addon-");
try {
const tempAddonPath = path.join(addonTempDir, "pty.node");
fs.copyFileSync(bundledPtyAddon, tempAddonPath);
const adhocSign = runSyncChecked(
runSync,
"codesign",
["--force", "--sign", "-", tempAddonPath],
{ encoding: "utf8", timeout: 15_000 },
);
if (adhocSign.status !== 0) {
throw new Error(
`Ad-hoc codesign failed for ${tempAddonPath} (code ${adhocSign.status}): ${
adhocSign.stderr?.trim() || adhocSign.stdout?.trim() || "<empty>"
}`,
);
}
const dlopenScript =
'const mod = { exports: {} }; process.dlopen(mod, process.argv[1]); console.log(Object.keys(mod.exports).sort().join(","));';
const execOptions = {
encoding: "utf8",
env: { ...process.env, ELECTRON_RUN_AS_NODE: "1" },
timeout: 15_000,
};
const pluginLoad = runSyncChecked(
runSync,
pluginHelperExecutable,
["-e", dlopenScript, tempAddonPath],
execOptions,
);
const pluginStdout = (pluginLoad.stdout ?? "").trim();
if (pluginLoad.status !== 0 || !pluginStdout.includes("fork")) {
throw new Error(
`Expected Helper (Plugin) to dlopen ad-hoc-signed addon ${tempAddonPath}, got code ${pluginLoad.status}.\nStdout:\n${
pluginStdout || "<empty>"
}\nStderr:\n${pluginLoad.stderr?.trim() || "<empty>"}`,
);
}
log(
`Packaged desktop smoke: Helper (Plugin) loaded ad-hoc-signed pty.node (exports: ${pluginStdout})`,
);
const sip = readDarwinSipStatus(runSync);
const genericLoad = runSyncChecked(
runSync,
genericHelperExecutable,
["-e", dlopenScript, tempAddonPath],
execOptions,
);
const genericOutput = `${genericLoad.stderr ?? ""}\n${genericLoad.stdout ?? ""}`.trim();
const rejectedByLibraryValidation =
genericLoad.status !== 0 && DARWIN_LIBRARY_VALIDATION_ERROR_PATTERN.test(genericOutput);
if (rejectedByLibraryValidation) {
const rejectionSummary =
genericOutput.split(/\r?\n/).find((line) => line.trim().length > 0) ?? "";
log(
`Packaged desktop smoke: generic Helper rejected ad-hoc-signed pty.node under Library Validation (code ${genericLoad.status}): ${rejectionSummary.slice(0, 300)}`,
);
return;
}
if (!sip.enabled && genericLoad.status === 0) {
log(
`Packaged desktop smoke: generic Helper loaded ad-hoc-signed pty.node because host SIP is disabled (${sip.raw}); Hardened Runtime flag and entitlements were verified via codesign`,
);
return;
}
throw new Error(
`Expected generic Helper to reject ad-hoc-signed addon ${tempAddonPath} under Library Validation (SIP status: ${sip.raw}), got code ${genericLoad.status}.\nOutput:\n${
genericOutput || "<empty>"
}`,
);
} finally {
fs.rmSync(addonTempDir, { recursive: true, force: true });
}
}
function assertDarwinSigningAndLibraryValidation(appPath, deps = {}) {
if ((deps.platform ?? process.platform) !== "darwin") {
return;
}
const runSync = deps.spawnSync ?? spawnSync;
const log = deps.log ?? console.log;
assertDarwinBundleEntitlements(appPath, { runSync, log });
assertDarwinAdhocAddonLibraryValidation(appPath, {
runSync,
arch: deps.arch ?? process.arch,
log,
findAddon: deps.findBundledDarwinPtyAddon ?? findBundledDarwinPtyAddon,
});
}
function assertDarwinProcessUsesPluginHelper({ appPath, pid, label }) {
const mainExecutablePath = getMacMainExecutablePath(appPath);
const pluginHelperPath = getMacHelperExecutablePath(appPath, " (Plugin)");
assertExecutable(mainExecutablePath, "Packaged app executable");
assertExecutable(pluginHelperPath, "Packaged Plugin Helper executable");
const textExecutables = listDarwinTextExecutables(pid);
if (textExecutables.includes(mainExecutablePath)) {
@@ -287,6 +557,17 @@ function assertDarwinProcessDoesNotUseMainAppExecutable({ appPath, pid, label })
)}`,
);
}
const expectedPaths = new Set([pluginHelperPath]);
try {
expectedPaths.add(fs.realpathSync(pluginHelperPath));
} catch {}
if (!textExecutables.some((entry) => expectedPaths.has(entry))) {
throw new Error(
`${label} PID ${pid} did not launch through Plugin Helper ${pluginHelperPath}.\nText executables:\n${textExecutables.join(
"\n",
)}`,
);
}
}
function readIfExists(filePath) {
@@ -812,14 +1093,14 @@ async function smokeColdCliDaemonStart({ appPath }) {
}
if (process.platform === "darwin") {
assertDarwinProcessDoesNotUseMainAppExecutable({
assertDarwinProcessUsesPluginHelper({
appPath,
pid: pidInfo.pid,
label: "Cold CLI daemon supervisor",
});
const childPids = await waitForChildPids(pidInfo.pid);
for (const childPid of childPids) {
assertDarwinProcessDoesNotUseMainAppExecutable({
assertDarwinProcessUsesPluginHelper({
appPath,
pid: childPid,
label: "Cold CLI daemon worker",
@@ -1026,6 +1307,7 @@ async function smokePackagedDesktopApp({
}) {
assertExecutable(executablePath, "Packaged app executable");
assertLinuxDesktopIdentity(appPath);
assertDarwinSigningAndLibraryValidation(appPath);
await smokeColdCliDaemonStart({ appPath });
const userData = createTempDir("paseo-smoke-user-data-");
@@ -1140,6 +1422,7 @@ async function smokePackagedDesktopApp({
}
module.exports = {
assertDarwinSigningAndLibraryValidation,
smokePackagedDesktopApp,
};
@@ -0,0 +1,201 @@
import { writeFileSync } from "node:fs";
import path from "node:path";
import type { Locator, Page } from "@playwright/test";
import { expect, test } from "../../app/e2e/support/fixtures";
import { openSettings } from "../../app/e2e/support/helpers/app";
import { openFileExplorer } from "../../app/e2e/support/helpers/file-explorer";
import { gotoWorkspace } from "../../app/e2e/support/helpers/launcher";
import { seedWorkspace } from "../../app/e2e/support/helpers/seed-client";
import { openChangesPanel } from "../../app/e2e/support/helpers/workspace-tabs";
async function installDesktopChromeHost(
page: Page,
mode: "native-mac" | "custom-windows",
): Promise<void> {
await page.addInitScript((windowChromeMode) => {
Object.assign(window, {
paseoDesktop: {
platform: windowChromeMode === "native-mac" ? "darwin" : "win32",
windowChromeMode,
invoke: async (command: string) => {
if (command === "get_desktop_settings") {
return {
releaseChannel: "stable",
daemon: { manageBuiltInDaemon: true, keepRunningAfterQuit: true },
};
}
return null;
},
events: { on: async () => () => undefined },
getPendingOpenProject: async () => null,
window: {
getCurrentWindow: () => ({
isFullscreen: async () => false,
isMaximized: async () => false,
onResized: async () => () => undefined,
}),
},
},
});
}, mode);
}
/**
* Electron does not clip app-region rects to scroll viewports or 1x1 overflow-hidden
* parking containers, so any element with `-webkit-app-region: no-drag` outside a drag
* surface or overlay can subtract from the titlebar.
*/
async function expectNoWindowRegions(root: Locator): Promise<void> {
await expect(root).toBeVisible({ timeout: 30_000 });
const regions = await root.evaluate((container) =>
[container, ...container.querySelectorAll<HTMLElement>("*")]
.map((node) => getComputedStyle(node).getPropertyValue("-webkit-app-region"))
.filter((region) => region !== "none"),
);
expect(regions).toEqual([]);
}
async function expectHasDragRegionOver(page: Page, anchor: Locator): Promise<void> {
await expect(anchor).toBeVisible({ timeout: 30_000 });
const hasDrag = await anchor.evaluate((target) => {
const targetRect = target.getBoundingClientRect();
const targetY = targetRect.top + targetRect.height / 2;
return [...document.querySelectorAll<HTMLElement>("[data-window-drag-region]")].some((node) => {
if (getComputedStyle(node).getPropertyValue("-webkit-app-region") !== "drag") return false;
const rect = node.getBoundingClientRect();
return (
rect.width > 0 &&
rect.height > 0 &&
rect.top <= targetY &&
rect.bottom >= targetY &&
rect.left <= targetRect.right &&
rect.right >= targetRect.left
);
});
});
expect(hasDrag).toBe(true);
}
function measureParkedBrowserAppRegions(): string[] {
const host = document.createElement("div");
host.id = "paseo-browser-resident-webviews-test";
host.style.cssText =
"position:fixed;left:0;top:0;width:100vw;height:100vh;pointer-events:none;z-index:0";
const surface = document.createElement("div");
surface.setAttribute("data-paseo-browser-surface", "test-browser");
surface.setAttribute("aria-hidden", "true");
surface.setAttribute("inert", "");
surface.setAttribute("tabindex", "-1");
surface.style.cssText =
"position:fixed;left:0;top:0;width:1px;height:1px;overflow:hidden;pointer-events:none";
const guest = document.createElement("div");
guest.setAttribute("data-paseo-browser-id", "test-browser");
guest.style.cssText = "position:absolute;left:0;top:0;width:1280px;height:800px";
surface.appendChild(guest);
host.appendChild(surface);
document.body.appendChild(host);
try {
return [surface, guest]
.map((node) => getComputedStyle(node).getPropertyValue("-webkit-app-region"))
.filter((region) => region !== "none");
} finally {
host.remove();
}
}
test("scrolled panes, settings, and parked browser surfaces emit no window regions while titlebar controls stay clickable", async ({
page,
}) => {
const workspace = await seedWorkspace({
repoPrefix: "titlebar-drag-wide-",
repo: { files: [{ path: "src/index.ts", content: "export const value = 1;\n" }] },
});
try {
writeFileSync(path.join(workspace.repoPath, "changed.txt"), "changed\n");
await page.setViewportSize({ width: 1280, height: 800 });
await installDesktopChromeHost(page, "native-mac");
await gotoWorkspace(page, workspace.workspaceId);
await test.step("sidebar workspace rows and nav emit no window regions", async () => {
const list = page
.getByTestId("sidebar-project-workspace-list-scroll")
.filter({ visible: true });
await expect(list.getByRole("button").first()).toBeVisible({ timeout: 30_000 });
await expectNoWindowRegions(list.first());
});
await test.step("Files tree, filter results, and Changes diff emit no window regions", async () => {
await openFileExplorer(page);
await expectNoWindowRegions(
page.getByTestId("file-explorer-tree-scroll").filter({ visible: true }).first(),
);
await page.getByPlaceholder("Search files").filter({ visible: true }).first().fill("index");
const results = page.getByTestId("file-filter-results").filter({ visible: true }).first();
await expect(results.getByText("index.ts", { exact: true })).toBeVisible({ timeout: 30_000 });
await expectNoWindowRegions(results);
await openChangesPanel(page);
await expectNoWindowRegions(
page.getByTestId("git-diff-scroll").filter({ visible: true }).first(),
);
});
await test.step("parked resident browser surface emits no window regions even with tabindex=-1", async () => {
const parkedRegions = await page.evaluate(measureParkedBrowserAppRegions);
expect(parkedRegions).toEqual([]);
});
await test.step("wide titlebar drag regions and header controls keep their regions", async () => {
await expectHasDragRegionOver(page, page.getByTestId("workspace-header-title").first());
await expect(page.getByRole("button", { name: "Close menu", exact: true })).toHaveCSS(
"-webkit-app-region",
"no-drag",
);
await expect(page.getByTestId("workspace-header-menu-trigger")).toHaveCSS(
"-webkit-app-region",
"no-drag",
);
await expect(page.getByTestId("workspace-explorer-toggle")).toHaveCSS(
"-webkit-app-region",
"no-drag",
);
});
await test.step("Settings scroll body emits no window regions", async () => {
await openSettings(page);
await expectNoWindowRegions(page.getByTestId("settings-sidebar-scroll-body"));
});
} finally {
await workspace.cleanup();
}
});
test("narrow desktop layout keeps the compact workspace header draggable and controls clickable", async ({
page,
}) => {
const workspace = await seedWorkspace({ repoPrefix: "titlebar-drag-compact-" });
try {
await page.setViewportSize({ width: 1280, height: 800 });
await installDesktopChromeHost(page, "custom-windows");
await gotoWorkspace(page, workspace.workspaceId);
await page.setViewportSize({ width: 560, height: 800 });
const title = page.getByTestId("workspace-header-title").filter({ visible: true }).first();
await expectHasDragRegionOver(page, title);
await expect(page.getByRole("button", { name: "Open menu", exact: true })).toHaveCSS(
"-webkit-app-region",
"no-drag",
);
await expect(page.getByRole("button", { name: "Minimize window", exact: true })).toHaveCSS(
"-webkit-app-region",
"no-drag",
);
await expect(page.getByRole("button", { name: "Close window", exact: true })).toHaveCSS(
"-webkit-app-region",
"no-drag",
);
} finally {
await workspace.cleanup();
}
});
+1 -12
View File
@@ -127,8 +127,7 @@ function inspectChatDragExclusions(scroll: Element) {
const headerRect = header.getBoundingClientRect();
const headerY = headerRect.top + headerRect.height / 2;
const content = scroll.firstElementChild;
const focusScope = scroll.closest("[data-window-content]")?.parentElement?.closest("[tabindex]");
if (!content || !focusScope) throw new Error("Expected chat content and its focus scope");
if (!content) throw new Error("Expected chat content");
const contentRect = content.getBoundingClientRect();
const chatX = (contentRect.left + contentRect.right) / 2;
const tabRow = [...document.querySelectorAll('[data-testid="workspace-tabs-row"]')].find(
@@ -154,7 +153,6 @@ function inspectChatDragExclusions(scroll: Element) {
return {
contentCrossesHeader: contentRect.top < headerY && contentRect.bottom > headerY,
contentCrossesTabRow: contentRect.top < tabY && contentRect.bottom > tabY,
focusScopeRegion: getComputedStyle(focusScope).getPropertyValue("-webkit-app-region"),
exclusions: exclusions.length,
};
}
@@ -194,7 +192,6 @@ test("scrolled chat does not exclude the workspace titlebar from dragging", asyn
.toEqual({
contentCrossesHeader: true,
contentCrossesTabRow: true,
focusScopeRegion: "no-drag",
exclusions: 0,
});
}
@@ -221,15 +218,8 @@ test("scrolled chat does not exclude the workspace titlebar from dragging", asyn
await page.keyboard.press("Meta+f");
const find = page.getByRole("textbox", { name: "Find in pane", exact: true });
await expect(find).toBeFocused();
await expect(find).toHaveCSS("-webkit-app-region", "no-drag");
await find.fill("Paragraph 40:");
await expect(page.getByRole("status", { name: "Find matches" })).toHaveText("1 of 1");
for (const name of ["Next match", "Previous match", "Close Find"]) {
await expect(page.getByRole("button", { name, exact: true })).toHaveCSS(
"-webkit-app-region",
"no-drag",
);
}
await page.getByRole("button", { name: "Close Find", exact: true }).click();
await expect(find).toBeHidden();
// Closing Find returns keyboard scrolling to the chat viewport, which emits no window region.
@@ -241,7 +231,6 @@ test("scrolled chat does not exclude the workspace titlebar from dragging", asyn
.toEqual({
contentCrossesHeader: true,
contentCrossesTabRow: true,
focusScopeRegion: "no-drag",
exclusions: 0,
});
await page.screenshot({ path: testInfo.outputPath("scrolled-chat-titlebar.png") });
+1
View File
@@ -47,6 +47,7 @@ mac:
icon: assets/icon.icon
hardenedRuntime: true
notarize: true
sign: ./scripts/mac-sign.js
entitlements: build/entitlements.mac.plist
entitlementsInherit: build/entitlements.mac.inherit.plist
extraResources:
+87
View File
@@ -0,0 +1,87 @@
const { createRequire } = require("node:module");
const path = require("node:path");
const PLUGIN_HELPER_ENTITLEMENTS_PATH = path.resolve(
__dirname,
"..",
"build",
"entitlements.mac.plugin.plist",
);
const SIGN_RETRY_ATTEMPTS = 4;
const SIGN_RETRY_BASE_DELAY_MS = 5_000;
function isPluginHelperPath(filePath, appPath) {
const resolvedAppPath = path.resolve(appPath);
const resolvedFilePath = path.resolve(filePath);
const relativePath = path.relative(resolvedAppPath, resolvedFilePath);
const normalizedRelative = relativePath.split(path.sep).join("/");
const appName = path.basename(resolvedAppPath, ".app");
const pluginHelperBundle = path.posix.join(
"Contents",
"Frameworks",
`${appName} Helper (Plugin).app`,
);
return (
normalizedRelative === pluginHelperBundle ||
normalizedRelative.startsWith(`${pluginHelperBundle}/`)
);
}
function resolveDefaultSignAsync() {
const electronBuilderPkg = require.resolve("electron-builder/package.json");
const appBuilderPkg = createRequire(electronBuilderPkg).resolve("app-builder-lib/package.json");
return createRequire(appBuilderPkg)("@electron/osx-sign").signAsync;
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function createMacSigner(deps = {}) {
const getSignAsync = () => deps.signAsync ?? resolveDefaultSignAsync();
const delay = deps.sleep ?? sleep;
const maxAttempts = deps.maxAttempts ?? SIGN_RETRY_ATTEMPTS;
const baseDelayMs = deps.baseDelayMs ?? SIGN_RETRY_BASE_DELAY_MS;
const pluginEntitlementsPath = deps.pluginEntitlementsPath ?? PLUGIN_HELPER_ENTITLEMENTS_PATH;
return async function signMacApp(opts) {
const signOptions =
opts.platform === "mas"
? opts
: {
...opts,
optionsForFile: (filePath) => {
const base = opts.optionsForFile ? opts.optionsForFile(filePath) : {};
if (!isPluginHelperPath(filePath, opts.app)) {
return base;
}
return {
...base,
entitlements: pluginEntitlementsPath,
};
},
};
const signAsync = getSignAsync();
for (let attempt = 1; ; attempt++) {
try {
return await signAsync(signOptions);
} catch (error) {
if (attempt >= maxAttempts) {
throw error;
}
await delay(baseDelayMs * attempt);
}
}
};
}
const signMacApp = createMacSigner();
module.exports = signMacApp;
module.exports.default = signMacApp;
module.exports.sign = signMacApp;
module.exports.createMacSigner = createMacSigner;
module.exports.PLUGIN_HELPER_ENTITLEMENTS_PATH = PLUGIN_HELPER_ENTITLEMENTS_PATH;
@@ -8,19 +8,36 @@ import {
rmSync,
writeFileSync,
} from "node:fs";
import { createRequire } from "node:module";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { dirname, join, posix } from "node:path";
import { fileURLToPath } from "node:url";
import { describe, expect, it } from "vitest";
const packageRoot = join(dirname(fileURLToPath(import.meta.url)), "..", "..");
const requireFromTest = createRequire(import.meta.url);
function parseBooleanEntitlementKeys(plistPath: string): string[] {
const xml = readFileSync(plistPath, "utf8");
const keys: string[] = [];
const pattern = /<key>([^<]+)<\/key>\s*<(true|false)\/>/g;
for (const match of xml.matchAll(pattern)) {
if (match[2] === "true") {
keys.push(match[1]!);
}
}
return keys.sort();
}
function writeExecutable(filePath: string, contents: string): void {
writeFileSync(filePath, contents, "utf8");
chmodSync(filePath, 0o755);
}
function createFakeMacBundle(options: { includeHelper: boolean }): {
function createFakeMacBundle(options: {
includePluginHelper: boolean;
includeGenericHelper?: boolean;
}): {
root: string;
shimPath: string;
} {
@@ -30,7 +47,7 @@ function createFakeMacBundle(options: { includeHelper: boolean }): {
const resourcesPath = join(contentsPath, "Resources");
const shimPath = join(resourcesPath, "bin", "paseo");
const mainPath = join(contentsPath, "MacOS", "Paseo");
const helperPath = join(
const genericHelperPath = join(
contentsPath,
"Frameworks",
"Paseo Helper.app",
@@ -38,6 +55,14 @@ function createFakeMacBundle(options: { includeHelper: boolean }): {
"MacOS",
"Paseo Helper",
);
const pluginHelperPath = join(
contentsPath,
"Frameworks",
"Paseo Helper (Plugin).app",
"Contents",
"MacOS",
"Paseo Helper (Plugin)",
);
mkdirSync(dirname(shimPath), { recursive: true });
mkdirSync(dirname(mainPath), { recursive: true });
@@ -46,13 +71,18 @@ function createFakeMacBundle(options: { includeHelper: boolean }): {
writeExecutable(mainPath, "#!/bin/sh\necho main-executable\n");
if (options.includeHelper) {
mkdirSync(dirname(helperPath), { recursive: true });
if (options.includeGenericHelper) {
mkdirSync(dirname(genericHelperPath), { recursive: true });
writeExecutable(genericHelperPath, "#!/bin/sh\necho generic-helper-executable\n");
}
if (options.includePluginHelper) {
mkdirSync(dirname(pluginHelperPath), { recursive: true });
writeExecutable(
helperPath,
pluginHelperPath,
[
"#!/bin/sh",
'printf "helper env=%s/%s cli=%s\\n" "$ELECTRON_RUN_AS_NODE" "$PASEO_NODE_ENV" "$PASEO_CLI"',
'printf "plugin-helper env=%s/%s cli=%s\\n" "$ELECTRON_RUN_AS_NODE" "$PASEO_NODE_ENV" "$PASEO_CLI"',
'printf "args=%s\\n" "$*"',
"",
].join("\n"),
@@ -143,39 +173,406 @@ describe("desktop packaging", () => {
}
});
it("launches the packaged macOS CLI through Helper instead of the main app executable", () => {
it("launches the packaged macOS CLI through Helper (Plugin) instead of the main app or generic Helper", () => {
if (process.platform === "win32") return;
const bundle = createFakeMacBundle({ includeHelper: true });
const bundle = createFakeMacBundle({
includePluginHelper: true,
includeGenericHelper: true,
});
try {
const result = spawnSync(bundle.shimPath, ["--version"], { encoding: "utf8" });
expect(result.status).toBe(0);
expect(result.stdout).toContain(`helper env=1/production cli=${bundle.shimPath}`);
expect(result.stdout).toContain(`plugin-helper env=1/production cli=${bundle.shimPath}`);
expect(result.stdout).toContain("node-entrypoint-runner.js");
expect(result.stdout).toContain("node-script");
expect(result.stdout).toContain("@getpaseo/cli/dist/index.js");
expect(result.stdout).toContain("--version");
expect(result.stdout).not.toContain("main-executable");
expect(result.stdout).not.toContain("generic-helper-executable");
} finally {
rmSync(bundle.root, { recursive: true, force: true });
}
});
it("fails packaged macOS CLI startup when Helper is missing", () => {
it("fails packaged macOS CLI startup when Helper (Plugin) is missing", () => {
if (process.platform === "win32") return;
const bundle = createFakeMacBundle({ includeHelper: false });
const bundle = createFakeMacBundle({
includePluginHelper: false,
includeGenericHelper: true,
});
try {
const result = spawnSync(bundle.shimPath, ["--version"], { encoding: "utf8" });
expect(result.status).toBe(1);
expect(result.stderr).toContain("Bundled Paseo Helper executable not found");
expect(result.stderr).toContain("Bundled Paseo Helper (Plugin) executable not found");
expect(result.stdout).not.toContain("main-executable");
expect(result.stdout).not.toContain("generic-helper-executable");
} finally {
rmSync(bundle.root, { recursive: true, force: true });
}
});
it("scopes macOS disable-library-validation to Helper (Plugin) while keeping main app and other helpers library-validated", () => {
const config = readFileSync(join(packageRoot, "electron-builder.yml"), "utf8");
expect(config).toContain("hardenedRuntime: true");
expect(config).toContain("sign: ./scripts/mac-sign.js");
expect(config).toContain("entitlements: build/entitlements.mac.plist");
expect(config).toContain("entitlementsInherit: build/entitlements.mac.inherit.plist");
const appEntitlements = parseBooleanEntitlementKeys(
join(packageRoot, "build", "entitlements.mac.plist"),
);
const inheritEntitlements = parseBooleanEntitlementKeys(
join(packageRoot, "build", "entitlements.mac.inherit.plist"),
);
const pluginEntitlements = parseBooleanEntitlementKeys(
join(packageRoot, "build", "entitlements.mac.plugin.plist"),
);
expect(appEntitlements).toEqual([
"com.apple.security.cs.allow-jit",
"com.apple.security.device.audio-input",
]);
expect(appEntitlements).not.toContain("com.apple.security.cs.disable-library-validation");
expect(appEntitlements).not.toContain("com.apple.security.cs.allow-unsigned-executable-memory");
expect(inheritEntitlements).toEqual(["com.apple.security.cs.allow-jit"]);
expect(inheritEntitlements).not.toContain("com.apple.security.cs.disable-library-validation");
expect(inheritEntitlements).not.toContain("com.apple.security.device.audio-input");
expect(pluginEntitlements).toEqual([
"com.apple.security.cs.allow-jit",
"com.apple.security.cs.allow-unsigned-executable-memory",
"com.apple.security.cs.disable-library-validation",
]);
for (const key of pluginEntitlements) {
expect(key).not.toMatch(/^com\.apple\.security\.(device|personal-information|automation)\./);
}
});
it("overrides only Helper (Plugin) entitlements through the mac.sign entry point while preserving electron-builder defaults", async () => {
interface MacSignOptions {
app: string;
platform: string;
optionsForFile?: (filePath: string) => Record<string, unknown>;
}
const macSign = requireFromTest(join(packageRoot, "scripts", "mac-sign.js")) as {
default: (opts: MacSignOptions) => Promise<void>;
sign: (opts: MacSignOptions) => Promise<void>;
PLUGIN_HELPER_ENTITLEMENTS_PATH: string;
createMacSigner: (deps?: {
signAsync?: (opts: MacSignOptions) => Promise<void>;
sleep?: (ms: number) => Promise<void>;
maxAttempts?: number;
baseDelayMs?: number;
}) => (opts: MacSignOptions) => Promise<void>;
};
expect(macSign.default).toBe(macSign.sign);
const appPath = "/tmp/release/mac-arm64/Paseo.app";
const appPlist = join(packageRoot, "build", "entitlements.mac.plist");
const inheritPlist = join(packageRoot, "build", "entitlements.mac.inherit.plist");
const loginHelperPlist = join(packageRoot, "build", "entitlements.mac.login.plist");
const received: MacSignOptions[] = [];
const sleeps: number[] = [];
const signMacApp = macSign.createMacSigner({
signAsync: async (opts) => {
received.push(opts);
if (received.length < 3) {
throw new Error("The timestamp service is not available.");
}
},
sleep: async (ms) => {
sleeps.push(ms);
},
maxAttempts: 4,
baseDelayMs: 100,
});
await signMacApp({
app: appPath,
platform: "darwin",
optionsForFile: (filePath) => {
let entitlements = inheritPlist;
if (filePath === appPath) {
entitlements = appPlist;
} else if (filePath.includes("Library/LoginItems")) {
entitlements = loginHelperPlist;
}
return {
entitlements,
hardenedRuntime: true,
timestamp: "http://timestamp.apple.com/ts01",
additionalArguments: ["--strict"],
};
},
});
expect(received).toHaveLength(3);
expect(sleeps).toEqual([100, 200]);
const forwarded = received[0]!;
const forFile = (relativePath: string) =>
forwarded.optionsForFile!(relativePath ? posix.join(appPath, relativePath) : appPath);
expect(forFile("")).toEqual({
hardenedRuntime: true,
timestamp: "http://timestamp.apple.com/ts01",
additionalArguments: ["--strict"],
entitlements: appPlist,
});
expect(forFile("Contents/Frameworks/Paseo Helper (Plugin).app")).toEqual({
hardenedRuntime: true,
timestamp: "http://timestamp.apple.com/ts01",
additionalArguments: ["--strict"],
entitlements: macSign.PLUGIN_HELPER_ENTITLEMENTS_PATH,
});
expect(
forFile("Contents/Frameworks/Paseo Helper (Plugin).app/Contents/MacOS/Paseo Helper (Plugin)")
.entitlements,
).toBe(macSign.PLUGIN_HELPER_ENTITLEMENTS_PATH);
for (const libraryValidatedPath of [
"Contents/Frameworks/Paseo Helper.app",
"Contents/Frameworks/Paseo Helper.app/Contents/MacOS/Paseo Helper",
"Contents/Frameworks/Paseo Helper (GPU).app",
"Contents/Frameworks/Paseo Helper (GPU).app/Contents/MacOS/Paseo Helper (GPU)",
"Contents/Frameworks/Paseo Helper (Renderer).app",
"Contents/Frameworks/Paseo Helper (Renderer).app/Contents/MacOS/Paseo Helper (Renderer)",
"Contents/Frameworks/Squirrel.framework/Versions/A/Resources/ShipIt",
"Contents/Resources/app.asar.unpacked/Paseo Helper (Plugin).app/Contents/MacOS/fake",
]) {
expect(forFile(libraryValidatedPath).entitlements, libraryValidatedPath).toBe(inheritPlist);
}
expect(forFile("Contents/Library/LoginItems/Paseo Login Helper.app").entitlements).toBe(
loginHelperPlist,
);
const masReceived: MacSignOptions[] = [];
const masOpts: MacSignOptions = { app: appPath, platform: "mas" };
await macSign.createMacSigner({
signAsync: async (opts) => {
masReceived.push(opts);
},
})(masOpts);
expect(masReceived).toEqual([masOpts]);
});
it("verifies signed macOS entitlements and live ad-hoc addon dlopen behavior in packaged smoke", () => {
const smoke = requireFromTest(join(packageRoot, "e2e", "packaged-app-smoke.js")) as {
assertDarwinSigningAndLibraryValidation: (
appPath: string,
deps?: {
platform?: NodeJS.Platform;
arch?: string;
log?: (message: string) => void;
spawnSync?: (
command: string,
args: string[],
options?: Record<string, unknown>,
) => { status: number | null; stdout: string; stderr: string };
},
) => void;
};
const root = mkdtempSync(join(tmpdir(), "paseo-darwin-smoke-test-"));
try {
const appPath = join(root, "Paseo.app");
const pluginHelperExe = join(
appPath,
"Contents",
"Frameworks",
"Paseo Helper (Plugin).app",
"Contents",
"MacOS",
"Paseo Helper (Plugin)",
);
const genericHelperExe = join(
appPath,
"Contents",
"Frameworks",
"Paseo Helper.app",
"Contents",
"MacOS",
"Paseo Helper",
);
const bundledAddon = join(
appPath,
"Contents",
"Resources",
"app.asar.unpacked",
"node_modules",
"@getpaseo",
"server",
"node_modules",
"node-pty",
"prebuilds",
"darwin-arm64",
"pty.node",
);
mkdirSync(dirname(pluginHelperExe), { recursive: true });
mkdirSync(dirname(genericHelperExe), { recursive: true });
mkdirSync(dirname(bundledAddon), { recursive: true });
writeExecutable(pluginHelperExe, "#!/bin/sh\n");
writeExecutable(genericHelperExe, "#!/bin/sh\n");
writeFileSync(bundledAddon, "fake-mach-o");
const entitlementsByPath = new Map<string, string>([
[appPath, readFileSync(join(packageRoot, "build", "entitlements.mac.plist"), "utf8")],
[
join(appPath, "Contents", "Frameworks", "Paseo Helper.app"),
readFileSync(join(packageRoot, "build", "entitlements.mac.inherit.plist"), "utf8"),
],
[
join(appPath, "Contents", "Frameworks", "Paseo Helper (GPU).app"),
readFileSync(join(packageRoot, "build", "entitlements.mac.inherit.plist"), "utf8"),
],
[
join(appPath, "Contents", "Frameworks", "Paseo Helper (Renderer).app"),
readFileSync(join(packageRoot, "build", "entitlements.mac.inherit.plist"), "utf8"),
],
[
join(appPath, "Contents", "Frameworks", "Paseo Helper (Plugin).app"),
readFileSync(join(packageRoot, "build", "entitlements.mac.plugin.plist"), "utf8"),
],
]);
const invocations: Array<{ command: string; args: string[] }> = [];
const createFakeSpawn = (overrides?: {
genericHelperResult?: { status: number; stdout: string; stderr: string };
sipEnabled?: boolean;
missingRuntimeFlagFor?: string;
entitlementsOverride?: Map<string, string>;
}) => {
const map = overrides?.entitlementsOverride ?? entitlementsByPath;
const sipStatusLine = `System Integrity Protection status: ${overrides?.sipEnabled === false ? "disabled" : "enabled"}.\n`;
const genericHelperResult = overrides?.genericHelperResult ?? {
status: 1,
stdout: "",
stderr:
"Error: dlopen(pty.node): code signature not valid for use in process: mapping process and mapped file (non-platform) have different Team IDs",
};
return (command: string, args: string[]) => {
invocations.push({ command, args });
if (command === "codesign") {
if (args[0] === "-d" && args[1] === "-v") {
const flags =
overrides?.missingRuntimeFlagFor === args[2]
? "flags=0x0(none)"
: "flags=0x10000(runtime)";
return { status: 0, stdout: "", stderr: `CodeDirectory v=20500 size=100 ${flags}\n` };
}
if (args[0] === "-d" && args[1] === "--entitlements") {
return { status: 0, stdout: map.get(args[3]!) ?? "", stderr: "" };
}
if (args[0] === "--force") {
return { status: 0, stdout: "", stderr: "" };
}
}
if (command === "csrutil") {
return { status: 0, stdout: sipStatusLine, stderr: "" };
}
if (command === pluginHelperExe) {
return { status: 0, stdout: "fork,open,process,resize\n", stderr: "" };
}
if (command === genericHelperExe) {
return genericHelperResult;
}
return { status: 1, stdout: "", stderr: `Unexpected command: ${command}` };
};
};
const addonLoadedResult = { status: 0, stdout: "fork,open,process,resize\n", stderr: "" };
smoke.assertDarwinSigningAndLibraryValidation(appPath, {
platform: "darwin",
arch: "arm64",
log: () => {},
spawnSync: createFakeSpawn(),
});
expect(
invocations.some((call) => call.command === "codesign" && call.args[0] === "--force"),
).toBe(true);
expect(invocations.some((call) => call.command === pluginHelperExe)).toBe(true);
expect(invocations.some((call) => call.command === genericHelperExe)).toBe(true);
// When SIP is enabled, generic Helper must reject the ad-hoc-signed addon.
expect(() =>
smoke.assertDarwinSigningAndLibraryValidation(appPath, {
platform: "darwin",
arch: "arm64",
log: () => {},
spawnSync: createFakeSpawn({
genericHelperResult: addonLoadedResult,
sipEnabled: true,
}),
}),
).toThrow(/Expected generic Helper to reject ad-hoc-signed addon/);
// When host SIP is disabled (e.g. GitHub Actions macOS runners), the smoke still passes
// after confirming Hardened Runtime flags, per-bundle entitlements, and Helper (Plugin) dlopen.
const sipDisabledLogs: string[] = [];
smoke.assertDarwinSigningAndLibraryValidation(appPath, {
platform: "darwin",
arch: "arm64",
log: (message) => sipDisabledLogs.push(message),
spawnSync: createFakeSpawn({
genericHelperResult: addonLoadedResult,
sipEnabled: false,
}),
});
expect(sipDisabledLogs.some((line) => line.includes("host SIP is disabled"))).toBe(true);
// Even when SIP is disabled, an unrelated non-zero generic Helper failure must still fail smoke.
expect(() =>
smoke.assertDarwinSigningAndLibraryValidation(appPath, {
platform: "darwin",
arch: "arm64",
log: () => {},
spawnSync: createFakeSpawn({
genericHelperResult: { status: 134, stdout: "", stderr: "Abort trap: 6" },
sipEnabled: false,
}),
}),
).toThrow(/Expected generic Helper to reject ad-hoc-signed addon/);
expect(() =>
smoke.assertDarwinSigningAndLibraryValidation(appPath, {
platform: "darwin",
arch: "arm64",
log: () => {},
spawnSync: createFakeSpawn({
missingRuntimeFlagFor: join(appPath, "Contents", "Frameworks", "Paseo Helper.app"),
}),
}),
).toThrow(/Expected Hardened Runtime flag on Paseo Helper\.app/);
const badEntitlements = new Map(entitlementsByPath);
badEntitlements.set(
appPath,
readFileSync(join(packageRoot, "build", "entitlements.mac.plugin.plist"), "utf8"),
);
expect(() =>
smoke.assertDarwinSigningAndLibraryValidation(appPath, {
platform: "darwin",
arch: "arm64",
log: () => {},
spawnSync: createFakeSpawn({ entitlementsOverride: badEntitlements }),
}),
).toThrow(/Unexpected macOS entitlements on Paseo\.app/);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
});
it("installs the Linux helper as root-owned 4755 regardless of root's namespace access", () => {
@@ -64,9 +64,9 @@ describe("runtime-paths", () => {
});
});
it("uses the macOS Helper executable for packaged daemon node launches", () => {
it("uses the macOS Plugin Helper executable for packaged daemon node launches", () => {
expect(resolveNodeExecPath()).toBe(
"/Applications/Paseo.app/Contents/Frameworks/Paseo Helper.app/Contents/MacOS/Paseo Helper",
"/Applications/Paseo.app/Contents/Frameworks/Paseo Helper (Plugin).app/Contents/MacOS/Paseo Helper (Plugin)",
);
});
});
+2 -2
View File
@@ -85,10 +85,10 @@ export function resolveNodeExecPath(): string {
bundleRoot,
"Contents",
"Frameworks",
`${name} Helper.app`,
`${name} Helper (Plugin).app`,
"Contents",
"MacOS",
`${name} Helper`,
`${name} Helper (Plugin)`,
);
if (existsSync(helperPath)) {
return helperPath;
+22 -1
View File
@@ -14,7 +14,7 @@ import path from "node:path";
import { randomBytes, randomUUID } from "node:crypto";
import { hostname } from "node:os";
import { pathToFileURL } from "node:url";
import { existsSync } from "node:fs";
import { existsSync, readFileSync } from "node:fs";
import { execFileSync } from "node:child_process";
import {
app,
@@ -799,11 +799,30 @@ function getWorkAreasPrimaryFirst(): Electron.Rectangle[] {
return [primary, ...others].map((display) => display.workArea);
}
function resolveDesktopOsVersion(): string | undefined {
if (process.platform === "linux") {
try {
const content = readFileSync("/etc/os-release", "utf8");
const match = content.match(/^PRETTY_NAME=(?:"([^"\n]+)"|'([^'\n]+)'|([^\n]+))$/m);
const prettyName = (match?.[1] ?? match?.[2] ?? match?.[3] ?? "").trim();
if (prettyName) {
return prettyName.slice(0, 48);
}
} catch {
// Fall through to Electron's process.getSystemVersion() when /etc/os-release is unavailable.
}
}
const systemVersion =
typeof process.getSystemVersion === "function" ? process.getSystemVersion().trim() : "";
return systemVersion ? systemVersion.slice(0, 48) : undefined;
}
const browserHostComputerName =
hostname()
.replace(/\.local$/i, "")
.trim()
.slice(0, 120) || "Desktop";
const desktopOsVersion = resolveDesktopOsVersion();
const browserHostSessionCode = randomBytes(3).toString("hex").toUpperCase();
let browserHostWindowNumber = 0;
@@ -846,6 +865,8 @@ async function createWindow(
preload: getPreloadPath(),
additionalArguments: [
windowChromeModeArgument(DESKTOP_WINDOW_CHROME_MODE),
`--paseo-device-name=${browserHostComputerName}`,
...(desktopOsVersion ? [`--paseo-os-version=${desktopOsVersion}`] : []),
`--paseo-browser-host-label=${browserHostLabel}`,
`--paseo-browser-host-instance-id=${randomUUID()}`,
],
+2
View File
@@ -39,6 +39,8 @@ interface AttachedBrowserRegistration {
contextBridge.exposeInMainWorld("paseoDesktop", {
platform: process.platform,
deviceName: readArgValue("--paseo-device-name="),
osVersion: readArgValue("--paseo-os-version="),
windowChromeMode: readWindowChromeMode(),
browserHostLabel: readArgValue("--paseo-browser-host-label="),
browserHostInstanceId: readArgValue("--paseo-browser-host-instance-id="),
+40
View File
@@ -1056,3 +1056,43 @@ describe("provider icon SDK boundary", () => {
).toEqual([]);
});
});
describe("agent chat SDK boundary", () => {
it("exposes AgentChat and its props from client UI", () => {
expect(
typeErrors(`
import type { PluginClientContext, PluginScreenProps } from "@getpaseo/plugin/client";
import {
AgentChat,
type AgentChatComposer,
type AgentChatProps,
} from "@getpaseo/plugin/client/ui";
const plain: AgentChatComposer = { controls: "none", placeholder: "Message this agent" };
function Screen({ host, params }: PluginScreenProps) {
const props: AgentChatProps = { agentId: params.agentId ?? "", hostId: host.id };
return (
<>
<AgentChat {...props} />
<AgentChat agentId="agent-1" composer={plain} />
<AgentChat agentId="agent-1" composer={{ controls: "all" }} />
<AgentChat agentId="agent-1" composer={false} testID="chat" />
{/* @ts-expect-error agentId is required */}
<AgentChat hostId={host.id} />
{/* @ts-expect-error composer is false or options, never true */}
<AgentChat agentId="agent-1" composer={true} />
{/* @ts-expect-error controls is "all" or "none" */}
<AgentChat agentId="agent-1" composer={{ controls: "some" }} />
</>
);
}
export default function contribute(client: PluginClientContext) {
client.addScreen({ id: "main", title: "Main", Component: Screen });
return () => {};
}
`),
).toEqual([]);
});
});
+25
View File
@@ -202,6 +202,31 @@ export interface MarkdownProps {
/** Renders Markdown using Paseo’s theme, selection, and link behavior. */
export declare const Markdown: ComponentType<MarkdownProps>;
export interface AgentChatComposer {
/**
* `"all"` (default): the agent tab's composer. `"none"`: a text box and Send; everything typed,
* slash commands included, goes to the agent as written.
*/
controls?: "all" | "none";
/** Replaces the default placeholder. */
placeholder?: string;
}
export interface AgentChatProps {
agentId: string;
/** The agent's host ID. Defaults to the current plugin installation's host. */
hostId?: string;
/** The agent tab's composer when omitted. `false` shows the conversation without a composer. */
composer?: false | AgentChatComposer;
testID?: string;
}
/**
* An agent's conversation as its tab shows it, with a composer, and without the tab's chrome.
* Fills its parent. Undefined in apps older than this API.
*/
export declare const AgentChat: ComponentType<AgentChatProps>;
export interface ComposerControlProps {
/** The control's label and tooltip. */
title: string;
@@ -2,11 +2,16 @@ import type { ChildProcessWithoutNullStreams } from "node:child_process";
import { readFileSync } from "node:fs";
import { spawnProcess, terminateProcess } from "../process.js";
import { Readable, Writable } from "node:stream";
import type {
ReadableStream as NodeReadableStream,
WritableStream as NodeWritableStream,
} from "node:stream/web";
import {
ClientSideConnection,
CLIENT_METHODS,
PROTOCOL_VERSION,
ndJsonStream,
RequestError,
type AnyMessage,
type Client,
type AgentCapabilities,
type ContentBlock,
@@ -25,6 +30,10 @@ import {
} from "@agentclientprotocol/sdk";
import { z } from "zod";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
import {
createBoundedNdJsonStream,
ProviderStreamLimitError,
} from "@getpaseo/protocol/provider-line-reader";
import type {
AcpConfigAccess,
AcpConfigChange,
@@ -664,6 +673,7 @@ class AcpRuntime {
private retirementFinalized = false;
private processFailed = false;
private processFailureMessage: string | null = null;
private streamFailure: ProviderStreamLimitError | null = null;
private canReopen = false;
private hadWorkAtTransportClose = false;
private configTransaction = false;
@@ -691,6 +701,7 @@ class AcpRuntime {
}) => Promise<void> = async () => {};
let whenConnectorClosed: () => Promise<void> | null = () => null;
let onPartialWireRead: (() => void) | null = null;
let onStreamLimit: ((error: ProviderStreamLimitError) => void) | null = null;
if (options.options.command) {
// COMPAT(pluginProviderLaunch): added in v0.10.0, remove after 2027-03-29 once plugin host floor >= v0.10.0.
// Standalone callers and older hosts do not send a daemon-resolved launch.
@@ -707,12 +718,10 @@ class AcpRuntime {
});
spawnFailure = new Promise<never>((_resolve, reject) => child!.once("error", reject));
child.stderr.on("data", () => undefined);
const output = Writable.toWeb(child.stdin) as unknown as Parameters<typeof ndJsonStream>[0];
const output = Writable.toWeb(child.stdin) as unknown as NodeWritableStream;
const rawInput = Readable.toWeb(child.stdout) as unknown as ReadableStream<Uint8Array>;
const input = observePartialWireReads(rawInput, () => onPartialWireRead?.()) as Parameters<
typeof ndJsonStream
>[1];
stream = ndJsonStream(output, input);
const input = observePartialWireReads(rawInput, () => onPartialWireRead?.());
stream = createBoundedAcpNdJsonStream(output, input, (error) => onStreamLimit?.(error));
} else {
if (options.wrap) throw new Error("An ACP connector cannot run behind a launch wrap");
const owned = ownConnectorStream(await options.options.connector());
@@ -722,6 +731,7 @@ class AcpRuntime {
}
const runtime = new AcpRuntime(stream, child, closeConnector, whenConnectorClosed, options);
onPartialWireRead = () => runtime.notePartialWireRead();
onStreamLimit = (error) => runtime.handleStreamLimit(error);
// Closing ends the transport, which fails the pending initialize below.
const closeOnAbort = () => void runtime.close().catch(() => undefined);
options.signal?.addEventListener("abort", closeOnAbort, { once: true });
@@ -2092,29 +2102,56 @@ class AcpRuntime {
private call<Value>(operation: Promise<Value>): Promise<Value> {
if (this.connection.signal.aborted) {
return Promise.reject(new Error("ACP transport is closed"));
return Promise.reject(this.transportClosedError("ACP transport is closed"));
}
return Promise.race([
operation,
this.connection.closed.then(() => {
throw new Error("ACP transport closed unexpectedly");
throw this.transportClosedError("ACP transport closed unexpectedly");
}),
]);
}
private transportClosedError(fallback: string): Error {
if (this.streamFailure) return this.streamFailure;
const reason = this.connection.signal.reason;
return reason instanceof ProviderStreamLimitError ? reason : new Error(fallback);
}
private handleStreamLimit(error: ProviderStreamLimitError): void {
this.streamFailure ??= error;
this.handleUnexpectedExit(error.message, { allowIdleReopen: false });
void this.closeQuietly();
}
private async closeQuietly(): Promise<void> {
try {
await this.close();
} catch {
// Best-effort cleanup after stream limit rejection.
}
}
private enqueueNotification(operation: () => void): Promise<void> {
const result = this.notificationLane.then(operation);
this.notificationLane = result.catch(() => undefined);
return result;
}
private handleUnexpectedExit(message: string): void {
private handleUnexpectedExit(message: string, options?: { allowIdleReopen?: boolean }): void {
if (this.closing || this.processFailed) return;
this.processFailed = true;
this.processFailureMessage = message;
const wasIdle = !this.hadWorkAtTransportClose && !this.hasPendingWork();
// A clean close lets the host reopen the session on the next prompt.
if (this.canReopen && wasIdle && this.options.onRetired?.()) return;
if (
options?.allowIdleReopen !== false &&
this.canReopen &&
wasIdle &&
this.options.onRetired?.()
) {
return;
}
this.settlePendingWork(message);
if (!this.nativeSessionId) return;
this.emit({
@@ -2533,6 +2570,34 @@ class AcpRuntime {
}
}
function createBoundedAcpNdJsonStream(
output: NodeWritableStream,
input: ReadableStream<Uint8Array>,
onStreamLimit: (error: ProviderStreamLimitError) => void,
): Stream {
return createBoundedNdJsonStream<AnyMessage>(output, input as unknown as NodeReadableStream, {
onStreamLimit,
onInvalidJson: async ({ write }) => {
await write({
jsonrpc: "2.0",
id: null,
error: RequestError.parseError().toErrorResponse(),
});
},
onParsedMessage: async ({ message, write }) => {
if ((typeof message === "object" && message !== null) || Array.isArray(message)) {
return message as AnyMessage;
}
await write({
jsonrpc: "2.0",
id: null,
error: RequestError.invalidRequest(message).toErrorResponse(),
});
return undefined;
},
}) as Stream;
}
function observePartialWireReads(
input: ReadableStream<Uint8Array>,
onPartialRead: () => void,
+241
View File
@@ -9420,3 +9420,244 @@ describe("includeToolCall", () => {
}
});
});
describe("ACP stdout byte admission", () => {
it("fails only the affected session on an oversized ACP notification while another session on the same connection stays alive", async () => {
const executable = await fakeAcp(`
const readline = require("node:readline");
const lines = readline.createInterface({ input: process.stdin });
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
lines.on("line", (line) => {
const message = JSON.parse(line);
if (message.method === "initialize") {
send({
jsonrpc: "2.0",
id: message.id,
result: { protocolVersion: message.params.protocolVersion, agentCapabilities: { loadSession: true } },
});
} else if (message.method === "session/new") {
send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "healthy-session", modes: null, configOptions: [] } });
} else if (message.method === "session/load") {
const chunk = Buffer.alloc(64 * 1024, "x").toString("utf8");
process.stdout.write('{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"poisoned","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"');
for (let index = 0; index < 1025; index += 1) process.stdout.write(chunk);
process.stdout.write('"}}}}\\n');
} else if (message.method === "session/prompt") {
send({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "healthy-session",
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "ok" } },
},
});
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
}
});
`);
const { connection, events } = await connect(executable, [
"prompt.message",
"session.persistence",
]);
try {
await connection.send({
type: "session.open",
requestId: "open-healthy",
sessionId: "healthy",
config: { cwd: process.cwd(), env: {}, mcpServers: {}, settings: {}, persist: true },
history: "skip",
});
await waitForEvent(
events,
(event) => event.type === "session.ready" && event.sessionId === "healthy",
);
await connection.send({
type: "session.open",
requestId: "open-poisoned",
sessionId: "poisoned",
persistence: { version: 1, data: { sessionId: "poisoned" } },
config: { cwd: process.cwd(), env: {}, mcpServers: {}, settings: {}, persist: true },
history: "replay",
});
const failed = await waitForEvent(
events,
(event) => event.type === "request.failed" && event.requestId === "open-poisoned",
);
expect(failed).toMatchObject({
type: "request.failed",
requestId: "open-poisoned",
error: {
message: expect.stringMatching(/Start a new thread or reduce the provider response size/),
},
});
await connection.send({
type: "session.prompt",
sessionId: "healthy",
prompt: {
clientMessageId: "msg-healthy",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "ping" }] },
},
});
await waitForEvent(
events,
(event) =>
event.type === "session.turn" &&
event.sessionId === "healthy" &&
event.state === "completed",
);
} finally {
await connection.close();
}
}, 15_000);
it("fails only the oversized ACP response request and keeps the session open for follow-up turns", async () => {
const executable = await fakeAcp(`
const readline = require("node:readline");
const lines = readline.createInterface({ input: process.stdin });
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
lines.on("line", (line) => {
const message = JSON.parse(line);
if (message.method === "initialize") {
send({
jsonrpc: "2.0",
id: message.id,
result: { protocolVersion: message.params.protocolVersion, agentCapabilities: {} },
});
} else if (message.method === "session/new") {
send({ jsonrpc: "2.0", id: message.id, result: { sessionId: "native-1", modes: null, configOptions: [] } });
} else if (message.method === "session/prompt") {
const text = message.params?.prompt?.[0]?.text ?? "";
if (text === "oversized-response") {
const chunk = Buffer.alloc(64 * 1024, "x").toString("utf8");
process.stdout.write('{"jsonrpc":"2.0","id":' + JSON.stringify(message.id) + ',"result":{"stopReason":"end_turn","extra":"');
for (let index = 0; index < 1025; index += 1) process.stdout.write(chunk);
process.stdout.write('"}}\\n');
} else {
send({
jsonrpc: "2.0",
method: "session/update",
params: {
sessionId: "native-1",
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "recovered" } },
},
});
send({ jsonrpc: "2.0", id: message.id, result: { stopReason: "end_turn" } });
}
}
});
`);
const { connection, events } = await connect(executable, ["prompt.message"]);
try {
await connection.send(openInput());
await waitForEvent(events, (event) => event.type === "session.ready");
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "msg-1",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "oversized-response" }] },
},
});
const failedTurn = await waitForEvent(
events,
(event) => event.type === "session.turn" && event.state === "failed",
);
expect(failedTurn).toMatchObject({
type: "session.turn",
state: "failed",
error: {
message: expect.stringMatching(/Start a new thread or reduce the provider response size/),
},
});
await connection.send({
type: "session.prompt",
sessionId: "session-1",
prompt: {
clientMessageId: "msg-2",
delivery: "auto",
input: { type: "message", content: [{ type: "text", text: "follow-up" }] },
},
});
await waitForEvent(
events,
(event) => event.type === "session.turn" && event.state === "completed",
);
expect(events).toContainEqual(
expect.objectContaining({
type: "timeline.item",
item: expect.objectContaining({ type: "assistant_message", text: "recovered" }),
}),
);
} finally {
await connection.close();
}
}, 15_000);
it("fails session open when a trailing loadReplayQuietPeriodMs notification exceeds 64 MiB", async () => {
const executable = await fakeAcp(`
const readline = require("node:readline");
const lines = readline.createInterface({ input: process.stdin });
const send = (message) => process.stdout.write(JSON.stringify(message) + "\\n");
lines.on("line", (line) => {
const message = JSON.parse(line);
if (message.method === "initialize") {
send({
jsonrpc: "2.0",
id: message.id,
result: { protocolVersion: message.params.protocolVersion, agentCapabilities: { loadSession: true } },
});
} else if (message.method === "session/load") {
send({ jsonrpc: "2.0", id: message.id, result: { modes: null, configOptions: [] } });
setTimeout(() => {
const chunk = Buffer.alloc(64 * 1024, "x").toString("utf8");
process.stdout.write('{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"trailing-poisoned","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"');
for (let index = 0; index < 1025; index += 1) process.stdout.write(chunk);
process.stdout.write('"}}}}\\n');
}, 20);
}
});
`);
const registration = runAcpProvider({
id: "test-acp-trailing",
label: "Test ACP Trailing",
command: [process.execPath, executable],
acpOptions: { loadReplayQuietPeriodMs: 200 },
});
const connection = await registration.connect({
versions: [1],
capabilities: ["prompt.message", "session.persistence"],
});
const events: ProviderEvent[] = [];
connection.onEvent((event) => events.push(event));
try {
await connection.send({
type: "session.open",
requestId: "open-trailing",
sessionId: "trailing-poisoned",
persistence: { version: 1, data: { sessionId: "trailing-poisoned" } },
config: { cwd: process.cwd(), env: {}, mcpServers: {}, settings: {}, persist: true },
history: "replay",
});
const failed = await waitForEvent(
events,
(event) => event.type === "request.failed" && event.requestId === "open-trailing",
);
expect(failed).toMatchObject({
type: "request.failed",
requestId: "open-trailing",
error: {
message: expect.stringMatching(/Start a new thread or reduce the provider response size/),
},
});
expect(events.some((event) => event.type === "session.ready")).toBe(false);
} finally {
await connection.close();
}
}, 15_000);
});
+103
View File
@@ -1,6 +1,7 @@
import { describe, expect, it, test } from "vitest";
import {
balanceToneFromRemaining,
isWrapperLaunch,
toneFromUsedPct,
usedPctOf,
windowFromUsedPct,
@@ -105,3 +106,105 @@ test.each([
expect(window.durationSeconds).toBe(durationSeconds ?? undefined);
},
);
describe("isWrapperLaunch", () => {
const isolatingFlags = ["--settings", "--bare", "-c", "-p"];
it("returns false for missing or empty launches and for the stock binary with harmless flags", () => {
expect(isWrapperLaunch({ launch: undefined, expectedBinary: "claude", isolatingFlags })).toBe(
false,
);
expect(
isWrapperLaunch({
launch: { command: " ", args: [] },
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(false);
expect(
isWrapperLaunch({
launch: { command: "claude", args: ["--chrome"] },
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(false);
expect(
isWrapperLaunch({
launch: {
command: "C:\\Users\\alice\\.local\\bin\\claude.exe",
args: ["--chrome", "-C", "dir"],
},
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(false);
expect(
isWrapperLaunch({
launch: {
command: "/opt/claude-nightly/claude",
args: ["--settings-extra", "--", "--bare"],
},
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(false);
});
it("returns true for renamed binaries and isolating long or short flags before --", () => {
expect(
isWrapperLaunch({
launch: { command: "/opt/homebrew/bin/teamclaude", args: [] },
expectedBinary: "claude",
}),
).toBe(true);
expect(
isWrapperLaunch({
launch: { command: "claude-proxy-wrapper.cmd", args: [] },
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(true);
expect(
isWrapperLaunch({
launch: { command: "claude", args: ["--settings", "/tmp/alt.json"] },
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(true);
expect(
isWrapperLaunch({
launch: { command: "claude", args: ["--settings=/tmp/alt.json"] },
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(true);
expect(
isWrapperLaunch({
launch: { command: "claude", args: ["--chrome", "--bare"] },
expectedBinary: "claude",
isolatingFlags,
}),
).toBe(true);
expect(
isWrapperLaunch({
launch: { command: "codex", args: ["-c", "model_provider=azure"] },
expectedBinary: "codex",
isolatingFlags,
}),
).toBe(true);
expect(
isWrapperLaunch({
launch: { command: "codex", args: ["-cmodel_provider=azure"] },
expectedBinary: "codex",
isolatingFlags,
}),
).toBe(true);
expect(
isWrapperLaunch({
launch: { command: "codex", args: ["-pwork"] },
expectedBinary: "codex",
isolatingFlags,
}),
).toBe(true);
});
});
+50 -1
View File
@@ -1,6 +1,6 @@
import { createHash } from "node:crypto";
import { z, type ZodType } from "zod";
import { ProviderLaunchSchema } from "./provider.js";
import { ProviderLaunchSchema, type ProviderLaunch } from "./provider.js";
import type { JsonValue } from "@getpaseo/protocol/agent-types";
export interface UsageWindow {
@@ -231,3 +231,52 @@ export function hashAccountKey(value: string): string {
export function unavailable(problem: UsageProblem): UsageReport {
return { status: "unavailable", problem };
}
export interface WrapperLaunchCheckInput {
readonly launch: Pick<ProviderLaunch, "command" | "args"> | undefined;
readonly expectedBinary: string;
/**
* CLI flags that isolate configuration, profile, endpoint, or credentials from
* the binary's default local store. Long flags (`--name`) match `--name` and
* `--name=value`; short flags (`-x`) match `-x`, `-xvalue`, and `-x=value`.
*/
readonly isolatingFlags?: readonly string[];
}
function matchesIsolatingFlag(arg: string, isolatingFlags: readonly string[]): boolean {
for (const flag of isolatingFlags) {
if (flag.startsWith("--")) {
if (arg === flag || arg.startsWith(`${flag}=`)) return true;
} else if (flag.startsWith("-") && flag.length === 2) {
if (arg === flag || arg.startsWith(flag)) return true;
} else if (arg === flag) {
return true;
}
}
return false;
}
/**
* Returns true when a provider launch invokes a different executable than `expectedBinary`
* (such as a wrapper script) or passes an isolating flag before `--`.
*/
export function isWrapperLaunch({
launch,
expectedBinary,
isolatingFlags,
}: WrapperLaunchCheckInput): boolean {
if (!launch) return false;
const command = launch.command.trim();
if (!command) return false;
const base = command.replaceAll("\\", "/").split("/").pop()?.toLowerCase() ?? "";
const stem = base.replace(/\.(?:exe|cmd|bat|ps1)$/, "");
if (stem !== expectedBinary.toLowerCase()) return true;
if (!isolatingFlags?.length) return false;
for (const arg of launch.args) {
if (arg === "--") break;
if (matchesIsolatingFlag(arg, isolatingFlags)) return true;
}
return false;
}
+18
View File
@@ -18,6 +18,12 @@ export type HelloClientPlatform = z.infer<typeof HelloClientPlatformSchema>;
export const HelloClientInfoSchema = z.object({
name: z.string().max(128).optional(),
platform: HelloClientPlatformSchema.optional(),
// Optional additive wire fields; older clients omit them and older daemons ignore unknown keys.
appKind: z.string().max(32).optional(),
osName: z.string().max(48).optional(),
osVersion: z.string().max(48).optional(),
deviceModel: z.string().max(96).optional(),
browserName: z.string().max(48).optional(),
});
export type HelloClientInfo = z.infer<typeof HelloClientInfoSchema>;
@@ -32,15 +38,27 @@ export const DaemonSessionTransportSchema = z.enum([
]);
export type DaemonSessionTransport = z.infer<typeof DaemonSessionTransportSchema>;
export const DaemonSessionIpSourceSchema = z.enum(["direct", "relay"]);
export type DaemonSessionIpSource = z.infer<typeof DaemonSessionIpSourceSchema>;
export const DaemonSessionSummarySchema = z.object({
sessionId: z.string(),
deviceKey: z.string().optional(),
principalId: z.string(),
isCurrentSession: z.boolean(),
name: z.string().nullable(),
platform: z.string().nullable(),
clientType: WSClientTypeSchema,
appKind: z.string().nullable().optional(),
osName: z.string().nullable().optional(),
osVersion: z.string().nullable().optional(),
deviceModel: z.string().nullable().optional(),
browserName: z.string().nullable().optional(),
appVersion: z.string().nullable(),
transport: DaemonSessionTransportSchema,
remoteIp: z.string().nullable().optional(),
ipSource: DaemonSessionIpSourceSchema.nullable().optional(),
authMethod: z.string().nullable().optional(),
viaSessionId: z.string().optional(),
servesHostLink: z.boolean().optional(),
permissions: z.array(DaemonPermissionSchema),
@@ -0,0 +1,121 @@
import { describe, expect, it } from "vitest";
import {
ProviderStreamLimitError,
createBoundedNdJsonStream,
parseOversizedJsonRpcResponseId,
} from "./provider-line-reader.js";
describe("parseOversizedJsonRpcResponseId", () => {
it("extracts numeric and string request ids from response heads", () => {
expect(parseOversizedJsonRpcResponseId('{"jsonrpc":"2.0","id":7,"result":')).toBe(7);
expect(parseOversizedJsonRpcResponseId('{"jsonrpc":"2.0","id":"req-1","error":')).toBe("req-1");
expect(parseOversizedJsonRpcResponseId('{"id":42,"result":')).toBe(42);
expect(parseOversizedJsonRpcResponseId('{"id":42,"jsonrpc":"2.0","result":')).toBe(42);
});
it("returns null for notifications, server requests, and null ids", () => {
expect(
parseOversizedJsonRpcResponseId('{"jsonrpc":"2.0","method":"session/update"'),
).toBeNull();
expect(
parseOversizedJsonRpcResponseId('{"jsonrpc":"2.0","id":1,"method":"fs/read_text_file"'),
).toBeNull();
expect(parseOversizedJsonRpcResponseId('{"jsonrpc":"2.0","id":null,"error":')).toBeNull();
});
});
describe("createBoundedNdJsonStream", () => {
it("decodes split UTF-8 chunks, CRLF, and trailing line without newline", async () => {
const input = new TransformStream<Uint8Array, Uint8Array>();
const output = new TransformStream<Uint8Array, Uint8Array>();
const stream = createBoundedNdJsonStream<Record<string, unknown>>(
output.writable as never,
input.readable as never,
);
const reader = stream.readable.getReader();
const writer = input.writable.getWriter();
const first = Buffer.from('{"text":"é🙂"}\r\n', "utf8");
const split = first.indexOf(Buffer.from("🙂")) + 1;
await writer.write(first.subarray(0, split));
await writer.write(first.subarray(split));
await writer.write(Buffer.from('{"tail":true}', "utf8"));
await writer.close();
expect((await reader.read()).value).toEqual({ text: "é🙂" });
expect((await reader.read()).value).toEqual({ tail: true });
expect((await reader.read()).done).toBe(true);
reader.releaseLock();
});
it("synthesizes a JSON-RPC error response for oversized response lines and continues", async () => {
const input = new TransformStream<Uint8Array, Uint8Array>();
const output = new TransformStream<Uint8Array, Uint8Array>();
const stream = createBoundedNdJsonStream<Record<string, unknown>>(
output.writable as never,
input.readable as never,
{ limitBytes: 128 },
);
const reader = stream.readable.getReader();
const writer = input.writable.getWriter();
await writer.write(Buffer.from(`{"jsonrpc":"2.0","id":3,"result":"${"x".repeat(256)}"}\n`));
await writer.write(Buffer.from('{"jsonrpc":"2.0","id":4,"result":{"ok":true}}\n'));
await writer.close();
expect((await reader.read()).value).toEqual({
jsonrpc: "2.0",
id: 3,
error: {
code: -32603,
message: expect.stringContaining("Start a new thread or reduce the provider response size"),
},
});
expect((await reader.read()).value).toEqual({ jsonrpc: "2.0", id: 4, result: { ok: true } });
reader.releaseLock();
});
it("errors the stream on oversized non-response lines", async () => {
const input = new TransformStream<Uint8Array, Uint8Array>();
const output = new TransformStream<Uint8Array, Uint8Array>();
const limitErrors: ProviderStreamLimitError[] = [];
const stream = createBoundedNdJsonStream<Record<string, unknown>>(
output.writable as never,
input.readable as never,
{
limitBytes: 128,
onStreamLimit: (error) => limitErrors.push(error),
},
);
const reader = stream.readable.getReader();
const writer = input.writable.getWriter();
await writer
.write(
Buffer.from(`{"jsonrpc":"2.0","method":"session/update","params":"${"x".repeat(256)}"}\n`),
)
.catch(() => undefined);
await expect(reader.read()).rejects.toBeInstanceOf(ProviderStreamLimitError);
expect(limitErrors).toHaveLength(1);
reader.releaseLock();
});
it("closes readable cleanly instead of erroring on underlying read errors when closeOnStreamLimit is enabled", async () => {
const output = new TransformStream<Uint8Array, Uint8Array>();
const input = new ReadableStream<Uint8Array>({
start(controller) {
controller.error(new Error("Premature close"));
},
});
const stream = createBoundedNdJsonStream<Record<string, unknown>>(
output.writable as never,
input as never,
{ closeOnStreamLimit: true },
);
const reader = stream.readable.getReader();
await expect(reader.read()).resolves.toEqual({ value: undefined, done: true });
reader.releaseLock();
});
});
@@ -0,0 +1,312 @@
import type {
ReadableStream as WebReadableStream,
WritableStream as WebWritableStream,
} from "node:stream/web";
// Provider-process stdout only; these are not app/daemon wire limits.
export const JSONL_PROVIDER_LINE_BYTES = 64 * 1024 * 1024;
// Enough of an oversized line to read its JSON-RPC header/id before discarding the rest.
const OVERSIZED_LINE_HEAD_BYTES = 256;
const OVERSIZED_JSON_RPC_RESPONSE_HEAD =
/^\s*\{\s*(?:"jsonrpc"\s*:\s*"2\.0"\s*,\s*)?"id"\s*:\s*(-?\d+|"(?:[^"\\]|\\.)*")\s*,\s*(?:"jsonrpc"\s*:\s*"2\.0"\s*,\s*)?"(?:result|error)"\s*:/;
export class ProviderStreamLimitError extends Error {
readonly code = "PROVIDER_STREAM_LINE_TOO_LARGE";
constructor(
readonly limitBytes: number,
/** The first bytes of the oversized line; the rest is discarded unread. */
readonly lineHead = "",
) {
super(
`Provider stdout line exceeds ${limitBytes} bytes. Start a new thread or reduce the provider response size.`,
);
this.name = "ProviderStreamLimitError";
}
}
function readLineHead(parts: Buffer[]): string {
const head: Buffer[] = [];
let bytes = 0;
for (const part of parts) {
if (bytes >= OVERSIZED_LINE_HEAD_BYTES) break;
head.push(part.subarray(0, OVERSIZED_LINE_HEAD_BYTES - bytes));
bytes += head[head.length - 1]!.byteLength;
}
return Buffer.concat(head).toString("utf8");
}
function toBuffer(chunk: Buffer | Uint8Array | string): Buffer {
if (Buffer.isBuffer(chunk)) return chunk;
if (typeof chunk === "string") return Buffer.from(chunk, "utf8");
return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength);
}
/**
* Admits raw UTF-8 bytes before retaining, decoding or joining a complete line.
* An oversized line is reported with its head and skipped up to its newline;
* the owner closes the reader if the stream cannot continue without it.
*/
export class ProviderLineReader {
private parts: Buffer[] = [];
private bytes = 0;
private skippingOversizedLine = false;
private stopped = false;
constructor(
private readonly limitBytes: number,
private readonly onLine: (line: string) => void,
private readonly onLimit: (error: ProviderStreamLimitError) => void,
) {}
write(chunk: Buffer | Uint8Array | string): void {
if (this.stopped) return;
const buffer = toBuffer(chunk);
let start = 0;
while (start < buffer.byteLength && !this.stopped) {
const newline = buffer.indexOf(10, start);
const end = newline === -1 ? buffer.byteLength : newline;
if (this.skippingOversizedLine) {
if (newline === -1) return;
this.skippingOversizedLine = false;
start = newline + 1;
continue;
}
const length = end - start;
if (length > this.limitBytes - this.bytes) {
const head = readLineHead([...this.parts, buffer.subarray(start, end)]);
this.parts = [];
this.bytes = 0;
this.skippingOversizedLine = true;
this.onLimit(new ProviderStreamLimitError(this.limitBytes, head));
continue;
}
if (length) this.parts.push(buffer.subarray(start, end));
this.bytes += length;
if (newline === -1) return;
this.emitBufferedLine();
start = newline + 1;
}
}
flush(): void {
if (this.stopped) return;
if (this.skippingOversizedLine || this.bytes === 0) {
this.parts = [];
this.bytes = 0;
this.skippingOversizedLine = false;
return;
}
this.emitBufferedLine();
}
close(): void {
this.stopped = true;
this.parts = [];
this.bytes = 0;
}
private emitBufferedLine(): void {
const line = Buffer.concat(this.parts, this.bytes).toString("utf8");
this.parts = [];
this.bytes = 0;
this.onLine(line.endsWith("\r") ? line.slice(0, -1) : line);
}
}
/**
* Extracts the JSON-RPC request `id` when an oversized line starts with a response envelope,
* so the caller can fail only that request instead of tearing down the whole session.
*/
export function parseOversizedJsonRpcResponseId(lineHead: string): string | number | null {
const match = OVERSIZED_JSON_RPC_RESPONSE_HEAD.exec(lineHead);
if (!match?.[1]) return null;
try {
const parsed: unknown = JSON.parse(match[1]);
return typeof parsed === "number" || typeof parsed === "string" ? parsed : null;
} catch {
return null;
}
}
export interface BoundedNdJsonStreamOptions<TMessage> {
limitBytes?: number;
/** Close readable instead of erroring it on stream limit (for SDK loops without a read catch). */
closeOnStreamLimit?: boolean;
onStreamLimit?: (error: ProviderStreamLimitError) => void;
onInvalidJson?: (context: {
line: string;
error: unknown;
write: (message: unknown) => Promise<void>;
}) => void | Promise<void>;
onParsedMessage?: (context: {
message: unknown;
write: (message: unknown) => Promise<void>;
}) => TMessage | undefined | Promise<TMessage | undefined>;
}
type QueuedNdJsonEntry = { kind: "line"; line: string } | { kind: "synthetic"; message: unknown };
/**
* Creates a byte-bounded newline-delimited JSON stream.
* Oversized response lines synthesize a JSON-RPC error response for their request ID and keep
* the stream open; oversized notifications or unidentifiable lines close the stream with
* `ProviderStreamLimitError`.
*/
export function createBoundedNdJsonStream<TMessage>(
output: WebWritableStream<Uint8Array>,
input: WebReadableStream<Uint8Array>,
options: BoundedNdJsonStreamOptions<TMessage> = {},
): {
readable: ReadableStream<TMessage>;
writable: WritableStream<TMessage>;
} {
const limitBytes = options.limitBytes ?? JSONL_PROVIDER_LINE_BYTES;
const textEncoder = new TextEncoder();
let cancelled = false;
let errored = false;
let inputReader: ReadableStreamDefaultReader<Uint8Array> | undefined;
let lineReader: ProviderLineReader | undefined;
let outputWrite = Promise.resolve();
const writeLine = async (previous: Promise<void>, content: string): Promise<void> => {
try {
await previous;
} catch {
// Previous write failures must not wedge subsequent serialized writes.
}
const writer = output.getWriter();
try {
await writer.write(textEncoder.encode(content));
} finally {
writer.releaseLock();
}
};
const writeJson = (message: unknown): Promise<void> => {
const content = `${JSON.stringify(message)}\n`;
const write = writeLine(outputWrite, content);
outputWrite = write;
return write;
};
const readable = new ReadableStream<TMessage>({
async start(controller) {
const queued: QueuedNdJsonEntry[] = [];
let streamLimitError: ProviderStreamLimitError | null = null;
const reader = input.getReader() as unknown as ReadableStreamDefaultReader<Uint8Array>;
inputReader = reader;
const lines = new ProviderLineReader(
limitBytes,
(line) => {
queued.push({ kind: "line", line });
},
(error) => {
const responseId = parseOversizedJsonRpcResponseId(error.lineHead);
if (responseId !== null) {
queued.push({
kind: "synthetic",
message: {
jsonrpc: "2.0",
id: responseId,
error: { code: -32603, message: error.message },
},
});
return;
}
errored = true;
streamLimitError = error;
lines.close();
options.onStreamLimit?.(error);
if (options.closeOnStreamLimit) {
controller.close();
} else {
controller.error(error);
}
},
);
lineReader = lines;
const isStopped = () => cancelled || errored;
const emitEntry = async (entry: QueuedNdJsonEntry): Promise<void> => {
if (isStopped()) return;
let parsed: unknown;
if (entry.kind === "synthetic") {
parsed = entry.message;
} else {
const trimmedLine = entry.line.trim();
if (!trimmedLine) return;
try {
parsed = JSON.parse(trimmedLine);
} catch (error) {
await options.onInvalidJson?.({ line: trimmedLine, error, write: writeJson });
return;
}
}
const message = options.onParsedMessage
? await options.onParsedMessage({ message: parsed, write: writeJson })
: (parsed as TMessage);
if (!isStopped() && message !== undefined) {
controller.enqueue(message);
}
};
const drainQueue = async (): Promise<void> => {
while (queued.length > 0 && !isStopped()) {
const entry = queued.shift()!;
await emitEntry(entry);
}
};
try {
while (true) {
const { value, done } = await reader.read();
if (isStopped()) break;
if (done) break;
if (!value) continue;
lines.write(value);
if (errored) {
await reader.cancel(streamLimitError ?? undefined).catch(() => undefined);
return;
}
await drainQueue();
if (isStopped()) return;
}
if (isStopped()) return;
lines.flush();
await drainQueue();
if (isStopped()) return;
controller.close();
} catch (error) {
if (cancelled || errored) return;
if (options.closeOnStreamLimit) {
controller.close();
return;
}
controller.error(streamLimitError ?? error);
} finally {
if (inputReader === reader) {
inputReader = undefined;
}
reader.releaseLock();
}
},
cancel(reason) {
cancelled = true;
lineReader?.close();
return inputReader?.cancel(reason);
},
});
const writable = new WritableStream<TMessage>({
write(message) {
return writeJson(message);
},
});
return { readable, writable };
}
@@ -141,7 +141,11 @@ import {
RewindOutcomeUnknownError,
type RewindMode,
} from "./rewind/rewind.js";
import { parseAgentMessage, projectAgentMessages } from "./agent-messages/index.js";
import {
isNotificationOnlyPrompt,
parseAgentMessage,
projectAgentMessages,
} from "./agent-messages/index.js";
import { isStaleProviderSessionError } from "./stale-provider-session-error.js";
import {
PASEO_MCP_SERVER_NAME,
@@ -1674,6 +1678,18 @@ export class AgentManager {
return current !== undefined && current.token !== ignoreToken;
}
hasPendingTurnWork(agentId: string): boolean {
const agent = this.agents.get(agentId);
if (!agent || agent.lifecycle !== "running") {
return false;
}
return !this.runs.isNotificationOnlyRun(agentId);
}
wasTurnNotificationOnly(agentId: string, turnId: string): boolean {
return this.runs.wasTurnNotificationOnly(agentId, turnId);
}
hasInFlightRun(agentId: string, options?: { ignoreSwitchReservationToken?: string }): boolean {
if (this.hasOtherProviderSwitchReservation(agentId, options?.ignoreSwitchReservationToken)) {
return true;
@@ -3629,6 +3645,7 @@ export class AgentManager {
this.paseoToolPolicies.delete(agentId);
await this.cascadeArchiveChildren(archivedRecord);
this.runs.discardAgentHistory(agentId);
return { archivedAt };
}
@@ -4927,7 +4944,9 @@ export class AgentManager {
agent.lastError = undefined;
agent.historySaveError = undefined;
const pendingRun = this.runs.createPendingRun(agentId);
const pendingRun = this.runs.createPendingRun(agentId, {
notificationOnly: isNotificationOnlyPrompt(prompt),
});
promptStart?.bind(pendingRun);
if (switchReservationToken) {
this.releaseProviderSwitchReservation(agentId, switchReservationToken);
@@ -5147,6 +5166,9 @@ export class AgentManager {
expectedTurnId,
});
if (admission.status === "accepted") {
if (!isNotificationOnlyPrompt(prompt)) {
this.runs.markHasRealWork(agent.id);
}
await this.recordAcceptedSteer(
agent,
prompt,
@@ -5189,6 +5211,9 @@ export class AgentManager {
expectedTurnId,
});
if (admission.status === "accepted") {
if (!isNotificationOnlyPrompt(prompt)) {
this.runs.markHasRealWork(agent.id);
}
await this.recordAcceptedSteer(
agent,
prompt,
@@ -5923,6 +5948,7 @@ export class AgentManager {
}
notifyAgentRemoved(agent: Pick<StoredAgentRecord, "id" | "workspaceId" | "internal">): void {
this.runs.discardAgentHistory(agent.id);
this.dispatch({
type: "agent_removed",
agentId: agent.id,
@@ -6640,6 +6666,7 @@ export class AgentManager {
this.paseoToolPolicies.delete(agentId);
this.detachPluginTools(agentId);
this.clearProviderBackgroundWork(agentId);
this.runs.discardAgentHistory(agentId);
}
private emitClosedAgent(
@@ -3860,3 +3860,27 @@ test("finish notices under a waiting human message still honor the 10-second col
await delivery.close();
});
test("hasPending excludes agent-notification items only when includeNotifications is false", async () => {
const recipient = createRecipient({ running: true });
await recipient.delivery.enqueue({
recipientId: "recipient",
messageId: "notice-1",
source: { kind: "agent-notification", agentId: "child", event: "finished" },
text: "Child finished.",
activeTurnBehavior: "queue",
});
await recipient.settle();
expect(recipient.delivery.hasPending("recipient")).toBe(true);
expect(recipient.delivery.hasPending("recipient", { includeNotifications: true })).toBe(true);
expect(recipient.delivery.hasPending("recipient", { includeNotifications: false })).toBe(false);
// Adding a real prompt alongside the notification makes includeNotifications: false true.
await recipient.send("queue", "Real work");
await recipient.settle();
expect(recipient.delivery.hasPending("recipient")).toBe(true);
expect(recipient.delivery.hasPending("recipient", { includeNotifications: false })).toBe(true);
await recipient.delivery.close();
});
@@ -253,8 +253,11 @@ export interface AgentMessageDelivery {
onWithdrawn(
listener: (message: { recipientId: string; id: string }) => void | Promise<void>,
): () => void;
/** Messages and dispatches that will proceed without a new prompt. Held messages do not count. */
hasPending(recipientId: string): boolean;
/**
* Messages and dispatches that will proceed without a new prompt. Held messages do not count.
* Pass `{ includeNotifications: false }` to exclude finish notices (`agent-notification`).
*/
hasPending(recipientId: string, options?: { includeNotifications?: boolean }): boolean;
/** Stop admission and wait for the dispatches in flight. The rest of the queue stays saved. */
close(): Promise<void>;
/** Completion waits include admitted messages, but return at permission checkpoints and holds. */
@@ -1498,9 +1501,13 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
withdrawnListeners.add(listener);
return () => withdrawnListeners.delete(listener);
},
hasPending(recipientId) {
hasPending(recipientId, options) {
const inbox = inboxes.get(recipientId);
return inbox !== undefined && inbox.phase !== "held";
if (!inbox || inbox.phase === "held") return false;
if (options?.includeNotifications === false) {
return inbox.messages.some((message) => message.source?.kind !== "agent-notification");
}
return true;
},
async waitForDispatch(recipientId, signal) {
signal.throwIfAborted();
@@ -502,3 +502,39 @@ test("splitting an urgent release persists the urgency downgrade so a restart wa
expect(second.sent.map(({ ids }) => ids)).toEqual([["direct-1"]]);
await second.delivery.close();
});
test("restored agent-notification source in SQLite still excludes finish notices from non-notification pending work", async () => {
const home = await createHome();
const first = openDaemon(home, { running: true });
await queue(first.delivery, "notice-1", {
source: { kind: "agent-notification", agentId: "child-1", event: "finished" },
activeTurnBehavior: "queue",
});
await first.settle();
await first.delivery.close();
const second = openDaemon(home, { running: true });
let resolveResume!: () => void;
const resume = new Promise<void>((resolve) => {
resolveResume = resolve;
});
await second.delivery.start({ waitForResume: () => resume });
expect(second.delivery.hasPending("parent")).toBe(true);
expect(second.delivery.hasPending("parent", { includeNotifications: false })).toBe(false);
// Adding a persisted peer message alongside or in another inbox marks non-notification work as pending across restart too.
await queue(second.delivery, "peer-after-restart", {
recipientId: "other",
activeTurnBehavior: "queue",
});
await second.settle();
await second.delivery.close();
const third = openDaemon(home, { running: true });
await third.delivery.start();
expect(third.delivery.hasPending("parent", { includeNotifications: false })).toBe(false);
expect(third.delivery.hasPending("other", { includeNotifications: false })).toBe(true);
resolveResume();
await third.delivery.close();
});
@@ -7,6 +7,7 @@ import type { AgentTimelineItem } from "../agent-sdk-types.js";
import {
formatAgentMessage,
formatSystemNotificationPrompt,
isNotificationOnlyPrompt,
parseAgentMessage,
parseAgentMessages,
prepareAgentMessage,
@@ -362,3 +363,57 @@ describe("legacy envelopes in provider transcripts", () => {
]);
});
});
describe("isNotificationOnlyPrompt", () => {
test("returns true for single and batched agent-notification prompts", () => {
const finishNotice = formatAgentMessage({
id: "n-1",
source: {
kind: "agent-notification",
agentId: "child-1",
title: "Child 1",
event: "finished",
},
text: "Agent Child 1 finished.",
});
const closedNotice = formatAgentMessage({
id: "n-2",
source: { kind: "agent-notification", agentId: "child-2", title: "Child 2", event: "closed" },
text: "Agent Child 2 was closed.",
});
expect(isNotificationOnlyPrompt(finishNotice)).toBe(true);
expect(isNotificationOnlyPrompt(`${finishNotice}\n\n${closedNotice}`)).toBe(true);
expect(isNotificationOnlyPrompt([{ type: "text", text: finishNotice }])).toBe(true);
});
test("returns false for human prompts, peer messages, change requests, or mixed batches", () => {
const finishNotice = formatAgentMessage({
id: "n-1",
source: { kind: "agent-notification", agentId: "child-1", event: "finished" },
text: "Agent child-1 finished.",
});
const peerMessage = formatAgentMessage({
id: "m-1",
source: { kind: "agent-message", agentId: "peer-1", title: "Peer" },
text: "Please check this",
});
const crUpdate = formatAgentMessage({
id: "cr-1",
source: { kind: "change-request-update", url: "https://github.com/o/r/pull/1" },
text: "CI failed",
});
expect(isNotificationOnlyPrompt("Regular user prompt")).toBe(false);
expect(isNotificationOnlyPrompt("")).toBe(false);
expect(isNotificationOnlyPrompt(peerMessage)).toBe(false);
expect(isNotificationOnlyPrompt(crUpdate)).toBe(false);
expect(isNotificationOnlyPrompt(`${finishNotice}\n\n${peerMessage}`)).toBe(false);
expect(
isNotificationOnlyPrompt([
{ type: "text", text: finishNotice },
{ type: "image", data: "aGVsbG8=", mimeType: "image/png" },
]),
).toBe(false);
});
});
@@ -218,6 +218,28 @@ export function parseAgentMessages(text: string): AgentMessage[] | null {
return parseMarkedMessages(text) ?? parseLegacyEnvelopes(text);
}
/** True when the prompt carries only finish/status notifications and no other user or agent message. */
export function isNotificationOnlyPrompt(prompt: AgentPromptInput): boolean {
let text: string;
if (typeof prompt === "string") {
text = prompt;
} else {
if (!Array.isArray(prompt)) return false;
const parts: string[] = [];
for (const block of prompt) {
if (block.type !== "text" || "mimeType" in block) return false;
parts.push(block.text);
}
text = parts.join("\n");
}
const messages = parseAgentMessages(text);
return (
messages !== null &&
messages.length > 0 &&
messages.every((message) => message.source?.kind === "agent-notification")
);
}
export function parseAgentMessage(text: string): AgentMessage | null {
const messages = parseAgentMessages(text);
return messages?.length === 1 ? messages[0]! : null;
@@ -1,5 +1,6 @@
export {
formatAgentMessage,
isNotificationOnlyPrompt,
parseAgentMessage,
parseAgentMessages,
prepareAgentMessage,
@@ -49,3 +49,47 @@ describe("waitForForegroundStart", () => {
await expect(runs.waitForForegroundStart("agent")).resolves.toBeUndefined();
});
});
describe("notificationOnly tracking", () => {
test("tracks notification-only runs, clears on markHasRealWork, and bounds remembered turn IDs", () => {
const runs = new AgentRunState();
const first = runs.createPendingRun("agent", { notificationOnly: true });
expect(runs.isNotificationOnlyRun("agent")).toBe(true);
runs.settleForegroundStart(first, { status: "started", turnId: "turn-notif" });
runs.settleTerminalRun("agent", "turn-notif");
expect(runs.isNotificationOnlyRun("agent")).toBe(false);
expect(runs.wasTurnNotificationOnly("agent", "turn-notif")).toBe(true);
const steered = runs.createPendingRun("agent", { notificationOnly: true });
runs.settleForegroundStart(steered, { status: "started", turnId: "turn-steered" });
runs.markHasRealWork("agent");
expect(runs.isNotificationOnlyRun("agent")).toBe(false);
runs.settleTerminalRun("agent", "turn-steered");
expect(runs.wasTurnNotificationOnly("agent", "turn-steered")).toBe(false);
// Bounded history evicts the oldest turn ID once more than 50 notification-only turns settle.
for (let i = 1; i <= 51; i++) {
const run = runs.createPendingRun("agent", { notificationOnly: true });
const turnId = `extra-${i}`;
runs.settleForegroundStart(run, { status: "started", turnId });
runs.settleTerminalRun("agent", turnId);
}
expect(runs.wasTurnNotificationOnly("agent", "turn-notif")).toBe(false);
expect(runs.wasTurnNotificationOnly("agent", "extra-1")).toBe(false);
expect(runs.wasTurnNotificationOnly("agent", "extra-51")).toBe(true);
runs.discardAgentHistory("agent");
expect(runs.wasTurnNotificationOnly("agent", "extra-51")).toBe(false);
// Bounded agent map evicts the oldest agent entry once more than 200 agents are retained.
for (let i = 1; i <= 201; i++) {
const id = `agent-${i}`;
const run = runs.createPendingRun(id, { notificationOnly: true });
runs.settleForegroundStart(run, { status: "started", turnId: `turn-${i}` });
runs.settleTerminalRun(id, `turn-${i}`);
}
expect(runs.wasTurnNotificationOnly("agent-1", "turn-1")).toBe(false);
expect(runs.wasTurnNotificationOnly("agent-201", "turn-201")).toBe(true);
});
});
@@ -18,6 +18,7 @@ type ForegroundRunStart =
export interface PendingForegroundRun {
token: string;
kind: "foreground";
notificationOnly: boolean;
stagedEvents: AgentStreamEvent[];
start: ForegroundRunStart;
turnStartedPromise: Promise<void>;
@@ -44,15 +45,66 @@ export interface ForegroundRunAgentState {
finalizedForegroundTurnIds: Set<string>;
}
const MAX_RETAINED_NOTIFICATION_TURN_IDS = 50;
const MAX_RETAINED_NOTIFICATION_AGENTS = 200;
export class AgentRunState {
private readonly runs = new Map<string, TrackedAgentRun>();
private readonly notificationOnlyTurnIds = new Map<string, Set<string>>();
createPendingRun(agentId: string): PendingForegroundRun {
const pendingRun = createPendingForegroundRun();
createPendingRun(
agentId: string,
options?: { notificationOnly?: boolean },
): PendingForegroundRun {
const pendingRun = createPendingForegroundRun(options?.notificationOnly ?? false);
this.runs.set(agentId, pendingRun);
return pendingRun;
}
markHasRealWork(agentId: string): void {
const run = this.runs.get(agentId);
if (run?.kind === "foreground") {
run.notificationOnly = false;
}
}
isNotificationOnlyRun(agentId: string): boolean {
const run = this.runs.get(agentId);
return run?.kind === "foreground" && run.notificationOnly;
}
wasTurnNotificationOnly(agentId: string, turnId: string): boolean {
return this.notificationOnlyTurnIds.get(agentId)?.has(turnId) ?? false;
}
discardAgentHistory(agentId: string): void {
this.notificationOnlyTurnIds.delete(agentId);
}
private rememberNotificationOnlyTurn(agentId: string, turnId: string): void {
let turns = this.notificationOnlyTurnIds.get(agentId);
if (turns) {
// Refresh LRU position while updating this agent's entry.
this.notificationOnlyTurnIds.delete(agentId);
} else {
turns = new Set();
}
this.notificationOnlyTurnIds.set(agentId, turns);
turns.add(turnId);
if (turns.size > MAX_RETAINED_NOTIFICATION_TURN_IDS) {
const oldestTurn = turns.values().next().value;
if (oldestTurn) {
turns.delete(oldestTurn);
}
}
if (this.notificationOnlyTurnIds.size > MAX_RETAINED_NOTIFICATION_AGENTS) {
const oldestAgent = this.notificationOnlyTurnIds.keys().next().value;
if (oldestAgent) {
this.notificationOnlyTurnIds.delete(oldestAgent);
}
}
}
getPendingRun(agentId: string): PendingForegroundRun | null {
const run = this.runs.get(agentId);
return run?.kind === "foreground" ? run : null;
@@ -135,6 +187,10 @@ export class AgentRunState {
return;
}
if (run.kind === "foreground" && run.notificationOnly && turnId) {
this.rememberNotificationOnlyTurn(agentId, turnId);
}
this.clearRun(agentId, run);
}
@@ -144,6 +200,11 @@ export class AgentRunState {
return;
}
const turnId = run.start.status === "started" ? run.start.turnId : undefined;
if (run.notificationOnly && turnId) {
this.rememberNotificationOnlyTurn(agentId, turnId);
}
this.clearRun(agentId, run);
}
@@ -302,7 +363,7 @@ export class ForegroundTurnStream {
}
}
function createPendingForegroundRun(): PendingForegroundRun {
function createPendingForegroundRun(notificationOnly: boolean): PendingForegroundRun {
let resolveTurnStarted!: () => void;
const turnStartedPromise = new Promise<void>((resolvePromise) => {
resolveTurnStarted = resolvePromise;
@@ -310,6 +371,7 @@ function createPendingForegroundRun(): PendingForegroundRun {
return {
...createTrackedRunState(),
kind: "foreground",
notificationOnly,
start: { status: "pending" },
turnStartedPromise,
resolveTurnStarted,
@@ -1,18 +1,37 @@
import { createIdleRuntimeCleanup } from "../idle-runtime-cleanup/index.js";
import { HostObservationError } from "../host-operations/index.js";
import { randomUUID } from "node:crypto";
import { mkdtemp, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import { formatAgentMessage, parseAgentMessage } from "../agent-messages/envelope.js";
import { openDaemonDatabase } from "../../database/index.js";
import { AgentManager } from "../agent-manager.js";
import { sendPreparedPromptToAgent, waitForQueuedRunStart } from "../agent-prompt.js";
import type {
AgentClient,
AgentPromptInput,
AgentSession,
AgentSessionConfig,
AgentStreamEvent,
} from "../agent-sdk-types.js";
import { AgentStorage } from "../agent-storage.js";
import {
formatAgentMessage,
parseAgentMessage,
parseAgentMessages,
} from "../agent-messages/envelope.js";
import {
agentMessageQueueSchema,
createAgentMessageDelivery,
createMemoryAgentMessageQueueStore,
createSqliteAgentMessageQueueStore,
} from "../agent-messages/index.js";
import type { WaitForFinishResult } from "@getpaseo/client/internal/daemon-client";
import { buildStoredAgentPayload } from "../agent-projections.js";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import {
createFinishObservation,
createFinishSubscriptions,
createJsonFinishSubscriptionStore,
type FinishMessages,
@@ -1080,3 +1099,893 @@ describe("suppressing redundant finished notices after an explicit child report"
expect(state.delivery.behaviors).toEqual(["steer"]);
});
});
describe("reciprocal finish subscriptions and finish-notice origin tracking", () => {
interface TurnRecord {
turnId: string;
prompt: string;
steers: string[];
}
class ControllableSession implements AgentSession {
readonly id = randomUUID();
readonly capabilities = {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: false,
supportsToolInvocations: true,
supportsRewindConversation: false,
supportsRewindFiles: false,
supportsRewindBoth: false,
};
private subscribers = new Set<(event: AgentStreamEvent) => void>();
private turnSeq = 0;
private activeTurnId: string | null = null;
readonly turns: TurnRecord[] = [];
readonly steers: string[] = [];
pendingWakeup = false;
canSteer: boolean;
readonly provider: string;
readonly config: AgentSessionConfig;
/** Optional callback invoked when a turn starts; return reply text to auto-complete or null to hold open. */
onTurnStart?: (turn: TurnRecord) => string | null;
constructor(options: {
provider: string;
config: AgentSessionConfig;
canSteer: boolean;
onTurnStart?: (turn: TurnRecord) => string | null;
}) {
this.provider = options.provider;
this.config = options.config;
this.canSteer = options.canSteer;
this.onTurnStart = options.onTurnStart;
if (!this.canSteer) {
this.steerActiveTurn = undefined;
}
}
hasPendingWakeup(): boolean {
return this.pendingWakeup;
}
subscribe(callback: (event: AgentStreamEvent) => void): () => void {
this.subscribers.add(callback);
return () => this.subscribers.delete(callback);
}
push(event: AgentStreamEvent): void {
for (const listener of this.subscribers) listener(event);
}
async startTurn(prompt: AgentPromptInput): Promise<{ turnId: string }> {
const turnId = `turn-${++this.turnSeq}`;
this.activeTurnId = turnId;
const text = typeof prompt === "string" ? prompt : JSON.stringify(prompt);
const record: TurnRecord = { turnId, prompt: text, steers: [] };
this.turns.push(record);
queueMicrotask(() => {
this.push({ type: "turn_started", provider: this.provider, turnId });
const autoReply = this.onTurnStart?.(record);
if (autoReply !== undefined && autoReply !== null) {
this.completeTurn(autoReply, turnId);
}
});
return { turnId };
}
steerActiveTurn?: AgentSession["steerActiveTurn"] = async (prompt, options) => {
if (!this.canSteer || options.expectedTurnId !== this.activeTurnId) {
return { status: "unavailable" };
}
const text = typeof prompt === "string" ? prompt : JSON.stringify(prompt);
this.steers.push(text);
const current = this.turns.find((t) => t.turnId === this.activeTurnId);
current?.steers.push(text);
return { status: "accepted" };
};
completeTurn(reply: string, turnId = this.activeTurnId): void {
if (!turnId || this.activeTurnId !== turnId) return;
this.activeTurnId = null;
this.push({
type: "timeline",
provider: this.provider,
item: { type: "assistant_message", text: reply },
});
this.push({ type: "turn_completed", provider: this.provider, turnId });
}
startAutonomousTurn(reply?: string): string {
const turnId = `auto-${++this.turnSeq}`;
this.activeTurnId = turnId;
this.push({ type: "turn_started", provider: this.provider, turnId });
if (reply !== undefined) {
queueMicrotask(() => this.completeTurn(reply, turnId));
}
return turnId;
}
async *streamHistory(): AsyncGenerator<AgentStreamEvent> {}
async getRuntimeInfo() {
return {
provider: this.provider,
sessionId: this.id,
model: null,
modeId: null,
};
}
async getAvailableModes() {
return [];
}
async getCurrentMode() {
return null;
}
async setMode(): Promise<void> {}
getPendingPermissions() {
return [];
}
async respondToPermission(): Promise<void> {}
describePersistence() {
return { provider: this.provider, sessionId: this.id };
}
async interrupt(): Promise<void> {
const turnId = this.activeTurnId;
this.activeTurnId = null;
if (turnId) {
this.push({ type: "turn_canceled", provider: this.provider, turnId });
}
}
async close(): Promise<void> {}
}
async function openIntegratedDaemon(
home: string,
options: {
canSteer?: boolean;
manualTimers?: boolean;
waitForResume?: (agentId: string) => Promise<void>;
onTurnStart?: (
agentId: string,
turn: TurnRecord,
session: ControllableSession,
) => string | null;
} = {},
) {
const logger = createTestLogger();
const database = openDaemonDatabase({
path: join(home, "paseo.db"),
modules: [agentMessageQueueSchema],
logger,
});
const storage = new AgentStorage(join(home, "agents"), logger);
await storage.initialize();
const sessions = new Map<string, ControllableSession>();
let lastCreatedSession: ControllableSession | null = null;
const pendingTimers = new Set<() => void>();
const schedule = options.manualTimers
? (_delayMs: number, callback: () => void) => {
pendingTimers.add(callback);
return () => pendingTimers.delete(callback);
}
: (_delayMs: number, callback: () => void) => {
const timer = setTimeout(callback, 10);
return () => clearTimeout(timer);
};
const client: AgentClient = {
provider: "codex",
capabilities: {
supportsStreaming: true,
supportsSessionPersistence: true,
supportsSessionListing: false,
supportsDynamicModes: false,
supportsMcpServers: false,
supportsReasoningStream: false,
supportsToolInvocations: true,
},
async isAvailable() {
return true;
},
async createSession(config) {
const session = new ControllableSession({
provider: "codex",
config,
canSteer: options.canSteer ?? true,
});
lastCreatedSession = session;
return session;
},
async resumeSession(handle, config) {
const session = new ControllableSession({
provider: "codex",
config: { provider: "codex", cwd: config?.cwd ?? home },
canSteer: options.canSteer ?? true,
});
session.onTurnStart = (turn) =>
options.onTurnStart?.(handle.sessionId, turn, session) ?? null;
return session;
},
};
const manager = new AgentManager({
clients: { codex: client },
registry: storage,
logger,
});
const delivery = createAgentMessageDelivery({
store: createSqliteAgentMessageQueueStore(database),
paseoHome: home,
schedule,
isRunning: (agentId) => manager.hasInFlightRun(agentId),
canSteer: (agentId) => manager.canSteer(agentId),
hasPendingPermission: (agentId) => manager.hasPendingPermissions(agentId),
subscribe: (notify) =>
manager.subscribe(
(event) => {
if (event.type === "agent_state") notify(event.agent.id);
},
{ replayState: false },
),
onStop: (notify) => manager.onStop(notify),
dispatch: async (request) => {
const result = await sendPreparedPromptToAgent({
agentManager: manager,
agentStorage: storage,
agentId: request.recipientId,
prompt: request.prompt,
activeTurnBehavior: request.activeTurnBehavior,
idleOnly: request.idleOnly,
admit: request.admit,
replaceRunning: request.replaceRunning,
clearPendingPermissions: request.clearPendingPermissions,
unarchive: request.unarchive,
runOptions: { clientMessageId: request.messageIds[0] },
logger,
});
if (result.disposition === "turn_started") {
await waitForQueuedRunStart(manager, request.recipientId, result.started);
}
return result.disposition;
},
onError: (error) => {
throw error;
},
});
const store = createJsonFinishSubscriptionStore(home);
const observation = createFinishObservation({
agentManager: manager,
agentStorage: storage,
waitForResume: options.waitForResume
? async (agentId) => options.waitForResume!(agentId)
: async () => {},
messages: () => delivery,
hosts: () => {
throw new Error("Remote hosts not configured");
},
serverId: "origin",
logger,
});
const finishSubscriptions = createFinishSubscriptions({
store,
messages: () => delivery,
callerIsActive: async (agentId) => !(await storage.get(agentId))?.archivedAt,
serverId: "origin",
logger,
retryDelayMs: 1,
...observation,
});
const unsubWithdrawn = delivery.onWithdrawn(({ id }) => finishSubscriptions.withdraw(id));
await delivery.start(
options.waitForResume ? { waitForResume: options.waitForResume } : undefined,
);
await finishSubscriptions.start();
async function createAgent(title: string) {
lastCreatedSession = null;
const created = await manager.createAgent(
{ provider: "codex", cwd: home, title },
undefined,
{
workspaceId: undefined,
},
);
const session = lastCreatedSession!;
session.onTurnStart = (turn) => options.onTurnStart?.(created.id, turn, session) ?? null;
sessions.set(created.id, session);
return { id: created.id, session };
}
function sendHumanPrompt(
recipientId: string,
text: string,
behavior: "queue" | "steer" | "interrupt" = "queue",
) {
return delivery.enqueue({
recipientId,
text,
activeTurnBehavior: behavior,
});
}
async function sendAgentPrompt(
callerId: string,
childId: string,
text: string,
behavior: "steer" | "queue" = "steer",
) {
const messageId = randomUUID();
const registration = await finishSubscriptions.register(
{ callerAgentId: callerId, childAgentId: childId, messageId },
true,
);
return delivery.enqueue({
recipientId: childId,
messageId,
text,
source: { kind: "agent-message", agentId: callerId },
activeTurnBehavior: behavior,
onDispatch: () => registration.accept(),
});
}
async function tickTimers() {
const due = Array.from(pendingTimers);
pendingTimers.clear();
for (const callback of due) callback();
await new Promise((resolve) => setTimeout(resolve, 10));
}
function notificationsReceived(session: ControllableSession): number {
let count = 0;
for (const turn of session.turns) {
const parsed = parseAgentMessages(turn.prompt);
if (parsed) {
count += parsed.filter((m) => m.source?.kind === "agent-notification").length;
}
}
for (const steer of session.steers) {
const parsed = parseAgentMessages(steer);
if (parsed) {
count += parsed.filter((m) => m.source?.kind === "agent-notification").length;
}
}
return count;
}
async function close() {
unsubWithdrawn();
await finishSubscriptions.close();
await delivery.close();
for (const agent of manager.listAgents()) {
await manager.closeAgent(agent.id);
}
await storage.flush();
database.close();
}
return {
manager,
storage,
delivery,
store,
observation,
finishSubscriptions,
sessions,
createAgent,
sendHumanPrompt,
sendAgentPrompt,
tickTimers,
notificationsReceived,
close,
};
}
test("reciprocal subscriptions settle cleanly when finish notices queue on non-steering providers", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-reciprocal-queue-"));
homes.push(home);
const daemon = await openIntegratedDaemon(home, {
canSteer: false,
onTurnStart: (_agentId, turn) => {
// Acknowledge finish notices with plain text; real work turns are completed explicitly.
const parsed = parseAgentMessages(turn.prompt);
if (parsed?.every((m) => m.source?.kind === "agent-notification")) {
return "Acknowledged";
}
return null;
},
});
try {
const a = await daemon.createAgent("Agent A");
const b = await daemon.createAgent("Agent B");
// Both agents run initial turns, queue prompts to each other, and finish Turn 1 so Turn 2 (the prompted work) starts.
await daemon.sendHumanPrompt(a.id, "Start A work", "queue");
await daemon.sendHumanPrompt(b.id, "Start B work", "queue");
await until(() => a.session.turns.length === 1 && b.session.turns.length === 1);
await daemon.sendAgentPrompt(a.id, b.id, "Check B status", "queue");
await daemon.sendAgentPrompt(b.id, a.id, "Check A status", "queue");
b.session.completeTurn("B turn 1 done");
a.session.completeTurn("A turn 1 done");
await until(() => a.session.turns.length === 2 && b.session.turns.length === 2);
// B finishes Turn 2 while A is still running Turn 2 -> finish notice to A sits queued.
b.session.completeTurn("B turn 2 done");
await until(() => daemon.delivery.hasPending(a.id));
// A finishes Turn 2 while B's finish notice is queued in A's inbox.
a.session.completeTurn("A turn 2 done");
// Wait for all finish subscriptions to settle.
await expect.poll(async () => (await daemon.store.list()).length, { timeout: 3000 }).toBe(0);
await until(
() =>
daemon.manager.getAgent(a.id)?.lifecycle === "idle" &&
daemon.manager.getAgent(b.id)?.lifecycle === "idle",
);
// Each side only got bounded notices and did not loop.
expect(daemon.notificationsReceived(a.session)).toBeLessThanOrEqual(2);
expect(daemon.notificationsReceived(b.session)).toBeLessThanOrEqual(2);
} finally {
await daemon.close();
}
});
test("reciprocal subscriptions settle cleanly with #11915 default-steer finish notices", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-reciprocal-steer-"));
homes.push(home);
const daemon = await openIntegratedDaemon(home, {
canSteer: true,
manualTimers: true,
});
try {
const a = await daemon.createAgent("Agent A");
const b = await daemon.createAgent("Agent B");
await daemon.sendHumanPrompt(a.id, "Task A");
await daemon.sendHumanPrompt(b.id, "Task B");
await daemon.tickTimers();
await until(() => a.session.turns.length === 1 && b.session.turns.length === 1);
// Reciprocal default-steer subscriptions, followed by tool work on both sides so turn 1 is not suppressed by #11583.
await daemon.sendAgentPrompt(a.id, b.id, "Ask B");
await daemon.sendAgentPrompt(b.id, a.id, "Ask A");
await daemon.tickTimers();
await until(() => a.session.steers.length === 1 && b.session.steers.length === 1);
a.session.push({
type: "timeline",
provider: "codex",
item: {
type: "tool_call",
callId: "a-tool",
name: "Bash",
status: "completed",
error: null,
},
});
b.session.push({
type: "timeline",
provider: "codex",
item: {
type: "tool_call",
callId: "b-tool",
name: "Bash",
status: "completed",
error: null,
},
});
// B finishes Turn 1 -> notice to A enters the 2s quiet window (default-steer batches there).
b.session.completeTurn("B done");
await until(() => daemon.delivery.hasPending(a.id));
// Before the 2s quiet window fires, A finishes Turn 1.
a.session.completeTurn("A done");
await until(() => daemon.delivery.hasPending(b.id));
await daemon.tickTimers();
// Both notification-only turns start. Complete both turns cleanly without looping:
// A received an interim notice in turn 2 (while waiting on B) and receives the final notice in turn 3;
// B receives only the final notice in turn 2.
await until(() => a.session.turns.length === 2 && b.session.turns.length === 2);
a.session.completeTurn("A ack");
b.session.completeTurn("B ack");
await until(() => daemon.delivery.hasPending(a.id));
await daemon.tickTimers();
await until(() => a.session.turns.length === 3);
a.session.completeTurn("A ack 2");
await daemon.tickTimers();
await expect.poll(async () => (await daemon.store.list()).length, { timeout: 3000 }).toBe(0);
expect(a.session.turns).toHaveLength(3);
expect(b.session.turns).toHaveLength(2);
expect(daemon.notificationsReceived(a.session)).toBe(2);
expect(daemon.notificationsReceived(b.session)).toBe(1);
} finally {
await daemon.close();
}
});
test("reciprocal subscriptions with active background work (#11853) do not wake each other in a loop", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-reciprocal-bg-"));
homes.push(home);
const daemon = await openIntegratedDaemon(home, {
canSteer: true,
onTurnStart: (_agentId, turn) => {
const parsed = parseAgentMessages(turn.prompt);
if (parsed?.every((m) => m.source?.kind === "agent-notification")) {
return ".";
}
return null;
},
});
try {
const a = await daemon.createAgent("Agent A");
const b = await daemon.createAgent("Agent B");
a.session.pendingWakeup = true;
b.session.pendingWakeup = true;
await daemon.sendHumanPrompt(a.id, "Start A bg");
await daemon.sendHumanPrompt(b.id, "Start B bg");
await until(() => a.session.turns.length === 1 && b.session.turns.length === 1);
await daemon.sendAgentPrompt(a.id, b.id, "Watch B");
await daemon.sendAgentPrompt(b.id, a.id, "Watch A");
await until(() => a.session.steers.length === 1 && b.session.steers.length === 1);
a.session.push({
type: "timeline",
provider: "codex",
item: {
type: "tool_call",
callId: "a-tool",
name: "Bash",
status: "completed",
error: null,
},
});
b.session.push({
type: "timeline",
provider: "codex",
item: {
type: "tool_call",
callId: "b-tool",
name: "Bash",
status: "completed",
error: null,
},
});
b.session.completeTurn("B waiting on bg");
await until(() => daemon.notificationsReceived(a.session) >= 1);
a.session.completeTurn("A waiting on bg");
await until(() => daemon.notificationsReceived(b.session) >= 1);
// Give any potential feedback turns plenty of time to fire.
await new Promise((resolve) => setTimeout(resolve, 150));
expect(daemon.notificationsReceived(a.session)).toBe(1);
expect(daemon.notificationsReceived(b.session)).toBe(1);
expect(await daemon.store.list()).toHaveLength(2);
// Once background work settles on both sides, both receive final notices and clear.
a.session.pendingWakeup = false;
a.session.startAutonomousTurn("A bg done");
await until(() => daemon.notificationsReceived(b.session) === 2);
b.session.pendingWakeup = false;
b.session.startAutonomousTurn("B bg done");
await expect.poll(async () => (await daemon.store.list()).length, { timeout: 3000 }).toBe(0);
} finally {
await daemon.close();
}
});
test("parent and child with reciprocal watches while parent waits on another child (#11589) do not loop", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-parent-child-sibling-"));
homes.push(home);
const daemon = await openIntegratedDaemon(home, {
canSteer: true,
onTurnStart: (_agentId, turn) => {
const parsed = parseAgentMessages(turn.prompt);
if (parsed?.every((m) => m.source?.kind === "agent-notification")) {
return "Noted";
}
return null;
},
});
try {
const parent = await daemon.createAgent("Parent");
const c1 = await daemon.createAgent("Child 1");
const c2 = await daemon.createAgent("Child 2");
await daemon.sendHumanPrompt(parent.id, "Parent work");
await until(() => parent.session.turns.length === 1);
await daemon.sendAgentPrompt(parent.id, c1.id, "C1 task");
await daemon.sendAgentPrompt(parent.id, c2.id, "C2 long task");
await until(() => c1.session.turns.length === 1 && c2.session.turns.length === 1);
// C1 reports to Parent with notifyOnFinish=true -> reciprocal watches between Parent and C1 while C2 runs.
await daemon.sendAgentPrompt(c1.id, parent.id, "C1 interim report");
await until(() => parent.session.steers.length === 1);
c1.session.push({
type: "timeline",
provider: "codex",
item: {
type: "tool_call",
callId: "c1-tool",
name: "Bash",
status: "completed",
error: null,
},
});
c1.session.completeTurn("C1 finished turn 1");
await until(() => daemon.notificationsReceived(parent.session) >= 1);
parent.session.completeTurn("Parent finished turn 1");
await until(() => daemon.notificationsReceived(c1.session) >= 1);
// No ongoing loop while C2 continues running.
await new Promise((resolve) => setTimeout(resolve, 150));
expect(daemon.notificationsReceived(parent.session)).toBe(1);
expect(daemon.notificationsReceived(c1.session)).toBe(1);
// Once C2 finishes, everyone settles cleanly.
c2.session.completeTurn("C2 done");
await expect.poll(async () => (await daemon.store.list()).length, { timeout: 3000 }).toBe(0);
} finally {
await daemon.close();
}
});
test("real queued prompts and #6346 background wakeups still count as pending work", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-real-work-"));
homes.push(home);
const daemon = await openIntegratedDaemon(home, {
canSteer: false,
manualTimers: true,
});
try {
const parent = await daemon.createAgent("Parent");
const child = await daemon.createAgent("Child");
// Case 1: Child ends Turn 1 while a real human prompt is queued on it.
await daemon.sendAgentPrompt(parent.id, child.id, "First task", "queue");
await daemon.tickTimers();
await until(() => child.session.turns.length === 1);
await daemon.delivery.enqueue({
recipientId: child.id,
text: "Real human follow-up",
activeTurnBehavior: "queue",
});
child.session.completeTurn("Interim reply");
await until(() => daemon.delivery.hasPending(parent.id));
await daemon.tickTimers();
await until(() => daemon.notificationsReceived(parent.session) === 1);
expect(parent.session.turns[0]!.prompt).toContain("It still has queued messages.");
parent.session.completeTurn("Parent ack");
await until(() => child.session.turns.length === 2);
child.session.completeTurn("Final after human prompt");
await until(() => daemon.delivery.hasPending(parent.id));
await daemon.tickTimers();
await until(() => daemon.notificationsReceived(parent.session) === 2);
expect(parent.session.turns[1]!.prompt).toContain("Final after human prompt");
parent.session.completeTurn("Parent done");
await expect.poll(async () => (await daemon.store.list()).length).toBe(0);
// Case 2: Child ends Turn 1 with background work (#6346) that wakes it autonomously.
child.session.pendingWakeup = true;
await daemon.sendAgentPrompt(parent.id, child.id, "Start bg work", "queue");
await daemon.tickTimers();
await until(() => child.session.turns.length === 3);
child.session.completeTurn("Spawned bg");
await until(() => daemon.delivery.hasPending(parent.id));
await daemon.tickTimers();
await until(() => daemon.notificationsReceived(parent.session) === 3);
expect(parent.session.turns[2]!.prompt).toContain("background work that will wake it");
parent.session.completeTurn("Parent ack bg");
child.session.pendingWakeup = false;
child.session.startAutonomousTurn("BG complete");
await until(() => daemon.delivery.hasPending(parent.id));
await daemon.tickTimers();
await until(() => daemon.notificationsReceived(parent.session) === 4);
expect(parent.session.turns[3]!.prompt).toContain("BG complete");
await expect.poll(async () => (await daemon.store.list()).length, { timeout: 3000 }).toBe(0);
} finally {
await daemon.close();
}
});
test("mixed batch (finish notice + real prompt in same turn) still counts as real work", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-mixed-batch-"));
homes.push(home);
const daemon = await openIntegratedDaemon(home, {
canSteer: false,
manualTimers: true,
});
try {
const parent = await daemon.createAgent("Parent");
const middle = await daemon.createAgent("Middle");
const sub = await daemon.createAgent("Sub");
// Parent watches Middle; Middle watches Sub.
await daemon.sendAgentPrompt(parent.id, middle.id, "Coordinate", "queue");
await daemon.sendAgentPrompt(middle.id, sub.id, "Subtask", "queue");
await daemon.tickTimers();
await until(() => middle.session.turns.length === 1 && sub.session.turns.length === 1);
// Sub finishes -> finish notice queued on Middle; also enqueue a real prompt on Middle.
sub.session.completeTurn("Sub done");
await until(() => daemon.delivery.hasPending(middle.id));
await daemon.delivery.enqueue({
recipientId: middle.id,
text: "Real prompt batched with notice",
activeTurnBehavior: "queue",
});
// Middle finishes Turn 1 while mixed batch [notice, real prompt] is queued -> counts as queued messages.
middle.session.completeTurn("Middle waiting on batch");
await until(() => daemon.delivery.hasPending(parent.id));
await daemon.tickTimers();
await until(() => daemon.notificationsReceived(parent.session) === 1);
expect(parent.session.turns[0]!.prompt).toContain("queued messages");
parent.session.completeTurn("Parent ack 1");
// Mixed batch starts Middle Turn 2 -> Turn 2 MUST count as real work ("turn") while running!
await until(() => middle.session.turns.length === 2);
expect(
daemon.observation.pendingWork({
id: "probe",
callerAgentId: parent.id,
childAgentId: middle.id,
}),
).toContain("turn");
middle.session.completeTurn("Middle final after mixed batch");
await until(() => daemon.delivery.hasPending(parent.id));
await daemon.tickTimers();
await until(() => daemon.notificationsReceived(parent.session) === 2);
expect(parent.session.turns[1]!.prompt).toContain("Middle final after mixed batch");
await expect.poll(async () => (await daemon.store.list()).length, { timeout: 3000 }).toBe(0);
} finally {
await daemon.close();
}
});
test("steering a real prompt into a running notification-only turn promotes it to real work", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-steer-upgrade-"));
homes.push(home);
const daemon = await openIntegratedDaemon(home, {
canSteer: true,
manualTimers: true,
});
try {
const parent = await daemon.createAgent("Parent");
const child = await daemon.createAgent("Child");
// Enqueue a pure finish notice onto idle child -> starts a notification-only turn.
await daemon.delivery.enqueue({
recipientId: child.id,
source: { kind: "agent-notification", agentId: "other", event: "finished" },
text: "Other finished",
activeTurnBehavior: "steer",
});
await daemon.tickTimers();
await until(() => child.session.turns.length === 1);
// Notification-only turn does NOT count as pendingWork.
expect(
daemon.observation.pendingWork({
id: "probe",
callerAgentId: parent.id,
childAgentId: child.id,
}),
).toEqual([]);
// Steer a real prompt into the running notification-only turn.
await daemon.delivery.enqueue({
recipientId: child.id,
source: { kind: "agent-message", agentId: parent.id },
text: "Now also do real work",
activeTurnBehavior: "steer",
});
await until(() => child.session.steers.length === 1);
expect(
daemon.observation.pendingWork({
id: "probe",
callerAgentId: parent.id,
childAgentId: child.id,
}),
).toContain("turn");
child.session.completeTurn("Real work done");
} finally {
await daemon.close();
}
});
test("queued finish notice still does not count as pendingWork across SQLite daemon restart", async () => {
const home = await mkdtemp(join(tmpdir(), "finish-sqlite-restart-"));
homes.push(home);
const first = await openIntegratedDaemon(home, {
canSteer: false,
manualTimers: true,
});
const a = await first.createAgent("Agent A");
const b = await first.createAgent("Agent B");
await first.sendHumanPrompt(a.id, "A task", "queue");
await first.sendHumanPrompt(b.id, "B task", "queue");
await first.tickTimers();
await until(() => a.session.turns.length === 1 && b.session.turns.length === 1);
await first.sendAgentPrompt(a.id, b.id, "Ask B", "queue");
await first.sendAgentPrompt(b.id, a.id, "Ask A", "queue");
a.session.completeTurn("A turn 1 done");
b.session.completeTurn("B turn 1 done");
await first.tickTimers();
await until(() => a.session.turns.length === 2 && b.session.turns.length === 2);
// B finishes Turn 2 while A is running Turn 2 -> finish notice queued on A in SQLite before restart.
b.session.completeTurn("B done before restart");
await expect
.poll(async () => (await first.delivery.list(a.id)).items.length, { timeout: 3000 })
.toBe(1);
expect((await first.delivery.list(a.id)).items[0]?.source?.kind).toBe("agent-notification");
await first.close();
// Reopen daemon against the same home & SQLite database, holding resume so we can inspect the restored queue.
const resumed = deferred<void>();
const second = await openIntegratedDaemon(home, {
canSteer: false,
waitForResume: () => resumed.promise,
onTurnStart: (_agentId, turn) => {
const parsed = parseAgentMessages(turn.prompt);
if (parsed?.every((m) => m.source?.kind === "agent-notification")) {
return "Ack after restart";
}
return null;
},
});
try {
// Restored queue on A still holds only the finish notice: must NOT count as pendingWork.
expect(second.delivery.hasPending(a.id)).toBe(true);
expect(
second.observation.pendingWork({
id: "probe",
callerAgentId: b.id,
childAgentId: a.id,
}),
).toEqual([]);
resumed.resolve();
await expect.poll(async () => (await second.store.list()).length, { timeout: 3000 }).toBe(0);
} finally {
resumed.resolve();
await second.close();
}
});
});

Some files were not shown because too many files have changed in this diff Show More