Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(remote): translate renderer IPC into RACP for remote sessions
vastsa1241ea2e72b4
diff --git a/apps/desktop/electron/main/remote/backend-router.ts b/apps/desktop/electron/main/remote/backend-router.tsindex 3f76bccba..9e38a4309 100644--- a/apps/desktop/electron/main/remote/backend-router.ts+++ b/apps/desktop/electron/main/remote/backend-router.ts@@ -21,6 +21,16 @@ export const ROUTE_LOCAL = Symbol("pi-desktop.route-local");/** Namespaced-id prefix for sessions owned by a remote host. */const REMOTE_PREFIX = "remote:";+/**+ * Delimiter that embeds the renderer-visible remote session id inside a tool+ * permission `requestId`. `toolResolvePermission` carries only `{requestId,+ * decision}` — no session id — so the id itself must name its owning session+ * for {@link sessionIdForCall} to route the resolution statelessly, with no+ * correlation map. Chosen so it cannot collide with a `remote:` session id or a+ * host-assigned approval id.+ */+const APPROVAL_ID_DELIMITER = "#racp-approval:";+/** A registered remote host's session, addressed by its renderer-visible id. */export interface RemoteBackend {/**@@ -79,10 +89,40 @@ export function parseRemoteSessionId(return { hostKey: rest.slice(0, sep), hostSessionId: rest.slice(sep + 1) };}+/**+ * Encode a tool permission `requestId` that names its owning remote session.+ * The renderer echoes this id back verbatim in `toolResolvePermission`, and the+ * router recovers the session from it without any server-side correlation.+ */+export function makeRemoteApprovalRequestId(+ remoteSessionId: string,+ hostApprovalId: string,+): string {+ return `${remoteSessionId}${APPROVAL_ID_DELIMITER}${hostApprovalId}`;+}++/**+ * Split an encoded approval `requestId` back into the remote session id and the+ * host's own approval id. Returns null for a plain (local) request id.+ */+export function parseRemoteApprovalRequestId(+ requestId: string,+): { remoteSessionId: string; hostApprovalId: string } | null {+ const at = requestId.indexOf(APPROVAL_ID_DELIMITER);+ if (at <= 0) return null;+ const remoteSessionId = requestId.slice(0, at);+ if (!isRemoteSessionId(remoteSessionId)) return null;+ const hostApprovalId = requestId.slice(at + APPROVAL_ID_DELIMITER.length);+ if (!hostApprovalId) return null;+ return { remoteSessionId, hostApprovalId };+}+/*** Best-effort session id for a renderer IPC call. Desktop channels pass the* session id either as the first positional argument or as `sessionId` on the- * first argument object; anything else has no session and is always local.+ * first argument object; `toolResolvePermission` carries neither, so its+ * remote-session-encoded `requestId` is decoded instead. Anything else has no+ * session and is always local.*/export function sessionIdForCall(args: readonly unknown[]): string | null {const first = args[0];@@ -90,6 +130,16 @@ export function sessionIdForCall(args: readonly unknown[]): string | null {if (first && typeof first === "object") {const id = (first as { sessionId?: unknown }).sessionId;if (typeof id === "string" && isRemoteSessionId(id)) return id;+ // `sessionGet` addresses the session as `{ id }` rather than `{ sessionId }`.+ // Matching a bare `id` is safe because only a `remote:`-prefixed value ever+ // resolves, and no other entity id carries that prefix.+ const bareId = (first as { id?: unknown }).id;+ if (typeof bareId === "string" && isRemoteSessionId(bareId)) return bareId;+ const requestId = (first as { requestId?: unknown }).requestId;+ if (typeof requestId === "string") {+ const parsed = parseRemoteApprovalRequestId(requestId);+ if (parsed) return parsed.remoteSessionId;+ }}return null;}diff --git a/apps/desktop/electron/main/remote/remote-backend.ts b/apps/desktop/electron/main/remote/remote-backend.tsnew file mode 100644index 000000000..b3237ab78--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-backend.ts@@ -0,0 +1,368 @@+/**+ * The remote backend: translates one paired host's renderer IPC calls into RACP+ * requests and reshapes the results into the exact response shapes the renderer+ * already expects from the local handlers. One instance serves every session of+ * a host; the owning host session id is derived from each call's arguments, so+ * the same instance is registered under each of the host's session ids.+ *+ * Ownership stays inside the frozen architecture: this runs in Electron Main and+ * speaks RACP-WS to the remote `pi-host`; the renderer is unaware of the+ * transport (spec §3.4). Channels the remote profile does not cover return+ * `false` from {@link RemoteBackend.handles} and fall back to the local handler.+ */+import { ErrorCodes, IPC } from "@pi-desktop/shared";+import type {+ AgentCompactResponse,+ AgentPromptRequest,+ AgentPromptResponse,+ AgentQueuePushRequest,+ AgentStatus,+ AgentStopResponse,+ AskToolResolution,+ PlanResolutionResult,+ PlanResolveRequest,+ QueuedTurnSummary,+ RacpApprovalResult,+ RacpRequestContext,+ RacpSession,+ RacpSessionSnapshot,+ RacpTurn,+ SessionDetail,+ SessionSummary,+ ToolPermissionResolution,+} from "@pi-desktop/shared";+import type { RemoteBackend } from "./backend-router.js";+import {+ makeRemoteSessionId,+ parseRemoteApprovalRequestId,+ parseRemoteSessionId,+ sessionIdForCall,+} from "./backend-router.js";+import { racpSessionToSummary, snapshotToSessionDetail } from "./remote-transcript.js";++/** The subset of `RacpClient` this backend needs; kept minimal for testing. */+export type RemoteRacpClient = {+ request<T>(method: string, params?: unknown): Promise<T>;+};++export type RemoteBackendOptions = {+ /** The host's routing key; the outward id of a forked session reuses it. */+ hostKey: string;+ client: RemoteRacpClient;+ /** Injectable id source for RACP request contexts; defaults to a UUID. */+ newRequestId?: () => string;+};++type AttachResultLike = { session: RacpSession; snapshot?: RacpSessionSnapshot };++function capabilityUnavailable(message: string): Error {+ return Object.assign(new Error(message), {+ errorCode: ErrorCodes.CAPABILITY_UNAVAILABLE,+ });+}++/** The channels a remote host serves; every other channel stays local. */+const HANDLED_CHANNELS: ReadonlySet<string> = new Set([+ IPC.invoke.agentPrompt,+ IPC.invoke.agentQueuePush,+ IPC.invoke.agentQueueList,+ IPC.invoke.agentStop,+ IPC.invoke.agentAbort,+ IPC.invoke.agentCompact,+ IPC.invoke.agentGetStatus,+ IPC.invoke.agentSteer,+ IPC.invoke.sessionGet,+ IPC.invoke.sessionConfigure,+ IPC.invoke.sessionFork,+ IPC.invoke.sessionRename,+ IPC.invoke.sessionDelete,+ IPC.invoke.toolResolvePermission,+ IPC.invoke.askToolResolve,+ IPC.invoke.plansResolve,+ IPC.invoke.plansPending,+]);++export function createRemoteBackend(options: RemoteBackendOptions): RemoteBackend {+ const { hostKey, client } = options;+ const newRequestId = options.newRequestId ?? (() => globalThis.crypto.randomUUID());+ const context = (idempotencyKey?: string): RacpRequestContext => ({+ requestId: newRequestId(),+ ...(idempotencyKey ? { idempotencyKey } : {}),+ });++ /** The remote-visible id for a call, or throw if it names no remote session. */+ const remoteIdFor = (args: readonly unknown[]): string => {+ const id = sessionIdForCall(args);+ if (!id) {+ throw Object.assign(new Error("call does not address a remote session"), {+ errorCode: ErrorCodes.INTERNAL,+ });+ }+ return id;+ };++ /** The host's own session id (the router only forwards remote-prefixed ids). */+ const hostIdFor = (args: readonly unknown[]): string => {+ const parsed = parseRemoteSessionId(remoteIdFor(args));+ if (!parsed) {+ throw Object.assign(new Error("malformed remote session id"), {+ errorCode: ErrorCodes.INTERNAL,+ });+ }+ return parsed.hostSessionId;+ };++ /** Resolve the turn to act on: an explicit id, else the session's active turn. */+ const resolveTurnId = async (+ hostSessionId: string,+ turnId?: string,+ ): Promise<string | undefined> => {+ if (turnId) return turnId;+ const { session } = await client.request<{ session: RacpSession }>("session/get", {+ sessionId: hostSessionId,+ });+ return session.activeTurnId;+ };++ const startTurn = async (+ req: AgentPromptRequest | AgentQueuePushRequest,+ admission: "reject_if_busy" | "queue",+ ): Promise<{ accepted: boolean; turn: RacpTurn }> => {+ if ("attachments" in req && req.attachments?.length) {+ throw capabilityUnavailable("this remote host does not accept attachments");+ }+ const hostSessionId = parseRemoteSessionId(req.sessionId)?.hostSessionId;+ if (!hostSessionId) {+ throw Object.assign(new Error("malformed remote session id"), {+ errorCode: ErrorCodes.INTERNAL,+ });+ }+ const idempotencyKey = "idempotencyKey" in req ? req.idempotencyKey : undefined;+ return client.request("turn/start", {+ sessionId: hostSessionId,+ admission,+ ...(idempotencyKey ? { idempotencyKey } : {}),+ input: {+ text: req.content,+ ...(req.sessionMessageId ? { sessionMessageId: req.sessionMessageId } : {}),+ ...("messageId" in req && req.messageId ? { messageId: req.messageId } : {}),+ },+ context: context(idempotencyKey),+ });+ };++ const invoke = async (channel: string, args: readonly unknown[]): Promise<unknown> => {+ switch (channel) {+ case IPC.invoke.agentPrompt: {+ const { accepted, turn } = await startTurn(args[0] as AgentPromptRequest, "reject_if_busy");+ return { accepted, turnId: turn.id } satisfies AgentPromptResponse;+ }+ case IPC.invoke.agentQueuePush: {+ const req = args[0] as AgentQueuePushRequest;+ const { turn } = await startTurn(req, "queue");+ // The prompt text is known here (the snapshot's queued turns do not carry+ // it), so the pushed entry renders with its content immediately.+ return {+ id: turn.id,+ sessionId: req.sessionId,+ content: req.content,+ ...(req.sessionMessageId ? { sessionMessageId: req.sessionMessageId } : {}),+ position: turn.queuePosition ?? 0,+ createdAt: new Date().toISOString(),+ } satisfies QueuedTurnSummary;+ }+ case IPC.invoke.agentQueueList: {+ const remoteSessionId = remoteIdFor(args);+ const attach = await client.request<AttachResultLike>("session/attach", {+ sessionId: parseRemoteSessionId(remoteSessionId)!.hostSessionId,+ includeSnapshot: true,+ });+ const entries: QueuedTurnSummary[] = (attach.snapshot?.queuedTurns ?? []).map(+ (turn, index) => ({+ id: turn.id,+ sessionId: remoteSessionId,+ // RACP turns do not carry the queued prompt text; the entry still+ // renders with its position and id, and live pushes fill content.+ content: "",+ position: turn.queuePosition ?? index + 1,+ createdAt: turn.startedAt ?? new Date().toISOString(),+ }),+ );+ return { entries };+ }+ case IPC.invoke.agentStop: {+ const req = args[0] as { sessionId: string; turnId?: string };+ const turnId = await resolveTurnId(hostIdFor(args), req.turnId);+ if (!turnId) return { requested: false } satisfies AgentStopResponse;+ await client.request("turn/stop", { turnId });+ return { requested: true } satisfies AgentStopResponse;+ }+ case IPC.invoke.agentAbort: {+ const req = args[0] as { sessionId: string; turnId?: string };+ const turnId = await resolveTurnId(hostIdFor(args), req.turnId);+ if (!turnId) return { aborted: false };+ await client.request("turn/interrupt", { turnId });+ return { aborted: true };+ }+ case IPC.invoke.agentCompact: {+ await client.request("session/compact", { sessionId: hostIdFor(args) });+ return { accepted: true } satisfies AgentCompactResponse;+ }+ case IPC.invoke.agentGetStatus: {+ const remoteSessionId = remoteIdFor(args);+ const { session } = await client.request<{ session: RacpSession }>("session/get", {+ sessionId: parseRemoteSessionId(remoteSessionId)!.hostSessionId,+ });+ const status: AgentStatus = {+ sessionId: remoteSessionId,+ isRunning: session.status === "running",+ ...(session.activeTurnId ? { currentTurnId: session.activeTurnId } : {}),+ pendingToolConfirmations: session.status === "waiting_permission" ? 1 : 0,+ planningState: session.planningState,+ };+ return { status };+ }+ case IPC.invoke.agentSteer:+ // Steering an in-flight turn is a local sidecar affordance with no RACP+ // operation; the renderer already guards it behind a capability check.+ throw capabilityUnavailable("steering is not available on a remote host");+ case IPC.invoke.sessionGet: {+ const remoteSessionId = remoteIdFor(args);+ const attach = await client.request<AttachResultLike>("session/attach", {+ sessionId: parseRemoteSessionId(remoteSessionId)!.hostSessionId,+ includeSnapshot: true,+ });+ if (!attach.snapshot) {+ throw Object.assign(new Error("remote host returned no snapshot"), {+ errorCode: ErrorCodes.INTERNAL,+ });+ }+ return { session: snapshotToSessionDetail(remoteSessionId, attach.snapshot) };+ }+ case IPC.invoke.sessionConfigure: {+ const remoteSessionId = remoteIdFor(args);+ const config = (args[1] ?? {}) as Partial<+ Pick<SessionSummary, "mode" | "providerId" | "modelId" | "thinkingLevel" | "permissionMode">+ >;+ const { session } = await client.request<{ session: RacpSession }>("session/configure", {+ sessionId: parseRemoteSessionId(remoteSessionId)!.hostSessionId,+ ...(config.mode ? { mode: config.mode } : {}),+ ...(config.providerId ? { providerId: config.providerId } : {}),+ ...(config.modelId ? { modelId: config.modelId } : {}),+ ...(config.thinkingLevel ? { thinkingLevel: config.thinkingLevel } : {}),+ ...(config.permissionMode ? { permissionMode: config.permissionMode } : {}),+ });+ return { session: racpSessionToSummary(remoteSessionId, session, 0) };+ }+ case IPC.invoke.sessionFork: {+ const req = args[0] as { sessionId: string; title?: string; throughMessageId?: string };+ const { session } = await client.request<{ session: RacpSession }>("session/fork", {+ sessionId: parseRemoteSessionId(req.sessionId)!.hostSessionId,+ ...(req.title ? { title: req.title } : {}),+ ...(req.throughMessageId ? { throughMessageId: req.throughMessageId } : {}),+ });+ // The fork is a new host session; the connection layer registers its+ // backend on the `session.created` event. Attach to build its transcript.+ const forkedRemoteId = makeRemoteSessionId(hostKey, session.id);+ const attach = await client.request<AttachResultLike>("session/attach", {+ sessionId: session.id,+ includeSnapshot: true,+ });+ const detail: SessionDetail = attach.snapshot+ ? snapshotToSessionDetail(forkedRemoteId, attach.snapshot)+ : { ...racpSessionToSummary(forkedRemoteId, session, 0), messages: [] };+ return { session: detail };+ }+ case IPC.invoke.sessionRename: {+ const title = args[1] as string;+ await client.request("session/rename", { sessionId: hostIdFor(args), title });+ return { ok: true };+ }+ case IPC.invoke.sessionDelete: {+ await client.request("session/delete", { sessionId: hostIdFor(args) });+ return { ok: true };+ }+ case IPC.invoke.toolResolvePermission: {+ const resolution = args[0] as ToolPermissionResolution;+ const parsed = parseRemoteApprovalRequestId(resolution.requestId);+ if (!parsed) {+ throw Object.assign(new Error("malformed remote approval request id"), {+ errorCode: ErrorCodes.INTERNAL,+ });+ }+ // The local tool decision literals equal the RACP tool decisions exactly.+ await client.request<RacpApprovalResult>("approval/respond", {+ approvalId: parsed.hostApprovalId,+ decision: resolution.decision,+ context: context(),+ });+ return { ok: true };+ }+ case IPC.invoke.askToolResolve: {+ const resolution = args[0] as AskToolResolution;+ // `answers` is `Array<string[] | null>` in both the local and RACP shapes.+ await client.request("input/respond", {+ inputId: resolution.requestId,+ answers: resolution.answers,+ context: context(),+ });+ return { ok: true };+ }+ case IPC.invoke.plansResolve: {+ const resolution = args[0] as PlanResolveRequest;+ const result = await client.request<RacpApprovalResult>("approval/respond", {+ approvalId: resolution.proposalId,+ // Contract decisions ("approve"/"reject") equal the plan actions.+ decision: resolution.action,+ ...(resolution.action === "approve"+ ? { permissionMode: resolution.targetPermissionMode }+ : {}),+ context: context(),+ });+ // The authoritative proposal and planning state arrive on the following+ // `session.changed` event, which the event bridge forwards; this return+ // value only dismisses the card optimistically without throwing.+ const now = new Date().toISOString();+ return {+ ok: result.status === "resolved",+ proposal: {+ id: resolution.proposalId,+ sessionId: resolution.sessionId,+ turnId: resolution.turnId,+ toolCallId: resolution.toolCallId,+ kind: "plan",+ title: "",+ markdown: "",+ // `plan` is the host's persisted-Markdown alias of `markdown`; empty+ // is fine — the authoritative snapshot arrives on the follow-up+ // `session.changed` event and replaces this placeholder.+ plan: "",+ question: "",+ version: resolution.version ?? 1,+ status: resolution.action === "approve" ? "approved" : "rejected",+ createdAt: now,+ updatedAt: now,+ },+ state: "inactive",+ action: resolution.action,+ ...(resolution.action === "approve"+ ? { targetPermissionMode: resolution.targetPermissionMode }+ : {}),+ } satisfies PlanResolutionResult;+ }+ case IPC.invoke.plansPending:+ // Pending plan cards are restored from the attach snapshot's approvals by+ // the event bridge, so this on-demand fetch stays empty for remote hosts.+ return { plans: [] };+ default:+ throw Object.assign(new Error(`remote backend has no handler for ${channel}`), {+ errorCode: ErrorCodes.INTERNAL,+ });+ }+ };++ return {+ handles: (channel: string) => HANDLED_CHANNELS.has(channel),+ invoke,+ };+}diff --git a/apps/desktop/electron/main/remote/remote-transcript.ts b/apps/desktop/electron/main/remote/remote-transcript.tsnew file mode 100644index 000000000..920e5fa82--- /dev/null+++ b/apps/desktop/electron/main/remote/remote-transcript.ts@@ -0,0 +1,57 @@+/**+ * Reshape a remote host's RACP session resources into the exact+ * {@link SessionSummary}/{@link SessionDetail} the renderer already consumes for+ * a local session. The renderer never learns the transport: only the+ * `source: "remote"` badge and the namespaced id distinguish it (spec §3.4).+ *+ * RACP does not carry a per-session `thinkingLevel` (it is a desktop provider+ * concern), so remote summaries default it to `"off"`; the renderer treats it+ * as advisory display state and never round-trips it back to the host.+ */+import type {+ RacpSession,+ RacpSessionSnapshot,+ SessionDetail,+ SessionSummary,+ UiMessage,+} from "@pi-desktop/shared";++/** Build the flat summary a session list / header row renders. */+export function racpSessionToSummary(+ remoteSessionId: string,+ session: RacpSession,+ messageCount: number,+): SessionSummary {+ return {+ id: remoteSessionId,+ source: "remote",+ title: session.title,+ messageCount,+ // RACP's mode and permission-mode literals are a subset of the renderer's,+ // so they pass through unchanged; `inherit` is desktop-only and never sent.+ mode: session.mode,+ thinkingLevel: "off",+ permissionMode: session.permissionMode,+ updatedAt: session.updatedAt,+ createdAt: session.createdAt,+ };+}++/**+ * Build the full transcript from an attach snapshot. `snapshot.items` already+ * carries the canonical {@link UiMessage} in each item's `content` (the host's+ * `toRacpItem` projection), so the transcript is a direct map with no lossy+ * reconstruction.+ */+export function snapshotToSessionDetail(+ remoteSessionId: string,+ snapshot: RacpSessionSnapshot,+): SessionDetail {+ const messages = snapshot.items.map((item) => item.content as UiMessage);+ return {+ ...racpSessionToSummary(remoteSessionId, snapshot.session, messages.length),+ messages,+ hasMoreBefore: snapshot.hasMoreHistory,+ hasMoreAfter: false,+ };+}diff --git a/apps/desktop/test/remote-backend.test.mjs b/apps/desktop/test/remote-backend.test.mjsnew file mode 100644index 000000000..8e2b3ea89--- /dev/null+++ b/apps/desktop/test/remote-backend.test.mjs@@ -0,0 +1,462 @@+import assert from "node:assert/strict";+import test from "node:test";+import { register } from "node:module";+import { dirname, join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";++const here = dirname(fileURLToPath(import.meta.url));+register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));++const { IPC } = await import("@pi-desktop/shared");+const { makeRemoteApprovalRequestId, makeRemoteSessionId } = await import(+ "../electron/main/remote/backend-router.ts"+);+const { racpSessionToSummary, snapshotToSessionDetail } = await import(+ "../electron/main/remote/remote-transcript.ts"+);+const { createRemoteBackend } = await import(+ "../electron/main/remote/remote-backend.ts"+);++const HOST_KEY = "hostA";+const HOST_SESSION_ID = "sess-1";+const REMOTE_SESSION_ID = makeRemoteSessionId(HOST_KEY, HOST_SESSION_ID);++/**+ * A fixture `RacpSession` shaped just like the schema; individual tests override+ * only the fields they care about via spread.+ */+function makeRacpSession(overrides = {}) {+ return {+ id: HOST_SESSION_ID,+ title: "Remote session",+ mode: "chat",+ status: "idle",+ planningState: "inactive",+ permissionMode: "default",+ queuedTurnIds: [],+ revision: 1,+ createdAt: "2026-09-18T10:00:00.000Z",+ updatedAt: "2026-09-18T10:00:00.000Z",+ ...overrides,+ };+}++function makeRacpTurn(overrides = {}) {+ return {+ id: "turn-1",+ sessionId: HOST_SESSION_ID,+ status: "running",+ admission: "reject_if_busy",+ effectivePermissionMode: "default",+ ...overrides,+ };+}++function makeRacpSnapshot(overrides = {}) {+ return {+ session: makeRacpSession(),+ queuedTurns: [],+ items: [],+ activeItems: [],+ pendingApprovals: [],+ pendingInputs: [],+ hasMoreHistory: false,+ cursor: { epoch: "e", sequence: 0 },+ revision: 1,+ generatedAt: "2026-09-18T10:00:00.000Z",+ ...overrides,+ };+}++/** A minimal RacpClient double that records every request and returns queued+ * responses. Each entry maps a RACP method to a value or an error to throw. */+function fakeClient(responses = {}) {+ const calls = [];+ return {+ calls,+ request: async (method, params) => {+ calls.push({ method, params });+ const handler = responses[method];+ if (typeof handler === "function") return handler(params);+ if (handler === undefined) {+ throw Object.assign(new Error(`no fake for ${method}`), { errorCode: "INTERNAL" });+ }+ return handler;+ },+ };+}++function makeBackend(responses = {}, extra = {}) {+ const client = fakeClient(responses);+ const backend = createRemoteBackend({+ hostKey: HOST_KEY,+ client,+ // A deterministic id keeps the recorded request context stable in assertions.+ newRequestId: () => "req-const",+ ...extra,+ });+ return { backend, client };+}++test("racpSessionToSummary maps the host-agnostic renderer summary", () => {+ const session = makeRacpSession({ mode: "agent", permissionMode: "allow" });+ const summary = racpSessionToSummary(REMOTE_SESSION_ID, session, 7);+ assert.equal(summary.id, REMOTE_SESSION_ID);+ assert.equal(summary.source, "remote");+ assert.equal(summary.mode, "agent");+ assert.equal(summary.permissionMode, "allow");+ // RACP never carries thinkingLevel; it defaults to "off" for the renderer.+ assert.equal(summary.thinkingLevel, "off");+ assert.equal(summary.messageCount, 7);+});++test("snapshotToSessionDetail lifts snapshot items directly into the transcript", () => {+ const snapshot = makeRacpSnapshot({+ hasMoreHistory: true,+ items: [+ { id: "i1", turnId: "t1", itemType: "message", status: "completed", createdAt: "x", content: { role: "user", text: "hi" } },+ { id: "i2", turnId: "t1", itemType: "message", status: "completed", createdAt: "x", content: { role: "assistant", text: "hello" } },+ ],+ });+ const detail = snapshotToSessionDetail(REMOTE_SESSION_ID, snapshot);+ assert.equal(detail.id, REMOTE_SESSION_ID);+ assert.equal(detail.hasMoreBefore, true);+ assert.equal(detail.hasMoreAfter, false);+ assert.equal(detail.messageCount, 2);+ assert.deepEqual(detail.messages[0], { role: "user", text: "hi" });+});++test("handles() covers exactly the channels the remote profile serves", () => {+ const { backend } = makeBackend();+ const covered = [+ IPC.invoke.agentPrompt,+ IPC.invoke.agentQueuePush,+ IPC.invoke.agentQueueList,+ IPC.invoke.agentStop,+ IPC.invoke.agentAbort,+ IPC.invoke.agentCompact,+ IPC.invoke.agentGetStatus,+ IPC.invoke.agentSteer,+ IPC.invoke.sessionGet,+ IPC.invoke.sessionConfigure,+ IPC.invoke.sessionFork,+ IPC.invoke.sessionRename,+ IPC.invoke.sessionDelete,+ IPC.invoke.toolResolvePermission,+ IPC.invoke.askToolResolve,+ IPC.invoke.plansResolve,+ IPC.invoke.plansPending,+ ];+ for (const channel of covered) assert.ok(backend.handles(channel), `${channel} should be handled`);+ // Unrelated desktop channels remain local.+ assert.equal(backend.handles(IPC.invoke.appSettings ?? "pi-desktop/settings/get"), false);+ assert.equal(backend.handles("pi-desktop/anything/unknown"), false);+});++test("agentPrompt starts a turn with reject_if_busy and returns the local response shape", async () => {+ const turn = makeRacpTurn({ id: "turn-42" });+ const { backend, client } = makeBackend({+ "turn/start": () => ({ accepted: true, turn }),+ });+ const result = await backend.invoke(IPC.invoke.agentPrompt, [+ { sessionId: REMOTE_SESSION_ID, content: "hi", sessionMessageId: "m1", messageId: "u1" },+ ]);+ assert.deepEqual(result, { accepted: true, turnId: "turn-42" });+ assert.equal(client.calls[0].method, "turn/start");+ assert.equal(client.calls[0].params.sessionId, HOST_SESSION_ID);+ assert.equal(client.calls[0].params.admission, "reject_if_busy");+ assert.deepEqual(client.calls[0].params.input, {+ text: "hi",+ sessionMessageId: "m1",+ messageId: "u1",+ });+});++test("agentPrompt with attachments raises CAPABILITY_UNAVAILABLE without any RACP call", async () => {+ const { backend, client } = makeBackend();+ await assert.rejects(+ backend.invoke(IPC.invoke.agentPrompt, [+ { sessionId: REMOTE_SESSION_ID, content: "hi", attachments: [{ id: "a" }] },+ ]),+ (error) => error.errorCode === "CAPABILITY_UNAVAILABLE",+ );+ assert.equal(client.calls.length, 0);+});++test("agentQueuePush queues with the local content, since RACP turns carry none", async () => {+ const turn = makeRacpTurn({ id: "turn-q", admission: "queue", queuePosition: 2 });+ const { backend, client } = makeBackend({+ "turn/start": () => ({ accepted: true, turn }),+ });+ const result = await backend.invoke(IPC.invoke.agentQueuePush, [+ { sessionId: REMOTE_SESSION_ID, content: "pushed prompt", idempotencyKey: "k1" },+ ]);+ assert.equal(result.id, "turn-q");+ assert.equal(result.sessionId, REMOTE_SESSION_ID);+ assert.equal(result.content, "pushed prompt");+ assert.equal(result.position, 2);+ assert.equal(client.calls[0].params.admission, "queue");+ assert.equal(client.calls[0].params.idempotencyKey, "k1");+});++test("agentQueueList reads the snapshot and renders entries without a prompt text", async () => {+ const { backend } = makeBackend({+ "session/attach": () => ({+ session: makeRacpSession(),+ snapshot: makeRacpSnapshot({+ queuedTurns: [+ makeRacpTurn({ id: "q1", admission: "queue", queuePosition: 1 }),+ makeRacpTurn({ id: "q2", admission: "queue" }),+ ],+ }),+ }),+ });+ const result = await backend.invoke(IPC.invoke.agentQueueList, [+ { sessionId: REMOTE_SESSION_ID },+ ]);+ assert.equal(result.entries.length, 2);+ assert.equal(result.entries[0].id, "q1");+ assert.equal(result.entries[0].sessionId, REMOTE_SESSION_ID);+ // RACP turns do not carry queued prompt text; the entry still renders.+ assert.equal(result.entries[0].content, "");+ assert.equal(result.entries[0].position, 1);+ // A missing queuePosition falls back to index + 1.+ assert.equal(result.entries[1].position, 2);+});++test("agentStop resolves the active turn when the renderer omits turnId", async () => {+ const { backend, client } = makeBackend({+ "session/get": () => ({ session: makeRacpSession({ activeTurnId: "turn-active" }) }),+ "turn/stop": () => ({ ok: true }),+ });+ const result = await backend.invoke(IPC.invoke.agentStop, [+ { sessionId: REMOTE_SESSION_ID },+ ]);+ assert.deepEqual(result, { requested: true });+ assert.equal(client.calls[0].method, "session/get");+ assert.equal(client.calls[1].method, "turn/stop");+ assert.equal(client.calls[1].params.turnId, "turn-active");+});++test("agentStop reports requested=false when the session has no active turn", async () => {+ const { backend, client } = makeBackend({+ "session/get": () => ({ session: makeRacpSession() }),+ });+ const result = await backend.invoke(IPC.invoke.agentStop, [+ { sessionId: REMOTE_SESSION_ID },+ ]);+ assert.deepEqual(result, { requested: false });+ // No turn/stop is sent when there is nothing to stop.+ assert.equal(client.calls.length, 1);+});++test("agentAbort maps to turn/interrupt", async () => {+ const { backend, client } = makeBackend({+ "turn/interrupt": () => ({ ok: true }),+ });+ const result = await backend.invoke(IPC.invoke.agentAbort, [+ { sessionId: REMOTE_SESSION_ID, turnId: "explicit-turn" },+ ]);+ assert.deepEqual(result, { aborted: true });+ assert.equal(client.calls[0].method, "turn/interrupt");+ assert.equal(client.calls[0].params.turnId, "explicit-turn");+});++test("agentSteer refuses with CAPABILITY_UNAVAILABLE — no RACP counterpart exists", async () => {+ const { backend, client } = makeBackend();+ await assert.rejects(+ backend.invoke(IPC.invoke.agentSteer, [{ sessionId: REMOTE_SESSION_ID }]),+ (error) => error.errorCode === "CAPABILITY_UNAVAILABLE",+ );+ assert.equal(client.calls.length, 0);+});++test("agentGetStatus lifts session status/planning into the local shape", async () => {+ const session = makeRacpSession({+ status: "waiting_permission",+ activeTurnId: "turn-x",+ planningState: "awaiting_approval",+ });+ const { backend } = makeBackend({ "session/get": () => ({ session }) });+ const { status } = await backend.invoke(IPC.invoke.agentGetStatus, [+ { sessionId: REMOTE_SESSION_ID },+ ]);+ assert.equal(status.sessionId, REMOTE_SESSION_ID);+ assert.equal(status.currentTurnId, "turn-x");+ assert.equal(status.isRunning, false);+ assert.equal(status.pendingToolConfirmations, 1);+ assert.equal(status.planningState, "awaiting_approval");+});++test("sessionGet returns SessionDetail built from the snapshot", async () => {+ const { backend } = makeBackend({+ "session/attach": () => ({+ session: makeRacpSession(),+ snapshot: makeRacpSnapshot({+ items: [+ { id: "i1", turnId: "t1", itemType: "message", status: "completed", createdAt: "x", content: { role: "user", text: "hi" } },+ ],+ }),+ }),+ });+ const { session } = await backend.invoke(IPC.invoke.sessionGet, [+ { id: REMOTE_SESSION_ID },+ ]);+ assert.equal(session.id, REMOTE_SESSION_ID);+ assert.equal(session.messages.length, 1);+});++test("sessionGet errors when the host returns no snapshot", async () => {+ const { backend } = makeBackend({+ "session/attach": () => ({ session: makeRacpSession() }),+ });+ await assert.rejects(+ backend.invoke(IPC.invoke.sessionGet, [{ id: REMOTE_SESSION_ID }]),+ (error) => error.errorCode === "INTERNAL",+ );+});++test("sessionConfigure forwards only the fields the renderer set", async () => {+ const { backend, client } = makeBackend({+ "session/configure": () => ({ session: makeRacpSession({ mode: "agent" }) }),+ });+ await backend.invoke(IPC.invoke.sessionConfigure, [REMOTE_SESSION_ID, { mode: "agent" }]);+ assert.equal(client.calls[0].method, "session/configure");+ assert.deepEqual(client.calls[0].params, { sessionId: HOST_SESSION_ID, mode: "agent" });+});++test("sessionFork attaches to the new host session and returns a SessionDetail", async () => {+ const forked = makeRacpSession({ id: "sess-forked", title: "Forked" });+ const { backend } = makeBackend({+ "session/fork": () => ({ session: forked }),+ "session/attach": () => ({ session: forked, snapshot: makeRacpSnapshot({ session: forked }) }),+ });+ const { session } = await backend.invoke(IPC.invoke.sessionFork, [+ { sessionId: REMOTE_SESSION_ID, title: "Forked" },+ ]);+ assert.equal(session.id, makeRemoteSessionId(HOST_KEY, "sess-forked"));+ assert.equal(session.title, "Forked");+ // A SessionDetail always carries a messages array; empty is fine.+ assert.ok(Array.isArray(session.messages));+});++test("sessionRename / sessionDelete forward positional args", async () => {+ const { backend, client } = makeBackend({+ "session/rename": () => ({ ok: true }),+ "session/delete": () => ({ ok: true }),+ });+ await backend.invoke(IPC.invoke.sessionRename, [REMOTE_SESSION_ID, "New title"]);+ assert.deepEqual(client.calls[0].params, { sessionId: HOST_SESSION_ID, title: "New title" });+ await backend.invoke(IPC.invoke.sessionDelete, [REMOTE_SESSION_ID]);+ assert.deepEqual(client.calls[1].params, { sessionId: HOST_SESSION_ID });+});++test("toolResolvePermission decodes the encoded requestId back to the host approval id", async () => {+ const requestId = makeRemoteApprovalRequestId(REMOTE_SESSION_ID, "approval-77");+ const { backend, client } = makeBackend({+ "approval/respond": () => ({+ approvalId: "approval-77",+ status: "resolved",+ alreadyResolved: false,+ revision: 2,+ }),+ });+ const result = await backend.invoke(IPC.invoke.toolResolvePermission, [+ { requestId, decision: "allow-once" },+ ]);+ assert.deepEqual(result, { ok: true });+ assert.equal(client.calls[0].params.approvalId, "approval-77");+ assert.equal(client.calls[0].params.decision, "allow-once");+});++test("toolResolvePermission refuses a requestId that does not name a remote session", async () => {+ const { backend, client } = makeBackend();+ await assert.rejects(+ backend.invoke(IPC.invoke.toolResolvePermission, [+ { requestId: "plain-local-request-id", decision: "deny" },+ ]),+ (error) => error.errorCode === "INTERNAL",+ );+ assert.equal(client.calls.length, 0);+});++test("askToolResolve forwards the RACP input/respond params", async () => {+ const { backend, client } = makeBackend({+ "input/respond": () => ({ ok: true }),+ });+ await backend.invoke(IPC.invoke.askToolResolve, [+ { requestId: "input-1", answers: [["yes"], null] },+ ]);+ assert.equal(client.calls[0].method, "input/respond");+ assert.deepEqual(client.calls[0].params.answers, [["yes"], null]);+ assert.equal(client.calls[0].params.inputId, "input-1");+});++test("plansResolve synthesizes the local PlanResolutionResult from the RACP result", async () => {+ const { backend, client } = makeBackend({+ "approval/respond": () => ({+ approvalId: "prop-1",+ status: "resolved",+ alreadyResolved: false,+ revision: 3,+ }),+ });+ const result = await backend.invoke(IPC.invoke.plansResolve, [+ {+ proposalId: "prop-1",+ sessionId: REMOTE_SESSION_ID,+ turnId: "turn-1",+ toolCallId: "call-1",+ action: "approve",+ targetPermissionMode: "allow",+ version: 4,+ },+ ]);+ assert.equal(result.ok, true);+ assert.equal(result.state, "inactive");+ assert.equal(result.action, "approve");+ assert.equal(result.targetPermissionMode, "allow");+ assert.equal(result.proposal.id, "prop-1");+ assert.equal(result.proposal.sessionId, REMOTE_SESSION_ID);+ assert.equal(result.proposal.status, "approved");+ assert.equal(result.proposal.version, 4);+ assert.equal(client.calls[0].params.permissionMode, "allow");+});++test("plansResolve on reject omits permissionMode from the RACP call", async () => {+ const { backend, client } = makeBackend({+ "approval/respond": () => ({+ approvalId: "prop-2",+ status: "resolved",+ alreadyResolved: false,+ revision: 4,+ }),+ });+ const result = await backend.invoke(IPC.invoke.plansResolve, [+ {+ proposalId: "prop-2",+ sessionId: REMOTE_SESSION_ID,+ turnId: "turn-1",+ toolCallId: "call-1",+ action: "reject",+ },+ ]);+ assert.equal(result.action, "reject");+ assert.equal(result.proposal.status, "rejected");+ assert.equal(client.calls[0].params.permissionMode, undefined);+});++test("plansPending stays empty — pending cards ride the snapshot at attach time", async () => {+ const { backend } = makeBackend();+ const result = await backend.invoke(IPC.invoke.plansPending, [{ sessionId: REMOTE_SESSION_ID }]);+ assert.deepEqual(result, { plans: [] });+});++test("an unknown channel is a bug and surfaces INTERNAL", async () => {+ const { backend } = makeBackend();+ await assert.rejects(+ backend.invoke("pi-desktop/channel/not-a-thing", [{ sessionId: REMOTE_SESSION_ID }]),+ (error) => error.errorCode === "INTERNAL",+ );+});