mirror of
https://github.com/getpaseo/paseo.git
synced 2026-12-03 13:46:00 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83aead6d08 | ||
|
|
d3918b95a5 |
+15
-15
@@ -154,15 +154,15 @@ Users can also detach an existing subagent from the subagents track. Detach is d
|
||||
|
||||
Agent-originated messages and automatic notifications share a recipient-daemon delivery module. The daemon saves a queued message, then acknowledges it with a receipt, before provider dispatch. The module keeps one ordered queue per recipient, and the recipient reads its prompts in the order the daemon admitted them. Nothing overtakes an older queued message. A prompt takes its place when the daemon admits it, even while the provider is still starting an earlier turn, and a message stays in the queue until the turn that carries it starts. The turn has started when the agent manager acknowledges the run start; a turn that fails after that point is not delivered again.
|
||||
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders default to `queue`; non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt`. Each kind of prompt is released this way:
|
||||
Any sender picks `queue`, `steer`, or `interrupt` with `activeTurnBehavior`. Agent senders and finish notifications default to `steer` (falling back to `queue` on providers without `steerActiveTurn`); non-agent senders (app, CLI, plugins, Hub, top-level MCP) default to `interrupt` (or `steer` in composer settings). Each kind of prompt is released this way:
|
||||
|
||||
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages. Finish notifications and change-request updates always queue.
|
||||
- **`steer`** waits for neither the quiet window nor the turn. It is dispatched at admission as one prompt that enters the running turn: the messages queued before it, then the steer. A provider that cannot steer, or that refuses this steer, gets the prompt as a replacing turn instead, the same as a person's steer.
|
||||
- **`interrupt`** is dispatched at admission the same way, as one prompt that replaces the running turn. An older queued message cannot start a turn after the newer `interrupt` that countermands it.
|
||||
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) is dispatched directly and takes the queue along the same way: the messages admitted before it first, then the person's text, in one provider prompt. Messages admitted after it follow it. The person's text keeps its own transcript row. When the turn does not start, the messages return to the queue in their place. That covers a start the provider rejects and a start that is not acknowledged within 60 seconds; a provider that starts the turn after those 60 seconds receives the messages twice.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. They go ahead of the recipient's next prompt, in that prompt's turn: a person's prompt, or an agent message or notification admitted after the Stop. A held steer or interrupt no longer enters the turn; it waits like a queued message. A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
- **`queue`** waits for any running or starting turn (including compaction) to end on its own or fail, then delivers the queued prompts together. The daemon releases it when it observes the recipient settle; a two-second timer also retries. On an idle recipient, agent messages wait two quiet seconds (steady arrivals cannot hold that window open past ten seconds); a non-agent queued message skips that quiet window and starts a turn at once. A non-agent queued message is sent unwrapped when dispatched alone, and in a `kind="user-message"` envelope when it shares a prompt with other messages.
|
||||
- **`steer`** from an agent sender enters the running turn without cutting it, carrying earlier agent-queued messages ahead of it while leaving human-queued items untouched in the queue. Finish notifications batch across the two-second quiet window before steering so parallel completions arrive together. If the provider cannot steer (`canSteer` is false, e.g., ACP agents) or rejects steering mid-turn without ending the turn, the daemon keeps the message queued until the turn ends rather than interrupting it.
|
||||
- **`interrupt`** is dispatched at admission the same way, replacing the running turn and carrying earlier non-human-queued messages ahead of it.
|
||||
- **A person's direct prompt** (`steer` or `interrupt` from app, CLI, plugins, Hub, or top-level MCP) runs immediately by itself and does **not** sweep queued messages. Queued messages stay intact in the queue track and dispatch once the turn settles, unless the queue is behind a staged provider switch (where the switch queues behind items meant for the current provider). When a non-command, non-resume direct human prompt succeeds on a held queue (after Stop or a refused start), it reopens the held queue so remaining queued items resume after the turn ends.
|
||||
- **Stop** (the stop button, Escape, `cancel_agent`, a Hub interrupt) starts nothing. Messages admitted before the Stop are held, not dropped, including an interrupt whose turn had not started yet. Held items wait until reopened by a direct non-command prompt, a newly admitted message, or explicit Send now (`promote`). A queue step or dispatch decided before the Stop is void, and the queue is held again when the message that reopened it is withdrawn. A replacing prompt, a reload, and a rewind are not a Stop. Neither is `cancel_agent` on a recipient with no running or starting turn: it stops nothing, reports that it canceled no run, and a queued message keeps its quiet window.
|
||||
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because the follow-up carries the queued message ahead of it and a resend would be read twice. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
The queued receipt carries the applied behavior and guidance text for the sender. The text comes from two facts known at admission: whether the recipient has a running turn, and whether its provider can steer (`AgentManager.canSteer`, which is true when the session offers `steerActiveTurn`). It does not wait for the outcome. Guidance for a message queued behind a running turn tells the sender to send a short `steer` or `interrupt` follow-up instead of resending, because an agent follow-up carries earlier agent-queued messages ahead of it. On non-steering providers, queued `steer` reports as `queue` and notes that `steer` waits until the turn ends. The MCP tool, the WebSocket `send_agent_message_response`, the CLI, and the connected-host path all relay this one text.
|
||||
|
||||
Older CLIs and connected hosts send an explicit `steer` for every default agent send. The daemon reads an agent sender's `steer` as `queue` unless the client advertises the `agent_active_turn_behaviors` capability. A new client talking to a daemon without `server_info.features.agentActiveTurnBehaviors` sends no behavior for `queue` and refuses a `steer`. A new client talking to a daemon without `server_info.features.nonAgentMessageQueue` refuses a non-agent `queue` before sending.
|
||||
|
||||
@@ -173,8 +173,8 @@ One provider prompt has one session mode. A batch released by a steer, an interr
|
||||
A provider switch can wait in the queue too (`agent.provider.switch.request` with
|
||||
`activeTurnBehavior: "queue"`). The message carries the target provider and settings, shares a prompt
|
||||
with nothing, and divides the queue: what is ahead of it goes to the current provider, and it and
|
||||
what follows go to the target. A direct prompt therefore takes along only the queued rows ahead of
|
||||
the switch. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
what follows go to the target. A direct provider switch queues right behind any items queued for
|
||||
the current provider so those items dispatch first. Promoting the switch cuts the running turn once the target is known to be usable. A chat
|
||||
already on the target takes the message and its settings as a plain prompt. A switch that fails keeps
|
||||
the message and holds the queue; the reason is in the daemon log.
|
||||
|
||||
@@ -184,10 +184,10 @@ queue holds references. An empty message is refused, and a recipient holds at mo
|
||||
messages.
|
||||
|
||||
A message is marked `dispatching` before the provider can receive it and removed when the provider
|
||||
admits it. A dispatch that is not admitted returns the message to its place. A refused turn start
|
||||
also holds the queue: retrying by itself would be refused again and would add the prompt to the
|
||||
history each time. A message that cannot be sent is removed so that it does not block the ones
|
||||
behind it.
|
||||
admits it. A dispatch that fails transiently (busy/non-steering turn, run-start timeout, mode/RPC
|
||||
error, or rejected start) returns the batch to the queue rather than deleting it; non-busy failures
|
||||
also hold the queue until the next prompt reopens it. Only pre-dispatch unresolvable payloads (such
|
||||
as missing local attachments) or rejected out-of-band commands are discarded so they do not block later messages.
|
||||
|
||||
Shutdown does not send the queue. It waits only for dispatches already in flight, and everything
|
||||
else stays saved, held messages included. Closing an idle runtime keeps the queue. Archiving or
|
||||
@@ -456,8 +456,8 @@ Rows take these commands:
|
||||
already started sending the row, the draft stays as it is.
|
||||
- **Cancel** withdraws the row.
|
||||
|
||||
A message you send directly (`steer` or `interrupt`) takes the queued rows with it, ahead of your
|
||||
text.
|
||||
A message you send directly (`steer` or `interrupt`) runs right away without sweeping the queue track;
|
||||
queued rows stay visible in place and dispatch after the turn ends (unless held by Stop).
|
||||
|
||||
A message sent mid-turn with a staged provider switch is queued whatever the send behavior, and its
|
||||
row names the target.
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ Authoritative terminology. UI label wins. Don't invent synonyms; use what's here
|
||||
- **Agent controls** — Provider, model, mode, thinking, and provider-feature controls for an agent or draft agent. Code: `AgentControls` / `DraftAgentControls` (`packages/app/src/composer/agent-controls/index.tsx`). Forbidden: "Agent status bar".
|
||||
- **Composer footer** — Optional area rendered below the composer input but still inside the keyboard-shifted composer layout. Code: `Composer.footer` (`packages/app/src/composer/index.tsx`).
|
||||
- **Composer track** — A contextual lane at the foot of a pane, by the composer input. Specific tracks use the `<thing> track` form: **Queue track**, **Subagents track**, **Tasks track**. The subagents and tasks tracks are pills floating over the transcript, each opening a panel with its rows; the [queue track](agent-lifecycle.md#the-queue-track) is a lane inside the composer itself. Code: `ComposerQueueTrack` (`packages/app/src/composer/queue/track.tsx`), pill and panel frame in `packages/app/src/composer/tracks.tsx`, `SubagentsTrack` (`packages/app/src/subagents/track.tsx`), `AgentTaskList` (`packages/app/src/composer/task-list/index.tsx`).
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn. An agent sender's `activeTurnBehavior: "steer"` (CLI `--behavior steer`) means the same as a person's steer. Agent senders default to `queue` instead: the daemon holds the message until the running turn ends, as it does for a person's queued message. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Steer** — A follow-up admitted into an agent's already-running turn instead of interrupting it. Interrupting the turn discards steers the provider has not read yet; there is no take-back short of that, and no provider offers one. The stop button and Escape both interrupt. A steer the provider never read keeps its transcript row, matching Codex. Sending while the agent waits on a permission denies that request first, so the message reaches the same turn instead of stalling behind it. UI: "Send and steer". Code: `steerActiveTurn` (`packages/server/src/server/agent/agent-sdk-types.ts`). Don't confuse with **Queue track**, which lists the messages the host holds until the turn ends. A queued message does not enter the running turn, and a person's direct steer leaves queued rows in the queue track. Agent senders and finish notifications default to `steer` (falling back to `queue` when the provider cannot steer) and never sweep human-queued items. Forbidden: "Delivery", "Queued prompt".
|
||||
- **Subagent** — User-facing term for an agent session related to a parent agent session. Use **subagents** in UI copy and docs. Internal daemon/provider plumbing may say "child agent" or `child_session`, especially for provider-managed imports; do not surface "child agent" as a product term.
|
||||
- **Attachment tray** — The selected-attachments row inside the composer input, above the text input. Code: `renderAttachmentTray` (`packages/app/src/composer/index.tsx`). Forbidden: "Attachment bar".
|
||||
- **Fork** — Starting a NEW agent session seeded with a copy of another session's curated chat history. The history rides along as a `chat_history` composer attachment on a draft; the fork does **not** resume or branch the provider-side session, and the source session keeps running untouched. Two targets, one surface, one RPC (`agent.fork_context`, gated on the `agentForkContext` host feature). UI: the fork menu lives in the assistant turn footer and offers "Fork in a new tab" / "Fork in a new workspace". On a **completed** turn it sits beside the copy button and pins a boundary to that turn, so the fork stops where the turn ended. On the **in-flight** turn it sits beside the progress loader and elapsed timer, and omits the boundary entirely — `selectForkContextRows` projects the whole timeline when no boundary is given, so the fork captures everything **up to now**, including the response still streaming. That omission is what makes mid-run forking work; pinning a boundary there would silently drop the live response. Forbidden on provider-subagent (read-only) panes. Code: `useForkAgent` (`packages/app/src/hooks/use-fork-agent.ts`), `selectForkContextRows` (`packages/server/src/server/agent/activity-curator.ts`). Don't confuse with: git fork (unrelated; Paseo has no such concept), **Worktree** (filesystem isolation, not history copying).
|
||||
|
||||
@@ -10,7 +10,7 @@ Two contracts follow from it.
|
||||
|
||||
A schema change must not break parsing in either direction. An old app still parses messages from a new daemon. A new daemon still parses messages from an old app.
|
||||
|
||||
`hello` carries an optional credential. The daemon accepts a client protocol version from its minimum through newer client versions, selects the lower of client and daemon maximum, and reports it as optional `server_info.protocolVersion`. A `hello.rejected` frame precedes a refusal close only when the client sent `hello.auth` or advertised `hello_rejection` or `evolvable_hello_rejection`; older clients receive only the WebSocket close code and reason so their validator does not reject an unknown top-level envelope. Clients advertising `evolvable_hello_rejection` accept open `reason`, optional `accepts`, and optional `message` fields and halt reconnects on any refusal. Reserve `hello.rejected` for refusals that require user or client-version action; transient restarts and temporary unavailability close the socket without `hello.rejected` so clients reconnect automatically. For `hello_rejection`-only clients, the daemon downgrades unknown reasons to `password_required` (when `accepts` includes `"password"`) or `incompatible_protocol`, restricts `accepts` to `["password"]` or `[]`, and omits `message`.
|
||||
`hello` carries an optional credential. The daemon accepts a client protocol version from its minimum through newer client versions, selects the lower of client and daemon maximum, and reports it as optional `server_info.protocolVersion`. A `hello.rejected` frame precedes an auth close only when the client sent `hello.auth` or advertised `hello_rejection`; older clients receive the existing WebSocket close code and reason. This avoids sending them a new top-level message their validator does not recognize.
|
||||
|
||||
- New fields are `.optional()` with a sensible default.
|
||||
- Never flip optional to required, remove a field, or narrow a type. `string` to `enum` and nullable to non-null are both narrowing.
|
||||
|
||||
@@ -33,13 +33,9 @@ import {
|
||||
expectHostPageVisible,
|
||||
seedSavedSettingsHosts,
|
||||
selectSettingsHost,
|
||||
expectNoHostRefusalSheet,
|
||||
expectHostRefusalSheet,
|
||||
dismissHostRefusalSheet,
|
||||
expectHostPasswordRefusalInline,
|
||||
reopenHostPasswordRefusalSheet,
|
||||
submitHostRefusalPassword,
|
||||
expectHostRefusalPasswordError,
|
||||
expectHostRejectedWithReAddGuidance,
|
||||
expectNoHostPasswordControls,
|
||||
removeHostFromHostPage,
|
||||
addDirectHostFromSettings,
|
||||
expectAddHostFieldDrawnAsInput,
|
||||
selectHostConnectionType,
|
||||
@@ -115,7 +111,7 @@ test.describe("Settings host page", () => {
|
||||
await expect(updateButton).toBeEnabled();
|
||||
});
|
||||
|
||||
test("a saved host rejected for its password reconnects in place from its settings page", async ({
|
||||
test("a host rejected for its password reconnects after being removed and added again with it", async ({
|
||||
page,
|
||||
}) => {
|
||||
const password = "e2e host password";
|
||||
@@ -137,29 +133,16 @@ test.describe("Settings host page", () => {
|
||||
]);
|
||||
await page.reload();
|
||||
await openSettings(page);
|
||||
await openClientHostSettings(page, daemon.serverId);
|
||||
|
||||
await test.step("background refusal stays quiet until the host page is opened", async () => {
|
||||
await expectNoHostRefusalSheet(page);
|
||||
await openClientHostSettings(page, daemon.serverId);
|
||||
await expectHostRefusalSheet(page, {
|
||||
title: "Password required",
|
||||
hostLabel: "Password host",
|
||||
});
|
||||
await test.step("the host page shows the reason and the re-add guidance, with no password UI", async () => {
|
||||
await expectHostRejectedWithReAddGuidance(page, "Password required");
|
||||
await expectNoHostPasswordControls(page);
|
||||
});
|
||||
|
||||
await test.step("dismissing leaves an inline password prompt that reopens the sheet", async () => {
|
||||
await dismissHostRefusalSheet(page);
|
||||
await expectHostPasswordRefusalInline(page, "Password required");
|
||||
await reopenHostPasswordRefusalSheet(page);
|
||||
});
|
||||
|
||||
await test.step("a wrong password stays inline and the right password brings the host online", async () => {
|
||||
await submitHostRefusalPassword(page, "wrong password");
|
||||
await expectHostRefusalPasswordError(page, "Incorrect password");
|
||||
await submitHostRefusalPassword(page, password);
|
||||
await expectNoHostRefusalSheet(page);
|
||||
await expect(page.getByTestId("host-connection-error")).toHaveCount(0);
|
||||
await selectSettingsHost(page, daemon.serverId);
|
||||
await test.step("removing the host and adding it again with the password brings it online", async () => {
|
||||
await removeHostFromHostPage(page, daemon.serverId);
|
||||
await addDirectHostFromSettings(page, { host: "127.0.0.1", port: daemon.port, password });
|
||||
await openHostSection(page, daemon.serverId, "daemon");
|
||||
await expectHostOnlineWithoutError(page);
|
||||
});
|
||||
|
||||
@@ -712,47 +712,27 @@ export async function expectLocalHostEntryFirst(page: Page, _serverId: string):
|
||||
await expect(picker.getByText(TEST_HOST_LABEL, { exact: true })).toBeVisible();
|
||||
}
|
||||
|
||||
export async function expectNoHostRefusalSheet(page: Page): Promise<void> {
|
||||
await expect(page.getByTestId("host-refusal-sheet")).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function expectHostRefusalSheet(
|
||||
export async function expectHostRejectedWithReAddGuidance(
|
||||
page: Page,
|
||||
expected: { title: string; hostLabel: string },
|
||||
reason: string,
|
||||
): Promise<void> {
|
||||
const sheet = page.getByTestId("host-refusal-sheet");
|
||||
await expect(sheet).toBeVisible();
|
||||
await expect(sheet.getByTestId("host-refusal-sheet-title")).toHaveText(expected.title);
|
||||
await expect(sheet.getByTestId("host-refusal-sheet-host")).toHaveText(expected.hostLabel);
|
||||
}
|
||||
|
||||
export async function dismissHostRefusalSheet(page: Page): Promise<void> {
|
||||
await page.getByTestId("host-refusal-sheet-dismiss").click();
|
||||
await expectNoHostRefusalSheet(page);
|
||||
}
|
||||
|
||||
export async function expectHostPasswordRefusalInline(page: Page, reason: string): Promise<void> {
|
||||
const error = page.getByTestId("host-connection-error");
|
||||
await expect(error).toContainText(reason);
|
||||
await expect(error.getByRole("button", { name: "Enter password", exact: true })).toBeVisible();
|
||||
await expect(error).toContainText(
|
||||
"Remove this host and add it again with the password this daemon asks for.",
|
||||
);
|
||||
}
|
||||
|
||||
export async function reopenHostPasswordRefusalSheet(page: Page): Promise<void> {
|
||||
await page
|
||||
.getByTestId("host-connection-error")
|
||||
.getByRole("button", { name: "Enter password", exact: true })
|
||||
.click();
|
||||
await expect(page.getByTestId("host-refusal-sheet")).toBeVisible();
|
||||
export async function expectNoHostPasswordControls(page: Page): Promise<void> {
|
||||
await expect(page.getByText("Password", { exact: true })).toHaveCount(0);
|
||||
await expect(page.locator('input[type="password"]')).toHaveCount(0);
|
||||
await expect(page.getByRole("button", { name: /password/i })).toHaveCount(0);
|
||||
}
|
||||
|
||||
export async function submitHostRefusalPassword(page: Page, password: string): Promise<void> {
|
||||
await page.getByTestId("host-password-input").fill(password);
|
||||
await page.getByTestId("host-refusal-sheet-submit").click();
|
||||
}
|
||||
|
||||
export async function expectHostRefusalPasswordError(page: Page, message: string): Promise<void> {
|
||||
await expect(page.getByTestId("host-refusal-sheet")).toBeVisible();
|
||||
await expect(page.getByTestId("host-password-field")).toContainText(message);
|
||||
export async function removeHostFromHostPage(page: Page, serverId: string): Promise<void> {
|
||||
await page.getByTestId("host-page-remove-host-button").click();
|
||||
await page.getByTestId("remove-host-confirm").click();
|
||||
await expect(page).not.toHaveURL(new RegExp(`/settings/(hosts|device-hosts)/${serverId}`));
|
||||
}
|
||||
|
||||
export async function expectHostOnlineWithoutError(page: Page): Promise<void> {
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
resolveDesktopDivisionLayout,
|
||||
} from "@/window-layout";
|
||||
import { AddHostProvider, AddHostFlowHost } from "@/hosts/add-host";
|
||||
import { HostRefusalSheetHost } from "@/hosts/host-refusal-sheet";
|
||||
import { useSafeAreaInsets } from "react-native-safe-area-context";
|
||||
import { useActiveWorkspaceSelection } from "@/stores/navigation-active-workspace-store";
|
||||
import { useIsExplorerSidebarOpen } from "@/workspace-tabs/explorer-sidebar";
|
||||
@@ -532,7 +531,6 @@ function AppContainer({ children, chromeEnabled: chromeEnabledOverride }: AppCon
|
||||
<View style={layoutStyles.surfaceFill}>
|
||||
{workspaceChrome}
|
||||
<AddHostFlowHost />
|
||||
<HostRefusalSheetHost />
|
||||
<WorkspaceArchiveShortcutHandler />
|
||||
<AppearanceStyleBoundary>
|
||||
{!isCompactLayout && appChromeLayout.sidebarToggleOwner === "window" ? (
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import { useCallback, useEffect, useMemo, useRef } from "react";
|
||||
import { useLocalSearchParams, useRouter, type Href } from "expo-router";
|
||||
import { useIsFocused } from "expo-router/react-navigation";
|
||||
import { HostRouteBootstrapBoundary } from "@/components/host-route-bootstrap-boundary";
|
||||
import { useFetchQuery } from "@/data/query";
|
||||
import { resolveAgentRoute, type AgentRouteLookup } from "@/navigation/agent-route-resolution";
|
||||
import { AgentRouteResolutionView } from "@/navigation/agent-route-resolution-view";
|
||||
import { useActiveRefusalHost } from "@/hosts/host-refusal-sheet-state";
|
||||
import { useHasHydratedWorkspaces } from "@/stores/session-store-hooks";
|
||||
import { useDirectoryDemand } from "@/hooks/use-directory-demand";
|
||||
import { useWorkspaceLayoutStoreHydrated } from "@/stores/workspace-layout-store";
|
||||
@@ -25,14 +23,13 @@ export default function HostAgentReadyRoute() {
|
||||
|
||||
function HostAgentReadyRouteContent() {
|
||||
const router = useRouter();
|
||||
const isRouteFocused = useIsFocused();
|
||||
const params = useLocalSearchParams<{
|
||||
serverId?: string;
|
||||
agentId?: string;
|
||||
}>();
|
||||
const handledNavigationRef = useRef<string | null>(null);
|
||||
const serverId = readStringParam(params.serverId);
|
||||
const agentId = readStringParam(params.agentId);
|
||||
const serverId = typeof params.serverId === "string" ? params.serverId : "";
|
||||
const agentId = typeof params.agentId === "string" ? params.agentId : "";
|
||||
const hosts = useHosts();
|
||||
const runtimeSnapshot = useHostRuntimeSnapshot(serverId);
|
||||
const client = runtimeSnapshot?.client ?? null;
|
||||
@@ -50,13 +47,9 @@ function HostAgentReadyRouteContent() {
|
||||
.prepareAgentRoute(serverId, agentId)
|
||||
.catch(() => undefined);
|
||||
}, [agentId, agentWorkspaceId, serverId]);
|
||||
const shouldLookupAgent = canLookupAgentRoute({
|
||||
serverId,
|
||||
agentId,
|
||||
hasClient: client !== null,
|
||||
connectionStatus,
|
||||
agentWorkspaceId,
|
||||
});
|
||||
const shouldLookupAgent = Boolean(
|
||||
serverId && agentId && client && connectionStatus === "online" && !agentWorkspaceId,
|
||||
);
|
||||
const lookupQuery = useFetchQuery({
|
||||
queryKey: ["agentRouteResolution", serverId, agentId, runtimeSnapshot?.clientGeneration ?? 0],
|
||||
queryFn: async () => {
|
||||
@@ -105,10 +98,16 @@ function HostAgentReadyRouteContent() {
|
||||
connectionStatus,
|
||||
lookup,
|
||||
});
|
||||
useActiveRefusalHost(serverId, isRouteFocused && isVisibleAgentRouteResolution(resolution));
|
||||
|
||||
useEffect(() => {
|
||||
const navigationKey = resolveAgentRouteNavigationKey(resolution);
|
||||
let navigationKey: string | null = null;
|
||||
if (resolution.kind === "invalid") {
|
||||
navigationKey = "invalid";
|
||||
} else if (resolution.kind === "resolved") {
|
||||
navigationKey = `workspace:${resolution.workspaceId}`;
|
||||
} else if (resolution.kind === "notFound") {
|
||||
navigationKey = "not-found";
|
||||
}
|
||||
if (!navigationKey || handledNavigationRef.current === navigationKey) {
|
||||
return;
|
||||
}
|
||||
@@ -127,7 +126,7 @@ function HostAgentReadyRouteContent() {
|
||||
return;
|
||||
}
|
||||
if (serverId) {
|
||||
void getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
|
||||
void getHostRuntimeStore().runProbeCycleNow(serverId);
|
||||
}
|
||||
}, [lookupQuery, resolution.kind, serverId]);
|
||||
const handleManageHost = useCallback(() => {
|
||||
@@ -143,16 +142,18 @@ function HostAgentReadyRouteContent() {
|
||||
router.replace(serverId ? buildHostRootRoute(serverId) : ("/" as Href));
|
||||
}, [router, serverId]);
|
||||
|
||||
if (isVisibleAgentRouteResolution(resolution)) {
|
||||
if (
|
||||
resolution.kind === "waitingForHost" ||
|
||||
resolution.kind === "fetchingAgent" ||
|
||||
resolution.kind === "lookupError"
|
||||
) {
|
||||
// Agent URLs intentionally omit workspaceId. Keep this route mounted while the target host
|
||||
// reconnects, then resolve the workspace from the authoritative agent record.
|
||||
return (
|
||||
<AgentRouteResolutionView
|
||||
serverId={serverId}
|
||||
resolution={resolution}
|
||||
hostName={hostName}
|
||||
lastHostError={runtimeSnapshot?.lastError ?? null}
|
||||
helloRejection={runtimeSnapshot?.helloRejection ?? null}
|
||||
onRetry={handleRetry}
|
||||
onManageHost={handleManageHost}
|
||||
onBack={handleBack}
|
||||
@@ -162,45 +163,3 @@ function HostAgentReadyRouteContent() {
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function readStringParam(value: string | undefined): string {
|
||||
return typeof value === "string" ? value : "";
|
||||
}
|
||||
|
||||
function canLookupAgentRoute(input: {
|
||||
serverId: string;
|
||||
agentId: string;
|
||||
hasClient: boolean;
|
||||
connectionStatus: string;
|
||||
agentWorkspaceId: string | null;
|
||||
}): boolean {
|
||||
return Boolean(
|
||||
input.serverId &&
|
||||
input.agentId &&
|
||||
input.hasClient &&
|
||||
input.connectionStatus === "online" &&
|
||||
!input.agentWorkspaceId,
|
||||
);
|
||||
}
|
||||
|
||||
function resolveAgentRouteNavigationKey(
|
||||
resolution: ReturnType<typeof resolveAgentRoute>,
|
||||
): string | null {
|
||||
if (resolution.kind === "invalid") return "invalid";
|
||||
if (resolution.kind === "resolved") return `workspace:${resolution.workspaceId}`;
|
||||
if (resolution.kind === "notFound") return "not-found";
|
||||
return null;
|
||||
}
|
||||
|
||||
function isVisibleAgentRouteResolution(
|
||||
resolution: ReturnType<typeof resolveAgentRoute>,
|
||||
): resolution is Extract<
|
||||
ReturnType<typeof resolveAgentRoute>,
|
||||
{ kind: "waitingForHost" | "fetchingAgent" | "lookupError" }
|
||||
> {
|
||||
return (
|
||||
resolution.kind === "waitingForHost" ||
|
||||
resolution.kind === "fetchingAgent" ||
|
||||
resolution.kind === "lookupError"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -84,19 +84,4 @@ describe("direct connection failure copy", () => {
|
||||
}),
|
||||
).toMatchObject({ detail: message, raw: message });
|
||||
});
|
||||
|
||||
it("preserves non-password hello rejections without falling back to generic unableToConnect", () => {
|
||||
const message = "Incompatible protocol version";
|
||||
expect(
|
||||
buildConnectionFailureCopy({
|
||||
endpoint: "example.test:6767",
|
||||
error: new DaemonConnectionTestError(message, {
|
||||
reason: message,
|
||||
lastError: message,
|
||||
helloRejection: { reason: "incompatible_protocol", accepts: [] },
|
||||
}),
|
||||
labels,
|
||||
}),
|
||||
).toMatchObject({ detail: message, raw: message });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import {
|
||||
DaemonConnectionTestError,
|
||||
getConnectionHelloRejection,
|
||||
getConnectionAuthFailureReason,
|
||||
} from "@/utils/test-daemon-connection";
|
||||
|
||||
interface ConnectionFailureLabels {
|
||||
@@ -73,7 +73,7 @@ export function buildConnectionFailureCopy(input: {
|
||||
const rawLower = raw?.toLowerCase() ?? "";
|
||||
let detail: string | null = null;
|
||||
|
||||
if (getConnectionHelloRejection(error)) {
|
||||
if (getConnectionAuthFailureReason(error)) {
|
||||
detail = error instanceof Error ? error.message : raw;
|
||||
} else if (rawLower.includes("timed out")) {
|
||||
detail = labels.timedOut;
|
||||
|
||||
@@ -733,23 +733,4 @@ describe("deriveAgentScreenViewState", () => {
|
||||
expect(ready.source).toBe("authoritative");
|
||||
expect(ready.sync).toEqual({ status: "catching_up", ui: "overlay" });
|
||||
});
|
||||
|
||||
it("stays idle instead of reconnecting when the host connection was refused", () => {
|
||||
const result = deriveAgentScreenViewState({
|
||||
input: {
|
||||
...createBaseInput(),
|
||||
agent: createAgent("agent-1"),
|
||||
isConnected: false,
|
||||
isConnectionRefused: true,
|
||||
hasHydratedHistoryBefore: true,
|
||||
},
|
||||
memory: createBaseMemory({
|
||||
hasRenderedReady: true,
|
||||
lastReadyAgent: createAgent("agent-1"),
|
||||
}),
|
||||
});
|
||||
|
||||
const ready = expectReadyState(result.state);
|
||||
expect(ready.sync).toEqual({ status: "idle" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -43,7 +43,6 @@ export interface AgentScreenMachineInput {
|
||||
isArchived: boolean;
|
||||
missingAgentState: AgentScreenMissingState;
|
||||
isConnected: boolean;
|
||||
isConnectionRefused?: boolean;
|
||||
isArchivingCurrentAgent: boolean;
|
||||
isHistorySyncing: boolean;
|
||||
needsAuthoritativeSync: boolean;
|
||||
@@ -182,9 +181,6 @@ function resolveAgentScreenSync(args: {
|
||||
) {
|
||||
return { status: "idle" };
|
||||
}
|
||||
if (input.isConnectionRefused) {
|
||||
return { status: "idle" };
|
||||
}
|
||||
// A reconnected chat is not back until the daemon answers whether it is current.
|
||||
if (
|
||||
(!input.isConnected || input.visibilityCatchUpStatus === "reattaching") &&
|
||||
|
||||
@@ -16,15 +16,8 @@ import {
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { SegmentedControl, type SegmentedControlOption } from "@/components/ui/segmented-control";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import {
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalPresentation,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import { useHardwareKeyboardPresent } from "@/keyboard/availability";
|
||||
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import {
|
||||
canSwitchToForm,
|
||||
editForm,
|
||||
@@ -35,7 +28,6 @@ import {
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
uriHostLabel,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
type DirectConnectionMode,
|
||||
@@ -177,9 +169,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
const [input, setInput] = useState<DirectConnectionInput>(openDirectConnection);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
|
||||
null,
|
||||
);
|
||||
// Switching modes mounts the other mode's fields. They take focus when the user was typing
|
||||
// or has a keyboard, so a phone's keyboard stays up instead of closing on the switch.
|
||||
const [focusModeBody, setFocusModeBody] = useState(false);
|
||||
@@ -237,7 +226,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
if (next.mode !== input.mode) {
|
||||
setFocusModeBody(keyboardPresent || fieldFocused.current);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
}
|
||||
setInput(next);
|
||||
},
|
||||
@@ -297,7 +285,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
const result = await connect(connection);
|
||||
if (!result) return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
@@ -305,29 +292,13 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
const targetHostName =
|
||||
connection.kind === "relay"
|
||||
? (uriHostLabel(connection.link) ?? "host")
|
||||
: connection.endpoint;
|
||||
setRefusalPresentation(
|
||||
resolveHostRefusal({
|
||||
rejection,
|
||||
hostName: targetHostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
}),
|
||||
);
|
||||
// URI mode has no Password field, so a password refusal asks for it here.
|
||||
if (input.mode === "uri" && isPasswordRefusal(rejection)) {
|
||||
setInput((current) => promptForPassword(current));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const message = describeFailure(connection, error);
|
||||
setErrorMessage(message);
|
||||
// URI mode has no Password field, so a rejected password is asked for here.
|
||||
if (input.mode === "uri" && getConnectionAuthFailureReason(error)) {
|
||||
setInput((current) => promptForPassword(current));
|
||||
return;
|
||||
}
|
||||
if (connection.kind === "direct" && !isMobile) {
|
||||
Alert.alert(t("pairing.direct.errors.failedTitle"), message);
|
||||
}
|
||||
@@ -447,9 +418,6 @@ function AddHostModalContent({ visible, onClose, onCancel, onSaved }: AddHostMod
|
||||
)}
|
||||
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
{refusalPresentation ? (
|
||||
<HostRefusalInlineAlert presentation={refusalPresentation} testID="direct-host-refusal" />
|
||||
) : null}
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,13 +21,7 @@ import {
|
||||
resolveControlInteractionStyles,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { resolveHostRefusal, type HostRefusalPresentation } from "@/hosts/host-refusal";
|
||||
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import {
|
||||
DaemonConnectionTestError,
|
||||
getConnectionHelloRejection,
|
||||
} from "@/utils/test-daemon-connection";
|
||||
import { DaemonConnectionTestError } from "@/utils/test-daemon-connection";
|
||||
import { AdaptiveModalSheet, type SheetHeader } from "@/components/adaptive-modal-sheet";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
@@ -111,9 +105,6 @@ export function AddRemoteSshHostModal({
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
|
||||
null,
|
||||
);
|
||||
const header = useMemo<SheetHeader>(() => ({ title: t("pairing.remoteSsh.title") }), [t]);
|
||||
|
||||
const clear = useCallback(() => {
|
||||
@@ -123,7 +114,6 @@ export function AddRemoteSshHostModal({
|
||||
passwordInputRef.current?.replaceText("");
|
||||
setIsPasswordVisible(false);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
}, []);
|
||||
|
||||
const handleClose = useCallback(() => {
|
||||
@@ -158,25 +148,11 @@ export function AddRemoteSshHostModal({
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
result = await probeAndUpsertRemoteSshConnection({
|
||||
...target,
|
||||
password: passwordRef.current === "" ? undefined : passwordRef.current,
|
||||
});
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
setRefusalPresentation(
|
||||
resolveHostRefusal({
|
||||
rejection,
|
||||
hostName: target.host,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
}),
|
||||
);
|
||||
return;
|
||||
}
|
||||
const message =
|
||||
error instanceof DaemonConnectionTestError
|
||||
? t("pairing.remoteSsh.errors.failedToConnect", { detail: error.message })
|
||||
@@ -288,9 +264,6 @@ export function AddRemoteSshHostModal({
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</Field>
|
||||
{refusalPresentation ? (
|
||||
<HostRefusalInlineAlert presentation={refusalPresentation} testID="remote-ssh-refusal" />
|
||||
) : null}
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
promptForPassword,
|
||||
resolveConnection,
|
||||
switchMode,
|
||||
uriHostLabel,
|
||||
type DirectConnectionForm,
|
||||
type DirectConnectionInput,
|
||||
} from "./direct-connection";
|
||||
@@ -268,11 +267,4 @@ describe("resolving the connection", () => {
|
||||
password: "pw",
|
||||
});
|
||||
});
|
||||
|
||||
it("extracts a short host label from pairing links without exposing query credentials", () => {
|
||||
const relayWithPassword = `${RELAY_LINK}&password=top-secret`;
|
||||
expect(uriHostLabel(relayWithPassword)).toBe("srv_abc");
|
||||
expect(uriHostLabel(OFFER_LINK)).toBe("srv_offer");
|
||||
expect(uriHostLabel("relay://invalid?password=top-secret")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -163,7 +163,7 @@ function uriToForm(uri: string): DirectConnectionForm {
|
||||
};
|
||||
}
|
||||
|
||||
export function uriHostLabel(uri: string): string | null {
|
||||
function uriHostLabel(uri: string): string | null {
|
||||
const trimmed = uri.trim();
|
||||
if (isPairingLink(trimmed)) {
|
||||
try {
|
||||
|
||||
@@ -6,20 +6,14 @@ import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { Link } from "lucide-react-native";
|
||||
import type { HostProfile } from "@/types/host-connection";
|
||||
import { useHosts, useHostMutations, type PasswordRequiredPairing } from "@/runtime/host-runtime";
|
||||
import { uriHostLabel } from "./direct-connection";
|
||||
import { parseRelayConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
AdaptiveTextInput,
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import {
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalPresentation,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
import { getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { PairingTargetTracker } from "@/components/pair-link-credentials";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
@@ -27,7 +21,14 @@ import type { EditingTextInputHandle } from "@/components/ui/text-input";
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
|
||||
function parsedHostLabel(input: string): string {
|
||||
return uriHostLabel(input) ?? "host";
|
||||
try {
|
||||
if (input.startsWith("relay://") || input.includes("#connect=")) {
|
||||
return parseRelayConnectionUri(input).offer.serverId;
|
||||
}
|
||||
return parseConnectionOfferFromUrl(input)?.serverId ?? "host";
|
||||
} catch {
|
||||
return "host";
|
||||
}
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
@@ -115,9 +116,6 @@ function PairLinkModalContent({
|
||||
const inputRef = useRef<EditingTextInputHandle>(null);
|
||||
const [isSaving, setIsSaving] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState("");
|
||||
const [refusalPresentation, setRefusalPresentation] = useState<HostRefusalPresentation | null>(
|
||||
null,
|
||||
);
|
||||
const [password, setPassword] = useState("");
|
||||
const [needsPassword, setNeedsPassword] = useState(passwordRequired !== undefined);
|
||||
const [passwordResetKey, resetPasswordInput] = useReducer((key: number) => key + 1, 0);
|
||||
@@ -128,7 +126,6 @@ function PairLinkModalContent({
|
||||
inputRef.current?.replaceText("");
|
||||
setPassword("");
|
||||
setNeedsPassword(false);
|
||||
setRefusalPresentation(null);
|
||||
resetPasswordInput();
|
||||
}, []);
|
||||
|
||||
@@ -164,7 +161,6 @@ function PairLinkModalContent({
|
||||
try {
|
||||
setIsSaving(true);
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
const result = await pairing.submit(raw, password || undefined);
|
||||
if (result.status === "cancelled") return;
|
||||
const { profile, serverId, hostname } = result;
|
||||
@@ -172,22 +168,13 @@ function PairLinkModalContent({
|
||||
onSaved?.({ profile, serverId, hostname, isNewHost });
|
||||
handleClose();
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
const presentation = resolveHostRefusal({
|
||||
rejection,
|
||||
hostName: parsedHostLabel(raw),
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
});
|
||||
setRefusalPresentation(presentation);
|
||||
setNeedsPassword(isPasswordRefusal(rejection));
|
||||
return;
|
||||
}
|
||||
const message =
|
||||
error instanceof Error ? error.message : t("pairing.link.errors.unableToPair");
|
||||
setErrorMessage(message);
|
||||
if (getConnectionAuthFailureReason(error)) {
|
||||
setNeedsPassword(true);
|
||||
return;
|
||||
}
|
||||
if (!isMobile) {
|
||||
Alert.alert(t("pairing.link.alert.failedTitle"), message);
|
||||
}
|
||||
@@ -204,7 +191,6 @@ function PairLinkModalContent({
|
||||
setNeedsPassword(false);
|
||||
resetPasswordInput();
|
||||
setErrorMessage("");
|
||||
setRefusalPresentation(null);
|
||||
}
|
||||
offerUrlRef.current = next;
|
||||
}, []);
|
||||
@@ -241,9 +227,6 @@ function PairLinkModalContent({
|
||||
keyboardType="url"
|
||||
/>
|
||||
{errorMessage ? <Text style={styles.error}>{errorMessage}</Text> : null}
|
||||
{refusalPresentation ? (
|
||||
<HostRefusalInlineAlert presentation={refusalPresentation} testID="pair-link-refusal" />
|
||||
) : null}
|
||||
</View>
|
||||
|
||||
{needsPassword ? (
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { DaemonHelloRejectedError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { ConnectionLinkImport, LinkPairing } from "@/runtime/host-runtime";
|
||||
import { openPairScan, type PairScanModel } from "./pair-scan-model";
|
||||
|
||||
@@ -92,35 +91,10 @@ describe("openPairScan", () => {
|
||||
await settled(scan);
|
||||
scan.scan(LINK);
|
||||
|
||||
expect(scan.getState()).toEqual({
|
||||
status: "stopped",
|
||||
error: "Server disconnected",
|
||||
helloRejection: null,
|
||||
hostName: "host",
|
||||
});
|
||||
expect(scan.getState()).toEqual({ status: "stopped", error: "Server disconnected" });
|
||||
expect(imports).toEqual([LINK]);
|
||||
});
|
||||
|
||||
it("stops with structured helloRejection for non-password refusals", async () => {
|
||||
const rejection = {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Re-pair device",
|
||||
};
|
||||
const { scan, imports } = createScanner([new DaemonHelloRejectedError(rejection)]);
|
||||
|
||||
scan.scan("relay://relay.example:443/srv_alpha?key=AAAA");
|
||||
await settled(scan);
|
||||
|
||||
expect(scan.getState()).toEqual({
|
||||
status: "stopped",
|
||||
error: "Connection refused (pairing_required)",
|
||||
helloRejection: rejection,
|
||||
hostName: "srv_alpha",
|
||||
});
|
||||
expect(imports).toEqual(["relay://relay.example:443/srv_alpha?key=AAAA"]);
|
||||
});
|
||||
|
||||
it("does not navigate for an attempt that finishes after the screen closed", async () => {
|
||||
let finish: (outcome: ConnectionLinkImport) => void = () => {};
|
||||
const connected: string[] = [];
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { parseConnectionOfferFromUrl } from "@getpaseo/protocol/connection-offer";
|
||||
import type { ConnectionLinkImport, PasswordRequiredPairing } from "@/runtime/host-runtime";
|
||||
import { parseRelayConnectionUri } from "@/utils/daemon-endpoints";
|
||||
import { getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
|
||||
/**
|
||||
* One visit to the QR scan screen. The camera reports every frame that shows
|
||||
@@ -15,12 +11,7 @@ export type PairScanState =
|
||||
| { status: "scanning" }
|
||||
| { status: "pairing" }
|
||||
| { status: "passwordRequired"; passwordRequired: PasswordRequiredPairing }
|
||||
| {
|
||||
status: "stopped";
|
||||
error: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
hostName?: string;
|
||||
}
|
||||
| { status: "stopped"; error: string | null }
|
||||
| { status: "connected" };
|
||||
|
||||
export interface PairScanModel {
|
||||
@@ -70,13 +61,7 @@ export function openPairScan(deps: PairScanDependencies): PairScanModel {
|
||||
}
|
||||
publish({ status: "stopped", error: null });
|
||||
} catch (error) {
|
||||
const helloRejection = getConnectionHelloRejection(error);
|
||||
publish({
|
||||
status: "stopped",
|
||||
error: error instanceof Error ? error.message : String(error),
|
||||
helloRejection,
|
||||
hostName: hostNameFromLink(link),
|
||||
});
|
||||
publish({ status: "stopped", error: error instanceof Error ? error.message : String(error) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,14 +101,3 @@ function pairingLinkFromScan(data: string): string | null {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function hostNameFromLink(link: string): string {
|
||||
try {
|
||||
if (link.startsWith("relay://") || link.includes("#connect=")) {
|
||||
return parseRelayConnectionUri(link).offer.serverId;
|
||||
}
|
||||
return parseConnectionOfferFromUrl(link)?.serverId ?? "host";
|
||||
} catch {
|
||||
return "host";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,10 +6,8 @@ import { StyleSheet } from "react-native-unistyles";
|
||||
import { CameraView, useCameraPermissions } from "expo-camera";
|
||||
import type { BarcodeScanningResult, BarcodeSettings } from "expo-camera";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { openPairScan, type PairScanState } from "./pair-scan-model";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { resolveHostRefusal } from "@/hosts/host-refusal";
|
||||
import { HostRefusalBody } from "@/hosts/host-refusal-body";
|
||||
import { openPairScan } from "./pair-scan-model";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { PairLinkModal } from "./pair-link-modal";
|
||||
import { Button } from "@/components/ui/button";
|
||||
|
||||
@@ -83,12 +81,6 @@ const styles = StyleSheet.create((theme) => ({
|
||||
textAlign: "center",
|
||||
fontSize: theme.fontSize.base,
|
||||
},
|
||||
refusalBox: {
|
||||
marginTop: theme.spacing[4],
|
||||
paddingHorizontal: theme.spacing[4],
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
permissionCard: {
|
||||
marginTop: theme.spacing[6],
|
||||
padding: theme.spacing[6],
|
||||
@@ -210,7 +202,9 @@ export function PairScanContent({
|
||||
{scanState.status === "pairing" ? (
|
||||
<Text style={styles.helperText}>{t("pairing.scan.pairing")}</Text>
|
||||
) : null}
|
||||
<PairScanStoppedError scanState={scanState} />
|
||||
{scanState.status === "stopped" && scanState.error ? (
|
||||
<Text style={styles.helperText}>{scanState.error}</Text>
|
||||
) : null}
|
||||
{scanState.status === "stopped" ? (
|
||||
<Button
|
||||
style={styles.scanAgainButton}
|
||||
@@ -237,34 +231,3 @@ export function PairScanContent({
|
||||
}
|
||||
|
||||
const BARCODE_SCANNER_SETTINGS: BarcodeSettings = { barcodeTypes: ["qr"] };
|
||||
|
||||
function PairScanStoppedError({ scanState }: { scanState: PairScanState }) {
|
||||
const { t } = useTranslation();
|
||||
if (scanState.status !== "stopped") return null;
|
||||
if (scanState.helloRejection) {
|
||||
const presentation = resolveHostRefusal({
|
||||
rejection: scanState.helloRejection,
|
||||
hostName: scanState.hostName ?? "host",
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
});
|
||||
return (
|
||||
<View style={styles.refusalBox} testID="pair-scan-refusal">
|
||||
<Text style={styles.helperText}>{presentation.title}</Text>
|
||||
<HostRefusalBody
|
||||
presentation={presentation}
|
||||
centered
|
||||
numberOfLines={3}
|
||||
testIDPrefix="pair-scan-refusal"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
if (!scanState.error) return null;
|
||||
return (
|
||||
<Text style={styles.helperText} dataDetectorType="none">
|
||||
{scanState.error}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,6 @@ import {
|
||||
type HostConnectionKind,
|
||||
} from "@/hosts/connection-display";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { resolveHostRefusal } from "@/hosts/host-refusal";
|
||||
import { HostStatusIcon } from "@/hosts/host-status-icon";
|
||||
import { useLocalDaemonServerId } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
@@ -161,16 +160,9 @@ export function HostLatencyLabel({ serverId }: { serverId: string }): ReactEleme
|
||||
}
|
||||
|
||||
if (status === "offline" || status === "error") {
|
||||
const label = snapshot?.helloRejection
|
||||
? resolveHostRefusal({
|
||||
rejection: snapshot.helloRejection,
|
||||
hostName: serverId,
|
||||
t,
|
||||
}).shortStatus
|
||||
: t("common.connectionStatus.offline");
|
||||
return (
|
||||
<Text style={styles.statusText} numberOfLines={1}>
|
||||
{label}
|
||||
{t("common.connectionStatus.offline")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,221 +0,0 @@
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { useRouter, type Href } from "expo-router";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Text, View } from "react-native";
|
||||
import { Settings } from "lucide-react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import { useAddHost } from "@/hosts/add-host";
|
||||
import { openHostRefusalSheet } from "@/hosts/host-refusal-sheet-state";
|
||||
import {
|
||||
getHostRefusalActionLabel,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalAction,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { HostRefusalBody, HostRefusalInlineAlert } from "@/hosts/host-refusal-body";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
import { buildSettingsSectionRoute } from "@/utils/host-routes";
|
||||
|
||||
export { HostRefusalBody, HostRefusalInlineAlert };
|
||||
|
||||
export function useHostRefusalAction(serverId: string): (action: HostRefusalAction) => void {
|
||||
const router = useRouter();
|
||||
const openPairLink = useAddHost({ method: "link" });
|
||||
const openScanQr = useAddHost({ method: "scan" });
|
||||
|
||||
return useCallback(
|
||||
(action: HostRefusalAction) => {
|
||||
switch (action.kind) {
|
||||
case "enter_password":
|
||||
if (serverId) openHostRefusalSheet(serverId);
|
||||
return;
|
||||
case "pair_link":
|
||||
openPairLink();
|
||||
return;
|
||||
case "scan_qr":
|
||||
openScanQr();
|
||||
return;
|
||||
case "update_app":
|
||||
router.push(buildSettingsSectionRoute("about") as Href);
|
||||
return;
|
||||
case "retry":
|
||||
if (serverId) {
|
||||
void getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
|
||||
}
|
||||
return;
|
||||
}
|
||||
},
|
||||
[openPairLink, openScanQr, router, serverId],
|
||||
);
|
||||
}
|
||||
|
||||
function useHostRefusalBindings(
|
||||
serverId: string,
|
||||
hostName: string,
|
||||
rejection: DaemonHelloRejection,
|
||||
) {
|
||||
const { t } = useTranslation();
|
||||
const runAction = useHostRefusalAction(serverId);
|
||||
const presentation = useMemo(
|
||||
() =>
|
||||
resolveHostRefusal({
|
||||
rejection,
|
||||
hostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
}),
|
||||
[hostName, rejection, t],
|
||||
);
|
||||
|
||||
const handlePrimary = useCallback(() => {
|
||||
runAction(presentation.primaryAction);
|
||||
}, [presentation.primaryAction, runAction]);
|
||||
|
||||
const handleSecondary = useCallback(() => {
|
||||
if (presentation.secondaryAction) {
|
||||
runAction(presentation.secondaryAction);
|
||||
}
|
||||
}, [presentation.secondaryAction, runAction]);
|
||||
|
||||
return { t, presentation, handlePrimary, handleSecondary };
|
||||
}
|
||||
|
||||
export function HostRefusalAlert({
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
testID,
|
||||
}: {
|
||||
serverId: string;
|
||||
hostName: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
testID?: string;
|
||||
}) {
|
||||
const { t, presentation, handlePrimary, handleSecondary } = useHostRefusalBindings(
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
);
|
||||
|
||||
const description = useMemo(
|
||||
() =>
|
||||
presentation.description || presentation.hostMessage ? (
|
||||
<HostRefusalBody presentation={presentation} numberOfLines={3} testIDPrefix={testID} />
|
||||
) : undefined,
|
||||
[presentation, testID],
|
||||
);
|
||||
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={presentation.title}
|
||||
description={description}
|
||||
testID={testID}
|
||||
>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="default"
|
||||
onPress={handlePrimary}
|
||||
testID={testID ? `${testID}-primary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.primaryAction, t)}
|
||||
</Button>
|
||||
{presentation.secondaryAction ? (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
onPress={handleSecondary}
|
||||
testID={testID ? `${testID}-secondary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
|
||||
</Button>
|
||||
) : null}
|
||||
</InlineAlert>
|
||||
);
|
||||
}
|
||||
|
||||
/** Centered full-view refusal state shared by unreachable workspace and agent routes. */
|
||||
export function HostRefusalEmptyState({
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
onManageHost,
|
||||
testID,
|
||||
testIDPrefix,
|
||||
}: {
|
||||
serverId: string;
|
||||
hostName: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
onManageHost: () => void;
|
||||
testID?: string;
|
||||
testIDPrefix?: string;
|
||||
}) {
|
||||
const { t, presentation, handlePrimary, handleSecondary } = useHostRefusalBindings(
|
||||
serverId,
|
||||
hostName,
|
||||
rejection,
|
||||
);
|
||||
|
||||
return (
|
||||
<View style={styles.emptyState} testID={testID}>
|
||||
<View style={styles.textStack}>
|
||||
<Text style={styles.title}>{presentation.title}</Text>
|
||||
<HostRefusalBody presentation={presentation} centered testIDPrefix={testIDPrefix} />
|
||||
</View>
|
||||
<View style={styles.actions}>
|
||||
<Button
|
||||
variant="default"
|
||||
onPress={handlePrimary}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-primary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.primaryAction, t)}
|
||||
</Button>
|
||||
{presentation.secondaryAction ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
onPress={handleSecondary}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-secondary-action` : undefined}
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
|
||||
</Button>
|
||||
) : null}
|
||||
<Button variant="outline" leftIcon={Settings} onPress={onManageHost}>
|
||||
{t("workspace.route.manageHost")}
|
||||
</Button>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
emptyState: {
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
paddingHorizontal: theme.spacing[6],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
textStack: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
maxWidth: 420,
|
||||
},
|
||||
title: {
|
||||
fontSize: theme.fontSize.lg,
|
||||
fontWeight: theme.fontWeight.semibold,
|
||||
color: theme.colors.foreground,
|
||||
textAlign: "center",
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
}));
|
||||
@@ -1,93 +0,0 @@
|
||||
import { useMemo } from "react";
|
||||
import { Text, View } from "react-native";
|
||||
import { StyleSheet } from "react-native-unistyles";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import type { HostRefusalPresentation } from "@/hosts/host-refusal";
|
||||
|
||||
export function HostRefusalBody({
|
||||
presentation,
|
||||
centered = false,
|
||||
numberOfLines,
|
||||
testIDPrefix,
|
||||
}: {
|
||||
presentation: HostRefusalPresentation;
|
||||
centered?: boolean;
|
||||
numberOfLines?: number;
|
||||
testIDPrefix?: string;
|
||||
}) {
|
||||
if (!presentation.description && !presentation.hostMessage) return null;
|
||||
|
||||
return (
|
||||
<View style={[styles.body, centered && styles.bodyCentered]}>
|
||||
{presentation.description ? (
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
numberOfLines={numberOfLines}
|
||||
style={[styles.description, centered && styles.textCentered]}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-description` : undefined}
|
||||
>
|
||||
{presentation.description}
|
||||
</Text>
|
||||
) : null}
|
||||
{presentation.hostMessage ? (
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
numberOfLines={numberOfLines}
|
||||
style={[styles.hostMessage, centered && styles.textCentered]}
|
||||
testID={testIDPrefix ? `${testIDPrefix}-host-message` : undefined}
|
||||
>
|
||||
{presentation.hostMessage}
|
||||
</Text>
|
||||
) : null}
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
/** Inline refusal alert without action buttons (used in pairing sheets). */
|
||||
export function HostRefusalInlineAlert({
|
||||
presentation,
|
||||
testID,
|
||||
}: {
|
||||
presentation: HostRefusalPresentation;
|
||||
testID?: string;
|
||||
}) {
|
||||
const description = useMemo(
|
||||
() =>
|
||||
presentation.description || presentation.hostMessage ? (
|
||||
<HostRefusalBody presentation={presentation} numberOfLines={3} testIDPrefix={testID} />
|
||||
) : undefined,
|
||||
[presentation, testID],
|
||||
);
|
||||
|
||||
return (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={presentation.title}
|
||||
description={description}
|
||||
testID={testID}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => ({
|
||||
body: {
|
||||
gap: theme.spacing[1],
|
||||
},
|
||||
bodyCentered: {
|
||||
alignItems: "center",
|
||||
},
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.4),
|
||||
},
|
||||
hostMessage: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.4),
|
||||
},
|
||||
textCentered: {
|
||||
textAlign: "center",
|
||||
},
|
||||
}));
|
||||
@@ -1,286 +0,0 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
dismissHostRefusalSheet,
|
||||
getActiveRefusalHostServerId,
|
||||
openHostRefusalSheet,
|
||||
registerActiveRefusalHost,
|
||||
resetHostRefusalSheetState,
|
||||
resolveHostRefusalSheetTarget,
|
||||
setHostRefusalFailed,
|
||||
setHostRefusalSubmitting,
|
||||
useHostRefusalSheetStore,
|
||||
type HostRefusalSnapshotSummary,
|
||||
} from "./host-refusal-sheet-state";
|
||||
|
||||
const PASSWORD_REJECTION: DaemonHelloRejection = {
|
||||
reason: "incorrect_password",
|
||||
accepts: ["password"],
|
||||
};
|
||||
|
||||
const EMPTY_SNAPSHOT: HostRefusalSnapshotSummary = {
|
||||
rejection: null,
|
||||
episode: 0,
|
||||
isOnline: false,
|
||||
};
|
||||
|
||||
describe("host-refusal-sheet-state", () => {
|
||||
beforeEach(() => {
|
||||
resetHostRefusalSheetState();
|
||||
});
|
||||
|
||||
it("auto-pops for the active host when refused and stays quiet when no host is active", () => {
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: null,
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("stays dismissed for the same refusal episode and re-pops on a new episode", () => {
|
||||
dismissHostRefusalSheet("srv_active", 1);
|
||||
const { dismissedEpisodes } = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 2 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 2,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("never cross-contaminates an online active host when another host has a stale manualOpen and refuses in background", () => {
|
||||
openHostRefusalSheet("srv_staging", 1);
|
||||
const state = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_local",
|
||||
activeSnapshot: EMPTY_SNAPSHOT,
|
||||
manualOpen: state.manualOpen,
|
||||
manualSnapshot: { rejection: PASSWORD_REJECTION, episode: 3 },
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: state.dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
});
|
||||
|
||||
it("reopens a dismissed episode when opened explicitly and keeps submitting mounted across transient clears", () => {
|
||||
dismissHostRefusalSheet("srv_active", 1);
|
||||
openHostRefusalSheet("srv_active", 1);
|
||||
const state = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: state.manualOpen,
|
||||
manualSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: state.dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: true,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
|
||||
setHostRefusalSubmitting("srv_active");
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: EMPTY_SNAPSHOT,
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: "srv_active",
|
||||
submittingSnapshot: { rejection: null, episode: 1 },
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: state.dismissedEpisodes,
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: null,
|
||||
episode: 1,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("keeps the sheet open with an actionable error after a failed retry or submit and expires once the host recovers", () => {
|
||||
setHostRefusalFailed({
|
||||
serverId: "srv_active",
|
||||
message: "Unable to connect to host",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
connectionEpoch: 1,
|
||||
});
|
||||
const { failedAction } = useHostRefusalSheetStore.getState();
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: EMPTY_SNAPSHOT,
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction,
|
||||
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 1, isOnline: false },
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_active",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: true,
|
||||
actionErrorMessage: "Unable to connect to host",
|
||||
});
|
||||
|
||||
// Auto-closes once the host comes back online (connectionEpoch increments to 2).
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_active",
|
||||
activeSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: true },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction,
|
||||
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: true },
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
// Even if that host later disconnects normally (still epoch 2, offline, no refusal), the stale
|
||||
// failedAction from epoch 1 never reactivates or blocks another host's refusal sheet.
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_other",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1, connectionEpoch: 0 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction,
|
||||
failedSnapshot: { rejection: null, episode: 1, connectionEpoch: 2, isOnline: false },
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: false,
|
||||
}),
|
||||
).toEqual({
|
||||
serverId: "srv_other",
|
||||
rejection: PASSWORD_REJECTION,
|
||||
episode: 1,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
});
|
||||
|
||||
// Explicitly opening another host's sheet also clears any prior failedAction immediately.
|
||||
openHostRefusalSheet("srv_other", 1);
|
||||
expect(useHostRefusalSheetStore.getState().failedAction).toBeNull();
|
||||
});
|
||||
|
||||
it("defers when a HostConfirmationSheet is active and stacks active scopes cleanly", () => {
|
||||
const unregisterFirst = registerActiveRefusalHost("srv_local");
|
||||
const unregisterSecond = registerActiveRefusalHost("srv_staging");
|
||||
|
||||
expect(getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes)).toBe(
|
||||
"srv_staging",
|
||||
);
|
||||
|
||||
expect(
|
||||
resolveHostRefusalSheetTarget({
|
||||
activeServerId: "srv_staging",
|
||||
activeSnapshot: { rejection: PASSWORD_REJECTION, episode: 1 },
|
||||
manualOpen: null,
|
||||
manualSnapshot: EMPTY_SNAPSHOT,
|
||||
submittingServerId: null,
|
||||
submittingSnapshot: EMPTY_SNAPSHOT,
|
||||
failedAction: null,
|
||||
failedSnapshot: EMPTY_SNAPSHOT,
|
||||
dismissedEpisodes: {},
|
||||
hasPendingConfirmation: true,
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
unregisterSecond();
|
||||
expect(getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes)).toBe(
|
||||
"srv_local",
|
||||
);
|
||||
unregisterFirst();
|
||||
expect(
|
||||
getActiveRefusalHostServerId(useHostRefusalSheetStore.getState().activeScopes),
|
||||
).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,234 +0,0 @@
|
||||
import { useEffect } from "react";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { create } from "zustand";
|
||||
import { getHostRuntimeStore } from "@/runtime/host-runtime";
|
||||
|
||||
export interface ActiveRefusalHostScope {
|
||||
id: number;
|
||||
serverId: string;
|
||||
}
|
||||
|
||||
export interface ManualRefusalSheetOpen {
|
||||
serverId: string;
|
||||
episode: number;
|
||||
}
|
||||
|
||||
export interface FailedRefusalSheetAction {
|
||||
serverId: string;
|
||||
message: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
connectionEpoch: number;
|
||||
}
|
||||
|
||||
export interface HostRefusalSnapshotSummary {
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
connectionEpoch?: number;
|
||||
isOnline?: boolean;
|
||||
}
|
||||
|
||||
export interface HostRefusalSheetState {
|
||||
activeScopes: ActiveRefusalHostScope[];
|
||||
manualOpen: ManualRefusalSheetOpen | null;
|
||||
submittingServerId: string | null;
|
||||
failedAction: FailedRefusalSheetAction | null;
|
||||
dismissedEpisodes: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface ResolveHostRefusalSheetTargetInput {
|
||||
activeServerId: string | null;
|
||||
activeSnapshot: HostRefusalSnapshotSummary;
|
||||
manualOpen: ManualRefusalSheetOpen | null;
|
||||
manualSnapshot: HostRefusalSnapshotSummary;
|
||||
submittingServerId: string | null;
|
||||
submittingSnapshot: HostRefusalSnapshotSummary;
|
||||
failedAction: FailedRefusalSheetAction | null;
|
||||
failedSnapshot: HostRefusalSnapshotSummary;
|
||||
dismissedEpisodes: Readonly<Record<string, number>>;
|
||||
hasPendingConfirmation: boolean;
|
||||
}
|
||||
|
||||
export interface HostRefusalSheetTarget {
|
||||
serverId: string;
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
isManual: boolean;
|
||||
actionErrorMessage: string | null;
|
||||
}
|
||||
|
||||
let nextScopeId = 1;
|
||||
|
||||
function createInitialState(): HostRefusalSheetState {
|
||||
return {
|
||||
activeScopes: [],
|
||||
manualOpen: null,
|
||||
submittingServerId: null,
|
||||
failedAction: null,
|
||||
dismissedEpisodes: {},
|
||||
};
|
||||
}
|
||||
|
||||
export const useHostRefusalSheetStore = create<HostRefusalSheetState>(() => createInitialState());
|
||||
|
||||
export function getActiveRefusalHostServerId(
|
||||
activeScopes: readonly ActiveRefusalHostScope[],
|
||||
): string | null {
|
||||
return activeScopes.length > 0 ? activeScopes[activeScopes.length - 1].serverId : null;
|
||||
}
|
||||
|
||||
export function resolveHostRefusalSheetTarget(
|
||||
input: ResolveHostRefusalSheetTargetInput,
|
||||
): HostRefusalSheetTarget | null {
|
||||
if (input.hasPendingConfirmation) return null;
|
||||
|
||||
if (input.submittingServerId) {
|
||||
return {
|
||||
serverId: input.submittingServerId,
|
||||
rejection: input.submittingSnapshot.rejection,
|
||||
episode: input.submittingSnapshot.episode,
|
||||
isManual: input.manualOpen?.serverId === input.submittingServerId,
|
||||
actionErrorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
input.failedAction &&
|
||||
!input.failedSnapshot.isOnline &&
|
||||
(input.failedSnapshot.connectionEpoch ?? 0) === input.failedAction.connectionEpoch
|
||||
) {
|
||||
return {
|
||||
serverId: input.failedAction.serverId,
|
||||
rejection: input.failedSnapshot.rejection ?? input.failedAction.rejection,
|
||||
episode: input.failedSnapshot.episode,
|
||||
isManual: true,
|
||||
actionErrorMessage: input.failedAction.message,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
input.manualOpen &&
|
||||
input.manualSnapshot.rejection !== null &&
|
||||
input.manualSnapshot.episode === input.manualOpen.episode
|
||||
) {
|
||||
return {
|
||||
serverId: input.manualOpen.serverId,
|
||||
rejection: input.manualSnapshot.rejection,
|
||||
episode: input.manualSnapshot.episode,
|
||||
isManual: true,
|
||||
actionErrorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
input.activeServerId &&
|
||||
input.activeSnapshot.rejection !== null &&
|
||||
input.dismissedEpisodes[input.activeServerId] !== input.activeSnapshot.episode
|
||||
) {
|
||||
return {
|
||||
serverId: input.activeServerId,
|
||||
rejection: input.activeSnapshot.rejection,
|
||||
episode: input.activeSnapshot.episode,
|
||||
isManual: false,
|
||||
actionErrorMessage: null,
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
export function registerActiveRefusalHost(serverId: string): () => void {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) return () => {};
|
||||
const id = nextScopeId++;
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
activeScopes: [...state.activeScopes, { id, serverId: normalized }],
|
||||
}));
|
||||
return () => {
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
activeScopes: state.activeScopes.filter((entry) => entry.id !== id),
|
||||
}));
|
||||
};
|
||||
}
|
||||
|
||||
export function useActiveRefusalHost(serverId: string | null | undefined, enabled = true): void {
|
||||
const normalized = serverId?.trim() ?? "";
|
||||
useEffect(() => {
|
||||
if (!enabled || !normalized) return;
|
||||
return registerActiveRefusalHost(normalized);
|
||||
}, [enabled, normalized]);
|
||||
}
|
||||
|
||||
export function openHostRefusalSheet(serverId: string, episode?: number): void {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) return;
|
||||
const resolvedEpisode =
|
||||
episode ?? getHostRuntimeStore().getSnapshot(normalized)?.helloRejectionEpisode ?? 0;
|
||||
useHostRefusalSheetStore.setState((state) => {
|
||||
const nextDismissed = { ...state.dismissedEpisodes };
|
||||
delete nextDismissed[normalized];
|
||||
return {
|
||||
manualOpen: { serverId: normalized, episode: resolvedEpisode },
|
||||
failedAction: null,
|
||||
dismissedEpisodes: nextDismissed,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
export function dismissHostRefusalSheet(serverId: string, episode: number): void {
|
||||
const normalized = serverId.trim();
|
||||
if (!normalized) return;
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
manualOpen: state.manualOpen?.serverId === normalized ? null : state.manualOpen,
|
||||
submittingServerId: state.submittingServerId === normalized ? null : state.submittingServerId,
|
||||
failedAction: state.failedAction?.serverId === normalized ? null : state.failedAction,
|
||||
dismissedEpisodes: {
|
||||
...state.dismissedEpisodes,
|
||||
[normalized]: episode,
|
||||
},
|
||||
}));
|
||||
}
|
||||
|
||||
export function setHostRefusalSubmitting(serverId: string | null): void {
|
||||
useHostRefusalSheetStore.setState((state) => ({
|
||||
submittingServerId: serverId,
|
||||
failedAction:
|
||||
serverId !== null && state.failedAction?.serverId === serverId ? null : state.failedAction,
|
||||
}));
|
||||
}
|
||||
|
||||
export function setHostRefusalFailed(input: {
|
||||
serverId: string;
|
||||
message: string;
|
||||
rejection: DaemonHelloRejection;
|
||||
connectionEpoch?: number;
|
||||
}): void {
|
||||
const normalized = input.serverId.trim();
|
||||
if (!normalized) return;
|
||||
const connectionEpoch =
|
||||
input.connectionEpoch ?? getHostRuntimeStore().getSnapshot(normalized)?.connectionEpoch ?? 0;
|
||||
useHostRefusalSheetStore.setState({
|
||||
failedAction: {
|
||||
serverId: normalized,
|
||||
message: input.message,
|
||||
rejection: input.rejection,
|
||||
connectionEpoch,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export function clearHostRefusalFailed(serverId: string): void {
|
||||
useHostRefusalSheetStore.setState((state) =>
|
||||
state.failedAction?.serverId === serverId ? { failedAction: null } : state,
|
||||
);
|
||||
}
|
||||
|
||||
export function clearManualHostRefusalOpen(serverId: string): void {
|
||||
useHostRefusalSheetStore.setState((state) =>
|
||||
state.manualOpen?.serverId === serverId ? { manualOpen: null } : state,
|
||||
);
|
||||
}
|
||||
|
||||
export function resetHostRefusalSheetState(): void {
|
||||
nextScopeId = 1;
|
||||
useHostRefusalSheetStore.setState(createInitialState());
|
||||
}
|
||||
@@ -1,611 +0,0 @@
|
||||
import { useCallback, useMemo, useReducer, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import {
|
||||
Text,
|
||||
View,
|
||||
type PressableStateCallbackType,
|
||||
type StyleProp,
|
||||
type ViewStyle,
|
||||
} from "react-native";
|
||||
import { AlertTriangle, Eye, EyeOff } from "lucide-react-native";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
AdaptiveModalSheet,
|
||||
SheetHeaderSubtitle,
|
||||
type SheetHeader,
|
||||
} from "@/components/adaptive-modal-sheet";
|
||||
import { Alert as InlineAlert } from "@/components/ui/alert";
|
||||
import { HeaderToggleButton } from "@/components/headers/header-toggle-button";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
CONTROL_HEIGHTS,
|
||||
createControlGeometry,
|
||||
resolveControlInteractionStyles,
|
||||
} from "@/components/ui/control-geometry";
|
||||
import { Field, FormTextInput } from "@/components/ui/form-field";
|
||||
import { iconButtonChromeGlyphSize } from "@/components/ui/icon-button-chrome";
|
||||
import { PressHighlight } from "@/components/ui/press-highlight";
|
||||
import { useIsCompactFormFactor } from "@/constants/layout";
|
||||
import { getIsElectron, isWeb } from "@/constants/platform";
|
||||
import {
|
||||
getHostRefusalActionLabel,
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
type HostRefusalAction,
|
||||
} from "@/hosts/host-refusal";
|
||||
import { useHostRefusalAction } from "@/hosts/host-refusal-alert";
|
||||
import {
|
||||
clearHostRefusalFailed,
|
||||
clearManualHostRefusalOpen,
|
||||
dismissHostRefusalSheet,
|
||||
getActiveRefusalHostServerId,
|
||||
openHostRefusalSheet,
|
||||
resolveHostRefusalSheetTarget,
|
||||
setHostRefusalFailed,
|
||||
setHostRefusalSubmitting,
|
||||
useHostRefusalSheetStore,
|
||||
} from "@/hosts/host-refusal-sheet-state";
|
||||
import {
|
||||
getHostRuntimeStore,
|
||||
useHostConfirmation,
|
||||
useHostMutations,
|
||||
useHostRuntimeHelloRejection,
|
||||
useHostRuntimeSnapshot,
|
||||
useHosts,
|
||||
} from "@/runtime/host-runtime";
|
||||
import type { ShortcutKey } from "@/utils/format-shortcut";
|
||||
|
||||
const FLEX_ONE_STYLE = { flex: 1 } as const;
|
||||
const NO_SHORTCUT: ShortcutKey[] = [];
|
||||
const ThemedEye = withUnistyles(Eye, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
const ThemedEyeOff = withUnistyles(EyeOff, (theme) => ({ color: theme.colors.foregroundMuted }));
|
||||
const ThemedAlertTriangle = withUnistyles(AlertTriangle, (theme) => ({
|
||||
color: theme.colors.destructive,
|
||||
}));
|
||||
|
||||
function toRefusalSnapshotSummary(snapshot: ReturnType<typeof useHostRuntimeSnapshot>): {
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
connectionEpoch: number;
|
||||
isOnline: boolean;
|
||||
} {
|
||||
return {
|
||||
rejection: snapshot?.helloRejection ?? null,
|
||||
episode: snapshot?.helloRejectionEpisode ?? 0,
|
||||
connectionEpoch: snapshot?.connectionEpoch ?? 0,
|
||||
isOnline: snapshot?.connectionStatus === "online",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Mount once at the app root. Auto-pops for the active host when refused, stays quiet for
|
||||
* background hosts, and reopens on explicit user action.
|
||||
*/
|
||||
export function HostRefusalSheetHost() {
|
||||
const activeScopes = useHostRefusalSheetStore((state) => state.activeScopes);
|
||||
const manualOpen = useHostRefusalSheetStore((state) => state.manualOpen);
|
||||
const submittingServerId = useHostRefusalSheetStore((state) => state.submittingServerId);
|
||||
const failedAction = useHostRefusalSheetStore((state) => state.failedAction);
|
||||
const dismissedEpisodes = useHostRefusalSheetStore((state) => state.dismissedEpisodes);
|
||||
const { pending: pendingConfirmation } = useHostConfirmation();
|
||||
|
||||
const activeServerId = getActiveRefusalHostServerId(activeScopes);
|
||||
const activeSnapshot = useHostRuntimeSnapshot(activeServerId ?? "");
|
||||
const manualSnapshot = useHostRuntimeSnapshot(manualOpen?.serverId ?? "");
|
||||
const submittingSnapshot = useHostRuntimeSnapshot(submittingServerId ?? "");
|
||||
const failedSnapshot = useHostRuntimeSnapshot(failedAction?.serverId ?? "");
|
||||
|
||||
const target = resolveHostRefusalSheetTarget({
|
||||
activeServerId,
|
||||
activeSnapshot: toRefusalSnapshotSummary(activeSnapshot),
|
||||
manualOpen,
|
||||
manualSnapshot: toRefusalSnapshotSummary(manualSnapshot),
|
||||
submittingServerId,
|
||||
submittingSnapshot: toRefusalSnapshotSummary(submittingSnapshot),
|
||||
failedAction,
|
||||
failedSnapshot: toRefusalSnapshotSummary(failedSnapshot),
|
||||
dismissedEpisodes,
|
||||
hasPendingConfirmation: pendingConfirmation !== null,
|
||||
});
|
||||
|
||||
if (!target) return null;
|
||||
|
||||
return (
|
||||
<HostRefusalSheet
|
||||
key={target.serverId}
|
||||
serverId={target.serverId}
|
||||
rejection={target.rejection}
|
||||
episode={target.episode}
|
||||
actionErrorMessage={target.actionErrorMessage}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
/** Compact warning icon button in workspace headers that reopens `HostRefusalSheet`. */
|
||||
export function HostRefusalHeaderButton({ serverId }: { serverId: string }) {
|
||||
const { t } = useTranslation();
|
||||
const rejection = useHostRuntimeHelloRejection(serverId);
|
||||
const hosts = useHosts();
|
||||
const hostName = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId)?.label?.trim() || serverId,
|
||||
[hosts, serverId],
|
||||
);
|
||||
|
||||
const handlePress = useCallback(() => {
|
||||
if (serverId) openHostRefusalSheet(serverId);
|
||||
}, [serverId]);
|
||||
|
||||
if (!serverId || !rejection) return null;
|
||||
|
||||
const presentation = resolveHostRefusal({
|
||||
rejection,
|
||||
hostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
});
|
||||
|
||||
return (
|
||||
<HeaderToggleButton
|
||||
onPress={handlePress}
|
||||
tooltipLabel={presentation.shortStatus}
|
||||
tooltipKeys={NO_SHORTCUT}
|
||||
tooltipSide="bottom"
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={presentation.shortStatus}
|
||||
testID="workspace-refusal-header-button"
|
||||
>
|
||||
<ThemedAlertTriangle size={iconButtonChromeGlyphSize("large")} />
|
||||
</HeaderToggleButton>
|
||||
);
|
||||
}
|
||||
|
||||
interface HostRefusalSheetProps {
|
||||
serverId: string;
|
||||
rejection: DaemonHelloRejection | null;
|
||||
episode: number;
|
||||
actionErrorMessage: string | null;
|
||||
}
|
||||
|
||||
function HostRefusalSheet({
|
||||
serverId,
|
||||
rejection,
|
||||
episode,
|
||||
actionErrorMessage,
|
||||
}: HostRefusalSheetProps) {
|
||||
const { t } = useTranslation();
|
||||
const isCompact = useIsCompactFormFactor();
|
||||
const hosts = useHosts();
|
||||
const { submitHostPassword } = useHostMutations();
|
||||
const runRefusalAction = useHostRefusalAction(serverId);
|
||||
const hostName = useMemo(
|
||||
() => hosts.find((entry) => entry.serverId === serverId)?.label?.trim() || serverId,
|
||||
[hosts, serverId],
|
||||
);
|
||||
const controlSize = isCompact ? "md" : "sm";
|
||||
|
||||
const [retainedRejection, setRetainedRejection] = useState<DaemonHelloRejection | null>(
|
||||
rejection,
|
||||
);
|
||||
if (rejection !== null && rejection !== retainedRejection) {
|
||||
setRetainedRejection(rejection);
|
||||
}
|
||||
const effectiveRejection = rejection ?? retainedRejection;
|
||||
|
||||
const [password, setPassword] = useState("");
|
||||
const [isPasswordVisible, setIsPasswordVisible] = useState(false);
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [resetCount, bumpResetCount] = useReducer((count: number) => count + 1, 0);
|
||||
|
||||
const presentation = useMemo(
|
||||
() =>
|
||||
effectiveRejection
|
||||
? resolveHostRefusal({
|
||||
rejection: effectiveRejection,
|
||||
hostName,
|
||||
t,
|
||||
canUpdateApp: getIsElectron(),
|
||||
canScanQr: !isWeb,
|
||||
})
|
||||
: null,
|
||||
[effectiveRejection, hostName, t],
|
||||
);
|
||||
|
||||
const showPasswordForm = effectiveRejection !== null && isPasswordRefusal(effectiveRejection);
|
||||
|
||||
const header = useMemo<SheetHeader>(
|
||||
() => ({
|
||||
title: presentation?.title ?? "",
|
||||
titleTestID: "host-refusal-sheet-title",
|
||||
subtitle: <SheetHeaderSubtitle text={hostName} testID="host-refusal-sheet-host" />,
|
||||
}),
|
||||
[hostName, presentation?.title],
|
||||
);
|
||||
|
||||
const handleDismiss = useCallback(() => {
|
||||
if (isSubmitting) return;
|
||||
dismissHostRefusalSheet(serverId, episode);
|
||||
}, [episode, isSubmitting, serverId]);
|
||||
|
||||
const handlePasswordChange = useCallback((value: string) => {
|
||||
setPassword(value);
|
||||
setErrorMessage(null);
|
||||
}, []);
|
||||
|
||||
const handleToggleVisibility = useCallback(() => {
|
||||
setIsPasswordVisible((visible) => !visible);
|
||||
}, []);
|
||||
|
||||
const handlePasswordSubmit = useCallback(async () => {
|
||||
if (isSubmitting) return;
|
||||
if (password.length === 0) {
|
||||
setErrorMessage(t("hostRefusal.passwordSheet.requiredError"));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
setHostRefusalSubmitting(serverId);
|
||||
setErrorMessage(null);
|
||||
try {
|
||||
const result = await submitHostPassword(serverId, password);
|
||||
if (result.status === "online") {
|
||||
clearManualHostRefusalOpen(serverId);
|
||||
clearHostRefusalFailed(serverId);
|
||||
return;
|
||||
}
|
||||
if (result.status === "rejected") {
|
||||
clearHostRefusalFailed(serverId);
|
||||
if (useHostRefusalSheetStore.getState().manualOpen?.serverId === serverId) {
|
||||
openHostRefusalSheet(serverId);
|
||||
}
|
||||
if (result.rejection.reason === "incorrect_password") {
|
||||
setPassword("");
|
||||
bumpResetCount();
|
||||
setErrorMessage(t("hostRefusal.incorrectPassword.title"));
|
||||
return;
|
||||
}
|
||||
setErrorMessage(null);
|
||||
return;
|
||||
}
|
||||
const message = result.message || t("pairing.direct.errors.unableToConnect");
|
||||
if (effectiveRejection) {
|
||||
setHostRefusalFailed({ serverId, message, rejection: effectiveRejection });
|
||||
}
|
||||
setErrorMessage(message);
|
||||
} finally {
|
||||
setHostRefusalSubmitting(null);
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
}, [effectiveRejection, isSubmitting, password, serverId, submitHostPassword, t]);
|
||||
|
||||
const handleSubmitPress = useCallback(() => {
|
||||
void handlePasswordSubmit();
|
||||
}, [handlePasswordSubmit]);
|
||||
|
||||
const executeNonPasswordAction = useCallback(
|
||||
async (action: HostRefusalAction) => {
|
||||
if (isSubmitting) return;
|
||||
if (action.kind === "retry") {
|
||||
setIsSubmitting(true);
|
||||
setHostRefusalSubmitting(serverId);
|
||||
try {
|
||||
await getHostRuntimeStore().runProbeCycleNow(serverId, { clearRefusals: true });
|
||||
const next = getHostRuntimeStore().getSnapshot(serverId);
|
||||
if (next?.connectionStatus === "online") {
|
||||
clearManualHostRefusalOpen(serverId);
|
||||
clearHostRefusalFailed(serverId);
|
||||
} else if (next?.helloRejection) {
|
||||
clearHostRefusalFailed(serverId);
|
||||
} else {
|
||||
const message = next?.lastError?.trim() || t("pairing.direct.errors.unableToConnect");
|
||||
if (effectiveRejection) {
|
||||
setHostRefusalFailed({
|
||||
serverId,
|
||||
message,
|
||||
rejection: effectiveRejection,
|
||||
connectionEpoch: next?.connectionEpoch,
|
||||
});
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
setHostRefusalSubmitting(null);
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
dismissHostRefusalSheet(serverId, episode);
|
||||
runRefusalAction(action);
|
||||
},
|
||||
[effectiveRejection, episode, isSubmitting, runRefusalAction, serverId, t],
|
||||
);
|
||||
|
||||
const handlePrimaryPress = useCallback(() => {
|
||||
if (!presentation) return;
|
||||
void executeNonPasswordAction(presentation.primaryAction);
|
||||
}, [executeNonPasswordAction, presentation]);
|
||||
|
||||
const handleSecondaryPress = useCallback(() => {
|
||||
if (!presentation?.secondaryAction) return;
|
||||
void executeNonPasswordAction(presentation.secondaryAction);
|
||||
}, [executeNonPasswordAction, presentation]);
|
||||
|
||||
const primaryButtonLabel = useMemo(() => {
|
||||
if (isSubmitting) return t("hostRefusal.passwordSheet.connecting");
|
||||
if (showPasswordForm) return t("hostRefusal.passwordSheet.connect");
|
||||
return presentation ? getHostRefusalActionLabel(presentation.primaryAction, t) : "";
|
||||
}, [isSubmitting, presentation, showPasswordForm, t]);
|
||||
|
||||
const footer = useMemo(
|
||||
() => (
|
||||
<View style={styles.footer}>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="secondary"
|
||||
size={controlSize}
|
||||
onPress={handleDismiss}
|
||||
disabled={isSubmitting}
|
||||
testID="host-refusal-sheet-dismiss"
|
||||
>
|
||||
{t("common.actions.dismiss")}
|
||||
</Button>
|
||||
<Button
|
||||
style={FLEX_ONE_STYLE}
|
||||
variant="default"
|
||||
size={controlSize}
|
||||
onPress={showPasswordForm ? handleSubmitPress : handlePrimaryPress}
|
||||
disabled={isSubmitting}
|
||||
testID={
|
||||
showPasswordForm ? "host-refusal-sheet-submit" : "host-refusal-sheet-primary-action"
|
||||
}
|
||||
>
|
||||
{primaryButtonLabel}
|
||||
</Button>
|
||||
</View>
|
||||
),
|
||||
[
|
||||
controlSize,
|
||||
handleDismiss,
|
||||
handlePrimaryPress,
|
||||
handleSubmitPress,
|
||||
isSubmitting,
|
||||
primaryButtonLabel,
|
||||
showPasswordForm,
|
||||
t,
|
||||
],
|
||||
);
|
||||
|
||||
if (!effectiveRejection || !presentation) return null;
|
||||
|
||||
return (
|
||||
<AdaptiveModalSheet
|
||||
header={header}
|
||||
visible
|
||||
onClose={handleDismiss}
|
||||
footer={footer}
|
||||
testID="host-refusal-sheet"
|
||||
>
|
||||
<View style={styles.content}>
|
||||
{presentation.description ? (
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
style={styles.description}
|
||||
testID="host-refusal-sheet-description"
|
||||
>
|
||||
{presentation.description}
|
||||
</Text>
|
||||
) : null}
|
||||
|
||||
{presentation.hostMessage ? (
|
||||
<View style={styles.hostMessageCard}>
|
||||
<Text
|
||||
dataDetectorType="none"
|
||||
style={styles.hostMessage}
|
||||
testID="host-refusal-sheet-host-message"
|
||||
>
|
||||
{presentation.hostMessage}
|
||||
</Text>
|
||||
</View>
|
||||
) : null}
|
||||
|
||||
{showPasswordForm ? (
|
||||
<HostRefusalPasswordField
|
||||
serverId={serverId}
|
||||
controlSize={controlSize}
|
||||
resetCount={resetCount}
|
||||
errorMessage={errorMessage ?? actionErrorMessage}
|
||||
isPasswordVisible={isPasswordVisible}
|
||||
isSubmitting={isSubmitting}
|
||||
onChangeText={handlePasswordChange}
|
||||
onToggleVisibility={handleToggleVisibility}
|
||||
onSubmit={handleSubmitPress}
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!showPasswordForm && actionErrorMessage ? (
|
||||
<InlineAlert
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={actionErrorMessage}
|
||||
testID="host-refusal-sheet-error"
|
||||
/>
|
||||
) : null}
|
||||
|
||||
{!showPasswordForm && presentation.secondaryAction ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size={controlSize}
|
||||
onPress={handleSecondaryPress}
|
||||
disabled={isSubmitting}
|
||||
testID="host-refusal-sheet-secondary-action"
|
||||
>
|
||||
{getHostRefusalActionLabel(presentation.secondaryAction, t)}
|
||||
</Button>
|
||||
) : null}
|
||||
</View>
|
||||
</AdaptiveModalSheet>
|
||||
);
|
||||
}
|
||||
|
||||
function HostRefusalPasswordField({
|
||||
serverId,
|
||||
controlSize,
|
||||
resetCount,
|
||||
errorMessage,
|
||||
isPasswordVisible,
|
||||
isSubmitting,
|
||||
onChangeText,
|
||||
onToggleVisibility,
|
||||
onSubmit,
|
||||
}: {
|
||||
serverId: string;
|
||||
controlSize: "sm" | "md";
|
||||
resetCount: number;
|
||||
errorMessage: string | null;
|
||||
isPasswordVisible: boolean;
|
||||
isSubmitting: boolean;
|
||||
onChangeText: (value: string) => void;
|
||||
onToggleVisibility: () => void;
|
||||
onSubmit: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const iconButtonStyle = useCallback(
|
||||
(
|
||||
state: PressableStateCallbackType & { hovered?: boolean; focused?: boolean },
|
||||
): StyleProp<ViewStyle> => [
|
||||
styles.iconButton,
|
||||
controlSize === "sm" ? styles.iconButtonSm : styles.iconButtonMd,
|
||||
resolveControlInteractionStyles(
|
||||
{
|
||||
controlRest: styles.controlRest,
|
||||
controlHover: styles.controlHover,
|
||||
controlActive: styles.controlActive,
|
||||
controlDisabled: styles.controlDisabled,
|
||||
},
|
||||
{
|
||||
hovered: state.hovered,
|
||||
pressed: state.pressed,
|
||||
focused: state.focused,
|
||||
disabled: isSubmitting,
|
||||
},
|
||||
),
|
||||
],
|
||||
[controlSize, isSubmitting],
|
||||
);
|
||||
|
||||
return (
|
||||
<Field
|
||||
label={t("hostRefusal.passwordSheet.label")}
|
||||
error={errorMessage}
|
||||
testID="host-password-field"
|
||||
>
|
||||
<View style={styles.passwordRow}>
|
||||
<View style={styles.passwordInputWrap}>
|
||||
<FormTextInput
|
||||
testID="host-password-input"
|
||||
nativeID="host-password-input"
|
||||
size={controlSize}
|
||||
resetKey={`host-password-${serverId}-${resetCount}`}
|
||||
initialValue=""
|
||||
accessibilityLabel={t("hostRefusal.passwordSheet.label")}
|
||||
placeholder={t("hostRefusal.passwordSheet.placeholder")}
|
||||
onChangeText={onChangeText}
|
||||
autoFocus
|
||||
secureTextEntry={!isPasswordVisible}
|
||||
autoCapitalize="none"
|
||||
autoCorrect={false}
|
||||
editable={!isSubmitting}
|
||||
invalid={errorMessage !== null}
|
||||
returnKeyType="done"
|
||||
onSubmitEditing={onSubmit}
|
||||
/>
|
||||
</View>
|
||||
<PressHighlight
|
||||
style={iconButtonStyle}
|
||||
onPress={onToggleVisibility}
|
||||
disabled={isSubmitting}
|
||||
accessibilityRole="button"
|
||||
accessibilityLabel={
|
||||
isPasswordVisible
|
||||
? t("pairing.direct.passwordVisibility.hide")
|
||||
: t("pairing.direct.passwordVisibility.show")
|
||||
}
|
||||
testID="host-password-visibility-toggle"
|
||||
>
|
||||
{isPasswordVisible ? <ThemedEyeOff size={18} /> : <ThemedEye size={18} />}
|
||||
</PressHighlight>
|
||||
</View>
|
||||
</Field>
|
||||
);
|
||||
}
|
||||
|
||||
const styles = StyleSheet.create((theme) => {
|
||||
const geometry = createControlGeometry(theme);
|
||||
return {
|
||||
content: {
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
description: {
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: Math.round(theme.fontSize.base * 1.45),
|
||||
},
|
||||
hostMessageCard: {
|
||||
backgroundColor: theme.colors.surface2,
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
borderWidth: 1,
|
||||
borderColor: theme.colors.border,
|
||||
paddingHorizontal: theme.spacing[3],
|
||||
paddingVertical: theme.spacing[3],
|
||||
},
|
||||
hostMessage: {
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.sm,
|
||||
lineHeight: Math.round(theme.fontSize.sm * 1.45),
|
||||
},
|
||||
passwordRow: {
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
alignSelf: "stretch",
|
||||
width: "100%",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
passwordInputWrap: {
|
||||
flex: 1,
|
||||
minWidth: 0,
|
||||
},
|
||||
iconButton: {
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
borderRadius: theme.borderRadius.lg,
|
||||
backgroundColor: theme.colors.surface2,
|
||||
},
|
||||
iconButtonSm: {
|
||||
minHeight: CONTROL_HEIGHTS.sm,
|
||||
width: CONTROL_HEIGHTS.sm,
|
||||
},
|
||||
iconButtonMd: {
|
||||
minHeight: CONTROL_HEIGHTS.md,
|
||||
width: CONTROL_HEIGHTS.md,
|
||||
},
|
||||
controlRest: {
|
||||
...geometry.controlRest,
|
||||
},
|
||||
controlHover: {
|
||||
...geometry.controlHover,
|
||||
},
|
||||
controlActive: {
|
||||
...geometry.controlActive,
|
||||
},
|
||||
controlDisabled: {
|
||||
...geometry.controlDisabled,
|
||||
},
|
||||
footer: {
|
||||
flex: 1,
|
||||
flexDirection: "row",
|
||||
gap: theme.spacing[3],
|
||||
},
|
||||
};
|
||||
});
|
||||
@@ -1,231 +0,0 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { TFunction } from "i18next";
|
||||
import { en } from "@/i18n/resources/en";
|
||||
import {
|
||||
SUPPORTED_CREDENTIAL_KINDS,
|
||||
getHostRefusalActionLabel,
|
||||
isPasswordRefusal,
|
||||
resolveHostRefusal,
|
||||
} from "./host-refusal";
|
||||
|
||||
function createTestT(): TFunction {
|
||||
const resolveKey = (key: string): string => {
|
||||
const parts = key.split(".");
|
||||
let current: unknown = en;
|
||||
for (const part of parts) {
|
||||
if (current && typeof current === "object" && part in current) {
|
||||
current = (current as Record<string, unknown>)[part];
|
||||
} else {
|
||||
throw new Error(`Missing i18n key in en: ${key}`);
|
||||
}
|
||||
}
|
||||
if (typeof current !== "string") {
|
||||
throw new Error(`Expected string for i18n key: ${key}`);
|
||||
}
|
||||
return current;
|
||||
};
|
||||
return ((key: string, params?: Record<string, unknown>) => {
|
||||
let text = resolveKey(key);
|
||||
if (params) {
|
||||
for (const [name, value] of Object.entries(params)) {
|
||||
text = text.replaceAll(`{{${name}}}`, String(value));
|
||||
}
|
||||
}
|
||||
return text;
|
||||
}) as unknown as TFunction;
|
||||
}
|
||||
|
||||
describe("resolveHostRefusal", () => {
|
||||
const t = createTestT();
|
||||
|
||||
it("uses trusted localized copy and ignores host message for known reasons", () => {
|
||||
const passwordRequired = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "password_required",
|
||||
accepts: ["password"],
|
||||
message: "Visit https://evil.test for password",
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
});
|
||||
expect(passwordRequired).toEqual({
|
||||
title: "Password required",
|
||||
description: "Enter this host's password to connect.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Password required",
|
||||
primaryAction: { kind: "enter_password" },
|
||||
});
|
||||
|
||||
const incorrectPassword = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "incorrect_password",
|
||||
accepts: ["password"],
|
||||
message: "Phishing text",
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
});
|
||||
expect(incorrectPassword).toEqual({
|
||||
title: "Incorrect password",
|
||||
description: "The saved password was rejected by this host.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Password required",
|
||||
primaryAction: { kind: "enter_password" },
|
||||
});
|
||||
|
||||
const incompatibleDesktop = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
message: "Download from https://evil.test",
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
canUpdateApp: true,
|
||||
});
|
||||
expect(incompatibleDesktop).toEqual({
|
||||
title: "Update Paseo to connect",
|
||||
description: "This host requires a newer version of Paseo.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Update required",
|
||||
primaryAction: { kind: "update_app" },
|
||||
});
|
||||
|
||||
const incompatibleWeb = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
},
|
||||
hostName: "Dev Box",
|
||||
t,
|
||||
canUpdateApp: false,
|
||||
});
|
||||
expect(incompatibleWeb.primaryAction).toEqual({ kind: "retry" });
|
||||
});
|
||||
|
||||
it("offers password recovery when an unknown reason accepts password", () => {
|
||||
const result = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "password_expired",
|
||||
accepts: ["password"],
|
||||
message: "Rotate your password.",
|
||||
},
|
||||
hostName: "Staging",
|
||||
t,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
title: "Password required",
|
||||
description: null,
|
||||
hostMessage: "Message from Staging: “Rotate your password.”",
|
||||
shortStatus: "Password required",
|
||||
primaryAction: { kind: "enter_password" },
|
||||
});
|
||||
expect(isPasswordRefusal({ reason: "password_expired", accepts: ["password"] })).toBe(true);
|
||||
});
|
||||
|
||||
it("asks to update Paseo when an unknown reason requires an unsupported credential kind", () => {
|
||||
expect(SUPPORTED_CREDENTIAL_KINDS).toEqual(["password"]);
|
||||
const result = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Visit https://evil.test",
|
||||
},
|
||||
hostName: "Prod Box",
|
||||
t,
|
||||
canUpdateApp: true,
|
||||
});
|
||||
expect(result).toEqual({
|
||||
title: "Update Paseo to connect",
|
||||
description: "This host requires a sign-in method this version of Paseo does not support.",
|
||||
hostMessage: "Message from Prod Box: “Visit https://evil.test”",
|
||||
shortStatus: "Update required",
|
||||
primaryAction: { kind: "update_app" },
|
||||
});
|
||||
expect(isPasswordRefusal({ reason: "pairing_required", accepts: ["invite"] })).toBe(false);
|
||||
});
|
||||
|
||||
it("automatically offers pairing actions once invite is in supportedCredentials", () => {
|
||||
const mobile = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite", "password"],
|
||||
message: "Device access expired.",
|
||||
},
|
||||
hostName: "Prod Box",
|
||||
t,
|
||||
supportedCredentials: ["password", "invite"],
|
||||
canScanQr: true,
|
||||
});
|
||||
expect(mobile).toEqual({
|
||||
title: "Pairing required",
|
||||
description: null,
|
||||
hostMessage: "Message from Prod Box: “Device access expired.”",
|
||||
shortStatus: "Pairing required",
|
||||
primaryAction: { kind: "scan_qr" },
|
||||
secondaryAction: { kind: "pair_link" },
|
||||
});
|
||||
|
||||
const desktop = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite", "password"],
|
||||
},
|
||||
hostName: "Prod Box",
|
||||
t,
|
||||
supportedCredentials: ["password", "invite"],
|
||||
canScanQr: false,
|
||||
});
|
||||
expect(desktop).toEqual({
|
||||
title: "Pairing required",
|
||||
description: "Pair this device with the host again to connect.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Pairing required",
|
||||
primaryAction: { kind: "pair_link" },
|
||||
secondaryAction: { kind: "enter_password" },
|
||||
});
|
||||
});
|
||||
|
||||
it("frames unknown non-credential refusals as host speech with Retry", () => {
|
||||
const withMessage = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
},
|
||||
hostName: "Build Server",
|
||||
t,
|
||||
});
|
||||
expect(withMessage).toEqual({
|
||||
title: "Connection refused by Build Server",
|
||||
description: null,
|
||||
hostMessage: "Message from Build Server: “Back in 5m”",
|
||||
shortStatus: "Refused",
|
||||
primaryAction: { kind: "retry" },
|
||||
});
|
||||
|
||||
const withoutMessage = resolveHostRefusal({
|
||||
rejection: {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
},
|
||||
hostName: "Build Server",
|
||||
t,
|
||||
});
|
||||
expect(withoutMessage).toEqual({
|
||||
title: "Connection refused by Build Server",
|
||||
description: "Check this host's settings and try again.",
|
||||
hostMessage: null,
|
||||
shortStatus: "Refused",
|
||||
primaryAction: { kind: "retry" },
|
||||
});
|
||||
});
|
||||
|
||||
it("maps every HostRefusalAction to a localized label", () => {
|
||||
expect(getHostRefusalActionLabel({ kind: "enter_password" }, t)).toBe("Enter password");
|
||||
expect(getHostRefusalActionLabel({ kind: "pair_link" }, t)).toBe("Paste pairing link");
|
||||
expect(getHostRefusalActionLabel({ kind: "scan_qr" }, t)).toBe("Scan QR code");
|
||||
expect(getHostRefusalActionLabel({ kind: "update_app" }, t)).toBe("Check for updates");
|
||||
expect(getHostRefusalActionLabel({ kind: "retry" }, t)).toBe("Retry");
|
||||
});
|
||||
});
|
||||
@@ -1,169 +0,0 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { TFunction } from "i18next";
|
||||
|
||||
export const SUPPORTED_CREDENTIAL_KINDS = ["password"] as const;
|
||||
export type SupportedCredentialKind = (typeof SUPPORTED_CREDENTIAL_KINDS)[number];
|
||||
|
||||
export type HostRefusalAction =
|
||||
| { kind: "enter_password" }
|
||||
| { kind: "pair_link" }
|
||||
| { kind: "scan_qr" }
|
||||
| { kind: "update_app" }
|
||||
| { kind: "retry" };
|
||||
|
||||
export interface HostRefusalPresentation {
|
||||
readonly title: string;
|
||||
readonly description: string | null;
|
||||
readonly hostMessage: string | null;
|
||||
readonly shortStatus: string;
|
||||
readonly primaryAction: HostRefusalAction;
|
||||
readonly secondaryAction?: HostRefusalAction;
|
||||
}
|
||||
|
||||
export interface ResolveHostRefusalOptions {
|
||||
readonly rejection: DaemonHelloRejection;
|
||||
readonly hostName: string;
|
||||
readonly t: TFunction;
|
||||
readonly supportedCredentials?: readonly string[];
|
||||
readonly canUpdateApp?: boolean;
|
||||
readonly canScanQr?: boolean;
|
||||
}
|
||||
|
||||
export function isPasswordRefusal(
|
||||
rejection: DaemonHelloRejection,
|
||||
supportedCredentials: readonly string[] = SUPPORTED_CREDENTIAL_KINDS,
|
||||
): boolean {
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return true;
|
||||
}
|
||||
if (rejection.reason === "incompatible_protocol") {
|
||||
return false;
|
||||
}
|
||||
return supportedCredentials.includes("password") && rejection.accepts.includes("password");
|
||||
}
|
||||
|
||||
function resolveKnownHostRefusal(
|
||||
reason: string,
|
||||
t: TFunction,
|
||||
canUpdateApp: boolean,
|
||||
): HostRefusalPresentation | null {
|
||||
// Known reasons ignore rejection.message completely and render only trusted client copy.
|
||||
if (reason === "password_required") {
|
||||
return {
|
||||
title: t("hostRefusal.passwordRequired.title"),
|
||||
description: t("hostRefusal.passwordRequired.description"),
|
||||
hostMessage: null,
|
||||
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
|
||||
primaryAction: { kind: "enter_password" },
|
||||
};
|
||||
}
|
||||
if (reason === "incorrect_password") {
|
||||
return {
|
||||
title: t("hostRefusal.incorrectPassword.title"),
|
||||
description: t("hostRefusal.incorrectPassword.description"),
|
||||
hostMessage: null,
|
||||
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
|
||||
primaryAction: { kind: "enter_password" },
|
||||
};
|
||||
}
|
||||
if (reason === "incompatible_protocol") {
|
||||
return {
|
||||
title: t("hostRefusal.updateRequired.title"),
|
||||
description: t("hostRefusal.updateRequired.incompatibleDescription"),
|
||||
hostMessage: null,
|
||||
shortStatus: t("hostRefusal.shortStatus.updateRequired"),
|
||||
primaryAction: canUpdateApp ? { kind: "update_app" } : { kind: "retry" },
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function resolveInviteSecondaryAction(
|
||||
canScanQr: boolean,
|
||||
acceptsPassword: boolean,
|
||||
): HostRefusalAction | undefined {
|
||||
if (canScanQr) return { kind: "pair_link" };
|
||||
if (acceptsPassword) return { kind: "enter_password" };
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolveHostRefusal(options: ResolveHostRefusalOptions): HostRefusalPresentation {
|
||||
const {
|
||||
rejection,
|
||||
hostName,
|
||||
t,
|
||||
supportedCredentials = SUPPORTED_CREDENTIAL_KINDS,
|
||||
canUpdateApp = false,
|
||||
canScanQr = false,
|
||||
} = options;
|
||||
|
||||
const known = resolveKnownHostRefusal(rejection.reason, t, canUpdateApp);
|
||||
if (known) return known;
|
||||
|
||||
const supportedSet = new Set<string>(supportedCredentials);
|
||||
const supportedAccepts = rejection.accepts.filter((kind) => supportedSet.has(kind));
|
||||
const hostMessage = rejection.message
|
||||
? t("hostRefusal.messageFromHost", { hostName, message: rejection.message })
|
||||
: null;
|
||||
|
||||
if (supportedAccepts.includes("invite")) {
|
||||
const primaryAction: HostRefusalAction = canScanQr
|
||||
? { kind: "scan_qr" }
|
||||
: { kind: "pair_link" };
|
||||
const secondaryAction = resolveInviteSecondaryAction(
|
||||
canScanQr,
|
||||
supportedAccepts.includes("password"),
|
||||
);
|
||||
return {
|
||||
title: t("hostRefusal.pairingRequired.title"),
|
||||
description: hostMessage ? null : t("hostRefusal.pairingRequired.description"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.pairingRequired"),
|
||||
primaryAction,
|
||||
...(secondaryAction ? { secondaryAction } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (supportedAccepts.includes("password")) {
|
||||
return {
|
||||
title: t("hostRefusal.passwordRequired.title"),
|
||||
description: hostMessage ? null : t("hostRefusal.passwordRequired.description"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.passwordRequired"),
|
||||
primaryAction: { kind: "enter_password" },
|
||||
};
|
||||
}
|
||||
|
||||
if (rejection.accepts.length > 0 && supportedAccepts.length === 0) {
|
||||
return {
|
||||
title: t("hostRefusal.updateRequired.title"),
|
||||
description: t("hostRefusal.updateRequired.unsupportedAuthDescription"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.updateRequired"),
|
||||
primaryAction: canUpdateApp ? { kind: "update_app" } : { kind: "retry" },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: t("hostRefusal.refusedByHost.title", { hostName }),
|
||||
description: hostMessage ? null : t("hostRefusal.refusedByHost.description"),
|
||||
hostMessage,
|
||||
shortStatus: t("hostRefusal.shortStatus.refused"),
|
||||
primaryAction: { kind: "retry" },
|
||||
};
|
||||
}
|
||||
|
||||
export function getHostRefusalActionLabel(action: HostRefusalAction, t: TFunction): string {
|
||||
switch (action.kind) {
|
||||
case "enter_password":
|
||||
return t("hostRefusal.actions.enterPassword");
|
||||
case "pair_link":
|
||||
return t("hostRefusal.actions.pairLink");
|
||||
case "scan_qr":
|
||||
return t("hostRefusal.actions.scanQr");
|
||||
case "update_app":
|
||||
return t("hostRefusal.actions.checkForUpdates");
|
||||
case "retry":
|
||||
return t("common.actions.retry");
|
||||
}
|
||||
}
|
||||
@@ -2135,50 +2135,6 @@ export const ar: TranslationResources = {
|
||||
daysAgo: "منذ {{count}} ي",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "كلمة المرور مطلوبة",
|
||||
description: "أدخل كلمة مرور هذا المضيف للاتصال.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "كلمة مرور غير صحيحة",
|
||||
description: "رفض هذا المضيف كلمة المرور المحفوظة.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "حدّث Paseo للاتصال",
|
||||
incompatibleDescription: "يتطلب هذا المضيف إصدارًا أحدث من Paseo.",
|
||||
unsupportedAuthDescription: "يتطلب هذا المضيف طريقة تسجيل دخول لا يدعمها هذا الإصدار من Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "الإقران مطلوب",
|
||||
description: "أعد إقران هذا الجهاز مع المضيف للاتصال.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "رفض {{hostName}} الاتصال",
|
||||
description: "تحقق من إعدادات هذا المضيف ثم حاول مجددًا.",
|
||||
},
|
||||
messageFromHost: "رسالة من {{hostName}}: «{{message}}»",
|
||||
shortStatus: {
|
||||
passwordRequired: "كلمة المرور مطلوبة",
|
||||
updateRequired: "التحديث مطلوب",
|
||||
pairingRequired: "الإقران مطلوب",
|
||||
refused: "مرفوض",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "إدخال كلمة المرور",
|
||||
pairLink: "لصق رابط الإقران",
|
||||
scanQr: "مسح رمز QR",
|
||||
checkForUpdates: "التحقق من التحديثات",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "كلمة مرور {{hostName}}",
|
||||
label: "كلمة المرور",
|
||||
placeholder: "أدخل كلمة مرور المضيف",
|
||||
connect: "اتصال",
|
||||
connecting: "جارٍ الاتصال...",
|
||||
requiredError: "أدخل كلمة مرور للمتابعة.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "كلمة المرور لـ {{host}}",
|
||||
|
||||
@@ -2166,51 +2166,6 @@ export const en = {
|
||||
daysAgo: "{{count}}d ago",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Password required",
|
||||
description: "Enter this host's password to connect.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Incorrect password",
|
||||
description: "The saved password was rejected by this host.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Update Paseo to connect",
|
||||
incompatibleDescription: "This host requires a newer version of Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"This host requires a sign-in method this version of Paseo does not support.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Pairing required",
|
||||
description: "Pair this device with the host again to connect.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Connection refused by {{hostName}}",
|
||||
description: "Check this host's settings and try again.",
|
||||
},
|
||||
messageFromHost: "Message from {{hostName}}: “{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "Password required",
|
||||
updateRequired: "Update required",
|
||||
pairingRequired: "Pairing required",
|
||||
refused: "Refused",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Enter password",
|
||||
pairLink: "Paste pairing link",
|
||||
scanQr: "Scan QR code",
|
||||
checkForUpdates: "Check for updates",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Password for {{hostName}}",
|
||||
label: "Password",
|
||||
placeholder: "Enter host password",
|
||||
connect: "Connect",
|
||||
connecting: "Connecting...",
|
||||
requiredError: "Enter a password to continue.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Password for {{host}}",
|
||||
|
||||
@@ -2192,51 +2192,6 @@ export const es: TranslationResources = {
|
||||
daysAgo: "hace {{count}} d",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Contraseña requerida",
|
||||
description: "Introduce la contraseña de este host para conectar.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Contraseña incorrecta",
|
||||
description: "Este host rechazó la contraseña guardada.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Actualiza Paseo para conectar",
|
||||
incompatibleDescription: "Este host requiere una versión más reciente de Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Este host requiere un método de inicio de sesión que esta versión de Paseo no admite.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Emparejamiento requerido",
|
||||
description: "Vuelve a emparejar este dispositivo con el host para conectar.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Conexión rechazada por {{hostName}}",
|
||||
description: "Revisa la configuración de este host e inténtalo de nuevo.",
|
||||
},
|
||||
messageFromHost: "Mensaje de {{hostName}}: «{{message}}»",
|
||||
shortStatus: {
|
||||
passwordRequired: "Contraseña requerida",
|
||||
updateRequired: "Actualización requerida",
|
||||
pairingRequired: "Emparejamiento requerido",
|
||||
refused: "Rechazado",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Introducir contraseña",
|
||||
pairLink: "Pegar enlace de emparejamiento",
|
||||
scanQr: "Escanear código QR",
|
||||
checkForUpdates: "Buscar actualizaciones",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Contraseña para {{hostName}}",
|
||||
label: "Contraseña",
|
||||
placeholder: "Introduce la contraseña del host",
|
||||
connect: "Conectar",
|
||||
connecting: "Conectando...",
|
||||
requiredError: "Introduce una contraseña para continuar.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Contraseña de {{host}}",
|
||||
|
||||
@@ -2188,51 +2188,6 @@ export const fr: TranslationResources = {
|
||||
daysAgo: "il y a {{count}} j",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Mot de passe requis",
|
||||
description: "Saisissez le mot de passe de cet hôte pour vous connecter.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Mot de passe incorrect",
|
||||
description: "Le mot de passe enregistré a été refusé par cet hôte.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Mettez à jour Paseo pour vous connecter",
|
||||
incompatibleDescription: "Cet hôte nécessite une version plus récente de Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Cet hôte nécessite une méthode de connexion non prise en charge par cette version de Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Appairage requis",
|
||||
description: "Associez de nouveau cet appareil à l'hôte pour vous connecter.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Connexion refusée par {{hostName}}",
|
||||
description: "Vérifiez les paramètres de cet hôte et réessayez.",
|
||||
},
|
||||
messageFromHost: "Message de {{hostName}} : « {{message}} »",
|
||||
shortStatus: {
|
||||
passwordRequired: "Mot de passe requis",
|
||||
updateRequired: "Mise à jour requise",
|
||||
pairingRequired: "Appairage requis",
|
||||
refused: "Refusé",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Saisir le mot de passe",
|
||||
pairLink: "Coller le lien d'appairage",
|
||||
scanQr: "Scanner le code QR",
|
||||
checkForUpdates: "Rechercher des mises à jour",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Mot de passe pour {{hostName}}",
|
||||
label: "Mot de passe",
|
||||
placeholder: "Saisissez le mot de passe de l'hôte",
|
||||
connect: "Se connecter",
|
||||
connecting: "Connexion…",
|
||||
requiredError: "Saisissez un mot de passe pour continuer.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Mot de passe pour {{host}}",
|
||||
|
||||
@@ -2158,51 +2158,6 @@ export const ja: TranslationResources = {
|
||||
daysAgo: "{{count}}日前",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "パスワードが必要です",
|
||||
description: "接続するにはこのホストのパスワードを入力してください。",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "パスワードが正しくありません",
|
||||
description: "保存されたパスワードがこのホストによって拒否されました。",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "接続するにはPaseoを更新してください",
|
||||
incompatibleDescription: "このホストには新しいバージョンのPaseoが必要です。",
|
||||
unsupportedAuthDescription:
|
||||
"このホストには、このバージョンのPaseoでサポートされていないサインイン方法が必要です。",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "ペアリングが必要です",
|
||||
description: "接続するには、このデバイスをホストと再度ペアリングしてください。",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "{{hostName}} によって接続が拒否されました",
|
||||
description: "このホストの設定を確認して、もう一度お試しください。",
|
||||
},
|
||||
messageFromHost: "{{hostName}} からのメッセージ: 「{{message}}」",
|
||||
shortStatus: {
|
||||
passwordRequired: "パスワードが必要",
|
||||
updateRequired: "更新が必要",
|
||||
pairingRequired: "ペアリングが必要",
|
||||
refused: "拒否されました",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "パスワードを入力",
|
||||
pairLink: "ペアリングリンクを貼り付け",
|
||||
scanQr: "QRコードをスキャン",
|
||||
checkForUpdates: "アップデートを確認",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "{{hostName}} のパスワード",
|
||||
label: "パスワード",
|
||||
placeholder: "ホストのパスワードを入力",
|
||||
connect: "接続",
|
||||
connecting: "接続中...",
|
||||
requiredError: "続行するにはパスワードを入力してください。",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} のパスワード",
|
||||
|
||||
@@ -2151,51 +2151,6 @@ export const ko: TranslationResources = {
|
||||
daysAgo: "{{count}}일 전",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "비밀번호가 필요합니다",
|
||||
description: "연결하려면 이 호스트의 비밀번호를 입력하세요.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "비밀번호가 올바르지 않습니다",
|
||||
description: "저장된 비밀번호가 이 호스트에서 거부되었습니다.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "연결하려면 Paseo를 업데이트하세요",
|
||||
incompatibleDescription: "이 호스트에는 최신 버전의 Paseo가 필요합니다.",
|
||||
unsupportedAuthDescription:
|
||||
"이 호스트에는 현재 버전의 Paseo에서 지원하지 않는 로그인 방식이 필요합니다.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "페어링이 필요합니다",
|
||||
description: "연결하려면 이 기기를 호스트와 다시 페어링하세요.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "{{hostName}}에서 연결을 거부했습니다",
|
||||
description: "이 호스트의 설정을 확인한 후 다시 시도하세요.",
|
||||
},
|
||||
messageFromHost: "{{hostName}}의 메시지: “{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "비밀번호 필요",
|
||||
updateRequired: "업데이트 필요",
|
||||
pairingRequired: "페어링 필요",
|
||||
refused: "거부됨",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "비밀번호 입력",
|
||||
pairLink: "페어링 링크 붙여넣기",
|
||||
scanQr: "QR 코드 스캔",
|
||||
checkForUpdates: "업데이트 확인",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "{{hostName}} 비밀번호",
|
||||
label: "비밀번호",
|
||||
placeholder: "호스트 비밀번호 입력",
|
||||
connect: "연결",
|
||||
connecting: "연결 중...",
|
||||
requiredError: "계속하려면 비밀번호를 입력하세요.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}}의 비밀번호",
|
||||
|
||||
@@ -2174,51 +2174,6 @@ export const ptBR: TranslationResources = {
|
||||
daysAgo: "há {{count}}d",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Senha necessária",
|
||||
description: "Digite a senha deste host para conectar.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Senha incorreta",
|
||||
description: "A senha salva foi recusada por este host.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Atualize o Paseo para conectar",
|
||||
incompatibleDescription: "Este host requer uma versão mais recente do Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Este host requer um método de login não suportado por esta versão do Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Pareamento necessário",
|
||||
description: "Pareie este dispositivo novamente com o host para conectar.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Conexão recusada por {{hostName}}",
|
||||
description: "Verifique as configurações deste host e tente novamente.",
|
||||
},
|
||||
messageFromHost: "Mensagem de {{hostName}}: “{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "Senha necessária",
|
||||
updateRequired: "Atualização necessária",
|
||||
pairingRequired: "Pareamento necessário",
|
||||
refused: "Recusado",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Digitar senha",
|
||||
pairLink: "Colar link de pareamento",
|
||||
scanQr: "Escanear código QR",
|
||||
checkForUpdates: "Verificar atualizações",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Senha para {{hostName}}",
|
||||
label: "Senha",
|
||||
placeholder: "Digite a senha do host",
|
||||
connect: "Conectar",
|
||||
connecting: "Conectando...",
|
||||
requiredError: "Digite uma senha para continuar.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Senha de {{host}}",
|
||||
|
||||
@@ -2173,51 +2173,6 @@ export const ru: TranslationResources = {
|
||||
daysAgo: "{{count}} дн назад",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "Требуется пароль",
|
||||
description: "Введите пароль этого хоста для подключения.",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "Неверный пароль",
|
||||
description: "Сохранённый пароль был отклонён этим хостом.",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "Обновите Paseo для подключения",
|
||||
incompatibleDescription: "Для этого хоста требуется более новая версия Paseo.",
|
||||
unsupportedAuthDescription:
|
||||
"Этот хост требует способ входа, который не поддерживается этой версией Paseo.",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "Требуется сопряжение",
|
||||
description: "Повторно выполните сопряжение этого устройства с хостом для подключения.",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "Подключение отклонено хостом {{hostName}}",
|
||||
description: "Проверьте настройки этого хоста и повторите попытку.",
|
||||
},
|
||||
messageFromHost: "Сообщение от {{hostName}}: «{{message}}»",
|
||||
shortStatus: {
|
||||
passwordRequired: "Требуется пароль",
|
||||
updateRequired: "Требуется обновление",
|
||||
pairingRequired: "Требуется сопряжение",
|
||||
refused: "Отклонено",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "Ввести пароль",
|
||||
pairLink: "Вставить ссылку сопряжения",
|
||||
scanQr: "Сканировать QR-код",
|
||||
checkForUpdates: "Проверить обновления",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "Пароль для {{hostName}}",
|
||||
label: "Пароль",
|
||||
placeholder: "Введите пароль хоста",
|
||||
connect: "Подключиться",
|
||||
connecting: "Подключение...",
|
||||
requiredError: "Введите пароль, чтобы продолжить.",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "Пароль для {{host}}",
|
||||
|
||||
@@ -2115,50 +2115,6 @@ export const zhCN: TranslationResources = {
|
||||
daysAgo: "{{count}} 天前",
|
||||
},
|
||||
},
|
||||
hostRefusal: {
|
||||
passwordRequired: {
|
||||
title: "需要密码",
|
||||
description: "输入此主机的密码以连接。",
|
||||
},
|
||||
incorrectPassword: {
|
||||
title: "密码错误",
|
||||
description: "已保存的密码被此主机拒绝。",
|
||||
},
|
||||
updateRequired: {
|
||||
title: "更新 Paseo 以连接",
|
||||
incompatibleDescription: "此主机需要更新版本的 Paseo。",
|
||||
unsupportedAuthDescription: "此主机需要当前版本的 Paseo 不支持的登录方式。",
|
||||
},
|
||||
pairingRequired: {
|
||||
title: "需要配对",
|
||||
description: "请将此设备重新与此主机配对以连接。",
|
||||
},
|
||||
refusedByHost: {
|
||||
title: "连接被 {{hostName}} 拒绝",
|
||||
description: "请检查此主机的设置并重试。",
|
||||
},
|
||||
messageFromHost: "来自 {{hostName}} 的消息:“{{message}}”",
|
||||
shortStatus: {
|
||||
passwordRequired: "需要密码",
|
||||
updateRequired: "需要更新",
|
||||
pairingRequired: "需要配对",
|
||||
refused: "已拒绝",
|
||||
},
|
||||
actions: {
|
||||
enterPassword: "输入密码",
|
||||
pairLink: "粘贴配对链接",
|
||||
scanQr: "扫描二维码",
|
||||
checkForUpdates: "检查更新",
|
||||
},
|
||||
passwordSheet: {
|
||||
title: "{{hostName}} 的密码",
|
||||
label: "密码",
|
||||
placeholder: "输入主机密码",
|
||||
connect: "连接",
|
||||
connecting: "正在连接...",
|
||||
requiredError: "请输入密码以继续。",
|
||||
},
|
||||
},
|
||||
pairing: {
|
||||
hostPassword: {
|
||||
title: "{{host}} 的密码",
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import { Text, View } from "react-native";
|
||||
import { ArrowLeftToLine, RotateCw, Settings } from "lucide-react-native";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { StyleSheet, withUnistyles } from "react-native-unistyles";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { HostRefusalEmptyState } from "@/hosts/host-refusal-alert";
|
||||
import type { AgentRouteResolution } from "@/navigation/agent-route-resolution";
|
||||
import { formatConnectionStatus } from "@/utils/daemons";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
@@ -21,20 +19,16 @@ const foregroundMutedColorMapping = (theme: Theme) => ({
|
||||
});
|
||||
|
||||
export function AgentRouteResolutionView({
|
||||
serverId,
|
||||
resolution,
|
||||
hostName,
|
||||
lastHostError,
|
||||
helloRejection,
|
||||
onRetry,
|
||||
onManageHost,
|
||||
onBack,
|
||||
}: {
|
||||
serverId: string;
|
||||
resolution: VisibleAgentRouteResolution;
|
||||
hostName: string;
|
||||
lastHostError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
onRetry: () => void;
|
||||
onManageHost: () => void;
|
||||
onBack: () => void;
|
||||
@@ -76,20 +70,6 @@ export function AgentRouteResolutionView({
|
||||
|
||||
const isConnecting =
|
||||
resolution.connectionStatus === "connecting" || resolution.connectionStatus === "idle";
|
||||
|
||||
if (!isConnecting && helloRejection) {
|
||||
return (
|
||||
<HostRefusalEmptyState
|
||||
serverId={serverId}
|
||||
hostName={hostName}
|
||||
rejection={helloRejection}
|
||||
onManageHost={onManageHost}
|
||||
testID="agent-route-refusal"
|
||||
testIDPrefix="agent-route-refusal"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
let title = t("workspace.route.cannotReachHost", { hostName });
|
||||
if (isConnecting) {
|
||||
title = t("agentPanel.unavailable.connecting", { serverLabel: hostName });
|
||||
@@ -132,35 +112,36 @@ const styles = StyleSheet.create((theme) => ({
|
||||
flex: 1,
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
gap: theme.spacing[3],
|
||||
paddingHorizontal: theme.spacing[6],
|
||||
gap: theme.spacing[4],
|
||||
},
|
||||
textStack: {
|
||||
alignItems: "center",
|
||||
gap: theme.spacing[2],
|
||||
maxWidth: 420,
|
||||
maxWidth: 520,
|
||||
},
|
||||
title: {
|
||||
fontSize: theme.fontSize.lg,
|
||||
fontWeight: theme.fontWeight.semibold,
|
||||
color: theme.colors.foreground,
|
||||
fontSize: theme.fontSize.base,
|
||||
fontWeight: theme.fontWeight.normal,
|
||||
textAlign: "center",
|
||||
},
|
||||
description: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.foregroundMuted,
|
||||
fontSize: theme.fontSize.base,
|
||||
textAlign: "center",
|
||||
},
|
||||
error: {
|
||||
fontSize: theme.fontSize.sm,
|
||||
color: theme.colors.destructive,
|
||||
fontSize: theme.fontSize.base,
|
||||
lineHeight: Math.round(theme.fontSize.base * 1.4),
|
||||
textAlign: "center",
|
||||
},
|
||||
actions: {
|
||||
flexDirection: "row",
|
||||
flexWrap: "wrap",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexWrap: "wrap",
|
||||
gap: theme.spacing[2],
|
||||
},
|
||||
}));
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useNativeSplashHold } from "@/native-splash";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import type { DaemonClient, DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { TFunction } from "i18next";
|
||||
import { SquarePen } from "lucide-react-native";
|
||||
import React, {
|
||||
@@ -79,12 +79,10 @@ import { PaneSubtitle } from "@/panels/pane-subtitle";
|
||||
import { definePanel } from "@/panels/panel-registry";
|
||||
import { RenderProfile } from "@/utils/render-profiler";
|
||||
import { buildDraftPanelDescriptor } from "@/panels/draft-panel-descriptor";
|
||||
import { HostRefusalAlert } from "@/hosts/host-refusal-alert";
|
||||
import {
|
||||
type HostRuntimeConnectionStatus,
|
||||
useHostRuntimeClient,
|
||||
useHostRuntimeConnectionStatus,
|
||||
useHostRuntimeHelloRejection,
|
||||
useHostRuntimeIsConnected,
|
||||
useHostRuntimeLastError,
|
||||
useHosts,
|
||||
@@ -468,7 +466,6 @@ function AgentPanelContent({
|
||||
const runtimeIsConnected = useHostRuntimeIsConnected(runtimeServerId);
|
||||
const runtimeConnectionStatus = useHostRuntimeConnectionStatus(runtimeServerId);
|
||||
const runtimeLastError = useHostRuntimeLastError(runtimeServerId);
|
||||
const runtimeHelloRejection = useHostRuntimeHelloRejection(runtimeServerId);
|
||||
const hasCachedAgent = useSessionStore((state) => {
|
||||
if (!resolvedServerId || !resolvedAgentId) return false;
|
||||
const session = state.sessions[resolvedServerId];
|
||||
@@ -493,11 +490,9 @@ function AgentPanelContent({
|
||||
if (target.kind === "agent" && (!resolvedServerId || (!runtimeClient && !hasCachedAgent))) {
|
||||
return (
|
||||
<AgentSessionUnavailableState
|
||||
serverId={resolvedServerId ?? null}
|
||||
serverLabel={serverLabel}
|
||||
connectionStatus={connectionStatus}
|
||||
lastError={lastConnectionError}
|
||||
helloRejection={runtimeHelloRejection}
|
||||
isUnknownDaemon={isUnknownDaemon}
|
||||
t={t}
|
||||
/>
|
||||
@@ -512,7 +507,6 @@ function AgentPanelContent({
|
||||
isPaneFocused={isPaneFocused}
|
||||
client={runtimeClient}
|
||||
isConnected={runtimeIsConnected}
|
||||
isConnectionRefused={runtimeHelloRejection !== null}
|
||||
onOpenWorkspaceFile={onOpenWorkspaceFile}
|
||||
/>
|
||||
);
|
||||
@@ -525,7 +519,6 @@ function AgentPanelBody({
|
||||
isPaneFocused,
|
||||
client,
|
||||
isConnected,
|
||||
isConnectionRefused,
|
||||
onOpenWorkspaceFile,
|
||||
}: {
|
||||
serverId: string;
|
||||
@@ -534,7 +527,6 @@ function AgentPanelBody({
|
||||
isPaneFocused: boolean;
|
||||
client: ReturnType<typeof useHostRuntimeClient>;
|
||||
isConnected: boolean;
|
||||
isConnectionRefused: boolean;
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -666,7 +658,6 @@ function AgentPanelBody({
|
||||
isPaneFocused={isPaneFocused}
|
||||
client={client}
|
||||
isConnected={isConnected}
|
||||
isConnectionRefused={isConnectionRefused}
|
||||
onOpenWorkspaceFile={onOpenWorkspaceFile}
|
||||
/>
|
||||
);
|
||||
@@ -719,7 +710,6 @@ function ChatAgentContent({
|
||||
isPaneFocused,
|
||||
client,
|
||||
isConnected,
|
||||
isConnectionRefused,
|
||||
onOpenWorkspaceFile,
|
||||
}: {
|
||||
serverId: string;
|
||||
@@ -728,7 +718,6 @@ function ChatAgentContent({
|
||||
isPaneFocused: boolean;
|
||||
client: ReturnType<typeof useHostRuntimeClient>;
|
||||
isConnected: boolean;
|
||||
isConnectionRefused: boolean;
|
||||
onOpenWorkspaceFile?: (request: WorkspaceFileOpenRequest) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
@@ -889,7 +878,6 @@ function ChatAgentContent({
|
||||
isArchived: agentState.archivedAt !== null,
|
||||
missingAgentState,
|
||||
isConnected,
|
||||
isConnectionRefused,
|
||||
isArchivingCurrentAgent,
|
||||
isHistorySyncing,
|
||||
needsAuthoritativeSync,
|
||||
@@ -1892,19 +1880,15 @@ function ActiveAgentComposer({
|
||||
}
|
||||
|
||||
function AgentSessionUnavailableState({
|
||||
serverId,
|
||||
serverLabel,
|
||||
connectionStatus,
|
||||
lastError,
|
||||
helloRejection,
|
||||
isUnknownDaemon = false,
|
||||
t,
|
||||
}: {
|
||||
serverId: string | null;
|
||||
serverLabel: string;
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
isUnknownDaemon?: boolean;
|
||||
t: TFunction;
|
||||
}) {
|
||||
@@ -1921,21 +1905,6 @@ function AgentSessionUnavailableState({
|
||||
);
|
||||
}
|
||||
|
||||
if (helloRejection && serverId) {
|
||||
return (
|
||||
<View style={styles.container}>
|
||||
<View style={styles.centerState}>
|
||||
<HostRefusalAlert
|
||||
serverId={serverId}
|
||||
hostName={serverLabel}
|
||||
rejection={helloRejection}
|
||||
testID="agent-panel-refusal-alert"
|
||||
/>
|
||||
</View>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
|
||||
const isConnecting = connectionStatus === "connecting";
|
||||
const isPreparingSession = connectionStatus === "online";
|
||||
|
||||
|
||||
@@ -10,11 +10,7 @@ import type {
|
||||
FetchAgentsEntry,
|
||||
FetchAgentsOptions,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
DaemonAuthenticationError,
|
||||
DaemonHelloRejectedError,
|
||||
type DaemonHelloRejection,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import { DaemonAuthenticationError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { HostDirectory } from "@getpaseo/protocol/hosts";
|
||||
import type { ConnectionOffer } from "@getpaseo/protocol/connection-offer";
|
||||
import type { SessionOutboundMessage } from "@getpaseo/protocol/messages";
|
||||
@@ -70,7 +66,6 @@ class FakeDaemonClient {
|
||||
private state: ConnectionState = { status: "idle" };
|
||||
private listeners = new Set<(status: ConnectionState) => void>();
|
||||
private error: string | null = null;
|
||||
helloRejection: DaemonHelloRejection | null = null;
|
||||
authFailureReason: "password_required" | "incorrect_password" | null = null;
|
||||
private heartbeatRttMs: number | null = null;
|
||||
private latencyMeasurementFailure: Error | null = null;
|
||||
@@ -5609,12 +5604,12 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
]),
|
||||
});
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
client.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
client.authFailureReason = "incorrect_password";
|
||||
client.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
(snapshot) => snapshot?.authFailureReason === "incorrect_password",
|
||||
);
|
||||
expect(store.getSnapshot(host.serverId)?.lastError).toBe("Incorrect password");
|
||||
expect(client.reconnectEnabledChanges.at(-1)).toBe(false);
|
||||
@@ -5668,12 +5663,12 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
]),
|
||||
});
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
relayClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
relayClient.authFailureReason = "incorrect_password";
|
||||
relayClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
(snapshot) => snapshot?.authFailureReason === "incorrect_password",
|
||||
);
|
||||
await store.runProbeCycleNow(host.serverId);
|
||||
await onceHostSnapshotMatches(
|
||||
@@ -5707,7 +5702,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "password_required",
|
||||
(snapshot) => snapshot?.authFailureReason === "password_required",
|
||||
);
|
||||
}
|
||||
for (let index = 1; index <= 5; index += 1) {
|
||||
@@ -5741,7 +5736,7 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_deep",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "password_required",
|
||||
(snapshot) => snapshot?.authFailureReason === "password_required",
|
||||
);
|
||||
expect(store.getSnapshot("srv_deep")?.connectionStatus).toBe("error");
|
||||
store.syncHosts([]);
|
||||
@@ -5799,419 +5794,18 @@ describe("HostRuntimeStore initial connection hint bootstrap", () => {
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_test",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "password_required",
|
||||
(snapshot) => snapshot?.authFailureReason === "password_required",
|
||||
);
|
||||
expect(store.getSnapshot("srv_test")?.connectionStatus).toBe("error");
|
||||
await store.setHostPassword("srv_test", "correct-password");
|
||||
await waitForHostOnline(store, "srv_test");
|
||||
expect(store.getHosts()[0]?.password).toBe("correct-password");
|
||||
expect(store.getSnapshot("srv_test")?.helloRejection).toBeNull();
|
||||
expect(store.getSnapshot("srv_test")?.authFailureReason).toBeNull();
|
||||
await store.setHostPassword("srv_test", "");
|
||||
expect(store.getHosts()[0]?.password).toBeUndefined();
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("halts automatic probes on non-password refusals and recovers on explicit clearRefusals retry", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const recoveredClient = makeConnectedProbeClient(5);
|
||||
const host = makeHost({
|
||||
serverId: "srv_maintenance",
|
||||
connections: [{ id: "direct:maint:6767", type: "directTcp", endpoint: "maint:6767" }],
|
||||
});
|
||||
let allowConnect = false;
|
||||
let probeAttempts = 0;
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async () => {
|
||||
probeAttempts += 1;
|
||||
if (!allowConnect) {
|
||||
throw new DaemonHelloRejectedError({
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
});
|
||||
}
|
||||
return {
|
||||
client: recoveredClient as unknown as DaemonClient,
|
||||
serverId: host.serverId,
|
||||
hostname: host.label,
|
||||
};
|
||||
},
|
||||
getClientId: async () => "cid_maintenance",
|
||||
},
|
||||
});
|
||||
store.syncHosts([host], {
|
||||
initialConnectionByServerId: new Map([
|
||||
[
|
||||
host.serverId,
|
||||
{
|
||||
connectionId: "direct:maint:6767",
|
||||
existingClient: initialClient as unknown as DaemonClient,
|
||||
},
|
||||
],
|
||||
]),
|
||||
});
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
|
||||
initialClient.helloRejection = {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
};
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Connection refused" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "maintenance",
|
||||
);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(1);
|
||||
|
||||
// Background probe cycle skips refused connection without bumping episode.
|
||||
await store.runProbeCycleNow(host.serverId);
|
||||
expect(probeAttempts).toBe(0);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(1);
|
||||
|
||||
// Explicit user retry clears refusals and reconnects once the host accepts again.
|
||||
allowConnect = true;
|
||||
await store.runProbeCycleNow(host.serverId, { clearRefusals: true });
|
||||
await waitForHostOnline(store, host.serverId);
|
||||
expect(probeAttempts).toBe(1);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejection).toBeNull();
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(1);
|
||||
|
||||
// Re-refusing after a reconnect bumps helloRejectionEpisode monotonically.
|
||||
const activeClient = store.getSnapshot(host.serverId)?.client as unknown as FakeDaemonClient;
|
||||
activeClient.helloRejection = {
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "Back in 5m",
|
||||
};
|
||||
activeClient.setConnectionState({ status: "disconnected", reason: "Connection refused" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
host.serverId,
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "maintenance",
|
||||
);
|
||||
expect(store.getSnapshot(host.serverId)?.helloRejectionEpisode).toBe(2);
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("submitHostPassword reports incorrect_password and closes cleanly once the right password succeeds", async () => {
|
||||
let activePassword = "old-password";
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: ({ host: currentHost }) => {
|
||||
const client = makeConnectedProbeClient(5);
|
||||
const originalConnect = client.connect.bind(client);
|
||||
client.connect = async () => {
|
||||
if (currentHost.password !== activePassword) {
|
||||
throw new DaemonAuthenticationError("incorrect_password");
|
||||
}
|
||||
return originalConnect();
|
||||
};
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost }) => {
|
||||
if (currentHost.password !== activePassword) {
|
||||
throw new DaemonAuthenticationError("incorrect_password");
|
||||
}
|
||||
return {
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
},
|
||||
getClientId: async () => "cid_pw_sheet",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_pw_sheet",
|
||||
endpoint: "pw:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_pw_sheet");
|
||||
|
||||
// Daemon rotates password.
|
||||
activePassword = "new-secret";
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_pw_sheet",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
|
||||
const wrongResult = await store.submitHostPassword("srv_pw_sheet", "still-wrong");
|
||||
expect(wrongResult).toEqual({
|
||||
status: "rejected",
|
||||
rejection: { reason: "incorrect_password", accepts: ["password"] },
|
||||
});
|
||||
expect(store.getSnapshot("srv_pw_sheet")?.helloRejection?.reason).toBe("incorrect_password");
|
||||
|
||||
const okResult = await store.submitHostPassword("srv_pw_sheet", "new-secret");
|
||||
expect(okResult).toEqual({ status: "online" });
|
||||
expect(store.getSnapshot("srv_pw_sheet")?.connectionStatus).toBe("online");
|
||||
expect(store.getSnapshot("srv_pw_sheet")?.helloRejection).toBeNull();
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("submitHostPassword bounds the wait and returns failed if the host hangs unreachable", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => {
|
||||
const client = new FakeDaemonClient();
|
||||
client.connect = () => new Promise<void>(() => {});
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost }) => ({
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
}),
|
||||
getClientId: async () => "cid_pw_timeout",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_pw_timeout",
|
||||
endpoint: "pw-timeout:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_pw_timeout");
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_pw_timeout",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
|
||||
const timedOut = await store.submitHostPassword("srv_pw_timeout", "new-password", {
|
||||
timeoutMs: 25,
|
||||
});
|
||||
expect(timedOut.status).toBe("failed");
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("superseding submitHostPassword closes a hanging password attempt and connects with the new password", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const hangingClients: FakeDaemonClient[] = [];
|
||||
const seenPasswords: Array<string | undefined> = [];
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: ({ host: currentHost }) => {
|
||||
seenPasswords.push(currentHost.password);
|
||||
const client = new FakeDaemonClient();
|
||||
if (currentHost.password === "stuck-password") {
|
||||
hangingClients.push(client);
|
||||
client.connect = () => new Promise<void>(() => {});
|
||||
}
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost }) => ({
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
}),
|
||||
getClientId: async () => "cid_pw_supersede",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_pw_supersede",
|
||||
endpoint: "pw-supersede:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_pw_supersede");
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_pw_supersede",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
|
||||
const timedOut = await store.submitHostPassword("srv_pw_supersede", "stuck-password", {
|
||||
timeoutMs: 25,
|
||||
});
|
||||
expect(timedOut.status).toBe("failed");
|
||||
expect(hangingClients).toHaveLength(1);
|
||||
|
||||
const recovered = await store.submitHostPassword("srv_pw_supersede", "working-password", {
|
||||
timeoutMs: 1_000,
|
||||
});
|
||||
expect(recovered).toEqual({ status: "online" });
|
||||
expect(hangingClients[0]?.getConnectionState()).toEqual({
|
||||
status: "disconnected",
|
||||
reason: "client_closed",
|
||||
});
|
||||
expect(seenPasswords).toEqual(["stuck-password", "working-password"]);
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("removing an active connection closes a hanging update attempt and switches to the remaining route", async () => {
|
||||
const initialClient = makeConnectedProbeClient(5);
|
||||
const hangingClients: FakeDaemonClient[] = [];
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: ({ connection }) => {
|
||||
const client = new FakeDaemonClient();
|
||||
if (connection.type === "directTcp" && connection.endpoint === "route-remove:6767") {
|
||||
hangingClients.push(client);
|
||||
client.connect = () => new Promise<void>(() => {});
|
||||
}
|
||||
return client as unknown as DaemonClient;
|
||||
},
|
||||
connectToDaemon: async ({ host: currentHost, connection }) => {
|
||||
if (connection.type === "directTcp" && connection.endpoint === "fallback:6767") {
|
||||
if (currentHost.password === "old-password") {
|
||||
throw new DaemonAuthenticationError("incorrect_password");
|
||||
}
|
||||
return {
|
||||
client: makeConnectedProbeClient(8) as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
}
|
||||
return {
|
||||
client: initialClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
},
|
||||
getClientId: async () => "cid_route_remove",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove",
|
||||
endpoint: "route-remove:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_route_remove");
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove",
|
||||
endpoint: "fallback:6767",
|
||||
password: "old-password",
|
||||
});
|
||||
initialClient.helloRejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
initialClient.setConnectionState({ status: "disconnected", reason: "Incorrect password" });
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_route_remove",
|
||||
(snapshot) => snapshot?.helloRejection?.reason === "incorrect_password",
|
||||
);
|
||||
const activeConnectionId = store.getSnapshot("srv_route_remove")?.activeConnectionId;
|
||||
expect(activeConnectionId).toBe("direct:route-remove:6767");
|
||||
|
||||
const timedOut = await store.submitHostPassword("srv_route_remove", "stuck-password", {
|
||||
timeoutMs: 25,
|
||||
});
|
||||
expect(timedOut.status).toBe("failed");
|
||||
expect(hangingClients).toHaveLength(1);
|
||||
|
||||
await store.removeConnection("srv_route_remove", activeConnectionId!);
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_route_remove",
|
||||
(snapshot) =>
|
||||
snapshot?.connectionStatus === "online" &&
|
||||
snapshot.activeConnectionId === "direct:fallback:6767",
|
||||
);
|
||||
expect(hangingClients[0]?.getConnectionState()).toEqual({
|
||||
status: "disconnected",
|
||||
reason: "client_closed",
|
||||
});
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("removing an online active connection when remaining routes are unreachable marks the host offline", async () => {
|
||||
const activeClient = makeConnectedProbeClient(5);
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async ({ host: currentHost, connection }) => {
|
||||
if (connection.type === "directTcp" && connection.endpoint === "active:6767") {
|
||||
return {
|
||||
client: activeClient as unknown as DaemonClient,
|
||||
serverId: currentHost.serverId,
|
||||
hostname: currentHost.label,
|
||||
};
|
||||
}
|
||||
throw new Error("Connection refused");
|
||||
},
|
||||
getClientId: async () => "cid_route_remove_down",
|
||||
},
|
||||
});
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove_down",
|
||||
endpoint: "active:6767",
|
||||
});
|
||||
await waitForHostOnline(store, "srv_route_remove_down");
|
||||
await store.upsertDirectConnection({
|
||||
serverId: "srv_route_remove_down",
|
||||
endpoint: "down:6767",
|
||||
});
|
||||
expect(store.getSnapshot("srv_route_remove_down")?.activeConnectionId).toBe(
|
||||
"direct:active:6767",
|
||||
);
|
||||
|
||||
await store.removeConnection("srv_route_remove_down", "direct:active:6767");
|
||||
await onceHostSnapshotMatches(
|
||||
store,
|
||||
"srv_route_remove_down",
|
||||
(snapshot) =>
|
||||
snapshot?.connectionStatus === "offline" &&
|
||||
snapshot.activeConnectionId === null &&
|
||||
snapshot.client === null,
|
||||
);
|
||||
expect(activeClient.getConnectionState()).toEqual({
|
||||
status: "disconnected",
|
||||
reason: "client_closed",
|
||||
});
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("importConnectionLink prompts for password only when refusal accepts password", async () => {
|
||||
let nextError: Error = new DaemonHelloRejectedError({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
});
|
||||
const store = new HostRuntimeStore({
|
||||
storage: createMemoryHostRuntimeStorage(),
|
||||
deps: {
|
||||
createClient: () => new FakeDaemonClient() as unknown as DaemonClient,
|
||||
connectToDaemon: async () => {
|
||||
throw nextError;
|
||||
},
|
||||
getClientId: async () => "cid_link_refusal",
|
||||
},
|
||||
});
|
||||
answerHostConfirmations(store, true);
|
||||
const link = "relay://relay.example:443/srv_refuse?key=AAAA&ssl=true";
|
||||
|
||||
await expect(store.importConnectionLink(link, "hostRoot")).rejects.toBeInstanceOf(
|
||||
DaemonHelloRejectedError,
|
||||
);
|
||||
|
||||
nextError = new DaemonHelloRejectedError({
|
||||
reason: "password_expired",
|
||||
accepts: ["password"],
|
||||
});
|
||||
await expect(store.importConnectionLink(link, "hostRoot")).resolves.toMatchObject({
|
||||
status: "password_required",
|
||||
link,
|
||||
});
|
||||
store.syncHosts([]);
|
||||
});
|
||||
|
||||
it("attempts the explicit initial connection hint before default localhost bootstrap", async () => {
|
||||
const seenProbes: { endpoint: string; useTls?: boolean }[] = [];
|
||||
const store = new HostRuntimeStore({
|
||||
|
||||
@@ -10,10 +10,8 @@ import AsyncStorage from "@react-native-async-storage/async-storage";
|
||||
import equal from "fast-deep-equal/es6";
|
||||
import {
|
||||
DaemonClient,
|
||||
createHelloRejectedError,
|
||||
normalizeHelloRejection,
|
||||
DaemonAuthenticationError,
|
||||
type DaemonClientConfig,
|
||||
type DaemonHelloRejection,
|
||||
type ConnectionState,
|
||||
type FetchAgentsOptions,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
@@ -51,8 +49,7 @@ import { ConnectionOfferSchema, type ConnectionOffer } from "@getpaseo/protocol/
|
||||
import { HostConfirmations, type HostConfirmationRequest } from "./host-confirmation";
|
||||
import { shouldUseDesktopDaemon } from "@/desktop/daemon/desktop-daemon";
|
||||
import { isWeb } from "@/constants/platform";
|
||||
import { connectToDaemon, getConnectionHelloRejection } from "@/utils/test-daemon-connection";
|
||||
import { isPasswordRefusal } from "@/hosts/host-refusal";
|
||||
import { connectToDaemon, getConnectionAuthFailureReason } from "@/utils/test-daemon-connection";
|
||||
import { getOrCreateClientId } from "@/utils/client-id";
|
||||
import { z } from "zod";
|
||||
import { readValidatedString } from "@/storage/validated-storage";
|
||||
@@ -155,8 +152,7 @@ export interface HostRuntimeSnapshot {
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
client: DaemonClient | null;
|
||||
lastError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
helloRejectionEpisode?: number;
|
||||
authFailureReason?: "password_required" | "incorrect_password" | null;
|
||||
lastOnlineAt: string | null;
|
||||
agentDirectoryStatus: HostRuntimeAgentDirectoryStatus;
|
||||
agentDirectoryError: string | null;
|
||||
@@ -336,7 +332,6 @@ type HostRuntimeConnectionMachineEvent =
|
||||
| { type: "select_connection"; connectionId: string; connection: ActiveConnection }
|
||||
| { type: "client_state"; state: ConnectionState; lastError: string | null }
|
||||
| { type: "connect_failed"; message: string }
|
||||
| { type: "active_connection_removed" }
|
||||
| { type: "no_connections" }
|
||||
| { type: "stopped" };
|
||||
|
||||
@@ -440,11 +435,7 @@ function nextConnectionMachineState(input: {
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
event.type === "no_connections" ||
|
||||
event.type === "stopped" ||
|
||||
event.type === "active_connection_removed"
|
||||
) {
|
||||
if (event.type === "no_connections" || event.type === "stopped") {
|
||||
return {
|
||||
tag: "offline",
|
||||
activeConnectionId: null,
|
||||
@@ -757,12 +748,10 @@ export class HostRuntimeController {
|
||||
private activeRttSamples: Array<{ at: number; rttMs: number }> = [];
|
||||
private clientIdPromise: Promise<string> | null = null;
|
||||
private clientIdHash: string | null = null;
|
||||
private hostUpdateVersion = 0;
|
||||
private switchRequestVersion = 0;
|
||||
private probeRequestVersion = 0;
|
||||
private probeCycleInFlight: Promise<void> | null = null;
|
||||
private hostUpdateInFlight: Promise<void> | null = null;
|
||||
private readonly refusedConnectionIds = new Set<string>();
|
||||
private readonly authRejectedConnectionIds = new Set<string>();
|
||||
|
||||
constructor(input: {
|
||||
host: HostProfile;
|
||||
@@ -781,8 +770,6 @@ export class HostRuntimeController {
|
||||
serverId: this.host.serverId,
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
helloRejection: null,
|
||||
helloRejectionEpisode: 0,
|
||||
agentDirectoryStatus: "idle",
|
||||
agentDirectoryError: null,
|
||||
hasEverLoadedAgentDirectory: false,
|
||||
@@ -834,7 +821,6 @@ export class HostRuntimeController {
|
||||
}
|
||||
|
||||
async stop(): Promise<void> {
|
||||
this.hostUpdateVersion += 1;
|
||||
this.switchRequestVersion += 1;
|
||||
this.probeRequestVersion += 1;
|
||||
this.started = false;
|
||||
@@ -865,49 +851,23 @@ export class HostRuntimeController {
|
||||
});
|
||||
}
|
||||
|
||||
updateHost(host: HostProfile): Promise<void> {
|
||||
const updateVersion = ++this.hostUpdateVersion;
|
||||
const run = this.performUpdateHost(host, updateVersion).finally(() => {
|
||||
if (this.hostUpdateInFlight === run) {
|
||||
this.hostUpdateInFlight = null;
|
||||
}
|
||||
});
|
||||
this.hostUpdateInFlight = run;
|
||||
return run;
|
||||
}
|
||||
|
||||
async waitForHostUpdate(): Promise<void> {
|
||||
if (this.hostUpdateInFlight) {
|
||||
await this.hostUpdateInFlight;
|
||||
}
|
||||
}
|
||||
|
||||
private async performUpdateHost(host: HostProfile, updateVersion: number): Promise<void> {
|
||||
async updateHost(host: HostProfile): Promise<void> {
|
||||
const passwordChanged = this.host.password !== host.password;
|
||||
const connectionsChanged = !equal(this.host.connections, host.connections);
|
||||
if (passwordChanged || connectionsChanged) {
|
||||
if (passwordChanged) {
|
||||
this.probeRequestVersion += 1;
|
||||
this.probeCycleInFlight = null;
|
||||
this.refusedConnectionIds.clear();
|
||||
this.updateSnapshot({ helloRejection: null });
|
||||
this.authRejectedConnectionIds.clear();
|
||||
this.updateSnapshot({ authFailureReason: null });
|
||||
}
|
||||
if (passwordChanged || connectionsChanged) {
|
||||
this.resetInactiveOnlineProbeBackoff();
|
||||
this.connectionLastProbedAt.clear();
|
||||
}
|
||||
const activeConnectionId = this.snapshot.activeConnectionId;
|
||||
const previousActiveConnection = findConnectionById(this.host, activeConnectionId);
|
||||
this.host = host;
|
||||
this.trackConnectionFirstSeen();
|
||||
const nextActiveConnection = findConnectionById(this.host, activeConnectionId);
|
||||
if (activeConnectionId && previousActiveConnection && !nextActiveConnection) {
|
||||
this.switchRequestVersion += 1;
|
||||
await this.disposePreviousActiveClient();
|
||||
if (!this.isCurrentHostUpdate(updateVersion)) return;
|
||||
this.applyConnectionEvent({ type: "active_connection_removed" });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
});
|
||||
} else if (
|
||||
if (
|
||||
activeConnectionId &&
|
||||
previousActiveConnection &&
|
||||
nextActiveConnection &&
|
||||
@@ -923,9 +883,9 @@ export class HostRuntimeController {
|
||||
connectionId: activeConnectionId,
|
||||
keepActiveUntilConnected: passwordChanged && this.snapshot.connectionStatus === "online",
|
||||
});
|
||||
if (!this.isCurrentHostUpdate(updateVersion)) return;
|
||||
}
|
||||
if (!this.isCurrentHostUpdate(updateVersion)) return;
|
||||
if (passwordChanged) this.connectionLastProbedAt.clear();
|
||||
if (passwordChanged) await this.probeCycleInFlight;
|
||||
await this.runProbeCycleNow();
|
||||
}
|
||||
|
||||
@@ -941,7 +901,7 @@ export class HostRuntimeController {
|
||||
(connection) =>
|
||||
connection.type === "routed" &&
|
||||
connection.originServerId === originServerId &&
|
||||
!this.refusedConnectionIds.has(connection.id),
|
||||
!this.authRejectedConnectionIds.has(connection.id),
|
||||
);
|
||||
if (routes.length === 0 || !this.started || isHostRuntimeConnected(this.snapshot)) return;
|
||||
if (routes.some((route) => route.id === this.snapshot.activeConnectionId))
|
||||
@@ -1050,14 +1010,8 @@ export class HostRuntimeController {
|
||||
this.setConnectionProbe(connectionId, { status: "available", latencyMs: rttMs });
|
||||
}
|
||||
|
||||
async runProbeCycleNow(options?: { clearRefusals?: boolean }): Promise<void> {
|
||||
if (options?.clearRefusals) {
|
||||
this.probeRequestVersion += 1;
|
||||
this.refusedConnectionIds.clear();
|
||||
this.connectionLastProbedAt.clear();
|
||||
this.updateSnapshot({ helloRejection: null });
|
||||
this.probeCycleInFlight = null;
|
||||
} else if (this.probeCycleInFlight) {
|
||||
async runProbeCycleNow(): Promise<void> {
|
||||
if (this.probeCycleInFlight) {
|
||||
return this.probeCycleInFlight;
|
||||
}
|
||||
|
||||
@@ -1091,7 +1045,7 @@ export class HostRuntimeController {
|
||||
|
||||
const inactiveOnlineIntervalMs = this.inactiveOnlineProbeIntervalMs();
|
||||
const connectionsToProbe = this.host.connections.filter((connection) => {
|
||||
if (this.refusedConnectionIds.has(connection.id)) return false;
|
||||
if (this.authRejectedConnectionIds.has(connection.id)) return false;
|
||||
const lastProbed = this.connectionLastProbedAt.get(connection.id);
|
||||
if (lastProbed == null) {
|
||||
return true;
|
||||
@@ -1128,7 +1082,7 @@ export class HostRuntimeController {
|
||||
this.updateSnapshot({ probeByConnectionId: initialProbes });
|
||||
|
||||
let remaining = connectionsToProbe.length;
|
||||
let probeHelloRejection: DaemonHelloRejection | null = null;
|
||||
let probeAuthFailure: "password_required" | "incorrect_password" | null = null;
|
||||
let activationLock: Promise<void> | null = null;
|
||||
|
||||
// Merge each connection result into the live snapshot map so a slow probe on another
|
||||
@@ -1144,7 +1098,7 @@ export class HostRuntimeController {
|
||||
connectionId: string,
|
||||
client: DaemonClient,
|
||||
): Promise<boolean> => {
|
||||
while (!this.snapshot.activeConnectionId || !this.snapshot.client) {
|
||||
while (!this.snapshot.activeConnectionId) {
|
||||
if (!activationLock) {
|
||||
activationLock = this.switchToConnection({
|
||||
connectionId,
|
||||
@@ -1154,9 +1108,7 @@ export class HostRuntimeController {
|
||||
activationLock = null;
|
||||
});
|
||||
await activationLock;
|
||||
return (
|
||||
this.snapshot.activeConnectionId === connectionId && this.snapshot.client === client
|
||||
);
|
||||
return this.snapshot.activeConnectionId === connectionId;
|
||||
}
|
||||
await activationLock;
|
||||
}
|
||||
@@ -1177,11 +1129,7 @@ export class HostRuntimeController {
|
||||
? probeByConnectionId.get(currentActiveConnectionId)
|
||||
: null;
|
||||
|
||||
if (
|
||||
!currentActiveConnectionId ||
|
||||
!this.snapshot.client ||
|
||||
!findConnectionById(this.host, currentActiveConnectionId)
|
||||
) {
|
||||
if (!currentActiveConnectionId || !findConnectionById(this.host, currentActiveConnectionId)) {
|
||||
const nextConnectionId = selectBestConnection({
|
||||
candidates: buildConnectionCandidates(this.host),
|
||||
probeByConnectionId,
|
||||
@@ -1191,12 +1139,12 @@ export class HostRuntimeController {
|
||||
connectionId: nextConnectionId,
|
||||
expectedProbeVersion: requestVersion,
|
||||
});
|
||||
} else if (probeHelloRejection) {
|
||||
const message = createHelloRejectedError(probeHelloRejection).message;
|
||||
} else if (probeAuthFailure) {
|
||||
const message = new DaemonAuthenticationError(probeAuthFailure).message;
|
||||
this.applyConnectionEvent({ type: "connect_failed", message });
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
helloRejection: probeHelloRejection,
|
||||
authFailureReason: probeAuthFailure,
|
||||
});
|
||||
}
|
||||
return;
|
||||
@@ -1359,10 +1307,10 @@ export class HostRuntimeController {
|
||||
});
|
||||
} catch (error) {
|
||||
if (this.isCurrentProbeRequest(requestVersion)) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
this.refusedConnectionIds.add(connection.id);
|
||||
probeHelloRejection = rejection;
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) {
|
||||
this.authRejectedConnectionIds.add(connection.id);
|
||||
probeAuthFailure = authFailure;
|
||||
}
|
||||
publishConnectionProbe(connection.id, {
|
||||
status: "unavailable",
|
||||
@@ -1440,7 +1388,7 @@ export class HostRuntimeController {
|
||||
probeByConnectionId: Map<string, ConnectionProbeState>,
|
||||
): void {
|
||||
if (probeByConnectionId.get(connectionId)?.status !== "unavailable") return;
|
||||
if (this.refusedConnectionIds.has(connectionId)) return;
|
||||
if (this.authRejectedConnectionIds.has(connectionId)) return;
|
||||
const client = this.snapshot.client;
|
||||
if (!client || client.getConnectionState().status !== "connected") return;
|
||||
const rttMs = client.getLastLivenessRttMs();
|
||||
@@ -1457,22 +1405,14 @@ export class HostRuntimeController {
|
||||
connectionId: string,
|
||||
probe: ConnectionProbeState | null | undefined,
|
||||
): boolean {
|
||||
return probe?.status === "unavailable" || this.refusedConnectionIds.has(connectionId);
|
||||
return probe?.status === "unavailable" || this.authRejectedConnectionIds.has(connectionId);
|
||||
}
|
||||
|
||||
private updateSnapshot(patch: HostRuntimeSnapshotPatch): void {
|
||||
const preservedPatch: HostRuntimeSnapshotPatch = { ...patch };
|
||||
if (
|
||||
"helloRejection" in patch &&
|
||||
patch.helloRejection !== null &&
|
||||
patch.helloRejection !== undefined &&
|
||||
!equal(this.snapshot.helloRejection, patch.helloRejection)
|
||||
) {
|
||||
preservedPatch.helloRejectionEpisode = (this.snapshot.helloRejectionEpisode ?? 0) + 1;
|
||||
}
|
||||
let hasChanged = this.host.serverId !== this.snapshot.serverId;
|
||||
for (const key of Object.keys(preservedPatch) as (keyof HostRuntimeSnapshotPatch)[]) {
|
||||
const incomingValue = preservedPatch[key];
|
||||
for (const key of Object.keys(patch) as (keyof HostRuntimeSnapshotPatch)[]) {
|
||||
const incomingValue = patch[key];
|
||||
if (equal(this.snapshot[key], incomingValue)) {
|
||||
setSnapshotPatchField(preservedPatch, key, this.snapshot[key]);
|
||||
continue;
|
||||
@@ -1539,10 +1479,6 @@ export class HostRuntimeController {
|
||||
}
|
||||
}
|
||||
|
||||
private isCurrentHostUpdate(version: number): boolean {
|
||||
return version === this.hostUpdateVersion;
|
||||
}
|
||||
|
||||
private isCurrentSwitchRequest(version: number): boolean {
|
||||
return version === this.switchRequestVersion;
|
||||
}
|
||||
@@ -1731,9 +1667,9 @@ export class HostRuntimeController {
|
||||
try {
|
||||
await replacement.connect();
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) {
|
||||
this.refusedConnectionIds.add(connection.id);
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) {
|
||||
this.authRejectedConnectionIds.add(connection.id);
|
||||
const probes = new Map(this.snapshot.probeByConnectionId);
|
||||
probes.set(connection.id, { status: "unavailable", latencyMs: null });
|
||||
this.updateSnapshot({ probeByConnectionId: probes });
|
||||
@@ -1781,16 +1717,11 @@ export class HostRuntimeController {
|
||||
this.deps.mountClientHandlers?.({ client, host: this.host, connection }) ?? null;
|
||||
this.unsubscribeClientStatus = client.subscribeConnectionStatus((state) => {
|
||||
if (this.activeClient !== client) return;
|
||||
const clientRejection =
|
||||
client.helloRejection ??
|
||||
(client.authFailureReason
|
||||
? normalizeHelloRejection({ reason: client.authFailureReason, accepts: ["password"] })
|
||||
: null);
|
||||
if (clientRejection) {
|
||||
if (client.authFailureReason) {
|
||||
void this.failActiveConnection({
|
||||
client,
|
||||
connection,
|
||||
error: createHelloRejectedError(clientRejection),
|
||||
error: new DaemonAuthenticationError(client.authFailureReason),
|
||||
});
|
||||
return;
|
||||
}
|
||||
@@ -1806,7 +1737,7 @@ export class HostRuntimeController {
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
...this.buildAgentDirectoryStatusPatch(),
|
||||
client,
|
||||
helloRejection: null,
|
||||
authFailureReason: null,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1818,9 +1749,8 @@ export class HostRuntimeController {
|
||||
}): Promise<void> {
|
||||
const { client, connection, error } = input;
|
||||
if (this.activeClient !== client) return;
|
||||
this.activeClient = null;
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (rejection) this.refusedConnectionIds.add(connection.id);
|
||||
const authFailure = getConnectionAuthFailureReason(error);
|
||||
if (authFailure) this.authRejectedConnectionIds.add(connection.id);
|
||||
this.unsubscribeClientStatus?.();
|
||||
this.unsubscribeClientStatus = null;
|
||||
this.unsubscribeClientHandlers?.();
|
||||
@@ -1830,14 +1760,14 @@ export class HostRuntimeController {
|
||||
this.updateSnapshot({
|
||||
...toSnapshotConnectionPatch(this.connectionMachineState, this.connectionEpoch),
|
||||
client: null,
|
||||
helloRejection: rejection,
|
||||
authFailureReason: authFailure,
|
||||
});
|
||||
if (rejection) {
|
||||
if (authFailure) {
|
||||
const probes = new Map(this.snapshot.probeByConnectionId);
|
||||
probes.set(connection.id, { status: "unavailable", latencyMs: null });
|
||||
this.updateSnapshot({ probeByConnectionId: probes });
|
||||
for (const candidate of this.host.connections) {
|
||||
if (!this.refusedConnectionIds.has(candidate.id)) {
|
||||
if (!this.authRejectedConnectionIds.has(candidate.id)) {
|
||||
this.connectionLastProbedAt.delete(candidate.id);
|
||||
}
|
||||
}
|
||||
@@ -1848,8 +1778,8 @@ export class HostRuntimeController {
|
||||
/* Preserve the compatibility/connection error. */
|
||||
}
|
||||
if (
|
||||
rejection &&
|
||||
this.host.connections.some((candidate) => !this.refusedConnectionIds.has(candidate.id))
|
||||
authFailure &&
|
||||
this.host.connections.some((candidate) => !this.authRejectedConnectionIds.has(candidate.id))
|
||||
) {
|
||||
void this.runProbeCycleNow();
|
||||
}
|
||||
@@ -1896,7 +1826,6 @@ export class HostRuntimeController {
|
||||
const REGISTRY_STORAGE_KEY = "@paseo:daemon-registry";
|
||||
const LOCALHOST_FALLBACK_ENDPOINT = "localhost:6767";
|
||||
const DEFAULT_LOCALHOST_BOOTSTRAP_TIMEOUT_MS = 2500;
|
||||
const DEFAULT_PASSWORD_SUBMIT_TIMEOUT_MS = 10_000;
|
||||
const E2E_STORAGE_KEY = "@paseo:e2e";
|
||||
const INITIAL_DAEMON_CONNECTION_HINT_GLOBAL_KEY = "__PASEO_INITIAL_DAEMON_CONNECTION__";
|
||||
|
||||
@@ -1960,22 +1889,6 @@ function delay(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
}
|
||||
|
||||
async function waitWithTimeout(promise: Promise<unknown>, timeoutMs: number): Promise<void> {
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
try {
|
||||
await Promise.race([
|
||||
promise,
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, timeoutMs);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (timer !== null) {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function rekeyMap<V>(map: Map<string, V>, oldKey: string, newKey: string): void {
|
||||
const value = map.get(oldKey);
|
||||
if (value === undefined) {
|
||||
@@ -2487,8 +2400,7 @@ export class HostRuntimeStore {
|
||||
if (result.status === "cancelled") return result;
|
||||
return { status: "connected", serverId: result.serverId };
|
||||
} catch (error) {
|
||||
const rejection = getConnectionHelloRejection(error);
|
||||
if (!rejection || !isPasswordRefusal(rejection)) throw error;
|
||||
if (!getConnectionAuthFailureReason(error)) throw error;
|
||||
return { status: "password_required", link: url, pairing };
|
||||
}
|
||||
}
|
||||
@@ -2587,37 +2499,6 @@ export class HostRuntimeStore {
|
||||
});
|
||||
}
|
||||
|
||||
async submitHostPassword(
|
||||
serverId: string,
|
||||
password: string,
|
||||
options?: { timeoutMs?: number },
|
||||
): Promise<HostPasswordSubmissionResult> {
|
||||
const existingHost = this.hosts.find((host) => host.serverId === serverId);
|
||||
if (!existingHost) {
|
||||
return { status: "failed", message: "Host not found" };
|
||||
}
|
||||
const previousPassword = existingHost.password ?? "";
|
||||
await this.setHostPassword(serverId, password);
|
||||
const controller = this.controllers.get(serverId);
|
||||
if (!controller) {
|
||||
return { status: "failed", message: "Host not found" };
|
||||
}
|
||||
const timeoutMs = options?.timeoutMs ?? DEFAULT_PASSWORD_SUBMIT_TIMEOUT_MS;
|
||||
const attempt =
|
||||
previousPassword === password
|
||||
? controller.runProbeCycleNow({ clearRefusals: true })
|
||||
: controller.waitForHostUpdate();
|
||||
await waitWithTimeout(attempt, timeoutMs);
|
||||
const snapshot = controller.getSnapshot();
|
||||
if (snapshot.connectionStatus === "online") {
|
||||
return { status: "online" };
|
||||
}
|
||||
if (snapshot.helloRejection) {
|
||||
return { status: "rejected", rejection: snapshot.helloRejection };
|
||||
}
|
||||
return { status: "failed", message: snapshot.lastError ?? "" };
|
||||
}
|
||||
|
||||
async setHostColor(serverId: string, color: HostColor): Promise<void> {
|
||||
await this.updateHostAppearance(serverId, (host) => ({
|
||||
...host,
|
||||
@@ -3144,12 +3025,12 @@ export class HostRuntimeStore {
|
||||
this.ensureConnectedAll({ verify: true });
|
||||
}
|
||||
|
||||
runProbeCycleNow(serverId?: string, options?: { clearRefusals?: boolean }): Promise<void> {
|
||||
runProbeCycleNow(serverId?: string): Promise<void> {
|
||||
if (serverId) {
|
||||
return this.controllers.get(serverId)?.runProbeCycleNow(options) ?? Promise.resolve();
|
||||
return this.controllers.get(serverId)?.runProbeCycleNow() ?? Promise.resolve();
|
||||
}
|
||||
return Promise.all(
|
||||
Array.from(this.controllers.values(), (controller) => controller.runProbeCycleNow(options)),
|
||||
Array.from(this.controllers.values(), (controller) => controller.runProbeCycleNow()),
|
||||
).then(() => undefined);
|
||||
}
|
||||
|
||||
@@ -3369,15 +3250,6 @@ export function useHostRuntimeLastError(serverId: string): string | null {
|
||||
);
|
||||
}
|
||||
|
||||
export function useHostRuntimeHelloRejection(serverId: string): DaemonHelloRejection | null {
|
||||
const store = getHostRuntimeStore();
|
||||
return useSyncExternalStore(
|
||||
(onStoreChange) => store.subscribe(serverId, onStoreChange),
|
||||
() => store.getSnapshot(serverId)?.helloRejection ?? null,
|
||||
() => store.getSnapshot(serverId)?.helloRejection ?? null,
|
||||
);
|
||||
}
|
||||
|
||||
export function useHostRuntimeAgentDirectoryStatus(
|
||||
serverId: string,
|
||||
): HostRuntimeAgentDirectoryStatus {
|
||||
@@ -3448,11 +3320,6 @@ export function useHostConfirmation(): {
|
||||
);
|
||||
}
|
||||
|
||||
export type HostPasswordSubmissionResult =
|
||||
| { status: "online" }
|
||||
| { status: "rejected"; rejection: DaemonHelloRejection }
|
||||
| { status: "failed"; message: string };
|
||||
|
||||
export interface HostMutations {
|
||||
upsertDirectConnection: (input: {
|
||||
serverId: string;
|
||||
@@ -3477,7 +3344,6 @@ export interface HostMutations {
|
||||
beginLinkPairing: () => LinkPairing;
|
||||
renameHost: (serverId: string, label: string) => Promise<void>;
|
||||
setHostPassword: (serverId: string, password: string) => Promise<void>;
|
||||
submitHostPassword: (serverId: string, password: string) => Promise<HostPasswordSubmissionResult>;
|
||||
setHostColor: (serverId: string, color: HostColor) => Promise<void>;
|
||||
setHostIcon: (serverId: string, icon: HostIcon | null) => Promise<void>;
|
||||
setHostBadgeDisplay: (serverId: string, badgeDisplay: HostBadgeDisplay) => Promise<void>;
|
||||
@@ -3495,7 +3361,6 @@ export function useHostMutations(): HostMutations {
|
||||
beginLinkPairing: () => store.beginLinkPairing(),
|
||||
renameHost: (serverId, label) => store.renameHost(serverId, label),
|
||||
setHostPassword: (serverId, password) => store.setHostPassword(serverId, password),
|
||||
submitHostPassword: (serverId, password) => store.submitHostPassword(serverId, password),
|
||||
setHostColor: (serverId, color) => store.setHostColor(serverId, color),
|
||||
setHostIcon: (serverId, icon) => store.setHostIcon(serverId, icon),
|
||||
setHostBadgeDisplay: (serverId, badgeDisplay) =>
|
||||
|
||||
@@ -25,7 +25,6 @@ import { useIsLocalDaemon, useLocalDaemonServerId } from "@/hooks/use-is-local-d
|
||||
import { resolveHostIcon } from "@/hosts/appearance";
|
||||
import { describeActiveConnection, describeHostConnection } from "@/hosts/connection-display";
|
||||
import { HostIconGlyph } from "@/hosts/host-icon-glyph";
|
||||
import { resolveHostRefusal } from "@/hosts/host-refusal";
|
||||
import { useHostMutations, useHostRuntimeSnapshot, useHosts } from "@/runtime/host-runtime";
|
||||
import { HostAppearanceSection } from "@/screens/settings/host-appearance-section";
|
||||
import { HostConnectionError } from "@/screens/settings/host-page";
|
||||
@@ -145,13 +144,7 @@ function ClientHostListRow({
|
||||
if (status === "online") {
|
||||
summary = formatDaemonVersion(serverInfo?.version ?? null);
|
||||
} else if (status === "offline" || status === "error") {
|
||||
summary = snapshot?.helloRejection
|
||||
? resolveHostRefusal({
|
||||
rejection: snapshot.helloRejection,
|
||||
hostName: host.label,
|
||||
t,
|
||||
}).shortStatus
|
||||
: t("settings.about.offline");
|
||||
summary = t("settings.about.offline");
|
||||
}
|
||||
|
||||
const leading = useMemo(
|
||||
@@ -376,7 +369,7 @@ function ClientHostRoutesSection({
|
||||
hosts={hosts}
|
||||
latencyMs={probe?.status === "available" ? probe.latencyMs : undefined}
|
||||
latencyLoading={!probe || probe.status === "pending"}
|
||||
latencyError={probe?.status === "unavailable" && !snapshot?.helloRejection}
|
||||
latencyError={probe?.status === "unavailable"}
|
||||
onRemove={handleRequestRemove}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -11,7 +11,6 @@ import {
|
||||
Trash2,
|
||||
} from "lucide-react-native";
|
||||
import type { TFunction } from "i18next";
|
||||
import { useIsFocused } from "expo-router/react-navigation";
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Alert, Text, View } from "react-native";
|
||||
@@ -37,7 +36,6 @@ import {
|
||||
} from "@/screens/settings/terminal-profile-edit-modal";
|
||||
import { LocalDaemonSection } from "@/desktop/components/desktop-updates-section";
|
||||
import { ConnectedDevicesView } from "@/devices";
|
||||
import { useActiveRefusalHost } from "@/hosts/host-refusal-sheet-state";
|
||||
import { useDaemonConfig } from "@/hooks/use-daemon-config";
|
||||
import { useIsLocalDaemon } from "@/hooks/use-is-local-daemon";
|
||||
import { useHostFeature } from "@/runtime/host-features";
|
||||
@@ -60,7 +58,6 @@ import { confirmDialog } from "@/utils/confirm-dialog";
|
||||
import { isVersionMismatch } from "@/desktop/updates/desktop-updates";
|
||||
import { resolveAppVersion } from "@/utils/app-version";
|
||||
import { formatConnectionStatus, getConnectionStatusTone } from "@/utils/daemons";
|
||||
import { HostRefusalAlert } from "@/hosts/host-refusal-alert";
|
||||
import { ICON_SIZE } from "@/styles/theme";
|
||||
import type { Theme } from "@/styles/theme";
|
||||
import { useProviderIcon } from "@/components/provider-icons";
|
||||
@@ -214,23 +211,8 @@ function HostStatusBadges({ serverId }: { serverId: string }) {
|
||||
}
|
||||
|
||||
export function HostConnectionError({ serverId }: { serverId: string }) {
|
||||
const isFocused = useIsFocused();
|
||||
useActiveRefusalHost(serverId, isFocused);
|
||||
const { t } = useTranslation();
|
||||
const snapshot = useHostRuntimeSnapshot(serverId);
|
||||
const host = useHostProfile(serverId);
|
||||
const hostName = host?.label?.trim() || serverId;
|
||||
if (snapshot?.helloRejection) {
|
||||
return (
|
||||
<View style={styles.connectionError}>
|
||||
<HostRefusalAlert
|
||||
serverId={serverId}
|
||||
hostName={hostName}
|
||||
rejection={snapshot.helloRejection}
|
||||
testID="host-connection-error"
|
||||
/>
|
||||
</View>
|
||||
);
|
||||
}
|
||||
const lastError = snapshot?.lastError ?? null;
|
||||
const connectionError =
|
||||
typeof lastError === "string" && lastError.trim().length > 0 ? lastError.trim() : null;
|
||||
@@ -241,6 +223,7 @@ export function HostConnectionError({ serverId }: { serverId: string }) {
|
||||
size="sm"
|
||||
variant="error"
|
||||
title={connectionError}
|
||||
description={snapshot?.authFailureReason ? t("settings.host.password.guidance") : undefined}
|
||||
testID="host-connection-error"
|
||||
/>
|
||||
</View>
|
||||
|
||||
@@ -9,7 +9,6 @@ import {
|
||||
WindowLayoutActions,
|
||||
} from "@/window-layout";
|
||||
import { IconButtonChromeProvider } from "@/components/ui/icon-button-chrome";
|
||||
import { HostRefusalHeaderButton } from "@/hosts/host-refusal-sheet";
|
||||
|
||||
export { MobileWorkspaceTabSwitcher } from "./tab-switcher";
|
||||
|
||||
@@ -60,12 +59,9 @@ export function CompactWorkspaceHeader({
|
||||
overflow: children,
|
||||
explorer: explorerAction,
|
||||
};
|
||||
const actions = [
|
||||
<HostRefusalHeaderButton key="refusal" serverId={serverId} />,
|
||||
...resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
)),
|
||||
];
|
||||
const actions = resolveWorkspaceBarActions(headerVariant).map((symbol) => (
|
||||
<Fragment key={symbol}>{symbols[symbol]}</Fragment>
|
||||
));
|
||||
|
||||
return (
|
||||
<IconButtonChromeProvider value="header-island">
|
||||
|
||||
@@ -6,7 +6,6 @@ import { Button } from "@/components/ui/button";
|
||||
import { LoadingSpinner } from "@/components/ui/loading-spinner";
|
||||
import { LoadingState } from "@/components/ui/loading-state";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import { HostRefusalEmptyState } from "@/hosts/host-refusal-alert";
|
||||
import { formatConnectionStatus } from "@/utils/daemons";
|
||||
import { useNativeSplashHold } from "@/native-splash";
|
||||
import type {
|
||||
@@ -29,7 +28,6 @@ interface WorkspaceRouteStateActions {
|
||||
}
|
||||
|
||||
export function renderWorkspaceRouteGate(input: {
|
||||
serverId: string;
|
||||
state: WorkspaceRouteState;
|
||||
actions: WorkspaceRouteStateActions;
|
||||
}): React.ReactNode {
|
||||
@@ -62,7 +60,6 @@ export function renderWorkspaceRouteGate(input: {
|
||||
case "unreachable":
|
||||
return (
|
||||
<WorkspaceUnreachable
|
||||
serverId={input.serverId}
|
||||
state={input.state}
|
||||
onRetry={input.actions.onRetryHost}
|
||||
onManageHost={input.actions.onManageHost}
|
||||
@@ -214,31 +211,15 @@ function WorkspaceRecoveryInspectionFailed({
|
||||
}
|
||||
|
||||
function WorkspaceUnreachable({
|
||||
serverId,
|
||||
state,
|
||||
onRetry,
|
||||
onManageHost,
|
||||
}: {
|
||||
serverId: string;
|
||||
state: Extract<WorkspaceRouteState, { kind: "unreachable" }>;
|
||||
onRetry: () => void;
|
||||
onManageHost: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
if (state.helloRejection) {
|
||||
return (
|
||||
<HostRefusalEmptyState
|
||||
serverId={serverId}
|
||||
hostName={state.hostName}
|
||||
rejection={state.helloRejection}
|
||||
onManageHost={onManageHost}
|
||||
testID="workspace-unreachable-refusal"
|
||||
testIDPrefix="workspace-refusal"
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<View style={styles.emptyState}>
|
||||
<View style={styles.textStack}>
|
||||
|
||||
@@ -31,8 +31,7 @@ function createWorkspaceDescriptor(): WorkspaceDescriptor {
|
||||
|
||||
function resolve(input: {
|
||||
workspace?: WorkspaceDescriptor | null;
|
||||
connectionStatus?: "online" | "offline" | "connecting" | "idle" | "error";
|
||||
helloRejection?: { reason: string; accepts: readonly string[]; message?: string } | null;
|
||||
connectionStatus?: "online" | "offline" | "connecting" | "idle";
|
||||
hasHydratedWorkspaces?: boolean;
|
||||
hasRestoredCachedDirectory?: boolean;
|
||||
recovery?: WorkspaceRecoveryModel;
|
||||
@@ -40,11 +39,7 @@ function resolve(input: {
|
||||
return resolveWorkspaceRouteState({
|
||||
hostName: "Laptop",
|
||||
connectionStatus: input.connectionStatus ?? "online",
|
||||
lastError:
|
||||
input.connectionStatus === "offline" || input.connectionStatus === "error"
|
||||
? "transport closed"
|
||||
: null,
|
||||
helloRejection: input.helloRejection ?? null,
|
||||
lastError: input.connectionStatus === "offline" ? "transport closed" : null,
|
||||
workspace: input.workspace ?? null,
|
||||
hasHydratedWorkspaces: input.hasHydratedWorkspaces ?? true,
|
||||
hasRestoredCachedDirectory: input.hasRestoredCachedDirectory ?? true,
|
||||
@@ -72,31 +67,6 @@ describe("resolveWorkspaceRouteState", () => {
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "transport closed",
|
||||
helloRejection: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("carries helloRejection on reconnecting cached workspaces and unreachable routes", () => {
|
||||
const rejection = { reason: "incorrect_password", accepts: ["password"] };
|
||||
expect(
|
||||
resolve({
|
||||
workspace: createWorkspaceDescriptor(),
|
||||
connectionStatus: "error",
|
||||
helloRejection: rejection,
|
||||
}),
|
||||
).toEqual({
|
||||
kind: "reconnecting",
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "error",
|
||||
lastError: "transport closed",
|
||||
helloRejection: rejection,
|
||||
});
|
||||
expect(resolve({ connectionStatus: "error", helloRejection: rejection })).toEqual({
|
||||
kind: "unreachable",
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "error",
|
||||
lastError: "transport closed",
|
||||
helloRejection: rejection,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -134,7 +104,6 @@ describe("resolveWorkspaceRouteState", () => {
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "transport closed",
|
||||
helloRejection: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -505,15 +474,8 @@ describe("post-restore handoff state machine", () => {
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "closed",
|
||||
helloRejection: null,
|
||||
},
|
||||
{
|
||||
kind: "unreachable",
|
||||
hostName: "Laptop",
|
||||
connectionStatus: "offline",
|
||||
lastError: "closed",
|
||||
helloRejection: null,
|
||||
},
|
||||
{ kind: "unreachable", hostName: "Laptop", connectionStatus: "offline", lastError: "closed" },
|
||||
{ kind: "loading", hostName: "Laptop", waitingFor: "workspace" },
|
||||
{ kind: "missing", hostName: "Laptop" },
|
||||
{ kind: "recoveryUnavailable", hostName: "Laptop", message: "missing" },
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import type { DaemonHelloRejection } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { HostRuntimeConnectionStatus } from "@/runtime/host-runtime";
|
||||
import type { WorkspaceDescriptor } from "@/stores/session-store";
|
||||
import type { WorkspaceRecoveryModel } from "@/workspace-recovery/model";
|
||||
@@ -10,14 +9,12 @@ export type WorkspaceRouteState =
|
||||
hostName: string;
|
||||
connectionStatus: Exclude<HostRuntimeConnectionStatus, "online">;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
}
|
||||
| {
|
||||
kind: "unreachable";
|
||||
hostName: string;
|
||||
connectionStatus: Extract<HostRuntimeConnectionStatus, "offline" | "error">;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
}
|
||||
| { kind: "loading"; hostName: string; waitingFor: WorkspaceLoadingSource }
|
||||
| { kind: "missing"; hostName: string }
|
||||
@@ -40,14 +37,12 @@ export function resolveWorkspaceRouteState(input: {
|
||||
hostName: string;
|
||||
connectionStatus: HostRuntimeConnectionStatus;
|
||||
lastError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
workspace: WorkspaceDescriptor | null;
|
||||
hasHydratedWorkspaces: boolean;
|
||||
/** The host's cached directory has been read, so a workspace it holds is in the store. */
|
||||
hasRestoredCachedDirectory: boolean;
|
||||
recovery: WorkspaceRecoveryModel;
|
||||
}): WorkspaceRouteState {
|
||||
const helloRejection = input.helloRejection ?? null;
|
||||
if (input.workspace) {
|
||||
if (input.connectionStatus === "online") {
|
||||
if (input.recovery.kind === "recoverable" && input.recovery.phase === "restoring") {
|
||||
@@ -61,7 +56,6 @@ export function resolveWorkspaceRouteState(input: {
|
||||
hostName: input.hostName,
|
||||
connectionStatus: input.connectionStatus,
|
||||
lastError: input.lastError,
|
||||
helloRejection,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -80,7 +74,6 @@ export function resolveWorkspaceRouteState(input: {
|
||||
hostName: input.hostName,
|
||||
connectionStatus: input.connectionStatus,
|
||||
lastError: input.lastError,
|
||||
helloRejection,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -172,8 +172,6 @@ import {
|
||||
renderWorkspaceRouteGate,
|
||||
WorkspaceLoading,
|
||||
} from "@/screens/workspace/workspace-route-state-views";
|
||||
import { HostRefusalHeaderButton } from "@/hosts/host-refusal-sheet";
|
||||
import { useActiveRefusalHost } from "@/hosts/host-refusal-sheet-state";
|
||||
import { useWorkspaceRecovery } from "@/workspace-recovery/use-workspace-recovery";
|
||||
import type { WorkspaceRecoveryModel } from "@/workspace-recovery/model";
|
||||
import {
|
||||
@@ -671,7 +669,7 @@ function useWorkspaceRouteActions(normalizedServerId: string): {
|
||||
if (!normalizedServerId) {
|
||||
return;
|
||||
}
|
||||
void getHostRuntimeStore().runProbeCycleNow(normalizedServerId, { clearRefusals: true });
|
||||
void getHostRuntimeStore().runProbeCycleNow(normalizedServerId);
|
||||
}, [normalizedServerId]);
|
||||
const handleManageHost = useCallback(() => {
|
||||
if (!normalizedServerId) {
|
||||
@@ -724,7 +722,6 @@ function useResolvedWorkspaceRouteState(input: {
|
||||
hostName: input.hostName,
|
||||
connectionStatus: hostSnapshot?.connectionStatus ?? "connecting",
|
||||
lastError: hostSnapshot?.lastError ?? null,
|
||||
helloRejection: hostSnapshot?.helloRejection ?? null,
|
||||
workspace: input.workspace,
|
||||
hasHydratedWorkspaces: input.hasHydratedWorkspaces,
|
||||
hasRestoredCachedDirectory,
|
||||
@@ -734,7 +731,6 @@ function useResolvedWorkspaceRouteState(input: {
|
||||
input.hostName,
|
||||
hostSnapshot?.connectionStatus,
|
||||
hostSnapshot?.lastError,
|
||||
hostSnapshot?.helloRejection,
|
||||
input.workspace,
|
||||
input.hasHydratedWorkspaces,
|
||||
hasRestoredCachedDirectory,
|
||||
@@ -1042,7 +1038,6 @@ function WorkspaceScreenContent({
|
||||
const toggleFocusMode = usePanelStore((state) => state.toggleFocusMode);
|
||||
|
||||
const normalizedServerId = useMemo(() => trimNonEmpty(decodeSegment(serverId)) ?? "", [serverId]);
|
||||
useActiveRefusalHost(normalizedServerId, isRouteFocused);
|
||||
|
||||
const normalizedWorkspaceId = useMemo(
|
||||
() => resolveWorkspaceRouteId({ routeWorkspaceId: workspaceId }) ?? "",
|
||||
@@ -2893,7 +2888,6 @@ function WorkspaceScreenContent({
|
||||
const containerStyle = [styles.container, styles.containerWorkspaceBackground];
|
||||
|
||||
const workspaceScreenGate = renderWorkspaceRouteGate({
|
||||
serverId: normalizedServerId,
|
||||
state: displayedWorkspaceRouteState,
|
||||
actions: {
|
||||
onRetryHost: handleRetryHost,
|
||||
@@ -2918,7 +2912,6 @@ function WorkspaceScreenContent({
|
||||
const headerRight = useMemo(
|
||||
() => (
|
||||
<View style={styles.headerRight}>
|
||||
{workspaceActionsInBar ? null : <HostRefusalHeaderButton serverId={normalizedServerId} />}
|
||||
<PluginHeaderButtons serverId={normalizedServerId} workspaceId={normalizedWorkspaceId} />
|
||||
{workspaceDescriptor && workspaceDescriptor.scripts.length > 0 ? (
|
||||
<WorkspaceScriptsButton
|
||||
|
||||
@@ -1,9 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DaemonClientConfig } from "@getpaseo/client/internal/daemon-client";
|
||||
import {
|
||||
DaemonAuthenticationError,
|
||||
DaemonHelloRejectedError,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import { DaemonAuthenticationError } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { DaemonConnectionDependencies, DaemonProbeClient } from "./test-daemon-connection";
|
||||
import { createHostLogger } from "@/runtime/host-logger";
|
||||
|
||||
@@ -338,37 +335,6 @@ describe("test-daemon-connection connectToDaemon", () => {
|
||||
).rejects.toMatchObject({
|
||||
message: "Incorrect password",
|
||||
authFailureReason: "incorrect_password",
|
||||
helloRejection: { reason: "incorrect_password", accepts: ["password"] },
|
||||
});
|
||||
});
|
||||
|
||||
it("propagates non-password hello.rejected refusals via getConnectionHelloRejection", async () => {
|
||||
const { connectToDaemon, getConnectionAuthFailureReason, getConnectionHelloRejection } =
|
||||
await import("./test-daemon-connection");
|
||||
probe.failNextConnection(
|
||||
new DaemonHelloRejectedError({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
}),
|
||||
"Connection refused (pairing_required)",
|
||||
);
|
||||
|
||||
const error = await connectToDaemon(
|
||||
{
|
||||
id: "direct:lan:6767",
|
||||
type: "directTcp",
|
||||
endpoint: "lan:6767",
|
||||
},
|
||||
{},
|
||||
probe.deps,
|
||||
).catch((caught: unknown) => caught);
|
||||
|
||||
expect(getConnectionAuthFailureReason(error)).toBeNull();
|
||||
expect(getConnectionHelloRejection(error)).toEqual({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,11 +1,8 @@
|
||||
import {
|
||||
DaemonAuthenticationError,
|
||||
DaemonClient,
|
||||
createHelloRejectedError,
|
||||
getDaemonAuthFailureReason,
|
||||
getDaemonHelloRejection,
|
||||
normalizeHelloRejection,
|
||||
type DaemonAuthFailureReason,
|
||||
type DaemonHelloRejection,
|
||||
} from "@getpaseo/client/internal/daemon-client";
|
||||
import type { DaemonClientConfig } from "@getpaseo/client/internal/daemon-client";
|
||||
import type { HostConnection } from "@/types/host-connection";
|
||||
@@ -26,7 +23,6 @@ import type { DesktopDaemonTransportTarget } from "@/desktop/daemon/desktop-daem
|
||||
|
||||
export interface DaemonProbeClient {
|
||||
readonly lastError: string | null;
|
||||
readonly helloRejection?: DaemonHelloRejection | null;
|
||||
readonly authFailureReason?: DaemonAuthFailureReason | null;
|
||||
connect(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
@@ -98,20 +94,9 @@ function pickBestReason(reason: string | null, lastError: string | null): string
|
||||
return "Unable to connect";
|
||||
}
|
||||
|
||||
function deriveAuthFailureReason(
|
||||
rejection: DaemonHelloRejection | null,
|
||||
): DaemonAuthFailureReason | null {
|
||||
if (!rejection) return null;
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return rejection.reason;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export class DaemonConnectionTestError extends Error {
|
||||
reason: string | null;
|
||||
lastError: string | null;
|
||||
helloRejection: DaemonHelloRejection | null;
|
||||
authFailureReason: DaemonAuthFailureReason | null;
|
||||
|
||||
constructor(
|
||||
@@ -119,7 +104,6 @@ export class DaemonConnectionTestError extends Error {
|
||||
details: {
|
||||
reason: string | null;
|
||||
lastError: string | null;
|
||||
helloRejection?: DaemonHelloRejection | null;
|
||||
authFailureReason?: DaemonAuthFailureReason | null;
|
||||
},
|
||||
) {
|
||||
@@ -127,21 +111,10 @@ export class DaemonConnectionTestError extends Error {
|
||||
this.name = "DaemonConnectionTestError";
|
||||
this.reason = details.reason;
|
||||
this.lastError = details.lastError;
|
||||
this.helloRejection =
|
||||
details.helloRejection ??
|
||||
(details.authFailureReason
|
||||
? normalizeHelloRejection({ reason: details.authFailureReason, accepts: ["password"] })
|
||||
: null);
|
||||
this.authFailureReason =
|
||||
details.authFailureReason ?? deriveAuthFailureReason(this.helloRejection);
|
||||
this.authFailureReason = details.authFailureReason ?? null;
|
||||
}
|
||||
}
|
||||
|
||||
export function getConnectionHelloRejection(error: unknown): DaemonHelloRejection | null {
|
||||
if (error instanceof DaemonConnectionTestError) return error.helloRejection;
|
||||
return getDaemonHelloRejection(error);
|
||||
}
|
||||
|
||||
export function getConnectionAuthFailureReason(error: unknown): DaemonAuthFailureReason | null {
|
||||
if (error instanceof DaemonConnectionTestError) return error.authFailureReason;
|
||||
return getDaemonAuthFailureReason(error);
|
||||
@@ -303,27 +276,13 @@ export function connectAndProbe(
|
||||
error instanceof Error ? error.message : String(error),
|
||||
);
|
||||
const lastError = normalizeNonEmptyString(client.lastError);
|
||||
const legacyAuthFailure =
|
||||
const authFailureReason =
|
||||
getDaemonAuthFailureReason(error) ?? client.authFailureReason ?? null;
|
||||
const helloRejection =
|
||||
getDaemonHelloRejection(error) ??
|
||||
client.helloRejection ??
|
||||
(legacyAuthFailure
|
||||
? normalizeHelloRejection({ reason: legacyAuthFailure, accepts: ["password"] })
|
||||
: null);
|
||||
const authFailureReason = deriveAuthFailureReason(helloRejection);
|
||||
const message = helloRejection
|
||||
? createHelloRejectedError(helloRejection).message
|
||||
const message = authFailureReason
|
||||
? new DaemonAuthenticationError(authFailureReason).message
|
||||
: pickBestReason(reason, lastError);
|
||||
void client.close().catch(() => undefined);
|
||||
reject(
|
||||
new DaemonConnectionTestError(message, {
|
||||
reason,
|
||||
lastError,
|
||||
helloRejection,
|
||||
authFailureReason,
|
||||
}),
|
||||
);
|
||||
reject(new DaemonConnectionTestError(message, { reason, lastError, authFailureReason }));
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@@ -50,7 +50,7 @@ export function addSendOptions(cmd: Command): Command {
|
||||
.addOption(
|
||||
new Option(
|
||||
"--behavior <behavior>",
|
||||
"Leave out unless the message cannot wait. From an agent (PASEO_AGENT_ID set): queue (default) waits for the running turn to end, steer joins it, interrupt replaces it. From a person: interrupt (default), steer, or queue",
|
||||
"From an agent (PASEO_AGENT_ID set): steer (default) joins the running turn or waits until it ends if the provider cannot steer, queue waits for the running turn to end, interrupt replaces it. From a person: interrupt (default), steer, or queue",
|
||||
).choices(["queue", "steer", "interrupt"]),
|
||||
)
|
||||
.option("--no-wait", "Return immediately without waiting for completion");
|
||||
|
||||
@@ -135,7 +135,6 @@ export const DEFAULT_CLIENT_CAPABILITIES = {
|
||||
[CLIENT_CAPS.terminalChunkedReplay]: true,
|
||||
[CLIENT_CAPS.binaryChunkingV1]: true,
|
||||
[CLIENT_CAPS.helloRejection]: true,
|
||||
[CLIENT_CAPS.evolvableHelloRejection]: true,
|
||||
[CLIENT_CAPS.ownedSubscriptions]: true,
|
||||
[CLIENT_CAPS.allProviders]: true,
|
||||
[CLIENT_CAPS.selectiveAgentTimeline]: true,
|
||||
|
||||
@@ -293,194 +293,26 @@ type HelloAuth =
|
||||
| { kind: "localCredential"; token: string }
|
||||
| undefined;
|
||||
|
||||
export interface DaemonHelloRejection {
|
||||
readonly reason: string;
|
||||
readonly accepts: readonly string[];
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
export type DaemonAuthFailureReason = "password_required" | "incorrect_password";
|
||||
|
||||
const MAX_HELLO_REJECTION_TOKEN_CODE_POINTS = 64;
|
||||
const MAX_HELLO_REJECTION_ACCEPTS = 16;
|
||||
const MAX_HELLO_REJECTION_MESSAGE_CODE_POINTS = 200;
|
||||
export class DaemonAuthenticationError extends Error {
|
||||
readonly reason: DaemonAuthFailureReason;
|
||||
|
||||
// Strip ANSI CSI sequences without control-character regex literals.
|
||||
function stripAnsiCsi(input: string): string {
|
||||
let out = "";
|
||||
let i = 0;
|
||||
while (i < input.length) {
|
||||
if (input.charCodeAt(i) === 0x1b && input.charCodeAt(i + 1) === 0x5b) {
|
||||
i += 2;
|
||||
while (i < input.length) {
|
||||
const code = input.charCodeAt(i);
|
||||
i += 1;
|
||||
if (code >= 0x40 && code <= 0x7e) break;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
out += input[i]!;
|
||||
i += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function isBidiOrFormatCodePoint(cp: number): boolean {
|
||||
return (
|
||||
(cp >= 0x200b && cp <= 0x200f) ||
|
||||
(cp >= 0x202a && cp <= 0x202e) ||
|
||||
(cp >= 0x2060 && cp <= 0x2069) ||
|
||||
cp === 0x061c ||
|
||||
cp === 0xfeff
|
||||
);
|
||||
}
|
||||
|
||||
function stripControlAndFormat(input: string, replaceWhitespaceControlsWithSpace: boolean): string {
|
||||
let out = "";
|
||||
for (const ch of stripAnsiCsi(input)) {
|
||||
const cp = ch.codePointAt(0);
|
||||
if (cp === undefined) continue;
|
||||
if (
|
||||
replaceWhitespaceControlsWithSpace &&
|
||||
(cp === 0x09 || cp === 0x0a || cp === 0x0b || cp === 0x0c || cp === 0x0d)
|
||||
) {
|
||||
out += " ";
|
||||
continue;
|
||||
}
|
||||
if (cp <= 0x1f || cp === 0x7f || isBidiOrFormatCodePoint(cp)) {
|
||||
continue;
|
||||
}
|
||||
out += ch;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function truncateCodePoints(text: string, maxCodePoints: number, ellipsis?: string): string {
|
||||
const codePoints = Array.from(text);
|
||||
if (codePoints.length <= maxCodePoints) return text;
|
||||
if (!ellipsis) return codePoints.slice(0, maxCodePoints).join("");
|
||||
const ellipsisLen = Array.from(ellipsis).length;
|
||||
const keep = Math.max(0, maxCodePoints - ellipsisLen);
|
||||
return `${codePoints.slice(0, keep).join("").trimEnd()}${ellipsis}`;
|
||||
}
|
||||
|
||||
function sanitizeHelloRejectionToken(raw: string): string {
|
||||
const cleaned = stripControlAndFormat(raw, false).trim();
|
||||
return truncateCodePoints(cleaned, MAX_HELLO_REJECTION_TOKEN_CODE_POINTS);
|
||||
}
|
||||
|
||||
function sanitizeHelloRejectionMessage(raw: string | undefined): string | undefined {
|
||||
if (typeof raw !== "string") return undefined;
|
||||
const cleaned = stripControlAndFormat(raw, true).replace(/\s+/g, " ").trim();
|
||||
if (cleaned.length === 0) return undefined;
|
||||
return truncateCodePoints(cleaned, MAX_HELLO_REJECTION_MESSAGE_CODE_POINTS, "…");
|
||||
}
|
||||
|
||||
export function normalizeHelloRejection(raw: {
|
||||
reason: string;
|
||||
accepts?: readonly string[];
|
||||
message?: string;
|
||||
}): DaemonHelloRejection {
|
||||
const reason = sanitizeHelloRejectionToken(raw.reason) || "connection_refused";
|
||||
const accepts: string[] = [];
|
||||
if (reason !== "incompatible_protocol" && Array.isArray(raw.accepts)) {
|
||||
const seen = new Set<string>();
|
||||
for (const entry of raw.accepts) {
|
||||
if (typeof entry !== "string") continue;
|
||||
const token = sanitizeHelloRejectionToken(entry);
|
||||
if (token.length === 0 || seen.has(token)) continue;
|
||||
seen.add(token);
|
||||
accepts.push(token);
|
||||
if (accepts.length >= MAX_HELLO_REJECTION_ACCEPTS) break;
|
||||
}
|
||||
}
|
||||
const message = sanitizeHelloRejectionMessage(raw.message);
|
||||
return message !== undefined ? { reason, accepts, message } : { reason, accepts };
|
||||
}
|
||||
|
||||
function describeHelloRejection(rejection: DaemonHelloRejection): string {
|
||||
switch (rejection.reason) {
|
||||
case "password_required":
|
||||
return "Password required";
|
||||
case "incorrect_password":
|
||||
return "Incorrect password";
|
||||
case "incompatible_protocol":
|
||||
return "Incompatible protocol version";
|
||||
default:
|
||||
return `Connection refused (${rejection.reason})`;
|
||||
}
|
||||
}
|
||||
|
||||
export class DaemonHelloRejectedError extends Error {
|
||||
readonly rejection: DaemonHelloRejection;
|
||||
readonly reason: string;
|
||||
readonly accepts: readonly string[];
|
||||
|
||||
constructor(rejection: DaemonHelloRejection, message?: string) {
|
||||
super(message ?? describeHelloRejection(rejection));
|
||||
this.name = "DaemonHelloRejectedError";
|
||||
this.rejection = rejection;
|
||||
this.reason = rejection.reason;
|
||||
this.accepts = rejection.accepts;
|
||||
}
|
||||
}
|
||||
|
||||
export class DaemonAuthenticationError extends DaemonHelloRejectedError {
|
||||
override readonly reason: DaemonAuthFailureReason;
|
||||
|
||||
constructor(reason: DaemonAuthFailureReason, rejection?: DaemonHelloRejection) {
|
||||
const normalized = rejection ?? normalizeHelloRejection({ reason, accepts: ["password"] });
|
||||
super(normalized, reason === "password_required" ? "Password required" : "Incorrect password");
|
||||
constructor(reason: DaemonAuthFailureReason) {
|
||||
super(reason === "password_required" ? "Password required" : "Incorrect password");
|
||||
this.name = "DaemonAuthenticationError";
|
||||
this.reason = reason;
|
||||
}
|
||||
}
|
||||
|
||||
export function createHelloRejectedError(
|
||||
rejection: DaemonHelloRejection,
|
||||
): DaemonHelloRejectedError {
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return new DaemonAuthenticationError(rejection.reason, rejection);
|
||||
}
|
||||
return new DaemonHelloRejectedError(rejection);
|
||||
}
|
||||
|
||||
export function getDaemonHelloRejection(error: unknown): DaemonHelloRejection | null {
|
||||
return error instanceof DaemonHelloRejectedError ? error.rejection : null;
|
||||
}
|
||||
|
||||
export function getDaemonAuthFailureReason(error: unknown): DaemonAuthFailureReason | null {
|
||||
return error instanceof DaemonAuthenticationError ? error.reason : null;
|
||||
}
|
||||
|
||||
function toAuthFailureReason(
|
||||
rejection: DaemonHelloRejection | null,
|
||||
): DaemonAuthFailureReason | null {
|
||||
if (!rejection) return null;
|
||||
if (rejection.reason === "password_required" || rejection.reason === "incorrect_password") {
|
||||
return rejection.reason;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function helloRejectionFromLegacyClose(event: unknown): DaemonHelloRejection | null {
|
||||
if (!event || typeof event !== "object") return null;
|
||||
const reason = "reason" in event && typeof event.reason === "string" ? event.reason : "";
|
||||
const code = "code" in event && typeof event.code === "number" ? event.code : null;
|
||||
if (reason === "Password required") {
|
||||
return normalizeHelloRejection({ reason: "password_required", accepts: ["password"] });
|
||||
}
|
||||
if (reason === "Incorrect password") {
|
||||
return normalizeHelloRejection({ reason: "incorrect_password", accepts: ["password"] });
|
||||
}
|
||||
// COMPAT(evolvableHelloRejection): added in v0.20.0, remove after 2027-06-03.
|
||||
// Daemons older than evolvable_hello_rejection close with 4003 without a hello.rejected frame.
|
||||
if (
|
||||
reason === "Incompatible protocol version" ||
|
||||
(code === 4003 && reason.toLowerCase().includes("incompatible protocol"))
|
||||
) {
|
||||
return normalizeHelloRejection({ reason: "incompatible_protocol", accepts: [] });
|
||||
}
|
||||
function authFailureFromLegacyClose(event: unknown): DaemonAuthFailureReason | null {
|
||||
if (!event || typeof event !== "object" || !("reason" in event)) return null;
|
||||
if (event.reason === "Password required") return "password_required";
|
||||
if (event.reason === "Incorrect password") return "incorrect_password";
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -1765,7 +1597,7 @@ export class DaemonClientCore {
|
||||
private lastErrorValue: string | null = null;
|
||||
private destinationServerId: string | undefined;
|
||||
private connectionFailure: Error | undefined;
|
||||
private helloRejectionValue: DaemonHelloRejection | null = null;
|
||||
private authFailureReasonValue: DaemonAuthFailureReason | null = null;
|
||||
private connectionState: ConnectionState = { status: "idle" };
|
||||
private readonly diffStreams = new DiffStreamRouter({
|
||||
modern: (compare) =>
|
||||
@@ -1937,7 +1769,7 @@ export class DaemonClientCore {
|
||||
trigger === "STALE_CONNECT_ON_FOREGROUND" ? "Stale connection attempt" : "Reconnecting",
|
||||
);
|
||||
this.lastServerInfoMessage = null;
|
||||
this.helloRejectionValue = null;
|
||||
this.authFailureReasonValue = null;
|
||||
const attempt: ConnectionAttempt = { startedAt: Date.now(), timeout: null };
|
||||
this.connectionAttempt = attempt;
|
||||
this.updateConnectionState(
|
||||
@@ -2022,14 +1854,14 @@ export class DaemonClientCore {
|
||||
clearTimeout(this.pendingGenericTransportErrorTimeout);
|
||||
this.pendingGenericTransportErrorTimeout = null;
|
||||
}
|
||||
this.helloRejectionValue ??= helloRejectionFromLegacyClose(event);
|
||||
this.authFailureReasonValue ??= authFailureFromLegacyClose(event);
|
||||
// An endpoint security policy close cannot be fixed by retrying.
|
||||
const securityFailure = describeEndpointSecurityClose(event);
|
||||
if (securityFailure) this.setReconnectEnabled(false);
|
||||
// A transport error may already have scheduled this socket's retry before its close.
|
||||
if (this.reconnectTimeout && !securityFailure && !this.helloRejectionValue) return;
|
||||
const reason = this.helloRejectionValue
|
||||
? describeHelloRejection(this.helloRejectionValue)
|
||||
if (this.reconnectTimeout && !securityFailure && !this.authFailureReasonValue) return;
|
||||
const reason = this.authFailureReasonValue
|
||||
? new DaemonAuthenticationError(this.authFailureReasonValue).message
|
||||
: (securityFailure ?? describeTransportClose(event));
|
||||
if (reason) {
|
||||
this.lastErrorValue = reason;
|
||||
@@ -2397,12 +2229,8 @@ export class DaemonClientCore {
|
||||
return this.lastErrorValue;
|
||||
}
|
||||
|
||||
get helloRejection(): DaemonHelloRejection | null {
|
||||
return this.helloRejectionValue;
|
||||
}
|
||||
|
||||
get authFailureReason(): DaemonAuthFailureReason | null {
|
||||
return toAuthFailureReason(this.helloRejectionValue);
|
||||
return this.authFailureReasonValue;
|
||||
}
|
||||
|
||||
getLastLivenessRttMs(): number | null {
|
||||
@@ -8430,10 +8258,15 @@ export class DaemonClientCore {
|
||||
}
|
||||
|
||||
if (parsed.data.type === "hello.rejected") {
|
||||
const rejection = normalizeHelloRejection(parsed.data);
|
||||
this.traceInstant("paseo.connection.rejected", { reason: rejection.reason });
|
||||
this.helloRejectionValue = rejection;
|
||||
this.lastErrorValue = describeHelloRejection(rejection);
|
||||
this.traceInstant("paseo.connection.rejected", { reason: parsed.data.reason });
|
||||
const reasonMessage = {
|
||||
password_required: "Password required",
|
||||
incorrect_password: "Incorrect password",
|
||||
incompatible_protocol: "Incompatible protocol version",
|
||||
};
|
||||
this.lastErrorValue = reasonMessage[parsed.data.reason];
|
||||
this.authFailureReasonValue =
|
||||
parsed.data.reason === "incompatible_protocol" ? null : parsed.data.reason;
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -8707,7 +8540,7 @@ export class DaemonClientCore {
|
||||
this.terminalStreams.clearSlots();
|
||||
this.lastServerInfoMessage = null;
|
||||
|
||||
if (this.helloRejectionValue) this.setReconnectEnabled(false);
|
||||
if (this.authFailureReasonValue) this.setReconnectEnabled(false);
|
||||
|
||||
if (wasDisposed) {
|
||||
this.rejectConnect(new Error(reason ?? "Daemon client is disposed"));
|
||||
@@ -8716,8 +8549,8 @@ export class DaemonClientCore {
|
||||
this.emitDisconnectedStateForReconnect(reason, input);
|
||||
if (!this.shouldReconnect || this.config.reconnect?.enabled === false) {
|
||||
this.rejectConnect(
|
||||
this.helloRejectionValue
|
||||
? createHelloRejectedError(this.helloRejectionValue)
|
||||
this.authFailureReasonValue
|
||||
? new DaemonAuthenticationError(this.authFailureReasonValue)
|
||||
: (input?.failure ?? new Error(reason ?? "Transport disconnected before connect")),
|
||||
);
|
||||
return;
|
||||
|
||||
@@ -2,13 +2,8 @@ import { readFileSync } from "node:fs";
|
||||
import { afterEach, describe, expect, expectTypeOf, test, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
import {
|
||||
DaemonAuthenticationError,
|
||||
DaemonClient,
|
||||
DaemonConnectionError,
|
||||
DaemonHelloRejectedError,
|
||||
getDaemonAuthFailureReason,
|
||||
getDaemonHelloRejection,
|
||||
normalizeHelloRejection,
|
||||
supportsUsageReports,
|
||||
type DaemonClientTrace,
|
||||
type CreateAgentRequestOptions,
|
||||
@@ -109,19 +104,12 @@ function createMockTransport() {
|
||||
return {
|
||||
transport,
|
||||
sent,
|
||||
triggerOpen: (options?: {
|
||||
preserveSent?: boolean;
|
||||
features?: Record<string, boolean>;
|
||||
skipServerInfo?: boolean;
|
||||
}) => {
|
||||
triggerOpen: (options?: { preserveSent?: boolean; features?: Record<string, boolean> }) => {
|
||||
onOpen();
|
||||
if (!options?.preserveSent) {
|
||||
// Ignore HELLO handshake payloads in assertions.
|
||||
sent.length = 0;
|
||||
}
|
||||
if (options?.skipServerInfo) {
|
||||
return;
|
||||
}
|
||||
onMessage(
|
||||
JSON.stringify({
|
||||
type: "session",
|
||||
@@ -1042,175 +1030,6 @@ test("stops reconnecting after a password rejection on an established connection
|
||||
socket.triggerClose({ code: 4003, reason: "Incorrect password" });
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
expect(client.authFailureReason).toBe("incorrect_password");
|
||||
expect(client.helloRejection).toEqual({
|
||||
reason: "incorrect_password",
|
||||
accepts: [],
|
||||
});
|
||||
expect(attempts).toBe(1);
|
||||
});
|
||||
|
||||
test("normalizeHelloRejection sanitizes, bounds, deduplicates, and clears legacy incompatible_protocol accepts", () => {
|
||||
const sanitized = normalizeHelloRejection({
|
||||
reason: ` ${"r".repeat(80)} `,
|
||||
accepts: [
|
||||
" password ",
|
||||
"password",
|
||||
"",
|
||||
" ",
|
||||
"invite",
|
||||
...Array.from({ length: 20 }, (_, i) => `kind_${i}_${"x".repeat(70)}`),
|
||||
],
|
||||
message:
|
||||
"Line 1\n\t\u001b[31mVisit https://evil.test\u001b[0m \u202E\u200B\u061C\uFEFF\u0007 now",
|
||||
});
|
||||
|
||||
expect([...sanitized.reason]).toHaveLength(64);
|
||||
expect(sanitized.accepts).toHaveLength(16);
|
||||
expect(sanitized.accepts[0]).toBe("password");
|
||||
expect(sanitized.accepts[1]).toBe("invite");
|
||||
expect([...sanitized.accepts[2]]).toHaveLength(64);
|
||||
expect(sanitized.message).toBe("Line 1 Visit https://evil.test now");
|
||||
|
||||
const truncated = normalizeHelloRejection({
|
||||
reason: "maintenance",
|
||||
accepts: [],
|
||||
message: "🚀".repeat(250),
|
||||
});
|
||||
expect(truncated.message).toBeDefined();
|
||||
expect([...truncated.message!]).toHaveLength(200);
|
||||
expect(truncated.message!.endsWith("…")).toBe(true);
|
||||
|
||||
const blankMessage = normalizeHelloRejection({
|
||||
reason: "maintenance",
|
||||
message: " \u202E\u200B\n\r\t ",
|
||||
});
|
||||
expect(blankMessage.message).toBeUndefined();
|
||||
|
||||
const legacyIncompatible = normalizeHelloRejection({
|
||||
reason: "incompatible_protocol",
|
||||
accepts: ["password"],
|
||||
message: "ignored or kept",
|
||||
});
|
||||
expect(legacyIncompatible.accepts).toEqual([]);
|
||||
});
|
||||
|
||||
test("stops reconnecting and rejects connect() on incompatible_protocol even with legacy accepts", async () => {
|
||||
const socket = createMockTransport();
|
||||
let attempts = 0;
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_incompatible_protocol_test",
|
||||
reconnect: { enabled: true, baseDelayMs: 1, maxDelayMs: 1 },
|
||||
transportFactory: () => {
|
||||
attempts += 1;
|
||||
return socket.transport;
|
||||
},
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
socket.triggerOpen({ skipServerInfo: true });
|
||||
socket.triggerMessage(
|
||||
JSON.stringify({
|
||||
type: "hello.rejected",
|
||||
reason: "incompatible_protocol",
|
||||
accepts: ["password"],
|
||||
}),
|
||||
);
|
||||
socket.triggerClose({ code: 4003, reason: "Incompatible protocol version" });
|
||||
|
||||
const error = await connectPromise.catch((caught: unknown) => caught);
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
|
||||
expect(error).toBeInstanceOf(DaemonHelloRejectedError);
|
||||
expect(error).not.toBeInstanceOf(DaemonAuthenticationError);
|
||||
expect(getDaemonAuthFailureReason(error)).toBeNull();
|
||||
expect(getDaemonHelloRejection(error)).toEqual({
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
});
|
||||
expect(client.authFailureReason).toBeNull();
|
||||
expect(client.helloRejection).toEqual({
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
});
|
||||
expect(attempts).toBe(1);
|
||||
});
|
||||
|
||||
test("stops reconnecting and surfaces sanitized rejection for unknown future reasons", async () => {
|
||||
const socket = createMockTransport();
|
||||
let attempts = 0;
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_future_reason_test",
|
||||
reconnect: { enabled: true, baseDelayMs: 1, maxDelayMs: 1 },
|
||||
transportFactory: () => {
|
||||
attempts += 1;
|
||||
return socket.transport;
|
||||
},
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
socket.triggerOpen({ skipServerInfo: true });
|
||||
socket.triggerMessage(
|
||||
JSON.stringify({
|
||||
type: "hello.rejected",
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Re-pair\nvia QR \u202E",
|
||||
}),
|
||||
);
|
||||
socket.triggerClose({ code: 4401, reason: "Pairing required" });
|
||||
|
||||
const error = await connectPromise.catch((caught: unknown) => caught);
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
|
||||
expect(error).toBeInstanceOf(DaemonHelloRejectedError);
|
||||
expect(getDaemonHelloRejection(error)).toEqual({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Re-pair via QR",
|
||||
});
|
||||
expect(client.helloRejection).toEqual({
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Re-pair via QR",
|
||||
});
|
||||
expect(client.authFailureReason).toBeNull();
|
||||
expect(attempts).toBe(1);
|
||||
});
|
||||
|
||||
test("synthesizes helloRejection from legacy incompatible protocol close frame and halts reconnect", async () => {
|
||||
const socket = createMockTransport();
|
||||
let attempts = 0;
|
||||
const client = new DaemonClient({
|
||||
url: "ws://test",
|
||||
clientId: "clsk_legacy_close_incompatible",
|
||||
reconnect: { enabled: true, baseDelayMs: 1, maxDelayMs: 1 },
|
||||
transportFactory: () => {
|
||||
attempts += 1;
|
||||
return socket.transport;
|
||||
},
|
||||
});
|
||||
clients.push(client);
|
||||
|
||||
const connectPromise = client.connect();
|
||||
socket.triggerOpen({ skipServerInfo: true });
|
||||
socket.triggerClose({ code: 4003, reason: "Incompatible protocol version" });
|
||||
|
||||
const error = await connectPromise.catch((caught: unknown) => caught);
|
||||
await new Promise((resolve) => setTimeout(resolve, 30));
|
||||
|
||||
expect(error).toBeInstanceOf(DaemonHelloRejectedError);
|
||||
expect(getDaemonHelloRejection(error)).toEqual({
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
});
|
||||
expect(client.helloRejection).toEqual({
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
});
|
||||
expect(attempts).toBe(1);
|
||||
});
|
||||
|
||||
@@ -1340,7 +1159,6 @@ test("advertises client capabilities in hello", async () => {
|
||||
workspace_setup_blocked: true,
|
||||
workspace_setup_observation: true,
|
||||
hello_rejection: true,
|
||||
evolvable_hello_rejection: true,
|
||||
background_agents: true,
|
||||
browser_host: {
|
||||
supportedCommands: ["list_tabs"],
|
||||
|
||||
@@ -6,6 +6,7 @@ import type {
|
||||
WSOutboundMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import {
|
||||
HELLO_REJECTED_REASONS,
|
||||
applyAgentSnapshotDefaults,
|
||||
applySessionInboundDefaults,
|
||||
applySessionOutboundDefaults,
|
||||
@@ -21,6 +22,8 @@ import type {
|
||||
ShutdownRequestedStatusPayload,
|
||||
} from "./daemon-protocol-codec.js";
|
||||
|
||||
const HELLO_REJECTED_REASON_SET = new Set<string>(HELLO_REJECTED_REASONS);
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
@@ -65,19 +68,9 @@ function validateOutbound(input: unknown): OutboundValidationResult {
|
||||
return { success: true, data: input as unknown as WSOutboundMessage, skipped: [] };
|
||||
}
|
||||
if (input.type === "hello.rejected") {
|
||||
if (typeof input.reason !== "string" || input.reason.length === 0) {
|
||||
if (typeof input.reason !== "string" || !HELLO_REJECTED_REASON_SET.has(input.reason)) {
|
||||
return { success: false, error: { message: "Invalid hello.rejected reason" } };
|
||||
}
|
||||
if (
|
||||
input.accepts !== undefined &&
|
||||
(!Array.isArray(input.accepts) ||
|
||||
!input.accepts.every((entry) => typeof entry === "string" && entry.length > 0))
|
||||
) {
|
||||
return { success: false, error: { message: "Invalid hello.rejected accepts" } };
|
||||
}
|
||||
if (input.message !== undefined && typeof input.message !== "string") {
|
||||
return { success: false, error: { message: "Invalid hello.rejected message" } };
|
||||
}
|
||||
return { success: true, data: input as unknown as WSOutboundMessage, skipped: [] };
|
||||
}
|
||||
if (input.type === "session") {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { WebSocketServer, type WebSocket } from "ws";
|
||||
import { KNOWN_HELLO_REJECTED_REASONS } from "@getpaseo/protocol/messages";
|
||||
import { WSHelloRejectedMessageSchema } from "@getpaseo/protocol/messages";
|
||||
import { HELLO_REJECTED_REASONS } from "@getpaseo/protocol/validation/message-defaults";
|
||||
import {
|
||||
exportPublicKey,
|
||||
generateKeyPair,
|
||||
@@ -161,41 +162,18 @@ describe("leanProtocolCodec", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("validates outbound WS envelopes and matches strictProtocolCodec on open hello.rejected frames", () => {
|
||||
it("validates outbound WS envelopes and rejects malformed frames", () => {
|
||||
expect([...HELLO_REJECTED_REASONS]).toEqual(WSHelloRejectedMessageSchema.shape.reason.options);
|
||||
expect(leanProtocolCodec.validateOutbound({ type: "pong" }).success).toBe(true);
|
||||
const validHelloRejectedFrames: unknown[] = [
|
||||
...KNOWN_HELLO_REJECTED_REASONS.map((reason) => ({
|
||||
type: "hello.rejected",
|
||||
reason,
|
||||
accepts: reason === "incompatible_protocol" ? [] : ["password"],
|
||||
})),
|
||||
{
|
||||
type: "hello.rejected",
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again.",
|
||||
},
|
||||
{ type: "hello.rejected", reason: "maintenance", accepts: [] },
|
||||
{ type: "hello.rejected", reason: "rate_limited" },
|
||||
];
|
||||
for (const frame of validHelloRejectedFrames) {
|
||||
expect(leanProtocolCodec.validateOutbound(frame).success).toBe(true);
|
||||
expect(strictProtocolCodec.validateOutbound(frame).success).toBe(true);
|
||||
for (const reason of WSHelloRejectedMessageSchema.shape.reason.options) {
|
||||
expect(
|
||||
leanProtocolCodec.validateOutbound({
|
||||
type: "hello.rejected",
|
||||
reason,
|
||||
accepts: ["password"],
|
||||
}).success,
|
||||
).toBe(true);
|
||||
}
|
||||
|
||||
const invalidHelloRejectedFrames: unknown[] = [
|
||||
{ type: "hello.rejected" },
|
||||
{ type: "hello.rejected", reason: "" },
|
||||
{ type: "hello.rejected", reason: 42 },
|
||||
{ type: "hello.rejected", reason: "pairing_required", accepts: "invite" },
|
||||
{ type: "hello.rejected", reason: "pairing_required", accepts: [""] },
|
||||
{ type: "hello.rejected", reason: "pairing_required", message: 123 },
|
||||
];
|
||||
for (const frame of invalidHelloRejectedFrames) {
|
||||
expect(leanProtocolCodec.validateOutbound(frame).success).toBe(false);
|
||||
expect(strictProtocolCodec.validateOutbound(frame).success).toBe(false);
|
||||
}
|
||||
|
||||
expect(
|
||||
leanProtocolCodec.validateOutbound({
|
||||
type: "session",
|
||||
@@ -205,6 +183,9 @@ describe("leanProtocolCodec", () => {
|
||||
expect(leanProtocolCodec.validateOutbound({ type: "session", message: {} }).success).toBe(
|
||||
false,
|
||||
);
|
||||
expect(
|
||||
leanProtocolCodec.validateOutbound({ type: "hello.rejected", reason: "bogus" }).success,
|
||||
).toBe(false);
|
||||
expect(leanProtocolCodec.validateOutbound({ type: "unknown" }).success).toBe(false);
|
||||
});
|
||||
|
||||
|
||||
@@ -372,6 +372,7 @@ function collectOrderedSharedNodes(node, counts, visited, ordered) {
|
||||
export function generateMessageDefaultsModule({
|
||||
sessionOutboundMessageOptions,
|
||||
sessionInboundMessageOptions,
|
||||
helloRejectedReasons,
|
||||
agentSnapshotPayloadSchema,
|
||||
legacySchemaTransformDefaults,
|
||||
}) {
|
||||
@@ -438,6 +439,8 @@ export function generateMessageDefaultsModule({
|
||||
"// AUTO-GENERATED by generate-validation-aot.mjs — DO NOT EDIT",
|
||||
'import type { DefaultsNode } from "../../validation/message-defaults.js";',
|
||||
"",
|
||||
`export const HELLO_REJECTED_REASONS: readonly string[] = ${JSON.stringify(helloRejectedReasons)};`,
|
||||
"",
|
||||
...decls,
|
||||
...(decls.length > 0 ? [""] : []),
|
||||
`export const AGENT_SNAPSHOT_DEFAULTS: DefaultsNode | null = ${agentSnapshot ? emitNodeExpr(agentSnapshot, sharedRefs) : "null"};`,
|
||||
|
||||
@@ -95,6 +95,7 @@ const [
|
||||
const {
|
||||
sessionOutboundMessageOptions,
|
||||
sessionInboundMessageOptions,
|
||||
helloRejectedReasons,
|
||||
agentSnapshotPayloadSchema,
|
||||
legacySchemaTransformDefaults,
|
||||
} = await loadSourceFile(envelopeSource, { cacheBust: true });
|
||||
@@ -172,6 +173,7 @@ await writeFile(output, `${content}\n${sessionMessageValidators}`);
|
||||
const generatedDefaults = generateMessageDefaultsModule({
|
||||
sessionOutboundMessageOptions,
|
||||
sessionInboundMessageOptions,
|
||||
helloRejectedReasons,
|
||||
agentSnapshotPayloadSchema,
|
||||
legacySchemaTransformDefaults,
|
||||
});
|
||||
|
||||
@@ -2,10 +2,6 @@ export const CLIENT_CAPS = {
|
||||
terminalChunkedReplay: "terminal_chunked_replay",
|
||||
binaryChunkingV1: "binary_chunking_v1",
|
||||
helloRejection: "hello_rejection",
|
||||
// COMPAT(evolvableHelloRejection): added in v0.20.0, remove after 2027-06-03 once client floor >= v0.20.0.
|
||||
// Clients advertising this accept open hello.rejected reason/accepts/message payloads; older
|
||||
// hello_rejection-only clients require legacy reasons, accepts restricted to ["password"] | [], and no message.
|
||||
evolvableHelloRejection: "evolvable_hello_rejection",
|
||||
// COMPAT(ownedSubscriptions): added in v0.8.0, remove legacy ownership after 2027-03-09.
|
||||
ownedSubscriptions: "owned_subscriptions",
|
||||
// Clients outside the Paseo app version series can explicitly accept provider IDs.
|
||||
|
||||
@@ -9046,7 +9046,6 @@ export const WSHelloMessageSchema = z.object({
|
||||
.object({
|
||||
voice: z.boolean().optional(),
|
||||
[CLIENT_CAPS.helloRejection]: z.boolean().optional(),
|
||||
[CLIENT_CAPS.evolvableHelloRejection]: z.boolean().optional(),
|
||||
pushNotifications: z.boolean().optional(),
|
||||
[CLIENT_CAPS.explicitEventSubscriptions]: z.boolean().optional(),
|
||||
[CLIENT_CAPS.allProviders]: z.boolean().optional(),
|
||||
@@ -9086,20 +9085,11 @@ export const WSSessionOutboundSchema = z.object({
|
||||
message: SessionOutboundMessageSchema,
|
||||
});
|
||||
|
||||
export const KNOWN_HELLO_REJECTED_REASONS = [
|
||||
"password_required",
|
||||
"incorrect_password",
|
||||
"incompatible_protocol",
|
||||
] as const;
|
||||
export type KnownHelloRejectedReason = (typeof KNOWN_HELLO_REJECTED_REASONS)[number];
|
||||
|
||||
export const WSHelloRejectedMessageSchema = z.object({
|
||||
type: z.literal("hello.rejected"),
|
||||
reason: z.string().min(1),
|
||||
accepts: z.array(z.string().min(1)).optional(),
|
||||
message: z.string().optional(),
|
||||
reason: z.enum(["password_required", "incorrect_password", "incompatible_protocol"]),
|
||||
accepts: z.array(z.literal("password")),
|
||||
});
|
||||
export type WSHelloRejectedMessage = z.infer<typeof WSHelloRejectedMessageSchema>;
|
||||
|
||||
export const WSTunnelHelloMessageSchema = z.object({
|
||||
type: z.literal("tunnel_hello"),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import {
|
||||
AGENT_SNAPSHOT_DEFAULTS,
|
||||
HELLO_REJECTED_REASONS,
|
||||
SESSION_INBOUND_DEFAULTS,
|
||||
SESSION_OUTBOUND_DEFAULTS,
|
||||
} from "../generated/validation/message-defaults.js";
|
||||
@@ -22,6 +23,8 @@ export type DefaultsNode =
|
||||
}
|
||||
| { readonly k: "s"; readonly s: readonly DefaultsNode[] };
|
||||
|
||||
export { HELLO_REJECTED_REASONS };
|
||||
|
||||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
|
||||
export const sessionOutboundMessageOptions = SessionOutboundMessageSchema.options;
|
||||
export const sessionInboundMessageOptions = SessionInboundMessageSchema.options;
|
||||
export const helloRejectedReasons = WSHelloRejectedMessageSchema.shape.reason.options;
|
||||
export const agentSnapshotPayloadSchema = AgentSnapshotPayloadSchema;
|
||||
|
||||
// Legacy `.transform()` schemas whose wire defaults cannot be seen as `.default()` nodes alone.
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import {
|
||||
SessionInboundMessageSchema,
|
||||
WSHelloRejectedMessageSchema,
|
||||
WSInboundMessageSchema,
|
||||
WSOutboundMessageSchema,
|
||||
} from "../../src/messages.js";
|
||||
@@ -292,51 +291,3 @@ describe("what still fails", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("evolvable hello.rejected refusals", () => {
|
||||
it("accepts known reasons, future reasons, future accepts, omitted accepts, and optional message in Zod and AOT", () => {
|
||||
const validFrames = [
|
||||
{ type: "hello.rejected", reason: "password_required", accepts: ["password"] },
|
||||
{ type: "hello.rejected", reason: "incorrect_password", accepts: ["password"] },
|
||||
{ type: "hello.rejected", reason: "incompatible_protocol", accepts: [] },
|
||||
{
|
||||
type: "hello.rejected",
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair this device again.",
|
||||
},
|
||||
{
|
||||
type: "hello.rejected",
|
||||
reason: "credential_revoked",
|
||||
accepts: ["password", "invite"],
|
||||
message: "Device access was revoked.",
|
||||
},
|
||||
{ type: "hello.rejected", reason: "maintenance", accepts: [], message: "Back in 5m" },
|
||||
{ type: "hello.rejected", reason: "rate_limited" },
|
||||
{ type: "hello.rejected", reason: "future_reason", extraField: true },
|
||||
];
|
||||
|
||||
for (const frame of validFrames) {
|
||||
expect(WSHelloRejectedMessageSchema.safeParse(frame).success).toBe(true);
|
||||
expect(WSOutboundMessageSchema.safeParse(frame).success).toBe(true);
|
||||
expect(validateWSOutboundMessage(frame).success).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects malformed hello.rejected payloads", () => {
|
||||
const invalidFrames = [
|
||||
{ type: "hello.rejected", reason: "" },
|
||||
{ type: "hello.rejected", reason: 42 },
|
||||
{ type: "hello.rejected" },
|
||||
{ type: "hello.rejected", reason: "pairing_required", accepts: "invite" },
|
||||
{ type: "hello.rejected", reason: "pairing_required", accepts: [""] },
|
||||
{ type: "hello.rejected", reason: "pairing_required", accepts: [123] },
|
||||
{ type: "hello.rejected", reason: "pairing_required", message: 123 },
|
||||
];
|
||||
|
||||
for (const frame of invalidFrames) {
|
||||
expect(WSHelloRejectedMessageSchema.safeParse(frame).success).toBe(false);
|
||||
expect(validateWSOutboundMessage(frame).success).toBe(false);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -18408,3 +18408,76 @@ test.each([
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("streamAgent throws AgentTurnBusyError and non-replacing steerOrReplaceActiveTurn returns busy without replacing an active turn", async () => {
|
||||
const workdir = mkdtempSync(join(tmpdir(), "agent-non-replacing-steer-"));
|
||||
class RejectingSteerSession extends SteeringTestSession {
|
||||
cancelCalls = 0;
|
||||
override async steerActiveTurn() {
|
||||
return { status: "unavailable" as const };
|
||||
}
|
||||
override async cancelRun() {
|
||||
this.cancelCalls += 1;
|
||||
await super.cancelRun();
|
||||
}
|
||||
}
|
||||
const session = new RejectingSteerSession({ provider: "codex", cwd: workdir });
|
||||
const client = new (class extends TestAgentClient {
|
||||
override async createSession(): Promise<AgentSession> {
|
||||
return session;
|
||||
}
|
||||
})();
|
||||
const storage = new AgentStorage(join(workdir, "agents"), logger);
|
||||
const manager = new AgentManager({ clients: { codex: client }, registry: storage, logger });
|
||||
const agent = await manager.createAgent({ provider: "codex", cwd: workdir }, undefined, {
|
||||
workspaceId: undefined,
|
||||
});
|
||||
const providerStarted = new Promise<void>((resolve) => {
|
||||
const unsubscribe = session.subscribe((event) => {
|
||||
if (event.type === "turn_started") {
|
||||
unsubscribe();
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
});
|
||||
try {
|
||||
await startAgentRun(manager, agent.id, "initial turn", logger);
|
||||
await manager.waitForAgentRunStart(agent.id);
|
||||
await providerStarted;
|
||||
|
||||
expect(() => manager.streamAgent(agent.id, "competing turn")).toThrow(AgentTurnBusyError);
|
||||
|
||||
const steerResult = await manager.steerOrReplaceActiveTurn(
|
||||
agent.id,
|
||||
"mid-turn steer",
|
||||
undefined,
|
||||
undefined,
|
||||
false,
|
||||
);
|
||||
expect(steerResult).toEqual({ status: "busy" });
|
||||
expect(session.cancelCalls).toBe(0);
|
||||
expect(session.startPrompts).toEqual(["initial turn"]);
|
||||
|
||||
await expect(
|
||||
sendPreparedPromptToAgent({
|
||||
agentManager: manager,
|
||||
agentStorage: storage,
|
||||
agentId: agent.id,
|
||||
prompt: "mid-turn steer",
|
||||
activeTurnBehavior: "steer",
|
||||
replaceRunning: false,
|
||||
logger,
|
||||
}),
|
||||
).rejects.toBeInstanceOf(AgentTurnBusyError);
|
||||
|
||||
session.pushEvent({ type: "turn_completed", provider: "codex", turnId: "active-turn-1" });
|
||||
await vi.waitFor(() => expect(manager.hasInFlightRun(agent.id)).toBe(false));
|
||||
|
||||
await expect(
|
||||
manager.steerOrReplaceActiveTurn(agent.id, "after settle", undefined, undefined, false),
|
||||
).resolves.toEqual({ status: "inactive" });
|
||||
} finally {
|
||||
await manager.closeAgent(agent.id);
|
||||
rmSync(workdir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -583,7 +583,7 @@ export interface AgentManagerOptions {
|
||||
}
|
||||
|
||||
export type ActiveTurnSteerDispatchResult =
|
||||
| { status: "inactive" | "steered" }
|
||||
| { status: "inactive" | "steered" | "busy" }
|
||||
| { status: "replaced"; iterator: AsyncGenerator<AgentStreamEvent> };
|
||||
|
||||
export interface AgentPromptSubmissionOptions extends AgentRunOptions {
|
||||
@@ -4878,7 +4878,7 @@ export class AgentManager {
|
||||
},
|
||||
"agent.manager.stream.reject",
|
||||
);
|
||||
throw new Error(`Agent ${agentId} already has an active run`);
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} already has an active run`);
|
||||
}
|
||||
|
||||
const agent = existingAgent;
|
||||
@@ -5130,6 +5130,7 @@ export class AgentManager {
|
||||
prompt: AgentPromptInput,
|
||||
options?: AgentPromptSteerOptions,
|
||||
promptStart?: ForegroundPromptStart,
|
||||
allowReplace = true,
|
||||
): Promise<ActiveTurnSteerDispatchResult> {
|
||||
// A turn that is still starting has no id to steer yet. Replacing it would drop its
|
||||
// prompt, so wait until it is accepted (or fails) and steer the turn it became.
|
||||
@@ -5169,6 +5170,11 @@ export class AgentManager {
|
||||
return { status: "inactive" };
|
||||
}
|
||||
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
if (!allowReplace) {
|
||||
return { status: "busy" };
|
||||
}
|
||||
|
||||
await this.beforeSteerUnavailableFallback?.({ agentId, expectedTurnId });
|
||||
this.assertSteerAdmissionOwnsTurn(agent, expectedTurnId);
|
||||
return {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
AgentTurnBusyError,
|
||||
AgentTurnChangedError,
|
||||
AgentTurnStartRejectedError,
|
||||
type PromptDispatchDisposition,
|
||||
type PromptDispatchResult,
|
||||
} from "../agent-prompt.js";
|
||||
@@ -73,6 +72,8 @@ interface Admitted extends QueuedContent {
|
||||
urgency: QueuedMessageUrgency | null;
|
||||
/** A Stop found it in the queue. It waits for a prompt admitted after that Stop. */
|
||||
held: boolean;
|
||||
/** True when explicitly released by Send now (`promote`) and allowed to replace a non-steering turn. */
|
||||
promoted: boolean;
|
||||
outOfBandDeclined: boolean;
|
||||
/** Settles once the store holds it. Nothing dispatches it before that. */
|
||||
saved: Promise<void>;
|
||||
@@ -120,6 +121,8 @@ interface DispatchRequest {
|
||||
uploadedImages: readonly UploadedImage[];
|
||||
activeTurnBehavior: "steer" | "interrupt";
|
||||
idleOnly: boolean;
|
||||
/** True when this batch may interrupt/replace an active turn if steering is unavailable. */
|
||||
replaceRunning: boolean;
|
||||
/**
|
||||
* Claim this exact prompt at provider admission. A withdrawn message or a Stop that reached
|
||||
* the recipient first invalidates it.
|
||||
@@ -210,11 +213,10 @@ export interface AgentMessageDelivery {
|
||||
*/
|
||||
enqueue(message: Message): Promise<AgentMessageReceipt>;
|
||||
/**
|
||||
* Send a prompt that does not wait its turn. Compatible messages admitted before it go ahead
|
||||
* of it in the same provider prompt, so none starts a turn of its own afterwards. When a
|
||||
* boundary (conflicting session mode, queued non-agent command, or provider switch) prevents
|
||||
* coalescing, the prompt is queued behind those messages and releases the first group at once.
|
||||
* A direct command or restart-resume travels alone.
|
||||
* Send a prompt directly without sweeping queued messages. Queued messages remain in the queue
|
||||
* and dispatch once the turn settles. A non-command prompt that starts after a Stop reopens any
|
||||
* Stop-held queue so it drains after this turn. A direct provider switch behind queued messages
|
||||
* for the current provider queues behind them so they run on the current provider first.
|
||||
*/
|
||||
sendDirect<Result extends PromptDispatchResult>(
|
||||
direct: DirectPrompt,
|
||||
@@ -261,6 +263,8 @@ export interface AgentMessageDelivery {
|
||||
const isQueued = (message: Admitted): boolean => message.state === "queued";
|
||||
const isWithdrawn = (message: Admitted): boolean => message.state === "withdrawn";
|
||||
const isUrgent = (message: Admitted): boolean => isQueued(message) && message.urgency !== null;
|
||||
const isHumanQueued = (message: Admitted): boolean =>
|
||||
message.source === null && message.urgency === null;
|
||||
const isOfferable = (message: Admitted): boolean =>
|
||||
isQueued(message) &&
|
||||
!message.outOfBandDeclined &&
|
||||
@@ -376,39 +380,10 @@ function boundaryOfAdmitted(message: Admitted): DispatchBoundary {
|
||||
};
|
||||
}
|
||||
|
||||
function boundaryOfDirect(input: {
|
||||
direct: DirectPrompt;
|
||||
includeProviderSwitch: boolean;
|
||||
}): DispatchBoundary {
|
||||
return {
|
||||
prompt: input.direct.prompt,
|
||||
source: input.direct.source,
|
||||
sessionMode: input.direct.sessionMode,
|
||||
...(input.includeProviderSwitch ? { providerSwitch: input.direct.providerSwitch } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function modeGroups(messages: readonly Admitted[]): Admitted[][] {
|
||||
return dispatchGroups({ entries: messages, boundaryOf: boundaryOfAdmitted });
|
||||
}
|
||||
|
||||
function canCoalesceDirect(input: { ahead: readonly Admitted[]; direct: DirectPrompt }): boolean {
|
||||
// A direct provider switch only carries a Stop-held queue when every held message has no
|
||||
// explicit sessionMode and the switch itself requests no mode override. Any unheld message
|
||||
// or explicit mode belongs to the current provider and must not move across providers.
|
||||
const carriesHeldSwitch =
|
||||
Boolean(input.direct.providerSwitch) &&
|
||||
!input.direct.providerSwitch?.modeId &&
|
||||
input.direct.sessionMode === undefined &&
|
||||
input.ahead.length > 0 &&
|
||||
input.ahead.every((message) => message.held && message.sessionMode === undefined);
|
||||
const entries: DispatchBoundary[] = [
|
||||
...input.ahead.map(boundaryOfAdmitted),
|
||||
boundaryOfDirect({ direct: input.direct, includeProviderSwitch: !carriesHeldSwitch }),
|
||||
];
|
||||
return dispatchGroups({ entries, boundaryOf: (entry) => entry }).length <= 1;
|
||||
}
|
||||
|
||||
function toUploadedImageAttachments(
|
||||
uploadedImages: readonly UploadedImage[] | undefined,
|
||||
): Array<UploadedFileAttachment & { role: "image" }> {
|
||||
@@ -488,6 +463,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
|
||||
const isRunning = (recipientId: string): boolean =>
|
||||
Boolean(dependencies.isRunning?.(recipientId));
|
||||
const canSteer = (recipientId: string): boolean =>
|
||||
dependencies.canSteer ? dependencies.canSteer(recipientId) : true;
|
||||
const isHeld = (recipientId: string): boolean => inboxes.get(recipientId)?.phase === "held";
|
||||
|
||||
function report(error: unknown, recipientId: string, messageIds: readonly string[] = []): void {
|
||||
@@ -547,8 +524,12 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
allowReplace = false,
|
||||
): DispatchRequest {
|
||||
const messages = messagesOf(batch);
|
||||
const resolvedBehavior =
|
||||
activeTurnBehavior ??
|
||||
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer");
|
||||
return {
|
||||
recipientId,
|
||||
idleOnly,
|
||||
@@ -561,9 +542,8 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
prompt: formatBatch(batch),
|
||||
uploadedImages: uploadedImagesOf(batch),
|
||||
// A batch that waited for the turn to end is dispatched idle-only, so it never steers.
|
||||
activeTurnBehavior:
|
||||
activeTurnBehavior ??
|
||||
(messages.some((message) => message.urgency === "interrupt") ? "interrupt" : "steer"),
|
||||
activeTurnBehavior: resolvedBehavior,
|
||||
replaceRunning: !idleOnly && (resolvedBehavior === "interrupt" || allowReplace),
|
||||
// Every message in a batch belongs to one compatible mode group.
|
||||
sessionMode: messages.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
providerSwitch: messages[0]?.providerSwitch,
|
||||
@@ -713,6 +693,58 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
|
||||
}
|
||||
|
||||
async function clearUrgency(recipientId: string, messages: Admitted[]): Promise<void> {
|
||||
if (!messages.length) return;
|
||||
for (const message of messages) {
|
||||
message.urgency = null;
|
||||
message.promoted = false;
|
||||
}
|
||||
const ids = idsOf(messages);
|
||||
await write(store.clearUrgency(recipientId, ids), recipientId, ids);
|
||||
}
|
||||
|
||||
/** Return `"retry"` to loop with remaining messages, or `"done"` once handled. */
|
||||
async function handleDispatchError(input: {
|
||||
error: unknown;
|
||||
recipientId: string;
|
||||
messages: Admitted[];
|
||||
request: DispatchRequest;
|
||||
stopped: () => boolean;
|
||||
}): Promise<"retry" | "done"> {
|
||||
const { error, recipientId, messages, request, stopped } = input;
|
||||
// A Stop reached the recipient before the provider admitted the prompt.
|
||||
if (stopped()) {
|
||||
await handBack(recipientId, messages);
|
||||
return "done";
|
||||
}
|
||||
// A withdrawal invalidated this exact prompt, or a steer's turn ended first: try again.
|
||||
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
|
||||
await handBack(recipientId, messages);
|
||||
return "retry";
|
||||
}
|
||||
if (error instanceof AgentTurnBusyError) {
|
||||
await handBack(recipientId, messages);
|
||||
// A non-replacing steer that found a busy/non-steering turn drops its urgency so it
|
||||
// waits for turn end rather than spinning immediately.
|
||||
if (!request.idleOnly && !request.replaceRunning && request.activeTurnBehavior === "steer") {
|
||||
await clearUrgency(recipientId, messages);
|
||||
}
|
||||
return "done";
|
||||
}
|
||||
// Shutdown cut this dispatch off. The next start tries it again.
|
||||
if (closed) {
|
||||
await handBack(recipientId, messages);
|
||||
return "done";
|
||||
}
|
||||
// Transient timeouts, non-fatal RPC failures, and rejected turn starts stay queued
|
||||
// and hold until the next user prompt instead of dropping batches.
|
||||
await handBack(recipientId, messages);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox) hold(recipientId, inbox);
|
||||
report(error, recipientId, request.messageIds);
|
||||
return "done";
|
||||
}
|
||||
|
||||
/** Dispatch one batch. A batch that finds the recipient stopped, or busy when idle-only, stays queued. */
|
||||
async function deliver(
|
||||
recipientId: string,
|
||||
@@ -720,6 +752,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
idleOnly: boolean,
|
||||
stopped: () => boolean,
|
||||
activeTurnBehavior?: QueuedMessageUrgency,
|
||||
allowReplace = false,
|
||||
): Promise<void> {
|
||||
for (;;) {
|
||||
const prepared = await prepare(recipientId, batch);
|
||||
@@ -732,35 +765,29 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await handBack(recipientId, messages);
|
||||
continue;
|
||||
}
|
||||
const request = requestFor(recipientId, dispatching, idleOnly, stopped, activeTurnBehavior);
|
||||
let disposition: PromptDispatchDisposition;
|
||||
const request = requestFor(
|
||||
recipientId,
|
||||
dispatching,
|
||||
idleOnly,
|
||||
stopped,
|
||||
activeTurnBehavior,
|
||||
allowReplace,
|
||||
);
|
||||
try {
|
||||
for (const message of messages) message.beforeDispatch?.();
|
||||
disposition = await dependencies.dispatch(request);
|
||||
const disposition = await dependencies.dispatch(request);
|
||||
return complete(recipientId, messages, disposition);
|
||||
} catch (error) {
|
||||
// A Stop reached the recipient before the provider admitted the prompt.
|
||||
if (stopped()) return handBack(recipientId, messages);
|
||||
// A withdrawal invalidated this exact prompt; the rest goes again without it.
|
||||
// A steer whose turn ended first goes again, into the next turn or as a new one.
|
||||
if (messages.some(isWithdrawn) || error instanceof AgentTurnChangedError) {
|
||||
await handBack(recipientId, messages);
|
||||
continue;
|
||||
}
|
||||
if (error instanceof AgentTurnBusyError && request.idleOnly)
|
||||
return handBack(recipientId, messages);
|
||||
// The provider refused to start a turn. Retrying by itself would refuse again and add
|
||||
// the prompt to the history each time, so the queue waits for the next prompt.
|
||||
if (error instanceof AgentTurnStartRejectedError) {
|
||||
await handBack(recipientId, messages);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox) hold(recipientId, inbox);
|
||||
return report(error, recipientId, request.messageIds);
|
||||
}
|
||||
// Shutdown cut this dispatch off. The next start tries it again.
|
||||
if (closed) return handBack(recipientId, messages);
|
||||
return discard(recipientId, messages, error);
|
||||
const outcome = await handleDispatchError({
|
||||
error,
|
||||
recipientId,
|
||||
messages,
|
||||
request,
|
||||
stopped,
|
||||
});
|
||||
if (outcome === "retry") continue;
|
||||
return;
|
||||
}
|
||||
return complete(recipientId, messages, disposition);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -818,26 +845,45 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
): Promise<boolean> {
|
||||
const last = ahead.findLastIndex(isUrgent);
|
||||
if (last < 0) return false;
|
||||
const released = ahead.slice(0, last + 1).filter(isQueued);
|
||||
const [first] = released;
|
||||
const prefix = ahead.slice(0, last + 1).filter(isQueued);
|
||||
const [first] = prefix;
|
||||
if (!first) return false;
|
||||
// Only releasing the switch itself replaces the running turn with it.
|
||||
if (first.providerSwitch && !isUrgent(first)) return false;
|
||||
const now = first.providerSwitch ? [first] : (modeGroups(released)[0] ?? []);
|
||||
const behavior: QueuedMessageUrgency = released.some(
|
||||
(message) => message.urgency === "interrupt",
|
||||
)
|
||||
// Do not jump over a queued provider switch ahead of urgent items.
|
||||
const segment = first.providerSwitch ? prefix : beforeSwitch(prefix);
|
||||
const behavior: QueuedMessageUrgency = prefix.some((message) => message.urgency === "interrupt")
|
||||
? "interrupt"
|
||||
: "steer";
|
||||
// Agent and finish steers must not sweep human-queued items sitting ahead of them, and wait
|
||||
// until turn end when the provider cannot steer. Explicit interrupts, Send now promotions,
|
||||
// and direct provider switches release the prefix in order and may replace the active turn.
|
||||
const replaceActiveTurn =
|
||||
behavior === "interrupt" ||
|
||||
prefix.some((message) => isUrgent(message) && (message.promoted || message.source === null));
|
||||
const released = replaceActiveTurn
|
||||
? segment
|
||||
: segment.filter((message) => !isHumanQueued(message));
|
||||
const [head] = released;
|
||||
if (!head) return false;
|
||||
const now = head.providerSwitch ? [head] : (modeGroups(released)[0] ?? []);
|
||||
// A non-steering provider keeps agent/finish steer messages queued until turn end rather
|
||||
// than interrupting it. Human promotions ("Send now") and interrupts still replace it.
|
||||
if (
|
||||
isRunning(recipientId) &&
|
||||
behavior === "steer" &&
|
||||
!replaceActiveTurn &&
|
||||
!canSteer(recipientId)
|
||||
) {
|
||||
await clearUrgency(recipientId, released);
|
||||
return false;
|
||||
}
|
||||
// The rest follows when the turn these start ends. Persist the downgrade before dispatching
|
||||
// so a daemon restart while the first group runs does not revive consumed urgency.
|
||||
const deferred = released.slice(now.length);
|
||||
if (deferred.length) {
|
||||
for (const message of deferred) message.urgency = null;
|
||||
const deferredIds = idsOf(deferred);
|
||||
await write(store.clearUrgency(recipientId, deferredIds), recipientId, deferredIds);
|
||||
}
|
||||
await deliver(recipientId, now, false, stopped, behavior);
|
||||
const nowIds = new Set(idsOf(now));
|
||||
const deferred = prefix.filter((message) => isUrgent(message) && !nowIds.has(message.id));
|
||||
await clearUrgency(recipientId, deferred);
|
||||
await deliver(recipientId, now, false, stopped, behavior, replaceActiveTurn);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -900,8 +946,16 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
inbox.phase = "waiting";
|
||||
const running = isRunning(recipientId);
|
||||
if (running) inbox.cancelTimer = schedule(QUIET_MS, () => attempt(recipientId));
|
||||
const nothingToOffer = !dependencies.tryRunOutOfBand || !inbox.messages.some(isOfferable);
|
||||
if (running && nothingToOffer) return;
|
||||
const hasSteerableUrgent = inbox.messages.some(
|
||||
(message) =>
|
||||
isUrgent(message) &&
|
||||
(message.urgency === "interrupt" ||
|
||||
message.promoted ||
|
||||
message.source === null ||
|
||||
canSteer(recipientId)),
|
||||
);
|
||||
const hasOfferable = Boolean(dependencies.tryRunOutOfBand) && inbox.messages.some(isOfferable);
|
||||
if (running && !hasOfferable && !hasSteerableUrgent) return;
|
||||
nudge(recipientId, inbox);
|
||||
}
|
||||
|
||||
@@ -926,7 +980,9 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (insertIndex >= 0) inbox.messages.splice(insertIndex, 0, item);
|
||||
else inbox.messages.push(item);
|
||||
inbox.cancelTimer();
|
||||
if (item.urgency) {
|
||||
const batchesInQuietWindow =
|
||||
item.source?.kind === "agent-notification" && item.urgency !== "interrupt";
|
||||
if (item.urgency && !batchesInQuietWindow) {
|
||||
// A steer or an interrupt does not wait: it closes the window and takes the queue along. Its place
|
||||
// is reserved now, so a prompt admitted after it cannot take it away.
|
||||
inbox.cancelCap();
|
||||
@@ -968,6 +1024,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
resolve,
|
||||
reject,
|
||||
state: "queued",
|
||||
promoted: false,
|
||||
outOfBandDeclined: false,
|
||||
saved: Promise.resolve(),
|
||||
persisted: false,
|
||||
@@ -984,7 +1041,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
guidance: describeAgentMessage({
|
||||
activeTurnBehavior,
|
||||
running: isRunning(recipientId),
|
||||
canSteer: Boolean(dependencies.canSteer?.(recipientId)),
|
||||
canSteer: canSteer(recipientId),
|
||||
immediateWhenIdle: !source,
|
||||
}),
|
||||
};
|
||||
@@ -1043,55 +1100,20 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
}
|
||||
}
|
||||
|
||||
function join(riders: Ready[], direct: DirectPrompt): JoinedPrompt {
|
||||
if (!riders.length) {
|
||||
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
|
||||
return {
|
||||
prompt: own.prompt,
|
||||
uploadedImages: direct.uploadedImages ?? [],
|
||||
messageId: own.messageId,
|
||||
sessionMode: direct.sessionMode,
|
||||
unarchive: direct.unarchive !== false,
|
||||
};
|
||||
}
|
||||
// Sharing a prompt with queued messages, each entry needs its own marker to stay
|
||||
// a separate row with its own identity.
|
||||
const own = envelopeMessage(direct.prompt, direct.source ?? null, direct.messageId);
|
||||
const queued = messagesOf(riders);
|
||||
function prepareDirectPrompt(direct: DirectPrompt): JoinedPrompt {
|
||||
const own = prepareAgentMessage(direct.prompt, direct.source, direct.messageId);
|
||||
return {
|
||||
prompt: combine([...riders.map(envelopeEntry), own.prompt]),
|
||||
uploadedImages: [...uploadedImagesOf(riders), ...(direct.uploadedImages ?? [])],
|
||||
prompt: own.prompt,
|
||||
uploadedImages: direct.uploadedImages ?? [],
|
||||
messageId: own.messageId,
|
||||
sessionMode:
|
||||
direct.sessionMode ?? queued.findLast((message) => message.sessionMode)?.sessionMode,
|
||||
unarchive: direct.unarchive !== false || queued.some((message) => message.unarchive),
|
||||
sessionMode: direct.sessionMode,
|
||||
unarchive: direct.unarchive !== false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Messages that rode a direct prompt are delivered when the provider admits that prompt.
|
||||
* Until it answers, nothing later may pass them.
|
||||
*/
|
||||
async function ride(
|
||||
recipientId: string,
|
||||
riders: Admitted[],
|
||||
result: PromptDispatchResult,
|
||||
): Promise<void> {
|
||||
if (!riders.length) return;
|
||||
if (result.disposition === "turn_started") {
|
||||
try {
|
||||
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
|
||||
} catch {
|
||||
// The provider rejected the prompt that carried them. They go again, in their place.
|
||||
return handBack(recipientId, riders);
|
||||
}
|
||||
}
|
||||
await complete(recipientId, riders, result.disposition);
|
||||
}
|
||||
|
||||
/**
|
||||
* The stopped recipient stays stopped. Its queue, steers and interrupts included, goes with whatever
|
||||
* prompts it next.
|
||||
* The stopped recipient stays stopped. Its queue, steers and interrupts included, waits until
|
||||
* a later prompt reopens it or a queued item is promoted.
|
||||
*/
|
||||
function hold(recipientId: string, inbox: Inbox): void {
|
||||
inbox.cancelTimer();
|
||||
@@ -1100,17 +1122,26 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
inbox.stops++;
|
||||
for (const message of inbox.messages) {
|
||||
message.urgency = null;
|
||||
message.promoted = false;
|
||||
message.held = true;
|
||||
}
|
||||
void write(store.markHeld(recipientId), recipientId);
|
||||
}
|
||||
|
||||
/** A prompt admitted after a Stop releases what it left in the queue. */
|
||||
function reopen(recipientId: string, messages: Admitted[]): void {
|
||||
/** A prompt admitted after a Stop unpauses any held queue so it drains after this turn. */
|
||||
async function reopenHeld(recipientId: string, stopped: () => boolean): Promise<void> {
|
||||
const inbox = inboxes.get(recipientId);
|
||||
if (inbox?.phase !== "held") return;
|
||||
for (const message of messages) message.held = false;
|
||||
if (closed || stopped() || inbox?.phase !== "held") return;
|
||||
for (const message of inbox.messages) message.held = false;
|
||||
inbox.phase = "waiting";
|
||||
if (inbox.messages.length) {
|
||||
await write(store.clearHeld(recipientId), recipientId);
|
||||
} else {
|
||||
changed(recipientId);
|
||||
}
|
||||
if (!closed && !stopped() && !isRunning(recipientId)) {
|
||||
attempt(recipientId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Without a message admitted since the Stop, the queue is held again. */
|
||||
@@ -1219,7 +1250,11 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
await queued.saved;
|
||||
return queued.receipt;
|
||||
}
|
||||
const activeTurnBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const requestedBehavior = message.activeTurnBehavior ?? "queue";
|
||||
const activeTurnBehavior: AgentMessageBehavior =
|
||||
requestedBehavior === "steer" && isRunning(recipientId) && !canSteer(recipientId)
|
||||
? "queue"
|
||||
: requestedBehavior;
|
||||
const source = message.source ?? null;
|
||||
const item = createAdmitted(
|
||||
{
|
||||
@@ -1310,7 +1345,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
): Promise<DirectSendResult<Result>> {
|
||||
const { recipientId } = direct;
|
||||
// A retried direct send whose earlier attempt was queued must return that queued entry
|
||||
// rather than coalescing with itself or interrupting the turn ahead of it.
|
||||
// rather than duplicating or interrupting the turn ahead of it.
|
||||
if (direct.messageId) {
|
||||
const existing = inboxes
|
||||
.get(recipientId)
|
||||
@@ -1322,56 +1357,53 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
return { disposition: "queued", receipt: existing.receipt };
|
||||
}
|
||||
}
|
||||
// Its place in line is decided now: what is queued goes with it, what comes later follows.
|
||||
// A queued provider switch, and what follows it, waits for the turn this prompt starts.
|
||||
const takesQueue = !closed && !direct.resumesTurn && !isCommand(direct.prompt);
|
||||
const inbox = inboxes.get(recipientId);
|
||||
const queued = takesQueue ? [...(inbox?.messages ?? [])] : [];
|
||||
const ahead = beforeSwitch(queued);
|
||||
const behind = queued.slice(ahead.length);
|
||||
const stopped = inbox ? watchForStop(inbox) : () => false;
|
||||
|
||||
// When queued messages ahead of this prompt cross a boundary (conflicting sessionMode or
|
||||
// queued non-agent command), insert this prompt immediately after `ahead` with urgency so
|
||||
// the earlier group runs first under its own mode and this prompt follows on its own turn
|
||||
// before any queued provider switch or later arrival.
|
||||
if (takesQueue && !canCoalesceDirect({ ahead: ahead.filter(isQueued), direct })) {
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId: behind[0]?.id });
|
||||
const stopsBefore = inboxes.get(recipientId)?.stops ?? 0;
|
||||
const stopped = () => (inboxes.get(recipientId)?.stops ?? 0) !== stopsBefore;
|
||||
const queuedBehindCurrentProvider = (): string | null | undefined => {
|
||||
if (closed || !direct.providerSwitch) return null;
|
||||
const current = [...(inboxes.get(recipientId)?.messages ?? [])];
|
||||
const ahead = beforeSwitch(current);
|
||||
return ahead.some(isQueued) ? current[ahead.length]?.id : null;
|
||||
};
|
||||
|
||||
// A direct provider switch must not move queued messages meant for the current provider
|
||||
// onto the target provider, so queue it right after them and release them first.
|
||||
const insertBeforeId = queuedBehindCurrentProvider();
|
||||
if (insertBeforeId !== null) {
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId });
|
||||
return { disposition: "queued", receipt };
|
||||
}
|
||||
|
||||
return new Promise<DirectSendResult<Result>>((resolve, reject) => {
|
||||
run(recipientId, async () => {
|
||||
let riders: Admitted[] = [];
|
||||
let result: Result;
|
||||
try {
|
||||
const pending = closed ? [] : await prepare(recipientId, ahead);
|
||||
if (
|
||||
!closed &&
|
||||
takesQueue &&
|
||||
!canCoalesceDirect({ ahead: messagesOf(pending), direct })
|
||||
) {
|
||||
const aheadSet = new Set(ahead);
|
||||
const insertBeforeId = inboxes
|
||||
.get(recipientId)
|
||||
?.messages.find((entry) => !aheadSet.has(entry))?.id;
|
||||
const receipt = await enqueueDirect({ direct, insertBeforeId });
|
||||
const deferredInsertBeforeId = queuedBehindCurrentProvider();
|
||||
if (deferredInsertBeforeId !== null) {
|
||||
const receipt = await enqueueDirect({
|
||||
direct,
|
||||
insertBeforeId: deferredInsertBeforeId,
|
||||
});
|
||||
resolve({ disposition: "queued", receipt });
|
||||
return;
|
||||
}
|
||||
const dispatching = await markDispatching(recipientId, pending);
|
||||
riders = messagesOf(dispatching);
|
||||
for (const message of riders) message.state = "claimed";
|
||||
for (const message of riders) message.beforeDispatch?.();
|
||||
result = await send(join(dispatching, direct));
|
||||
result = await send(prepareDirectPrompt(direct));
|
||||
} catch (error) {
|
||||
await handBack(recipientId, riders);
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
resolve(result);
|
||||
await ride(recipientId, riders, result);
|
||||
if (behind.length && !stopped()) reopen(recipientId, behind);
|
||||
if (result.disposition === "turn_started") {
|
||||
try {
|
||||
await (dependencies.awaitStart?.(recipientId, result.started) ?? result.started);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (!direct.resumesTurn && !isCommand(direct.prompt)) {
|
||||
await reopenHeld(recipientId, stopped);
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
@@ -1412,6 +1444,7 @@ export function createAgentMessageDelivery(dependencies: Dependencies): AgentMes
|
||||
if (!promoted.has(message.id)) continue;
|
||||
message.urgency = urgency;
|
||||
message.held = false;
|
||||
message.promoted = true;
|
||||
}
|
||||
inbox.cancelTimer();
|
||||
inbox.cancelCap();
|
||||
|
||||
@@ -305,16 +305,16 @@ test("Stop holds the queue across a restart until it is promoted", async () => {
|
||||
await second.delivery.close();
|
||||
});
|
||||
|
||||
test("a prompt sent after a restart carries the held messages", async () => {
|
||||
test("a prompt sent after a restart runs alone, clears the hold, and delivers held messages after the turn ends", async () => {
|
||||
const home = await createHome();
|
||||
const first = openDaemon(home, { running: true });
|
||||
await queue(first.delivery, "held");
|
||||
await first.stop();
|
||||
await first.delivery.close();
|
||||
|
||||
const second = openDaemon(home);
|
||||
await second.delivery.start();
|
||||
let prompt: AgentPromptInput = "";
|
||||
const second = openDaemon(home, { running: true });
|
||||
await second.delivery.start();
|
||||
await second.delivery.sendDirect(
|
||||
{ recipientId: "parent", prompt: "continue", messageId: "next" },
|
||||
async (joined) => {
|
||||
@@ -323,7 +323,12 @@ test("a prompt sent after a restart carries the held messages", async () => {
|
||||
},
|
||||
);
|
||||
await second.settle();
|
||||
expect(String(prompt)).toContain('message-id="held"');
|
||||
expect(prompt).toBe("continue");
|
||||
expect(await second.saved("parent")).toEqual([{ id: "held", state: "queued", held: false }]);
|
||||
expect(second.ids()).toEqual([]);
|
||||
|
||||
await second.endTurn();
|
||||
expect(second.ids()).toEqual([["held"]]);
|
||||
expect(await second.saved("parent")).toEqual([]);
|
||||
await second.delivery.close();
|
||||
});
|
||||
|
||||
@@ -79,6 +79,28 @@ describe("trailing marker", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("gives each bundled user message its own messageId instead of copying the outer one", () => {
|
||||
const text = [
|
||||
formatAgentMessage({ id: "user-1", source: null, text: "First question" }),
|
||||
formatAgentMessage({ id: "user-2", source: null, text: "Second question" }),
|
||||
].join("\n\n");
|
||||
|
||||
expect(project(text, "provider-echo")).toEqual([
|
||||
{
|
||||
type: "user_message",
|
||||
text: "First question",
|
||||
clientMessageId: "user-1",
|
||||
messageId: "user-1",
|
||||
},
|
||||
{
|
||||
type: "user_message",
|
||||
text: "Second question",
|
||||
clientMessageId: "user-2",
|
||||
messageId: "user-2",
|
||||
},
|
||||
]);
|
||||
});
|
||||
|
||||
test("a body with leading whitespace replays the same after a provider trims the prompt", () => {
|
||||
const source = { kind: "agent-message" as const, agentId: "lead", title: "Lead" };
|
||||
for (const text of ["\n indented code", " - list"]) {
|
||||
|
||||
@@ -277,7 +277,9 @@ export function envelopeMessage(
|
||||
export function projectAgentMessages(item: AgentTimelineItem): AgentTimelineItem[] {
|
||||
if (item.type !== "user_message") return [item];
|
||||
const messages = parseAgentMessages(item.text);
|
||||
return messages ? messages.map((message) => projectAgentMessage(item, message)) : [item];
|
||||
if (!messages) return [item];
|
||||
const bundled = messages.length > 1;
|
||||
return messages.map((message) => projectAgentMessage(item, message, bundled));
|
||||
}
|
||||
|
||||
const AGENT_MESSAGE_CALL = "paseo-agent-message:";
|
||||
@@ -300,9 +302,18 @@ export function projectedMessageIds(item: AgentTimelineItem): string[] {
|
||||
function projectAgentMessage(
|
||||
item: Extract<AgentTimelineItem, { type: "user_message" }>,
|
||||
message: AgentMessage,
|
||||
bundled: boolean,
|
||||
): AgentTimelineItem {
|
||||
const { source } = message;
|
||||
if (!source) return { ...item, text: message.text, clientMessageId: message.id };
|
||||
if (!source) {
|
||||
return {
|
||||
...item,
|
||||
text: message.text,
|
||||
clientMessageId: message.id,
|
||||
// Keep each bundled human row uniquely identified instead of cloning the outer messageId.
|
||||
...(bundled && item.messageId !== undefined ? { messageId: message.id } : {}),
|
||||
};
|
||||
}
|
||||
switch (source.kind) {
|
||||
case "schedule":
|
||||
return {
|
||||
|
||||
@@ -32,7 +32,7 @@ export function describeAgentMessage(admission: Admission): string {
|
||||
"Queued, not delivered yet. The agent is working and reads your message when its current turn ends.";
|
||||
const followUp = canSteer
|
||||
? 'If the message cannot wait, send a short follow-up with activeTurnBehavior "steer" (it joins the running turn) or "interrupt" (it stops the turn and starts a new one).'
|
||||
: 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also stops the turn.';
|
||||
: 'If the message cannot wait, send a short follow-up with activeTurnBehavior "interrupt" (it stops the turn and starts a new one). This agent\'s provider cannot steer, so "steer" also waits until the current turn ends.';
|
||||
return `${waiting} ${followUp} ${DO_NOT_REPEAT}`;
|
||||
}
|
||||
if (!running) return "The agent is idle, so your message starts a turn now.";
|
||||
@@ -40,5 +40,5 @@ export function describeAgentMessage(admission: Admission): string {
|
||||
return "Interrupting the running turn. A new turn starts with your message.";
|
||||
return canSteer
|
||||
? "Steering the running turn. The agent reads your message at its next step and keeps working."
|
||||
: "This agent's provider cannot steer, so your message interrupts the running turn. A new turn starts with your message.";
|
||||
: "This agent's provider cannot steer, so your message is queued until the running turn ends.";
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { AgentMessageQueueStore, PersistedQueuedMessage } from "../store.js";
|
||||
import {
|
||||
assertValidRecipientId,
|
||||
clearHeldInQueue,
|
||||
clearQueue,
|
||||
clearUrgencyInQueue,
|
||||
cloneQueuedMessage,
|
||||
@@ -62,6 +63,7 @@ export function createMemoryAgentMessageQueueStore(): AgentMessageQueueStore {
|
||||
revertDispatching: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => revertDispatchingInQueue(current, ids)),
|
||||
markHeld: (recipientId) => mutate(recipientId, (current) => markHeldInQueue(current)),
|
||||
clearHeld: (recipientId) => mutate(recipientId, (current) => clearHeldInQueue(current)),
|
||||
clearUrgency: (recipientId, ids) =>
|
||||
mutate(recipientId, (current) => clearUrgencyInQueue(current, ids)),
|
||||
promote: (recipientId, targetId, urgency) =>
|
||||
|
||||
@@ -322,6 +322,32 @@ export function markHeldInQueue(
|
||||
};
|
||||
}
|
||||
|
||||
export function clearHeldInQueue(current: RecipientQueueState): TransitionOutcome<void> {
|
||||
if (current.items.length === 0) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
let changed = false;
|
||||
const nextItems = current.items.map((item) => {
|
||||
const copy = cloneQueuedMessage(item);
|
||||
if (copy.held) {
|
||||
copy.held = false;
|
||||
changed = true;
|
||||
}
|
||||
return copy;
|
||||
});
|
||||
|
||||
if (!changed) {
|
||||
return { nextState: current, changed: false, result: undefined };
|
||||
}
|
||||
|
||||
return {
|
||||
nextState: { nextSeq: current.nextSeq, items: nextItems },
|
||||
changed: true,
|
||||
result: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
export function promoteInQueue(
|
||||
current: RecipientQueueState,
|
||||
targetId: string,
|
||||
|
||||
@@ -391,6 +391,16 @@ export function createSqliteAgentMessageQueueStore(
|
||||
});
|
||||
},
|
||||
|
||||
async clearHeld(recipientId: string): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
database.write((sql) => {
|
||||
sql.run(
|
||||
"UPDATE agent_message_queue_items SET held = 0 WHERE recipient_id = ? AND held = 1",
|
||||
recipientId,
|
||||
);
|
||||
});
|
||||
},
|
||||
|
||||
async clearUrgency(recipientId: string, ids: readonly string[]): Promise<void> {
|
||||
assertValidRecipientId(recipientId);
|
||||
if (ids.length === 0) {
|
||||
|
||||
@@ -562,6 +562,19 @@ describe.each(adapters)("AgentMessageQueueStore contract ($name)", (adapter) =>
|
||||
state: "queued",
|
||||
}),
|
||||
]);
|
||||
|
||||
await store.clearHeld("agent-1");
|
||||
expect(
|
||||
(await store.listByRecipient("agent-1")).map((item) => ({
|
||||
id: item.id,
|
||||
held: item.held,
|
||||
urgency: item.urgency,
|
||||
state: item.state,
|
||||
})),
|
||||
).toEqual([
|
||||
{ id: "m1", held: false, urgency: null, state: "dispatching" },
|
||||
{ id: "m2", held: false, urgency: null, state: "queued" },
|
||||
]);
|
||||
});
|
||||
|
||||
test("promote promotes FIFO prefix 0..k, clears held, and reports not_found / already_dispatching", async () => {
|
||||
|
||||
@@ -73,6 +73,7 @@ export interface AgentMessageQueueStore {
|
||||
): Promise<PersistedQueuedMessage[]>;
|
||||
revertDispatching(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
markHeld(recipientId: string): Promise<PersistedQueuedMessage[]>;
|
||||
clearHeld(recipientId: string): Promise<void>;
|
||||
clearUrgency(recipientId: string, ids: readonly string[]): Promise<void>;
|
||||
promote(
|
||||
recipientId: string,
|
||||
|
||||
@@ -99,10 +99,14 @@ async function steerOrReplaceActiveRun(
|
||||
prompt,
|
||||
steerOptions,
|
||||
promptStart,
|
||||
options.replaceRunning,
|
||||
);
|
||||
if (result.status === "steered") {
|
||||
return { disposition: "steered" };
|
||||
}
|
||||
if (result.status === "busy") {
|
||||
throw new AgentTurnBusyError(`Agent ${agentId} is running`);
|
||||
}
|
||||
if (result.status === "replaced") {
|
||||
return { disposition: "turn_started", iterator: result.iterator };
|
||||
}
|
||||
@@ -325,6 +329,8 @@ export interface SendPromptToAgentParams {
|
||||
source?: AgentPromptSource;
|
||||
messageId?: string;
|
||||
activeTurnBehavior?: ActiveTurnBehavior;
|
||||
/** Override whether an active turn that cannot steer may be interrupted/replaced. */
|
||||
replaceRunning?: boolean;
|
||||
runOptions?: AgentRunOptions;
|
||||
/** Optional mode to set on the agent before the run starts. */
|
||||
sessionMode?: string;
|
||||
@@ -452,8 +458,8 @@ async function resolvePromptSource(
|
||||
* chat mentions, notify-on-finish) MUST go through this so behavior can never
|
||||
* drift between them.
|
||||
*
|
||||
* The prompt does not wait in the agent's message queue, and it does not jump it either:
|
||||
* messages already queued for the agent are delivered ahead of it in the same provider prompt.
|
||||
* The prompt does not wait in the agent's message queue and does not sweep queued messages:
|
||||
* existing queued items stay in the queue until the turn settles or are explicitly promoted.
|
||||
*
|
||||
* When `unarchive` is false and the agent is archived, the call is a silent
|
||||
* no-op (returns the normal turn-start disposition) — the agent is not run.
|
||||
@@ -548,7 +554,7 @@ export async function sendPreparedPromptToAgent(
|
||||
throw new Error("Queued agent message was withdrawn");
|
||||
}
|
||||
return await startAgentRun(params.agentManager, params.agentId, params.prompt, params.logger, {
|
||||
replaceRunning: !params.idleOnly,
|
||||
replaceRunning: params.replaceRunning ?? !params.idleOnly,
|
||||
idleOnly: params.idleOnly,
|
||||
admit: params.admit,
|
||||
onDispatch: params.onDispatch,
|
||||
|
||||
@@ -74,12 +74,14 @@ class Observation implements FinishObservation {
|
||||
}
|
||||
class Delivery implements FinishMessages {
|
||||
prompts: string[] = [];
|
||||
behaviors: Array<string | undefined> = [];
|
||||
/** Prompts as the recipient's provider receives them, inside their envelope. */
|
||||
enqueued: string[] = [];
|
||||
acknowledgments: Array<ReturnType<typeof deferred<"steered">>> = [];
|
||||
enqueuedListeners = new Set<Parameters<FinishMessages["onEnqueued"]>[0]>();
|
||||
async enqueue(message: Parameters<FinishMessages["enqueue"]>[0]) {
|
||||
this.prompts.push(message.text);
|
||||
this.behaviors.push(message.activeTurnBehavior);
|
||||
this.enqueued.push(
|
||||
formatAgentMessage({
|
||||
id: "notification",
|
||||
@@ -1067,4 +1069,14 @@ describe("suppressing redundant finished notices after an explicit child report"
|
||||
await until(() => state.delivery.prompts.length === 2);
|
||||
expect(state.delivery.prompts[1]).toContain("Done after bash");
|
||||
});
|
||||
|
||||
test("finish notifications default to activeTurnBehavior steer", async () => {
|
||||
const state = await scenario();
|
||||
await state.service.register(intent);
|
||||
await until(() => state.observation.waits.length === 1);
|
||||
|
||||
state.observation.waits[0]!.result.resolve(outcome("idle", "child", "All tests passed"));
|
||||
await until(() => state.delivery.prompts.length === 1);
|
||||
expect(state.delivery.behaviors).toEqual(["steer"]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -337,8 +337,8 @@ export function createFinishSubscriptions(deps: Dependencies): FinishSubscriptio
|
||||
title,
|
||||
event: finishNotificationEvents[reason],
|
||||
},
|
||||
// A finish report never enters a running turn.
|
||||
activeTurnBehavior: "queue",
|
||||
// A finish report steers when the provider supports it and queues until turn end otherwise.
|
||||
activeTurnBehavior: "steer",
|
||||
unarchive: false,
|
||||
});
|
||||
const acknowledge = () => {
|
||||
|
||||
@@ -4083,9 +4083,9 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
agentScoped: true,
|
||||
behavior: undefined,
|
||||
steering: "accepted",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries',
|
||||
applied: "steer",
|
||||
outcome: "steered",
|
||||
guidance: "Steering the running turn.",
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
@@ -4093,7 +4093,23 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
steering: "none",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also stops the turn',
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "queue",
|
||||
steering: "accepted",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'or "interrupt" (it stops the turn and starts a new one). The follow-up carries',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "queue",
|
||||
steering: "none",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
{
|
||||
agentScoped: true,
|
||||
@@ -4107,17 +4123,18 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
agentScoped: true,
|
||||
behavior: "steer",
|
||||
steering: "none",
|
||||
applied: "steer",
|
||||
outcome: "replaced",
|
||||
guidance: "This agent's provider cannot steer, so your message interrupts the running turn.",
|
||||
applied: "queue",
|
||||
outcome: "queued",
|
||||
guidance: 'provider cannot steer, so "steer" also waits until the current turn ends',
|
||||
},
|
||||
// A provider that can steer may refuse one steer; the turn is replaced all the same.
|
||||
// A provider that can steer may refuse one steer mid-turn; keep the message queued instead of
|
||||
// replacing the running turn.
|
||||
{
|
||||
agentScoped: true,
|
||||
behavior: "steer",
|
||||
steering: "unavailable",
|
||||
applied: "steer",
|
||||
outcome: "replaced",
|
||||
outcome: "queued",
|
||||
guidance: "Steering the running turn.",
|
||||
},
|
||||
{
|
||||
@@ -4318,10 +4335,10 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
);
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
activeTurnBehavior: "steer",
|
||||
});
|
||||
expect(response.structuredContent.guidance).toContain(
|
||||
"Queued. The agent is idle, so your message starts a turn in about 2 seconds.",
|
||||
"The agent is idle, so your message starts a turn now.",
|
||||
);
|
||||
expect(client.sessions[1]!.prompts).toHaveLength(1);
|
||||
} finally {
|
||||
@@ -4373,7 +4390,12 @@ describe("send_agent_prompt MCP tool", () => {
|
||||
if (rejected) session.rejectNextTurnStart(new Error("Start rejected"));
|
||||
const response = await mcpClient.callTool({
|
||||
name: "send_agent_prompt",
|
||||
arguments: { agentId: child.id, prompt: "New message", notifyOnFinish: true },
|
||||
arguments: {
|
||||
agentId: child.id,
|
||||
prompt: "New message",
|
||||
activeTurnBehavior: "queue",
|
||||
notifyOnFinish: true,
|
||||
},
|
||||
});
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
success: true,
|
||||
@@ -5241,7 +5263,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("a person's prompt takes the queued message into its own turn", async () => {
|
||||
it("a person's prompt runs alone without sweeping the queued message, which dispatches after the turn settles", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5249,10 +5271,8 @@ describe("message order for one recipient", () => {
|
||||
|
||||
await recipient.personSends("Pause the release");
|
||||
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts[1]).toBe("Pause the release");
|
||||
const rows = await recipient.agentManager.getTimeline(recipient.recipientId);
|
||||
expect(rows.flatMap((row) => (row.type === "user_message" ? [row.text] : []))).toEqual([
|
||||
"Pause the release",
|
||||
@@ -5260,13 +5280,16 @@ describe("message order for one recipient", () => {
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(10 * 60_000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
it("Stop holds the queued steer for the recipient's next prompt", async () => {
|
||||
it("Stop holds the queued steer until a later prompt reopens the queue without sweeping it", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5280,9 +5303,14 @@ describe("message order for one recipient", () => {
|
||||
expect(recipient.agentManager.getAgent(recipient.recipientId)?.lifecycle).toBe("idle");
|
||||
|
||||
await recipient.personSends("Carry on");
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
expect(recipient.session.prompts).toHaveLength(2);
|
||||
expect(recipient.session.prompts[1]).toBe("Carry on");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Carry on" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
@@ -5312,7 +5340,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("prompts sent while the provider is still starting a turn reach it in the order sent", async () => {
|
||||
it("a person's direct prompt does not sweep queued prompts while queued agent messages keep their order", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
const acknowledgeStart = recipient.session.holdTurnStart();
|
||||
@@ -5327,15 +5355,15 @@ describe("message order for one recipient", () => {
|
||||
acknowledgeStart();
|
||||
await Promise.all([interrupt, person]);
|
||||
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts[2]).toBe("Pause the release");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(4);
|
||||
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Tests passed" }]);
|
||||
expect(recipient.prompt(3)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: recipient.senderId, text: "Tests passed" },
|
||||
]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
@@ -5353,14 +5381,16 @@ describe("message order for one recipient", () => {
|
||||
await recipient.stop();
|
||||
await person;
|
||||
|
||||
// The next prompt is sent after the interrupt's dispatch has ended, so a turn the
|
||||
// interrupt started on its own would show up as a prompt between the two.
|
||||
// The next prompt is sent after the interrupt's dispatch has ended, so it runs alone and
|
||||
// reopens the held interrupt to run after this turn finishes.
|
||||
await recipient.personSends("Carry on");
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
expect(recipient.prompt(2)).toEqual([
|
||||
{ from: recipient.senderId, text: "Skip the backup" },
|
||||
{ from: "person", text: "Carry on" },
|
||||
]);
|
||||
expect(recipient.session.prompts[2]).toBe("Carry on");
|
||||
recipient.session.finishTurn();
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(4);
|
||||
expect(recipient.prompt(3)).toEqual([{ from: recipient.senderId, text: "Skip the backup" }]);
|
||||
} finally {
|
||||
await recipient.cleanup();
|
||||
}
|
||||
@@ -5427,7 +5457,7 @@ describe("message order for one recipient", () => {
|
||||
}
|
||||
});
|
||||
|
||||
it("a queued message returns to the queue when the provider rejects the person's turn", async () => {
|
||||
it("a queued message stays in the queue when the provider rejects the person's turn", async () => {
|
||||
const recipient = await setupRecipient();
|
||||
try {
|
||||
await recipient.agentSends("Go ahead and cut the release");
|
||||
@@ -5437,12 +5467,9 @@ describe("message order for one recipient", () => {
|
||||
await expect(recipient.personSends("Pause the release")).rejects.toThrow(
|
||||
"Provider is overloaded",
|
||||
);
|
||||
expect(recipient.prompt(1)).toEqual([
|
||||
{ from: recipient.senderId, text: "Go ahead and cut the release" },
|
||||
{ from: "person", text: "Pause the release" },
|
||||
]);
|
||||
expect(recipient.session.prompts[1]).toBe("Pause the release");
|
||||
|
||||
// The provider never took that prompt, so the steer is delivered on its own.
|
||||
// The provider rejected the person's prompt; the queued steer still dispatches on its own.
|
||||
recipient.advance(2000);
|
||||
await recipient.settled();
|
||||
expect(recipient.session.prompts).toHaveLength(3);
|
||||
|
||||
@@ -1408,7 +1408,7 @@ function createToolCatalog(
|
||||
const agentToAgentSendAgentPromptInputSchema = {
|
||||
...commonSendAgentPromptInputSchema,
|
||||
activeTurnBehavior: AgentActiveTurnBehaviorSchema.optional().describe(
|
||||
'Leave this out unless the message cannot wait. Default "queue": the message waits until the agent\'s running turn ends. "steer": the message joins the running turn; a provider that cannot steer interrupts the turn instead. "interrupt": the running turn stops and a new turn starts with the message. A steer or interrupt carries the messages you queued before it, in order.',
|
||||
'Default "steer": the message joins the running turn, or waits until the turn ends if the provider cannot steer. "queue": the message waits until the running turn ends. "interrupt": the running turn stops and a new turn starts with the message. A steer or interrupt carries earlier agent-queued messages ahead of it (never human-queued items), in order.',
|
||||
),
|
||||
notifyOnFinish: z
|
||||
.boolean()
|
||||
@@ -2117,7 +2117,7 @@ function createToolCatalog(
|
||||
title: "Send agent prompt",
|
||||
description:
|
||||
scope === "agent"
|
||||
? "Send a message to another agent. The response returns at once. Its guidance says whether the message waits for the running turn to end, joins it, or interrupts it, and how to deliver a waiting message now. Leave activeTurnBehavior out unless the message cannot wait. The recipient reads your messages in the order you sent them. A steer the recipient has not read is lost if its turn stops or is interrupted, along with the messages it carried. Completion reports include the target’s last response by default. Paseo supplies caller identity."
|
||||
? "Send a message to another agent. The response returns at once. Its guidance says whether the message steers the running turn, waits for it to end, or interrupts it, and how to deliver a waiting message now. By default activeTurnBehavior is steer (or queue if the provider cannot steer); pass queue to wait for turn end. The recipient reads your messages in the order you sent them. A steer the recipient has not read is lost if its turn stops or is interrupted, along with the agent-queued messages it carried. Completion reports include the target’s last response by default. Paseo supplies caller identity."
|
||||
: "Send a prompt to an agent. A running turn is interrupted unless activeTurnBehavior is steer.",
|
||||
inputSchema: sendAgentPromptInputSchema,
|
||||
outputSchema: {
|
||||
@@ -2201,7 +2201,7 @@ function createToolCatalog(
|
||||
title: resolveCallerAgent()?.config.title ?? undefined,
|
||||
},
|
||||
sessionMode,
|
||||
activeTurnBehavior,
|
||||
activeTurnBehavior: activeTurnBehavior ?? "steer",
|
||||
onDispatch: confirmDispatch,
|
||||
})
|
||||
.catch((error) => {
|
||||
|
||||
@@ -7,7 +7,6 @@ import { beforeEach, describe, expect, test, vi } from "vitest";
|
||||
import { createTestPaseoDaemon } from "./test-utils/paseo-daemon.js";
|
||||
import { DaemonAuthenticationError, DaemonClient } from "@getpaseo/client/internal/daemon-client";
|
||||
import { readLocalCredentialForTarget } from "./local-credential.js";
|
||||
import { formatHelloRejectedFrame } from "./websocket-server.js";
|
||||
|
||||
const originalEnv = { ...process.env };
|
||||
const CORRECT_PASSWORD_HASH = "$2b$12$OLxyuuP9uLK30Uzc4wQX0O6liuU/Q1t5P2b0Ebf36mULvpVK3DRZW";
|
||||
@@ -428,167 +427,4 @@ describe("daemon bearer auth", () => {
|
||||
await daemonHandle.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("sends accepts: [] for incompatible_protocol to capable clients and omits frame for oldest clients", async () => {
|
||||
const daemonHandle = await createTestPaseoDaemon({});
|
||||
try {
|
||||
// Oldest client: no hello_rejection / evolvable_hello_rejection / hello.auth -> close code only
|
||||
{
|
||||
const { ws } = await connectWebSocket({ port: daemonHandle.port });
|
||||
const frames: unknown[] = [];
|
||||
const closed = new Promise<{ code: number; reason: string }>((resolve) => {
|
||||
ws.on("message", (data) => frames.push(JSON.parse(data.toString())));
|
||||
ws.once("close", (code, reason) => resolve({ code, reason: reason.toString() }));
|
||||
});
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "hello",
|
||||
clientId: "oldest-client",
|
||||
clientType: "cli",
|
||||
protocolVersion: 0,
|
||||
}),
|
||||
);
|
||||
await expect(closed).resolves.toEqual({
|
||||
code: 4003,
|
||||
reason: "Incompatible protocol version",
|
||||
});
|
||||
expect(frames).toEqual([]);
|
||||
}
|
||||
|
||||
// Legacy hello_rejection-only client -> incompatible_protocol with accepts: []
|
||||
{
|
||||
const { ws } = await connectWebSocket({ port: daemonHandle.port });
|
||||
const frames: unknown[] = [];
|
||||
const closed = new Promise<{ code: number; reason: string }>((resolve) => {
|
||||
ws.on("message", (data) => frames.push(JSON.parse(data.toString())));
|
||||
ws.once("close", (code, reason) => resolve({ code, reason: reason.toString() }));
|
||||
});
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "hello",
|
||||
clientId: "legacy-hello-rejection",
|
||||
clientType: "cli",
|
||||
protocolVersion: 0,
|
||||
capabilities: { hello_rejection: true },
|
||||
}),
|
||||
);
|
||||
await expect(closed).resolves.toEqual({
|
||||
code: 4003,
|
||||
reason: "Incompatible protocol version",
|
||||
});
|
||||
expect(frames).toEqual([
|
||||
{ type: "hello.rejected", reason: "incompatible_protocol", accepts: [] },
|
||||
]);
|
||||
}
|
||||
|
||||
// Evolvable client -> incompatible_protocol with accepts: []
|
||||
{
|
||||
const { ws } = await connectWebSocket({ port: daemonHandle.port });
|
||||
const frames: unknown[] = [];
|
||||
const closed = new Promise<{ code: number; reason: string }>((resolve) => {
|
||||
ws.on("message", (data) => frames.push(JSON.parse(data.toString())));
|
||||
ws.once("close", (code, reason) => resolve({ code, reason: reason.toString() }));
|
||||
});
|
||||
ws.send(
|
||||
JSON.stringify({
|
||||
type: "hello",
|
||||
clientId: "evolvable-client",
|
||||
clientType: "cli",
|
||||
protocolVersion: 0,
|
||||
capabilities: { hello_rejection: true, evolvable_hello_rejection: true },
|
||||
}),
|
||||
);
|
||||
await expect(closed).resolves.toEqual({
|
||||
code: 4003,
|
||||
reason: "Incompatible protocol version",
|
||||
});
|
||||
expect(frames).toEqual([
|
||||
{ type: "hello.rejected", reason: "incompatible_protocol", accepts: [] },
|
||||
]);
|
||||
}
|
||||
} finally {
|
||||
await daemonHandle.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("formatHelloRejectedFrame enforces the wire compatibility matrix across client generations", () => {
|
||||
const oldestHello = {
|
||||
type: "hello" as const,
|
||||
clientId: "oldest",
|
||||
clientType: "cli" as const,
|
||||
protocolVersion: 1,
|
||||
};
|
||||
const legacyHello = {
|
||||
...oldestHello,
|
||||
clientId: "legacy",
|
||||
capabilities: { hello_rejection: true },
|
||||
};
|
||||
const evolvableHello = {
|
||||
...oldestHello,
|
||||
clientId: "evolvable",
|
||||
capabilities: { hello_rejection: true, evolvable_hello_rejection: true },
|
||||
};
|
||||
|
||||
// Oldest client never gets a hello.rejected frame.
|
||||
expect(
|
||||
formatHelloRejectedFrame(oldestHello, {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
}),
|
||||
).toBeNull();
|
||||
|
||||
// Legacy client: unknown reason without password -> incompatible_protocol, accepts: [], no message.
|
||||
expect(
|
||||
formatHelloRejectedFrame(legacyHello, {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "hello.rejected",
|
||||
reason: "incompatible_protocol",
|
||||
accepts: [],
|
||||
});
|
||||
|
||||
// Legacy client: unknown reason accepting password -> password_required, accepts: ["password"], no message.
|
||||
expect(
|
||||
formatHelloRejectedFrame(legacyHello, {
|
||||
reason: "password_expired",
|
||||
accepts: ["password", "invite"],
|
||||
message: "Rotate password",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "hello.rejected",
|
||||
reason: "password_required",
|
||||
accepts: ["password"],
|
||||
});
|
||||
|
||||
// Legacy client: known reason strips message and keeps compatible accepts.
|
||||
expect(
|
||||
formatHelloRejectedFrame(legacyHello, {
|
||||
reason: "incorrect_password",
|
||||
accepts: ["password", "invite"],
|
||||
message: "Try again",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "hello.rejected",
|
||||
reason: "incorrect_password",
|
||||
accepts: ["password"],
|
||||
});
|
||||
|
||||
// Evolvable client receives full open payload.
|
||||
expect(
|
||||
formatHelloRejectedFrame(evolvableHello, {
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
}),
|
||||
).toEqual({
|
||||
type: "hello.rejected",
|
||||
reason: "pairing_required",
|
||||
accepts: ["invite"],
|
||||
message: "Pair again",
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -345,7 +345,7 @@ export class ConnectedHosts {
|
||||
});
|
||||
} catch (error) {
|
||||
if (stopped) return;
|
||||
row.error = connectionFailure(error, client.helloRejection !== null) ?? {
|
||||
row.error = connectionFailure(error, client.authFailureReason !== null) ?? {
|
||||
code: "host_offline",
|
||||
message: "Host connection failed",
|
||||
};
|
||||
@@ -379,7 +379,7 @@ export class ConnectedHosts {
|
||||
Object.assign(new Error("Check the SSH configuration and daemon credentials"), {
|
||||
code: state.failureCode,
|
||||
}),
|
||||
client.helloRejection !== null,
|
||||
client.authFailureReason !== null,
|
||||
) ?? {
|
||||
code: "host_offline",
|
||||
message: "Cannot reach host. Check the connection; retrying automatically.",
|
||||
|
||||
@@ -79,20 +79,31 @@ async function createWorkingRecipient(options: { olderClient?: boolean } = {}) {
|
||||
}
|
||||
}
|
||||
|
||||
test("an agent's message without a behavior waits for the running turn and says how to deliver it now", async () => {
|
||||
test("an agent's message without a behavior steers a steering turn and can be overridden to queue", async () => {
|
||||
const { client, runtime, recipient, sender, close } = await createWorkingRecipient();
|
||||
try {
|
||||
const receipt = await client.sendAgentMessage(recipient.id, "Report when done", {
|
||||
const steered = await client.sendAgentMessage(recipient.id, "Adjust approach", {
|
||||
sourceAgentId: sender.id,
|
||||
});
|
||||
expect(receipt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
expect(receipt.guidance).toContain("Queued, not delivered yet.");
|
||||
expect(receipt.guidance).toContain('"steer" (it joins the running turn)');
|
||||
expect(runtime.prompts).toHaveLength(1);
|
||||
expect(steered).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "steer" });
|
||||
expect(steered.guidance).toBe(
|
||||
"Steering the running turn. The agent reads your message at its next step and keeps working.",
|
||||
);
|
||||
await expect.poll(() => runtime.prompts.length).toBe(2);
|
||||
expect(runtime.prompts[1]).toContain("Adjust approach");
|
||||
|
||||
const queued = await client.sendAgentMessage(recipient.id, "Report when done", {
|
||||
sourceAgentId: sender.id,
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
expect(queued).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
expect(queued.guidance).toContain("Queued, not delivered yet.");
|
||||
expect(queued.guidance).toContain('"steer" (it joins the running turn)');
|
||||
expect(runtime.prompts).toHaveLength(2);
|
||||
|
||||
runtime.finishExecution();
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2);
|
||||
expect(runtime.prompts[1]).toContain("Report when done");
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
|
||||
expect(runtime.prompts[2]).toContain("Report when done");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
@@ -229,6 +240,11 @@ async function createModeBoundaryRecipient(input: {
|
||||
onStartTurn: (prompt, config) => {
|
||||
executedTurns.push({ prompt: String(prompt), modeId: config.modeId });
|
||||
},
|
||||
onInterrupt: () => {
|
||||
for (const gate of gates.values()) {
|
||||
gate.release();
|
||||
}
|
||||
},
|
||||
beforeTurnComplete: async (prompt) => {
|
||||
const text = String(prompt);
|
||||
for (const [needle, gate] of gates) {
|
||||
@@ -277,12 +293,12 @@ async function createModeBoundaryRecipient(input: {
|
||||
}
|
||||
}
|
||||
|
||||
test("a direct broader-mode send behind a queued plan-mode message runs as two separate turns in their respective modes", async () => {
|
||||
test("a direct broader-mode send while a plan-mode message is queued runs as two separate turns in their respective modes", async () => {
|
||||
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
|
||||
initialModeId: "default",
|
||||
title: "Mode Boundary Worker",
|
||||
initialPrompt: "Initial work",
|
||||
heldPrompts: ["Inspect files read-only"],
|
||||
heldPrompts: ["Edit production files"],
|
||||
});
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(agent.id, "Inspect files read-only", {
|
||||
@@ -295,34 +311,33 @@ test("a direct broader-mode send behind a queued plan-mode message runs as two s
|
||||
activeTurnBehavior: "interrupt",
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
expect(directReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(directReceipt).toEqual({});
|
||||
|
||||
releaseTurn("Initial work");
|
||||
expect(await waitForTurn(1)).toEqual({
|
||||
prompt: "Inspect files read-only",
|
||||
modeId: "plan",
|
||||
});
|
||||
|
||||
releaseTurn("Inspect files read-only");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Edit production files",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
expect((await client.listAgentQueue(agent.id)).items).toMatchObject([
|
||||
{ text: "Inspect files read-only", state: "queued" },
|
||||
]);
|
||||
|
||||
releaseTurn("Edit production files");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Inspect files read-only",
|
||||
modeId: "plan",
|
||||
});
|
||||
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a direct bypassPermissions send behind a queued implicit-mode message on a restricted-mode agent runs as two separate turns", async () => {
|
||||
test("a direct bypassPermissions send while an implicit-mode message is queued on a restricted-mode agent runs as two separate turns", async () => {
|
||||
const { agent, client, releaseTurn, waitForTurn, close } = await createModeBoundaryRecipient({
|
||||
initialModeId: "always-ask",
|
||||
title: "Implicit Mode Worker",
|
||||
initialPrompt: "Initial restricted turn",
|
||||
heldPrompts: ["Queued in existing mode"],
|
||||
heldPrompts: ["Apply edits in bypass mode"],
|
||||
});
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(agent.id, "Queued in existing mode", {
|
||||
@@ -334,24 +349,156 @@ test("a direct bypassPermissions send behind a queued implicit-mode message on a
|
||||
activeTurnBehavior: "interrupt",
|
||||
sessionMode: "bypassPermissions",
|
||||
});
|
||||
expect(directReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(directReceipt).toEqual({});
|
||||
|
||||
releaseTurn("Initial restricted turn");
|
||||
expect(await waitForTurn(1)).toEqual({
|
||||
prompt: "Queued in existing mode",
|
||||
modeId: "always-ask",
|
||||
});
|
||||
|
||||
releaseTurn("Queued in existing mode");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Apply edits in bypass mode",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
expect((await client.listAgentQueue(agent.id)).items).toMatchObject([
|
||||
{ text: "Queued in existing mode", state: "queued" },
|
||||
]);
|
||||
|
||||
releaseTurn("Apply edits in bypass mode");
|
||||
expect(await waitForTurn(2)).toEqual({
|
||||
prompt: "Queued in existing mode",
|
||||
modeId: "bypassPermissions",
|
||||
});
|
||||
await client.waitForAgentUpsert(agent.id, (snapshot) => snapshot.status === "idle");
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
test.each(["steer", "interrupt"] as const)(
|
||||
"a human direct %s keeps queued user messages in the host queue and dispatches them after the turn ends",
|
||||
async (behavior) => {
|
||||
const { client, runtime, recipient, close } = await createWorkingRecipient();
|
||||
try {
|
||||
const queuedReceipt = await client.sendAgentMessage(recipient.id, "Queued user follow-up", {
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
expect(queuedReceipt).toMatchObject({
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
|
||||
const directReceipt = await client.sendAgentMessage(recipient.id, "Human direct prompt", {
|
||||
activeTurnBehavior: behavior,
|
||||
});
|
||||
expect(directReceipt).toEqual({});
|
||||
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 5_000 }).toBe(2);
|
||||
expect(runtime.prompts[1]).toBe("Human direct prompt");
|
||||
expect(runtime.prompts[1]).not.toContain("Queued user follow-up");
|
||||
|
||||
const queueState = await client.listAgentQueue(recipient.id);
|
||||
expect(queueState.items).toHaveLength(1);
|
||||
expect(queueState.items[0]).toMatchObject({
|
||||
text: "Queued user follow-up",
|
||||
state: "queued",
|
||||
});
|
||||
|
||||
runtime.finishExecution();
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
|
||||
expect(runtime.prompts[2]).toBe("Queued user follow-up");
|
||||
await expect
|
||||
.poll(async () => (await client.listAgentQueue(recipient.id)).items.length, {
|
||||
timeout: 5_000,
|
||||
})
|
||||
.toBe(0);
|
||||
} finally {
|
||||
await close();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
test("agent steer falls back to queue on a non-steering provider without interrupting, while explicit interrupt replaces the turn", async () => {
|
||||
const artifacts = path.resolve(".artifacts");
|
||||
await mkdir(artifacts, { recursive: true });
|
||||
const root = await mkdtemp(path.join(artifacts, "agent-non-steering-behavior-"));
|
||||
const runtime = new V2Harness();
|
||||
runtime.autoComplete = false;
|
||||
runtime.api.model.list = async () => ({ location: runtime.info.location, data: [] });
|
||||
runtime.api.provider.list = async () => ({
|
||||
location: runtime.info.location,
|
||||
data: [{ id: "test", name: "Test", activation: "enabled", package: "test" }],
|
||||
});
|
||||
let interrupts = 0;
|
||||
const origInterrupt = runtime.api.session.interrupt;
|
||||
runtime.api.session.interrupt = async (input, options) => {
|
||||
interrupts += 1;
|
||||
return origInterrupt(input, options);
|
||||
};
|
||||
runtime.prompt = async (input) => {
|
||||
runtime.prompts.push(input.text);
|
||||
runtime.startExecution();
|
||||
};
|
||||
const bridge = new OpenCodeBridge({
|
||||
paseoHome: path.join(root, "bridge"),
|
||||
logger: createTestLogger(),
|
||||
});
|
||||
await bridge.start();
|
||||
const opencodeClient = new OpenCodeV2AgentClient({
|
||||
logger: createTestLogger(),
|
||||
runtime: runtime.runtime,
|
||||
bridge,
|
||||
});
|
||||
// Disable mid-turn steering to model an ACP provider without steerActiveTurn.
|
||||
const originalCreateSession = opencodeClient.createSession.bind(opencodeClient);
|
||||
opencodeClient.createSession = async (config) => {
|
||||
const session = await originalCreateSession(config);
|
||||
session.steerActiveTurn = undefined;
|
||||
return session;
|
||||
};
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
agentClients: {
|
||||
...createTestAgentClients(),
|
||||
opencode: opencodeClient,
|
||||
},
|
||||
paseoHomeRoot: path.join(root, "daemon"),
|
||||
staticDir: path.join(root, "static"),
|
||||
cleanup: false,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.fetchAgents({ subscribe: {} });
|
||||
const recipient = await client.createAgent({
|
||||
provider: "opencode",
|
||||
cwd: root,
|
||||
title: "ACP-like",
|
||||
});
|
||||
const sender = await client.createAgent({ provider: "claude", cwd: root });
|
||||
await client.sendMessage(recipient.id, "Long initial turn");
|
||||
await client.waitForAgentUpsert(recipient.id, (agent) => agent.status === "running");
|
||||
|
||||
// Default omitted behavior and explicit steer both fall back to queue without interrupting.
|
||||
const defaultSteer = await client.sendAgentMessage(recipient.id, "Default steer note", {
|
||||
sourceAgentId: sender.id,
|
||||
});
|
||||
expect(defaultSteer).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "queue" });
|
||||
expect(interrupts).toBe(0);
|
||||
expect(runtime.prompts).toHaveLength(1);
|
||||
|
||||
runtime.finishExecution();
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(2);
|
||||
expect(runtime.prompts[1]).toContain("Default steer note");
|
||||
await client.waitForAgentUpsert(recipient.id, (agent) => agent.status === "running");
|
||||
|
||||
// Explicit interrupt still interrupts and starts a new turn.
|
||||
const interrupt = await client.sendAgentMessage(recipient.id, "Urgent stop", {
|
||||
sourceAgentId: sender.id,
|
||||
activeTurnBehavior: "interrupt",
|
||||
});
|
||||
expect(interrupt).toMatchObject({ deliveryStatus: "queued", activeTurnBehavior: "interrupt" });
|
||||
await expect.poll(() => runtime.prompts.length, { timeout: 10_000 }).toBe(3);
|
||||
expect(interrupts).toBeGreaterThanOrEqual(1);
|
||||
expect(runtime.prompts[2]).toContain("Urgent stop");
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await bridge.close();
|
||||
await rm(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
@@ -7745,4 +7745,89 @@ describe("session agent_update and agent_stream ordering", () => {
|
||||
await session.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test("agent-originated send_agent_message defaults omitted activeTurnBehavior to steer for modern clients and keeps explicit queue", async () => {
|
||||
const receiptDir = mkdtempSync(join(tmpdir(), "paseo-agent-default-steer-"));
|
||||
const dispatched: Array<{ activeTurnBehavior: string; idleOnly: boolean }> = [];
|
||||
const agentMessages = createAgentMessageDelivery({
|
||||
store: createMemoryAgentMessageQueueStore(),
|
||||
paseoHome: receiptDir,
|
||||
isRunning: () => true,
|
||||
canSteer: () => true,
|
||||
dispatch: async (request) => {
|
||||
dispatched.push({
|
||||
activeTurnBehavior: request.activeTurnBehavior,
|
||||
idleOnly: request.idleOnly,
|
||||
});
|
||||
return "steered";
|
||||
},
|
||||
onError: (error) => {
|
||||
throw error;
|
||||
},
|
||||
});
|
||||
const messages: SessionOutboundMessage[] = [];
|
||||
const session = createSessionForTest({
|
||||
messages,
|
||||
agentMessages,
|
||||
messageReceipts: new MessageReceipts(receiptDir),
|
||||
paseoHome: receiptDir,
|
||||
agentManager: {
|
||||
getAgent: (id: string) =>
|
||||
({
|
||||
id,
|
||||
status: "running",
|
||||
config: { title: id === "sender-1" ? "Sender" : null },
|
||||
}) as never,
|
||||
},
|
||||
agentStorage: {
|
||||
get: async (id: string) =>
|
||||
({ id, title: id === "sender-1" ? "Sender" : null, lastUserMessageAt: null }) as never,
|
||||
},
|
||||
});
|
||||
session.updateClientCapabilities({ agent_active_turn_behaviors: true });
|
||||
|
||||
try {
|
||||
await session.handleMessage({
|
||||
type: "send_agent_message_request",
|
||||
requestId: "req-default",
|
||||
agentId: "agent-1",
|
||||
sourceAgentId: "sender-1",
|
||||
text: "Steer by default",
|
||||
messageId: "msg-steer-default",
|
||||
});
|
||||
expect(findByType(messages, "send_agent_message_response")).toMatchObject({
|
||||
payload: {
|
||||
requestId: "req-default",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "steer",
|
||||
},
|
||||
});
|
||||
await expect.poll(() => dispatched.length).toBe(1);
|
||||
expect(dispatched[0]).toEqual({ activeTurnBehavior: "steer", idleOnly: false });
|
||||
|
||||
messages.length = 0;
|
||||
await session.handleMessage({
|
||||
type: "send_agent_message_request",
|
||||
requestId: "req-explicit-queue",
|
||||
agentId: "agent-1",
|
||||
sourceAgentId: "sender-1",
|
||||
text: "Wait explicitly",
|
||||
messageId: "msg-explicit-queue",
|
||||
activeTurnBehavior: "queue",
|
||||
});
|
||||
expect(findByType(messages, "send_agent_message_response")).toMatchObject({
|
||||
payload: {
|
||||
requestId: "req-explicit-queue",
|
||||
accepted: true,
|
||||
deliveryStatus: "queued",
|
||||
activeTurnBehavior: "queue",
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
await session.cleanup();
|
||||
await agentMessages.close();
|
||||
rmSync(receiptDir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9918,7 +9918,7 @@ export class Session {
|
||||
}
|
||||
}
|
||||
|
||||
/** An agent sender's message waits for the running turn to end unless it asks otherwise. */
|
||||
/** An agent sender's message steers by default (or queues if its provider cannot steer). */
|
||||
private agentSenderBehavior(
|
||||
requested: AgentActiveTurnBehavior | undefined,
|
||||
): AgentMessageBehavior {
|
||||
@@ -9927,7 +9927,7 @@ export class Session {
|
||||
// meaning wait for the turn to end, so only their interrupt stays an interrupt.
|
||||
if (!this.supports(CLIENT_CAPS.agentActiveTurnBehaviors))
|
||||
return requested === "interrupt" ? "interrupt" : "queue";
|
||||
return requested ?? "queue";
|
||||
return requested ?? "steer";
|
||||
}
|
||||
|
||||
private async handleAgentProviderSwitchRequest(
|
||||
|
||||
@@ -33,12 +33,7 @@ import {
|
||||
createWorkspaceBaseBranchService,
|
||||
type WorkspaceBaseBranchService,
|
||||
} from "./session/workspace-base-branch/service.js";
|
||||
import {
|
||||
KNOWN_HELLO_REJECTED_REASONS,
|
||||
type CreationSnapshot,
|
||||
type KnownHelloRejectedReason,
|
||||
type WSHelloRejectedMessage,
|
||||
} from "@getpaseo/protocol/messages";
|
||||
import type { CreationSnapshot } from "@getpaseo/protocol/messages";
|
||||
import { CreationService } from "./creation/index.js";
|
||||
import { MessageReceipts } from "./message-receipts/index.js";
|
||||
import { WebSocket, WebSocketServer } from "ws";
|
||||
@@ -603,64 +598,6 @@ export class MissingDaemonVersionError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export interface HelloRejectionSpec {
|
||||
readonly reason: string;
|
||||
readonly accepts?: readonly string[];
|
||||
readonly message?: string;
|
||||
}
|
||||
|
||||
const KNOWN_HELLO_REJECTED_REASON_SET = new Set<string>(KNOWN_HELLO_REJECTED_REASONS);
|
||||
|
||||
export function formatHelloRejectedFrame(
|
||||
hello: WSHelloMessage,
|
||||
rejection: HelloRejectionSpec,
|
||||
): WSHelloRejectedMessage | null {
|
||||
const accepts = rejection.accepts ? [...rejection.accepts] : [];
|
||||
if (hello.capabilities?.[CLIENT_CAPS.evolvableHelloRejection] === true) {
|
||||
return {
|
||||
type: "hello.rejected",
|
||||
reason: rejection.reason,
|
||||
accepts,
|
||||
...(rejection.message ? { message: rejection.message } : {}),
|
||||
};
|
||||
}
|
||||
// Older clients discard unknown frames, then use the close code and reason.
|
||||
// They never send hello.auth, so avoid sending an unknown envelope to them.
|
||||
if (!hello.auth && hello.capabilities?.[CLIENT_CAPS.helloRejection] !== true) {
|
||||
return null;
|
||||
}
|
||||
// COMPAT(evolvableHelloRejection): added in v0.20.0, remove after 2027-06-03 once client floor >= v0.20.0.
|
||||
const acceptsPassword = accepts.includes("password");
|
||||
let legacyReason: KnownHelloRejectedReason;
|
||||
if (KNOWN_HELLO_REJECTED_REASON_SET.has(rejection.reason)) {
|
||||
legacyReason = rejection.reason as KnownHelloRejectedReason;
|
||||
} else if (acceptsPassword) {
|
||||
legacyReason = "password_required";
|
||||
} else {
|
||||
legacyReason = "incompatible_protocol";
|
||||
}
|
||||
const legacyAccepts =
|
||||
legacyReason !== "incompatible_protocol" && acceptsPassword ? ["password"] : [];
|
||||
return {
|
||||
type: "hello.rejected",
|
||||
reason: legacyReason,
|
||||
accepts: legacyAccepts,
|
||||
};
|
||||
}
|
||||
|
||||
function closeReasonForHelloRejection(reason: string): string {
|
||||
switch (reason) {
|
||||
case "password_required":
|
||||
return "Password required";
|
||||
case "incorrect_password":
|
||||
return "Incorrect password";
|
||||
case "incompatible_protocol":
|
||||
return "Incompatible protocol version";
|
||||
default:
|
||||
return "Connection refused";
|
||||
}
|
||||
}
|
||||
|
||||
interface RequiredWebSocketServices {
|
||||
scheduleService: ScheduleService;
|
||||
checkoutDiffManager: CheckoutDiffManager;
|
||||
@@ -956,6 +893,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
})
|
||||
: await sendPreparedPromptToAgent({
|
||||
...send,
|
||||
replaceRunning: batch.replaceRunning,
|
||||
sessionMode: batch.sessionMode,
|
||||
runOptions: { clientMessageId: batch.messageIds[0] },
|
||||
});
|
||||
@@ -2162,7 +2100,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
},
|
||||
"Rejected hello due to protocol version mismatch",
|
||||
);
|
||||
await this.rejectHello(ws, message, { reason: "incompatible_protocol", accepts: [] });
|
||||
await this.rejectHello(ws, message, "incompatible_protocol");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2288,14 +2226,7 @@ export class VoiceAssistantWebSocketServer {
|
||||
if (this.pendingConnections.get(ws) !== pending) return false;
|
||||
if ("rejection" in resolved) {
|
||||
this.clearPendingConnection(ws);
|
||||
if (resolved.rejection === "throttled") {
|
||||
this.closeThrottledHello(ws);
|
||||
} else {
|
||||
await this.rejectHello(ws, message, {
|
||||
reason: resolved.rejection,
|
||||
accepts: ["password"],
|
||||
});
|
||||
}
|
||||
await this.rejectHello(ws, message, resolved.rejection);
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
@@ -2305,10 +2236,11 @@ export class VoiceAssistantWebSocketServer {
|
||||
this.passwordStore.getPasswordHash()
|
||||
) {
|
||||
this.clearPendingConnection(ws);
|
||||
await this.rejectHello(ws, message, {
|
||||
reason: message.auth ? "incorrect_password" : "password_required",
|
||||
accepts: ["password"],
|
||||
});
|
||||
await this.rejectHello(
|
||||
ws,
|
||||
message,
|
||||
message.auth ? "incorrect_password" : "password_required",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
pending.admission = resolved.admission;
|
||||
@@ -2317,40 +2249,42 @@ export class VoiceAssistantWebSocketServer {
|
||||
pending.connectionLogger.error({ err: error }, "Failed to resolve hello credential");
|
||||
if (this.pendingConnections.get(ws) === pending) {
|
||||
this.clearPendingConnection(ws);
|
||||
await this.rejectHello(ws, message, {
|
||||
reason: "incorrect_password",
|
||||
accepts: ["password"],
|
||||
});
|
||||
await this.rejectHello(ws, message, "incorrect_password");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private closeThrottledHello(ws: WebSocketLike): void {
|
||||
try {
|
||||
ws.close(WS_CLOSE_TRY_AGAIN_LATER, "Too many password attempts");
|
||||
} catch {
|
||||
// Ignore a transport that closed while the rejection was sent.
|
||||
}
|
||||
}
|
||||
|
||||
private async rejectHello(
|
||||
ws: WebSocketLike,
|
||||
hello: WSHelloMessage,
|
||||
rejection: HelloRejectionSpec,
|
||||
reason: "password_required" | "incorrect_password" | "incompatible_protocol" | "throttled",
|
||||
): Promise<void> {
|
||||
const frame = formatHelloRejectedFrame(hello, rejection);
|
||||
if (frame) {
|
||||
if (reason === "throttled") {
|
||||
try {
|
||||
await ws.send(JSON.stringify(frame));
|
||||
ws.close(WS_CLOSE_TRY_AGAIN_LATER, "Too many password attempts");
|
||||
} catch {
|
||||
// Ignore a transport that closed while the rejection was sent.
|
||||
}
|
||||
return;
|
||||
}
|
||||
// Older clients discard unknown frames, then use the close code and reason.
|
||||
// They never send hello.auth, so avoid sending an unknown envelope to them.
|
||||
if (hello.auth || hello.capabilities?.[CLIENT_CAPS.helloRejection] === true) {
|
||||
try {
|
||||
await ws.send(JSON.stringify({ type: "hello.rejected", reason, accepts: ["password"] }));
|
||||
} catch {
|
||||
// The close reason remains the compatibility signal.
|
||||
}
|
||||
}
|
||||
const closeReason = closeReasonForHelloRejection(rejection.reason);
|
||||
const closeReason = {
|
||||
password_required: "Password required",
|
||||
incorrect_password: "Incorrect password",
|
||||
incompatible_protocol: "Incompatible protocol version",
|
||||
}[reason];
|
||||
try {
|
||||
ws.close(
|
||||
rejection.reason === "incompatible_protocol"
|
||||
reason === "incompatible_protocol"
|
||||
? WS_CLOSE_INCOMPATIBLE_PROTOCOL
|
||||
: WS_CLOSE_DAEMON_AUTH_FAILED,
|
||||
closeReason,
|
||||
|
||||
@@ -96,13 +96,13 @@ Agent-scoped `create_agent` defaults `notifyOnFinish` to true. Set it to `false`
|
||||
|
||||
**`send_agent_prompt`** — `{ agentId, prompt, activeTurnBehavior? }`. Sends a follow-up to an existing agent and returns at once.
|
||||
|
||||
Leave `activeTurnBehavior` out unless the message cannot wait. It decides what happens when the agent is mid-turn:
|
||||
Leave `activeTurnBehavior` out unless you want non-default handling when the agent is mid-turn:
|
||||
|
||||
- `queue` (default): the message waits for the turn to end.
|
||||
- `steer`: the agent reads the message at its next step and keeps working. If its provider cannot steer, the turn is interrupted instead.
|
||||
- `interrupt`: the turn stops, and a new turn starts with the message.
|
||||
- `steer` (default): the agent reads the message at its next step and keeps working. If its provider cannot steer (or refuses steering mid-turn), the message waits until the turn ends instead of interrupting it.
|
||||
- `queue`: wait until the running turn ends.
|
||||
- `interrupt`: stop the running turn and start a new turn with the message.
|
||||
|
||||
Read `guidance` in the response. If it says your message is waiting and the message cannot wait, such as a course correction, send a short follow-up with `steer` or `interrupt`. Do not resend the message: the follow-up carries it, and a resent message is read twice.
|
||||
Read `guidance` in the response. If your message is waiting for turn end and cannot wait, send a short `interrupt` follow-up instead of resending (agent follow-ups carry earlier agent-queued messages ahead of them).
|
||||
|
||||
A steer the agent has not read is lost if its turn stops or is interrupted, along with the messages it carried. For a message that must arrive, use `queue` or `interrupt`.
|
||||
|
||||
|
||||
Reference in New Issue
Block a user