Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(remote): keep host project groups collapsible and their rows in the group
koeria87068f4b8fa2
diff --git a/apps/desktop/src/components/remote/RemoteProjectGroups.tsx b/apps/desktop/src/components/remote/RemoteProjectGroups.tsxindex 212ff44ce..1c0091429 100644--- a/apps/desktop/src/components/remote/RemoteProjectGroups.tsx+++ b/apps/desktop/src/components/remote/RemoteProjectGroups.tsx@@ -1,20 +1,32 @@import { useState, type ReactNode } from "react";import { useTranslation } from "react-i18next";import type { SessionSummary } from "@pi-desktop/shared";-import type { RemoteProjectEntry, RemoteProjectGroup } from "../../lib/remote-project-catalog";+import type {+ RemoteProjectEntry,+ RemoteProjectGroup,+} from "../../lib/remote-project-catalog";+import { remoteProjectCollapseKey } from "../../lib/remote-project-catalog";import {projectRunSummaryIsLive,resolveSidebarRunningAffordances,summarizeProjectRuns,} from "../../lib/sidebar-project-runs";import { useAppStore } from "../../stores/app-store";-import { ProjectRunBadge, ProjectRunCount, ProjectRunRail } from "../ProjectRunIndicator";-import { IconFolder, IconNewProject } from "../icons";+import {+ ProjectRunBadge,+ ProjectRunCount,+ ProjectRunRail,+} from "../ProjectRunIndicator";+import { IconChevronDown, IconFolder, IconNewProject } from "../icons";import { Button, TooltipButton } from "../ui";/** The same project/chat hierarchy, keyed by Host identity rather than local paths. */-export function RemoteProjectGroups({ groups, renderSessions }: {- groups: RemoteProjectGroup[]; renderSessions: (sessions: SessionSummary[]) => ReactNode;+export function RemoteProjectGroups({+ groups,+ renderSessions,+}: {+ groups: RemoteProjectGroup[];+ renderSessions: (sessions: SessionSummary[]) => ReactNode;}) {const { t } = useTranslation();const [busy, setBusy] = useState<string | null>(null);@@ -24,37 +36,107 @@ export function RemoteProjectGroups({ groups, renderSessions }: {const runAffordances = resolveSidebarRunningAffordances(settings);const runningSessions = useAppStore((state) => state.runningSessions);const pendingPermissions = useAppStore((state) => state.pendingPermissions);+ // The same collapse state and persistence as local project groups; the+ // `remote::` prefix keeps these keys out of the local path namespace, and the+ // persisted fold survives a restart like a local one.+ const projectCollapsed = useAppStore((state) => state.projectCollapsed);+ const setProjectCollapsed = useAppStore((state) => state.setProjectCollapsed);const open = async (project: RemoteProjectEntry) => {if (busy) return;setBusy(project.key);- try { await useAppStore.getState().newSession({ remoteProject: project }); }- catch (error) { useAppStore.getState().showToast(error instanceof Error ? error.message : String(error), { variant: "error" }); }- finally { setBusy(null); }+ try {+ await useAppStore.getState().newSession({ remoteProject: project });+ } catch (error) {+ useAppStore+ .getState()+ .showToast(error instanceof Error ? error.message : String(error), {+ variant: "error",+ });+ } finally {+ setBusy(null);+ }};- return <>{groups.map(({ project, sessions }) => {- const runSummary = summarizeProjectRuns(sessions, runningSessions, pendingPermissions);- const runIsLive = projectRunSummaryIsLive(runSummary);- const showRunBadge = runAffordances.badge && runIsLive;- const showRunRail = runAffordances.rail && runIsLive;- // Same exclusivity rule as the local sidebar: one set of numbers, owned by- // the badge while it is on and by the rail when it is off.- const showRunCount = runAffordances.railCount && runIsLive;- return <section- className={`sidebar-session-group project-group ${runIsLive ? "has-running-sessions" : ""} ${showRunRail ? "has-run-rail" : ""}`}- key={project.key}- >- {showRunRail ? <ProjectRunRail summary={runSummary} /> : null}- <div className="sidebar-session-group-header">- <Button variant="ghost" className="sidebar-session-group-title" disabled={busy !== null}- title={`${project.hostLabel} · ${project.label}`} onClick={() => void open(project)}>- <IconFolder size={13} aria-hidden /><span>{project.label} · {project.hostLabel}</span>- {showRunBadge ? <ProjectRunBadge summary={runSummary} /> : null}- {showRunCount ? <ProjectRunCount summary={runSummary} /> : null}- </Button>- <TooltipButton tooltip={t("nav.newTask")} ariaLabel={`${t("nav.newTask")}: ${project.label} · ${project.hostLabel}`}- disabled={busy !== null} onClick={() => void open(project)}><IconNewProject size={14} /></TooltipButton>- </div>- {renderSessions(sessions)}- </section>;- })}</>;+ return (+ <>+ {groups.map(({ project, sessions }) => {+ const runSummary = summarizeProjectRuns(+ sessions,+ runningSessions,+ pendingPermissions,+ );+ const runIsLive = projectRunSummaryIsLive(runSummary);+ const showRunBadge = runAffordances.badge && runIsLive;+ const showRunRail = runAffordances.rail && runIsLive;+ // Same exclusivity rule as the local sidebar: one set of numbers, owned by+ // the badge while it is on and by the rail when it is off.+ const showRunCount = runAffordances.railCount && runIsLive;+ const collapseKey = remoteProjectCollapseKey(project.key);+ const collapsed = projectCollapsed[collapseKey] ?? false;+ return (+ <section+ className={`sidebar-session-group project-group ${runIsLive ? "has-running-sessions" : ""} ${showRunRail ? "has-run-rail" : ""} ${collapsed ? "is-collapsed" : ""}`}+ key={project.key}+ data-sidebar-project-group={project.key}+ >+ {showRunRail ? <ProjectRunRail summary={runSummary} /> : null}+ <div+ className="sidebar-session-group-header"+ onClick={(event) => {+ // Same one-target rule as a local project group: the header's own+ // controls stay the only spelled-out targets, so the gutter next to a+ // hidden control still activates and toggles the group.+ const target = event.target as HTMLElement | null;+ if (target?.closest("button, [data-action]")) return;+ setProjectCollapsed(collapseKey, !collapsed);+ }}+ >+ <Button+ variant="ghost"+ className="sidebar-session-group-title project-toggle"+ disabled={busy !== null}+ title={`${project.hostLabel} · ${project.label}`}+ aria-expanded={!collapsed}+ aria-controls={`${project.key}-sessions`}+ data-action="toggle-project-collapse"+ onClick={() => setProjectCollapsed(collapseKey, !collapsed)}+ >+ <IconChevronDown+ size={13}+ className={`sidebar-disclosure-icon ${collapsed ? "collapsed" : ""}`}+ aria-hidden+ />+ <IconFolder size={13} aria-hidden />+ <span>+ {project.label} · {project.hostLabel}+ </span>+ {showRunBadge ? <ProjectRunBadge summary={runSummary} /> : null}+ {showRunCount ? <ProjectRunCount summary={runSummary} /> : null}+ </Button>+ <TooltipButton+ tooltip={t("nav.newTask")}+ ariaLabel={`${t("nav.newTask")}: ${project.label} · ${project.hostLabel}`}+ disabled={busy !== null}+ onClick={() => void open(project)}+ >+ <IconNewProject size={14} />+ </TooltipButton>+ </div>+ <div+ id={`${project.key}-sessions`}+ className={`sidebar-session-group-body project ${collapsed ? "collapsed" : ""}`}+ role="region"+ aria-hidden={collapsed}+ inert={collapsed ? true : undefined}+ >+ <div className="sidebar-session-group-clip">+ <div className="sidebar-session-group-list">+ {renderSessions(sessions)}+ </div>+ </div>+ </div>+ </section>+ );+ })}+ </>+ );}diff --git a/apps/desktop/src/lib/remote-project-catalog.ts b/apps/desktop/src/lib/remote-project-catalog.tsindex b44429bfc..6016394ff 100644--- a/apps/desktop/src/lib/remote-project-catalog.ts+++ b/apps/desktop/src/lib/remote-project-catalog.ts@@ -1,19 +1,40 @@-import type { RemoteHostSummary, RacpProjectSummary, SessionSummary } from "@pi-desktop/shared";+import type {+ RemoteHostSummary,+ RacpProjectSummary,+ SessionSummary,+} from "@pi-desktop/shared";import type { RemoteProjectTarget } from "./remote-project-session";import { isRemoteSession } from "./remote-session-safety";-export type RemoteProjectEntry = RemoteProjectTarget & { key: string; hostLabel: string; connected: boolean };-export const remoteProjectKey = (hostKey: string, projectId: string) => JSON.stringify([hostKey, projectId]);+export type RemoteProjectEntry = RemoteProjectTarget & {+ key: string;+ hostLabel: string;+ connected: boolean;+};+export const remoteProjectKey = (hostKey: string, projectId: string) =>+ JSON.stringify([hostKey, projectId]);+/** Collapse-state key for a host project group; the prefix keeps these entries out of the local path namespace. */+export const remoteProjectCollapseKey = (key: string) => `remote::${key}`;-export type RemoteProjectGroup = { project: RemoteProjectEntry; sessions: SessionSummary[] };+export type RemoteProjectGroup = {+ project: RemoteProjectEntry;+ sessions: SessionSummary[];+};/** Rendering and range selection consume one grouped order. */export function groupRemoteProjectSessions(- sessions: SessionSummary[], compare: (left: SessionSummary, right: SessionSummary) => number,+ sessions: SessionSummary[],+ compare: (left: SessionSummary, right: SessionSummary) => number,): RemoteProjectGroup[] {return listRemoteProjects([], [], sessions).map((project) => ({- project, sessions: sessions.filter((session) => session.remoteHostKey === project.hostKey- && session.remoteProjectId === project.projectId).sort(compare),+ project,+ sessions: sessions+ .filter(+ (session) =>+ session.remoteHostKey === project.hostKey &&+ session.remoteProjectId === project.projectId,+ )+ .sort(compare),}));}@@ -24,22 +45,44 @@ export function listRemoteProjects(): RemoteProjectEntry[] {const entries = new Map<string, RemoteProjectEntry>();for (const session of sessions) {- if (!isRemoteSession(session) || !session.remoteHostKey || !session.remoteProjectId) continue;+ if (+ !isRemoteSession(session) ||+ !session.remoteHostKey ||+ !session.remoteProjectId+ )+ continue;const host = hosts.find((item) => item.hostKey === session.remoteHostKey);- const key = remoteProjectKey(session.remoteHostKey, session.remoteProjectId);- entries.set(key, { key, hostKey: session.remoteHostKey, projectId: session.remoteProjectId,+ const key = remoteProjectKey(+ session.remoteHostKey,+ session.remoteProjectId,+ );+ entries.set(key, {+ key,+ hostKey: session.remoteHostKey,+ projectId: session.remoteProjectId,label: session.remoteWorkspaceLabel ?? session.remoteProjectId,- hostLabel: host?.label ?? session.remoteHostLabel ?? session.remoteHostKey,- connected: host?.connected === true });+ hostLabel:+ host?.label ?? session.remoteHostLabel ?? session.remoteHostKey,+ connected: host?.connected === true,+ });}for (const inventory of inventories) {const host = hosts.find((item) => item.hostKey === inventory.hostKey);if (!host) continue;for (const project of inventory.projects) {const key = remoteProjectKey(host.hostKey, project.id);- if (project.archived) { entries.delete(key); continue; }- entries.set(key, { key, hostKey: host.hostKey, projectId: project.id,- label: project.label, hostLabel: host.label, connected: host.connected });+ if (project.archived) {+ entries.delete(key);+ continue;+ }+ entries.set(key, {+ key,+ hostKey: host.hostKey,+ projectId: project.id,+ label: project.label,+ hostLabel: host.label,+ connected: host.connected,+ });}}return [...entries.values()];diff --git a/apps/desktop/src/styles/sidebar-threads.css b/apps/desktop/src/styles/sidebar-threads.cssindex 65cc177b3..30b424669 100644--- a/apps/desktop/src/styles/sidebar-threads.css+++ b/apps/desktop/src/styles/sidebar-threads.css@@ -9,7 +9,9 @@min-height: 28px;border-radius: var(--radius-sm);color: var(--ds-text-secondary);- transition: background var(--motion-duration-fast) var(--motion-ease-out), color var(--motion-duration-fast) var(--motion-ease-out);+ transition:+ background var(--motion-duration-fast) var(--motion-ease-out),+ color var(--motion-duration-fast) var(--motion-ease-out);}.thread-item {@@ -37,12 +39,24 @@min-width: 0;flex: 1 1 auto;overflow: hidden;- font-size: var(--text-md); /* session titles stay compact within the sidebar */+ font-size: var(+ --text-md+ ); /* session titles stay compact within the sidebar */line-height: var(--leading-row);text-overflow: ellipsis;white-space: nowrap;}+/* Source tags (Pi, Remote) are badges: they never shrink or wrap into stacked+ words in a narrow sidebar — the title next to them truncates instead. */+.thread-item-source {+ flex: 0 0 auto;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+ line-height: var(--leading-row);+ white-space: nowrap;+}+.thread-item-meta {/* The action and date overlap in one slot; opacity keeps its width stable. */display: grid;@@ -85,7 +99,9 @@/* Window blur releases hover, not selection or drag feedback. */.sidebar[data-window-blur="true"] .thread-item:hover:not(.active),-.sidebar[data-window-blur="true"] .project-group:not(.is-drop-target) > .sidebar-session-group-header:hover {+.sidebar[data-window-blur="true"]+ .project-group:not(.is-drop-target)+ > .sidebar-session-group-header:hover {background: transparent;color: var(--ds-text-secondary);}@@ -177,7 +193,9 @@padding: 5px 6px;background: transparent;color: inherit;- font-size: var(--text-md); /* project/group labels one step quieter than sessions */+ font-size: var(+ --text-md+ ); /* project/group labels one step quieter than sessions */font-weight: var(--font-weight-medium);line-height: var(--leading-compact);text-align: left;@@ -241,7 +259,8 @@grid-template-rows: 1fr;margin-left: 13px;padding-left: 9px;- transition: grid-template-rows var(--motion-duration-normal) var(--motion-ease-out);+ transition: grid-template-rows var(--motion-duration-normal)+ var(--motion-ease-out);}.sidebar-session-group-body.project.collapsed {@@ -281,7 +300,9 @@color: var(--ds-text-muted);font-size: var(--text-xs-plus);text-align: left;- transition: background var(--motion-duration-fast) var(--motion-ease-out), color var(--motion-duration-fast) var(--motion-ease-out);+ transition:+ background var(--motion-duration-fast) var(--motion-ease-out),+ color var(--motion-duration-fast) var(--motion-ease-out);}.sidebar-load-more:hover {@@ -355,8 +376,6 @@background: var(--ds-bg-active);}--/* ============================================================Project-level running affordances: count badge + activity rail.diff --git a/apps/desktop/test/remote-project-session.test.mjs b/apps/desktop/test/remote-project-session.test.mjsindex 28d3af9c8..f1f009dba 100644--- a/apps/desktop/test/remote-project-session.test.mjs+++ b/apps/desktop/test/remote-project-session.test.mjs@@ -3,31 +3,66 @@ import test, { beforeEach, afterEach } from "node:test";import { register } from "node:module";register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));const { api } = await import("../src/lib/api.ts");-const { openRemoteProjectSession, remoteProjectForSession } = await import("../src/lib/remote-project-session.ts");-const { listRemoteProjects, groupRemoteProjectSessions } = await import("../src/lib/remote-project-catalog.ts");-const { createNavigationIntentController } = await import("../src/lib/navigation-intent.ts");+const { openRemoteProjectSession, remoteProjectForSession } =+ await import("../src/lib/remote-project-session.ts");+const {+ listRemoteProjects,+ groupRemoteProjectSessions,+ remoteProjectKey,+ remoteProjectCollapseKey,+} = await import("../src/lib/remote-project-catalog.ts");+const { createNavigationIntentController } =+ await import("../src/lib/navigation-intent.ts");const project = { hostKey: "ssh-one", projectId: "project", label: "app" };const remote = (hostKey = project.hostKey, count = 0) => ({- id: `remote:${hostKey}:one`, source: "remote", remoteHostKey: hostKey,- remoteProjectId: project.projectId, remoteWorkspaceLabel: "app", messageCount: count,- title: "Chat", updatedAt: "2026-10-11T00:00:00Z",+ id: `remote:${hostKey}:one`,+ source: "remote",+ remoteHostKey: hostKey,+ remoteProjectId: project.projectId,+ remoteWorkspaceLabel: "app",+ messageCount: count,+ title: "Chat",+ updatedAt: "2026-10-11T00:00:00Z",});const originalRead = api.getSession;-beforeEach(() => { api.getSession = async () => ({ session: { ...remote(), messages: [], hasMoreBefore: false } }); });-afterEach(() => { api.getSession = originalRead; });+beforeEach(() => {+ api.getSession = async () => ({+ session: { ...remote(), messages: [], hasMoreBefore: false },+ });+});+afterEach(() => {+ api.getSession = originalRead;+});function fixture(sessions = []) {const nav = createNavigationIntentController();const selections = [];- let state = { sessions, sessionMeta: {}, runningSessions: {}, workspace: { path: "/local/app" },- selectSession: async (id, options) => { selections.push({ id, options }); } };+ let state = {+ sessions,+ sessionMeta: {},+ runningSessions: {},+ workspace: { path: "/local/app" },+ selectSession: async (id, options) => {+ selections.push({ id, options });+ },+ };return {get: () => state,- set: (patch) => { state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) }; },- runtime: { pendingNewSessionRequests: new Map(), submittedComposerDrafts: new Map(),- beginNavigationIntent: nav.begin, navigationIntentIsCurrent: nav.isCurrent,- liveMessageCountForSession: () => 0 },- nav, selections,+ set: (patch) => {+ state = {+ ...state,+ ...(typeof patch === "function" ? patch(state) : patch),+ };+ },+ runtime: {+ pendingNewSessionRequests: new Map(),+ submittedComposerDrafts: new Map(),+ beginNavigationIntent: nav.begin,+ navigationIntentIsCurrent: nav.isCurrent,+ liveMessageCountForSession: () => 0,+ },+ nav,+ selections,};}@@ -37,32 +72,79 @@ test("remote New chat reuses an empty chat only in the same host/project", asyncassert.equal(f.selections[0].id, "remote:ssh-one:one");assert.equal(f.get().workspace.path, "/local/app");assert.deepEqual(remoteProjectForSession(remote()), project);- assert.equal(remoteProjectForSession({ ...remote(), id: "local", source: "desktop" }), undefined);+ assert.equal(+ remoteProjectForSession({ ...remote(), id: "local", source: "desktop" }),+ undefined,+ );+});++test("host project groups keep their rows keyed by the remote project id", () => {+ const groups = groupRemoteProjectSessions(+ [remote("ssh-two"), remote()],+ (a, b) => 0,+ );+ const group = groups.find(+ (entry) => entry.project.key === remoteProjectKey("ssh-one", "project"),+ );+ assert.ok(+ group,+ "the host project group exists for sessions with a remoteProjectId",+ );+ assert.deepEqual(+ group.sessions.map((session) => session.id),+ ["remote:ssh-one:one"],+ );+ // Collapse keys never collide with local project paths.+ assert.equal(+ remoteProjectCollapseKey(group.project.key).startsWith("remote::"),+ true,+ );+ assert.notEqual(+ remoteProjectCollapseKey(group.project.key),+ group.project.key,+ );});test("remote project creation coalesces duplicate clicks and keeps local paths isolated", async () => {const original = api.createRemoteSession;let resolve;const calls = [];- api.createRemoteSession = (input) => { calls.push(input); return new Promise((done) => { resolve = done; }); };+ api.createRemoteSession = (input) => {+ calls.push(input);+ return new Promise((done) => {+ resolve = done;+ });+ };try {const f = fixture([remote("ssh-two")]);const first = openRemoteProjectSession(f, project);const duplicate = openRemoteProjectSession(f, project);resolve({ session: { ...remote(), projectPath: "/remote/app" } });await Promise.all([first, duplicate]);- assert.deepEqual(calls, [{ hostKey: "ssh-one", projectId: "project", mode: "agent", permissionMode: "ask" }]);+ assert.deepEqual(calls, [+ {+ hostKey: "ssh-one",+ projectId: "project",+ mode: "agent",+ permissionMode: "ask",+ },+ ]);assert.equal(f.selections.length, 1);assert.equal(f.get().sessions[0].projectPath, undefined);assert.equal(f.get().workspace.path, "/local/app");assert.equal(f.runtime.pendingNewSessionRequests.size, 0);- } finally { api.createRemoteSession = original; }+ } finally {+ api.createRemoteSession = original;+ }});test("navigation during a remote create preserves its result without stealing focus", async () => {const original = api.createRemoteSession;let resolve;- api.createRemoteSession = () => new Promise((done) => { resolve = done; });+ api.createRemoteSession = () =>+ new Promise((done) => {+ resolve = done;+ });try {const f = fixture();const request = openRemoteProjectSession(f, project);@@ -71,7 +153,9 @@ test("navigation during a remote create preserves its result without stealing foawait request;assert.equal(f.get().sessions.length, 1);assert.equal(f.selections.length, 0);- } finally { api.createRemoteSession = original; }+ } finally {+ api.createRemoteSession = original;+ }});test("a busy or nonempty chat is never reused, and failed creation can be retried", async () => {@@ -90,53 +174,122 @@ test("a busy or nonempty chat is never reused, and failed creation can be retrieassert.equal(attempts, 2);assert.equal(f.selections[0].id, "remote:ssh-one:two");assert.equal(f.runtime.pendingNewSessionRequests.size, 0);- } finally { api.createRemoteSession = original; }+ } finally {+ api.createRemoteSession = original;+ }});test("remote project discovery distinguishes identical paths and labels across hosts", () => {- const hosts = [{ hostKey: "ssh-one", label: "One", connected: true }, { hostKey: "ssh-two", label: "Two", connected: false }];- const projects = listRemoteProjects(hosts, [{ hostKey: "ssh-one", projects: [{ id: "project", label: "app", archived: false }] }], [remote(), remote("ssh-two")]);+ const hosts = [+ { hostKey: "ssh-one", label: "One", connected: true },+ { hostKey: "ssh-two", label: "Two", connected: false },+ ];+ const projects = listRemoteProjects(+ hosts,+ [+ {+ hostKey: "ssh-one",+ projects: [{ id: "project", label: "app", archived: false }],+ },+ ],+ [remote(), remote("ssh-two")],+ );assert.equal(projects.length, 2);assert.notEqual(projects[0].key, projects[1].key);assert.equal(projects[0].connected, true);assert.equal(projects[1].connected, false);- assert.deepEqual(listRemoteProjects(hosts, [{ hostKey: "ssh-one", projects: [{ id: "project", label: "app", archived: true }] }], [remote()]), []);+ assert.deepEqual(+ listRemoteProjects(+ hosts,+ [+ {+ hostKey: "ssh-one",+ projects: [{ id: "project", label: "app", archived: true }],+ },+ ],+ [remote()],+ ),+ [],+ );});test("remote project groups share sorted visible order with range selection", () => {const a1 = { ...remote(), id: "a1", title: "Zulu" };const b1 = { ...remote("ssh-two"), id: "b1", title: "Other host" };const a2 = { ...remote(), id: "a2", title: "Alpha" };- const groups = groupRemoteProjectSessions([a1, b1, a2], (left, right) => left.title.localeCompare(right.title));- assert.deepEqual(groups.map((group) => group.sessions.map((session) => session.id)), [["a2", "a1"], ["b1"]]);- assert.deepEqual(groups.flatMap((group) => group.sessions.map((session) => session.id)), ["a2", "a1", "b1"]);+ const groups = groupRemoteProjectSessions([a1, b1, a2], (left, right) =>+ left.title.localeCompare(right.title),+ );+ assert.deepEqual(+ groups.map((group) => group.sessions.map((session) => session.id)),+ [["a2", "a1"], ["b1"]],+ );+ assert.deepEqual(+ groups.flatMap((group) => group.sessions.map((session) => session.id)),+ ["a2", "a1", "b1"],+ );});test("a cold RACP catalog count of zero never reuses a chat with actual history", async () => {- const { createRemoteSessionCatalog } = await import("../electron/main/remote/remote-session-catalog.ts");+ const { createRemoteSessionCatalog } =+ await import("../electron/main/remote/remote-session-catalog.ts");const host = {- hostKey: "ssh-one", label: "Host", connection: { ensureSession: async () => {} },- client: { request: async () => ({ sessions: [{ id: "one", title: "Previous chat", projectId: "project",- workspaceLabel: "app", mode: "agent", permissionMode: "ask", status: "idle", planningState: "inactive",- queuedTurnIds: [], createdAt: "2026-10-11T00:00:00Z", updatedAt: "2026-10-11T00:00:00Z" }] }) },+ hostKey: "ssh-one",+ label: "Host",+ connection: { ensureSession: async () => {} },+ client: {+ request: async () => ({+ sessions: [+ {+ id: "one",+ title: "Previous chat",+ projectId: "project",+ workspaceLabel: "app",+ mode: "agent",+ permissionMode: "ask",+ status: "idle",+ planningState: "inactive",+ queuedTurnIds: [],+ createdAt: "2026-10-11T00:00:00Z",+ updatedAt: "2026-10-11T00:00:00Z",+ },+ ],+ }),+ },};const catalog = createRemoteSessionCatalog({ getHost: () => host });const rows = await catalog.sessions("ssh-one");- assert.equal(rows[0].messageCount, 0, "list count is a projection, not proof of emptiness");+ assert.equal(+ rows[0].messageCount,+ 0,+ "list count is a projection, not proof of emptiness",+ );const f = fixture(rows);- api.getSession = async () => ({ session: { ...rows[0], messages: [{ id: "m1", role: "user", content: "Earlier request" }] } });+ api.getSession = async () => ({+ session: {+ ...rows[0],+ messages: [{ id: "m1", role: "user", content: "Earlier request" }],+ },+ });const original = api.createRemoteSession;- api.createRemoteSession = async () => ({ session: { ...remote(), id: "remote:ssh-one:new" } });+ api.createRemoteSession = async () => ({+ session: { ...remote(), id: "remote:ssh-one:new" },+ });try {await openRemoteProjectSession(f, project);assert.equal(f.selections[0].id, "remote:ssh-one:new");- } finally { api.createRemoteSession = original; }+ } finally {+ api.createRemoteSession = original;+ }});test("a history confirmation cannot reuse a chat after a newer navigation", async () => {const f = fixture([remote()]);let resolve;- api.getSession = () => new Promise((done) => { resolve = done; });+ api.getSession = () =>+ new Promise((done) => {+ resolve = done;+ });const pending = openRemoteProjectSession(f, project);f.nav.begin();resolve({ session: { ...remote(), messages: [] } });@@ -147,14 +300,21 @@ test("a history confirmation cannot reuse a chat after a newer navigation", asyntest("a chat archived during history confirmation is not reused", async () => {const f = fixture([remote()]);let resolve;- api.getSession = () => new Promise((done) => { resolve = done; });+ api.getSession = () =>+ new Promise((done) => {+ resolve = done;+ });const original = api.createRemoteSession;- api.createRemoteSession = async () => ({ session: { ...remote(), id: "remote:ssh-one:new" } });+ api.createRemoteSession = async () => ({+ session: { ...remote(), id: "remote:ssh-one:new" },+ });try {const pending = openRemoteProjectSession(f, project);f.get().sessionMeta[remote().id] = { archived: true };resolve({ session: { ...remote(), messages: [] } });await pending;assert.equal(f.selections[0].id, "remote:ssh-one:new");- } finally { api.createRemoteSession = original; }+ } finally {+ api.createRemoteSession = original;+ }});diff --git a/apps/pi-host/src/host-operations.ts b/apps/pi-host/src/host-operations.tsindex 45400a6a0..cbbe15e87 100644--- a/apps/pi-host/src/host-operations.ts+++ b/apps/pi-host/src/host-operations.ts@@ -5,38 +5,65 @@ import { readdir, realpath, stat } from "node:fs/promises";import { homedir } from "node:os";import { basename, dirname, isAbsolute, join, resolve } from "node:path";-import { RacpError, type Principal, type SessionSummary } from "@pi-desktop/agent-host";+import {+ RacpError,+ type Principal,+ type SessionSummary,+} from "@pi-desktop/agent-host";import {collectWorkspaceDiff,listDir,readWorkspaceFile,toSessionSummary,+ withSessionProjectIds,type HostRpc,type HostSessionRecord,type RuntimeService,} from "@pi-desktop/host-runtime";-import type { RacpHostOperations, RacpProjectCatalog, RacpSessionCatalog, RacpWorkspaceAccess } from "@pi-desktop/racp";+import type {+ RacpHostOperations,+ RacpProjectCatalog,+ RacpSessionCatalog,+ RacpWorkspaceAccess,+} from "@pi-desktop/racp";import type { RacpProjectSummary } from "@pi-desktop/shared";/** A project row as host-core lists it. */type ProjectRow = { id: number; path: string; name: string; pinned?: boolean };/** Directory names never offered by the folder picker. */-const HIDDEN_BROWSE_NAMES = new Set([".git", "node_modules", "__pycache__", ".Trash"]);+const HIDDEN_BROWSE_NAMES = new Set([+ ".git",+ "node_modules",+ "__pycache__",+ ".Trash",+]);const MAX_BROWSE_ENTRIES = 500;function hostError(error: unknown): never {- const code = (error as { errorCode?: string; data?: { errorCode?: string } })?.data?.errorCode ?? (error as { errorCode?: string })?.errorCode;+ const code =+ (error as { errorCode?: string; data?: { errorCode?: string } })?.data+ ?.errorCode ?? (error as { errorCode?: string })?.errorCode;const message = error instanceof Error ? error.message : String(error);- if (code === "NOT_FOUND" || code === "SESSION_NOT_FOUND") throw new RacpError("NOT_FOUND", message);- if (code === "CONFLICT" || (code && code.startsWith("PLAN_"))) throw new RacpError("CONFLICT", message, { details: { code } });- if (code === "INVALID_PARAMS" || code === "INVALID_ARGUMENT") throw new RacpError("INVALID_ARGUMENT", message);- if (code === "HOST_UNAVAILABLE") throw new RacpError("AGENT_UNAVAILABLE", message, { retriable: true });- throw new RacpError("INTERNAL", message, { details: code ? { code } : undefined });+ if (code === "NOT_FOUND" || code === "SESSION_NOT_FOUND")+ throw new RacpError("NOT_FOUND", message);+ if (code === "CONFLICT" || (code && code.startsWith("PLAN_")))+ throw new RacpError("CONFLICT", message, { details: { code } });+ if (code === "INVALID_PARAMS" || code === "INVALID_ARGUMENT")+ throw new RacpError("INVALID_ARGUMENT", message);+ if (code === "HOST_UNAVAILABLE")+ throw new RacpError("AGENT_UNAVAILABLE", message, { retriable: true });+ throw new RacpError("INTERNAL", message, {+ details: code ? { code } : undefined,+ });}function projectSummary(row: ProjectRow): RacpProjectSummary {- return { id: String(row.id), label: row.name || basename(row.path), archived: false };+ return {+ id: String(row.id),+ label: row.name || basename(row.path),+ archived: false,+ };}export type HostOperationsDeps = {@@ -53,18 +80,30 @@ export type HostOperationsDeps = {function requireHost(getHost: () => HostRpc | null): HostRpc {const host = getHost();- if (!host) throw new RacpError("AGENT_UNAVAILABLE", "host-core is not running", { retriable: true });+ if (!host)+ throw new RacpError("AGENT_UNAVAILABLE", "host-core is not running", {+ retriable: true,+ });return host;}/** Session catalog over host-core RPC. */-export function createSessionCatalog(deps: HostOperationsDeps): RacpSessionCatalog {+export function createSessionCatalog(+ deps: HostOperationsDeps,+): RacpSessionCatalog {const { getHost } = deps;- async function projectPathFor(projectId: string | undefined, host: HostRpc): Promise<string | undefined> {+ async function projectPathFor(+ projectId: string | undefined,+ host: HostRpc,+ ): Promise<string | undefined> {if (!projectId) return undefined;- const { projects } = await host.call<{ projects: ProjectRow[] }>("projects.list", {});+ const { projects } = await host.call<{ projects: ProjectRow[] }>(+ "projects.list",+ {},+ );const project = projects.find((row) => String(row.id) === projectId);- if (!project) throw new RacpError("NOT_FOUND", `project ${projectId} is unknown`);+ if (!project)+ throw new RacpError("NOT_FOUND", `project ${projectId} is unknown`);return project.path;}/**@@ -72,28 +111,32 @@ export function createSessionCatalog(deps: HostOperationsDeps): RacpSessionCatal* (spec §5.1), so the summary is decorated from the projects table. A path* with no row (a session whose project was removed) simply has no id.*/- async function withProjectIds(host: HostRpc, records: HostSessionRecord[]): Promise<SessionSummary[]> {- const needsLookup = records.some((record) => record.projectPath);- const byPath = new Map<string, string>();- if (needsLookup) {- const { projects } = await host.call<{ projects: ProjectRow[] }>("projects.list", {}).catch(hostError);- for (const project of projects ?? []) byPath.set(project.path, String(project.id));- }- return records.map((record) => {- const summary = toSessionSummary(record);- const projectId = record.projectPath ? byPath.get(record.projectPath) : undefined;- return projectId ? { ...summary, projectId } : summary;- });+ async function withProjectIds(+ host: HostRpc,+ records: HostSessionRecord[],+ ): Promise<SessionSummary[]> {+ return withSessionProjectIds(host, records).catch(hostError);}- async function get(host: HostRpc, sessionId: string): Promise<SessionSummary> {- const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId, messageLimit: 1 }).catch(hostError);- if (!result.session) throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);+ async function get(+ host: HostRpc,+ sessionId: string,+ ): Promise<SessionSummary> {+ const result = await host+ .call<{ session?: HostSessionRecord | null }>("session.get", {+ id: sessionId,+ messageLimit: 1,+ })+ .catch(hostError);+ if (!result.session)+ throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);return (await withProjectIds(host, [result.session]))[0]!;}return {async list() {const host = requireHost(getHost);- const result = await host.call<{ sessions: HostSessionRecord[] }>("session.list", {}).catch(hostError);+ const result = await host+ .call<{ sessions: HostSessionRecord[] }>("session.list", {})+ .catch(hostError);return withProjectIds(host, result.sessions ?? []);},async create(input, _principal: Principal) {@@ -105,30 +148,44 @@ export function createSessionCatalog(deps: HostOperationsDeps): RacpSessionCatal...(input.mode ? { mode: input.mode } : {}),...(input.providerId ? { providerId: input.providerId } : {}),...(input.modelId ? { modelId: input.modelId } : {}),- ...(input.thinkingLevel ? { thinkingLevel: input.thinkingLevel } : {}),+ ...(input.thinkingLevel+ ? { thinkingLevel: input.thinkingLevel }+ : {}),...(projectPath ? { projectPath } : {}),}).catch(hostError);- if (!result.session) throw new RacpError("INTERNAL", "session.create returned no session");+ if (!result.session)+ throw new RacpError("INTERNAL", "session.create returned no session");if (input.permissionMode) {await host- .call("session.configure", { id: result.session.id, mode: result.session.mode ?? input.mode ?? "agent", permissionMode: input.permissionMode })+ .call("session.configure", {+ id: result.session.id,+ mode: result.session.mode ?? input.mode ?? "agent",+ permissionMode: input.permissionMode,+ }).catch(hostError);}return get(host, result.session.id);},async configure(sessionId, input) {const host = requireHost(getHost);- if (deps.runtime.isBusy(sessionId)) throw new RacpError("CONFLICT", "the session has an active turn");+ if (deps.runtime.isBusy(sessionId))+ throw new RacpError("CONFLICT", "the session has an active turn");const current = await get(host, sessionId);await host.call("session.configure", {id: sessionId,mode: input.mode ?? current.mode,- ...(input.providerId !== undefined ? { providerId: input.providerId } : {}),+ ...(input.providerId !== undefined+ ? { providerId: input.providerId }+ : {}),...(input.modelId !== undefined ? { modelId: input.modelId } : {}),- ...(input.thinkingLevel !== undefined ? { thinkingLevel: input.thinkingLevel } : {}),- ...(input.permissionMode !== undefined ? { permissionMode: input.permissionMode } : {}),+ ...(input.thinkingLevel !== undefined+ ? { thinkingLevel: input.thinkingLevel }+ : {}),+ ...(input.permissionMode !== undefined+ ? { permissionMode: input.permissionMode }+ : {}),}).catch(hostError);return get(host, sessionId);@@ -139,24 +196,35 @@ export function createSessionCatalog(deps: HostOperationsDeps): RacpSessionCatal.call<{ session?: HostSessionRecord | null }>("session.fork", {sessionId,...(input.title ? { title: input.title } : {}),- ...(input.throughMessageId ? { throughMessageId: input.throughMessageId } : {}),+ ...(input.throughMessageId+ ? { throughMessageId: input.throughMessageId }+ : {}),}).catch(hostError);- if (!result.session) throw new RacpError("INTERNAL", "session.fork returned no session");+ if (!result.session)+ throw new RacpError("INTERNAL", "session.fork returned no session");return get(host, result.session.id);},async rename(sessionId, title) {- await requireHost(getHost).call("session.rename", { id: sessionId, title }).catch(hostError);+ await requireHost(getHost)+ .call("session.rename", { id: sessionId, title })+ .catch(hostError);},async deriveTitle(sessionId, title) {const result = await requireHost(getHost)- .call<{ updated?: boolean }>("session.deriveTitle", { id: sessionId, title })+ .call<{ updated?: boolean }>("session.deriveTitle", {+ id: sessionId,+ title,+ }).catch(hostError);return result.updated === true;},async delete(sessionId) {- if (deps.runtime.isBusy(sessionId)) throw new RacpError("CONFLICT", "the session has an active turn");- await requireHost(getHost).call("session.delete", { id: sessionId }).catch(hostError);+ if (deps.runtime.isBusy(sessionId))+ throw new RacpError("CONFLICT", "the session has an active turn");+ await requireHost(getHost)+ .call("session.delete", { id: sessionId })+ .catch(hostError);await deps.disposeSession?.(sessionId).catch(() => undefined);},async compact(sessionId) {@@ -170,7 +238,8 @@ export function createSessionCatalog(deps: HostOperationsDeps): RacpSessionCatal}async function canonicalDirectory(path: string): Promise<string> {- if (!isAbsolute(path)) throw new RacpError("INVALID_ARGUMENT", "path must be absolute");+ if (!isAbsolute(path))+ throw new RacpError("INVALID_ARGUMENT", "path must be absolute");let real: string;try {real = await realpath(path);@@ -178,39 +247,65 @@ async function canonicalDirectory(path: string): Promise<string> {throw new RacpError("REMOTE_PATH_NOT_FOUND", `no such directory: ${path}`);}const info = await stat(real).catch(() => null);- if (!info?.isDirectory()) throw new RacpError("REMOTE_PATH_NOT_FOUND", `not a directory: ${path}`);+ if (!info?.isDirectory())+ throw new RacpError("REMOTE_PATH_NOT_FOUND", `not a directory: ${path}`);return real;}/** Projects over host-core: registration canonicalizes on the Host (D448). */-export function createProjectCatalog(deps: HostOperationsDeps): RacpProjectCatalog {+export function createProjectCatalog(+ deps: HostOperationsDeps,+): RacpProjectCatalog {const { getHost } = deps;const browseRoot = resolve(deps.browseRoot ?? homedir());return {async list() {const host = requireHost(getHost);- const result = await host.call<{ projects: ProjectRow[] }>("projects.list", {}).catch(hostError);+ const result = await host+ .call<{ projects: ProjectRow[] }>("projects.list", {})+ .catch(hostError);return (result.projects ?? []).map(projectSummary);},async register(path) {const host = requireHost(getHost);const real = await canonicalDirectory(path);- const result = await host.call<{ project?: ProjectRow | null }>("projects.create", { path: real }).catch(hostError);- if (!result.project) throw new RacpError("INTERNAL", "projects.create returned no project");+ const result = await host+ .call<{ project?: ProjectRow | null }>("projects.create", {+ path: real,+ })+ .catch(hostError);+ if (!result.project)+ throw new RacpError("INTERNAL", "projects.create returned no project");return { ...projectSummary(result.project), path: result.project.path };},async browse(path) {const target = await canonicalDirectory(path ?? browseRoot);const rootReal = await realpath(browseRoot).catch(() => browseRoot);- if (target !== rootReal && !target.startsWith(rootReal.endsWith("/") ? rootReal : `${rootReal}/`)) {- throw new RacpError("REMOTE_PATH_FORBIDDEN", "path is outside the browsable root");+ if (+ target !== rootReal &&+ !target.startsWith(rootReal.endsWith("/") ? rootReal : `${rootReal}/`)+ ) {+ throw new RacpError(+ "REMOTE_PATH_FORBIDDEN",+ "path is outside the browsable root",+ );}- const dirents = await readdir(target, { withFileTypes: true }).catch(() => {- throw new RacpError("REMOTE_PATH_FORBIDDEN", `cannot read ${target}`);- });+ const dirents = await readdir(target, { withFileTypes: true }).catch(+ () => {+ throw new RacpError("REMOTE_PATH_FORBIDDEN", `cannot read ${target}`);+ },+ );const entries = dirents- .filter((dirent) => dirent.isDirectory() && !HIDDEN_BROWSE_NAMES.has(dirent.name) && !dirent.name.startsWith("."))- .map((dirent) => ({ name: dirent.name, path: join(target, dirent.name) }))+ .filter(+ (dirent) =>+ dirent.isDirectory() &&+ !HIDDEN_BROWSE_NAMES.has(dirent.name) &&+ !dirent.name.startsWith("."),+ )+ .map((dirent) => ({+ name: dirent.name,+ path: join(target, dirent.name),+ })).sort((a, b) => a.name.localeCompare(b.name)).slice(0, MAX_BROWSE_ENTRIES);const parent = target === rootReal ? undefined : dirname(target);@@ -220,21 +315,33 @@ export function createProjectCatalog(deps: HostOperationsDeps): RacpProjectCatal}/** Workspace reads against the session's durable root, on the Host's filesystem. */-export function createWorkspaceAccess(deps: HostOperationsDeps): RacpWorkspaceAccess {+export function createWorkspaceAccess(+ deps: HostOperationsDeps,+): RacpWorkspaceAccess {const { getHost } = deps;async function sessionRoot(sessionId: string): Promise<string> {const host = requireHost(getHost);- const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", { id: sessionId, messageLimit: 1 }).catch(hostError);- if (!result.session) throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);+ const result = await host+ .call<{ session?: HostSessionRecord | null }>("session.get", {+ id: sessionId,+ messageLimit: 1,+ })+ .catch(hostError);+ if (!result.session)+ throw new RacpError("NOT_FOUND", `session ${sessionId} is unknown`);const root = result.session.projectPath?.trim();- if (!root) throw new RacpError("CONFLICT", "the session has no project root");+ if (!root)+ throw new RacpError("CONFLICT", "the session has no project root");return root;}const forbidden = (error: unknown): never => {const message = error instanceof Error ? error.message : String(error);- if (/escapes workspace root|outside allowed roots/.test(message)) throw new RacpError("REMOTE_PATH_FORBIDDEN", message);- if ((error as NodeJS.ErrnoException)?.code === "ENOENT") throw new RacpError("REMOTE_PATH_NOT_FOUND", message);- if (/not a file/.test(message)) throw new RacpError("INVALID_ARGUMENT", message);+ if (/escapes workspace root|outside allowed roots/.test(message))+ throw new RacpError("REMOTE_PATH_FORBIDDEN", message);+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT")+ throw new RacpError("REMOTE_PATH_NOT_FOUND", message);+ if (/not a file/.test(message))+ throw new RacpError("INVALID_ARGUMENT", message);throw new RacpError("INTERNAL", message);};return {@@ -252,7 +359,9 @@ export function createWorkspaceAccess(deps: HostOperationsDeps): RacpWorkspaceAc};}-export function createHostOperations(deps: HostOperationsDeps): Omit<RacpHostOperations, "terminal"> {+export function createHostOperations(+ deps: HostOperationsDeps,+): Omit<RacpHostOperations, "terminal"> {return {sessions: createSessionCatalog(deps),projects: createProjectCatalog(deps),@@ -264,7 +373,9 @@ export function createHostOperations(deps: HostOperationsDeps): Omit<RacpHostOpeprotectedPaths: [deps.dataDir ?? join(homedir(), ".pi-desktop")],isRegisteredRoot: async (root) => {const host = requireHost(deps.getHost);- const result = await host.call<{ projects: ProjectRow[] }>("projects.list", {}).catch(hostError);+ const result = await host+ .call<{ projects: ProjectRow[] }>("projects.list", {})+ .catch(hostError);return (result.projects ?? []).some((project) => project.path === root);},}),diff --git a/packages/host-runtime/src/host-ports.test.ts b/packages/host-runtime/src/host-ports.test.tsindex 7e5d534fb..7cf44f5ea 100644--- a/packages/host-runtime/src/host-ports.test.ts+++ b/packages/host-runtime/src/host-ports.test.ts@@ -1,6 +1,11 @@import { describe, expect, it } from "vitest";-import { createHostQueueStore, createHostSessionPort, fromHostQueueEntry, toSessionSummary } from "./host-ports.js";+import {+ createHostQueueStore,+ createHostSessionPort,+ fromHostQueueEntry,+ toSessionSummary,+} from "./host-ports.js";describe("host ports", () => {it("maps a host session record to the Agent Host summary without leaking the absolute path", () => {@@ -27,7 +32,14 @@ describe("host ports", () => {updatedAt: "2026-09-18T00:00:00.000Z",});expect(JSON.stringify(summary)).not.toContain("/home/user/work/pi");- expect(toSessionSummary({ id: "x", mode: "weird", permissionMode: "yolo", planningState: "?" })).toMatchObject({+ expect(+ toSessionSummary({+ id: "x",+ mode: "weird",+ permissionMode: "yolo",+ planningState: "?",+ }),+ ).toMatchObject({mode: "agent",permissionMode: "ask",planningState: "inactive",@@ -69,8 +81,54 @@ describe("host ports", () => {expect(calls).toEqual([{ id: "s1", messageLimit: 1 }, { id: "s1" }]);});+ it("decorates the attach summary with the project id resolved from the project path", async () => {+ // The renderer replaces its cached summary with the attach snapshot, so a+ // bare host record (project path only) used to drop the row from its+ // sidebar project group.+ const port = createHostSessionPort(() => ({+ async call<T>(method: string) {+ if (method === "projects.list") {+ return {+ projects: [{ id: 7, path: "/remote/app", name: "app" }],+ } as T;+ }+ return {+ session: { id: "s1", projectPath: "/remote/app", messages: [] },+ } as T;+ },+ }));+ const summary = await port.get("s1");+ expect(summary).toMatchObject({+ id: "s1",+ projectId: "7",+ workspaceLabel: "app",+ });+ // A session whose project was removed keeps no fabricated id.+ const orphanPort = createHostSessionPort(() => ({+ async call<T>(method: string) {+ if (method === "projects.list") return { projects: [] } as T;+ return {+ session: { id: "s2", projectPath: "/remote/gone", messages: [] },+ } as T;+ },+ }));+ const orphan = await orphanPort.get("s2");+ expect(orphan?.projectId).toBeUndefined();+ // No project path means no projects.list round-trip at all.+ const calls: string[] = [];+ const plainPort = createHostSessionPort(() => ({+ async call<T>(method: string) {+ calls.push(method);+ return { session: { id: "s3", messages: [] } } as T;+ },+ }));+ await plainPort.get("s3");+ expect(calls).toEqual(["session.get"]);+ });+it("round-trips queue records through the host-core RPC shape", async () => {- const calls: Array<{ method: string; params: Record<string, unknown> }> = [];+ const calls: Array<{ method: string; params: Record<string, unknown> }> =+ [];const store = createHostQueueStore(() => ({async call<T>(method: string, params: Record<string, unknown> = {}) {calls.push({ method, params });@@ -97,13 +155,36 @@ describe("host ports", () => {},}));const [record] = await store.listAll();- expect(record).toMatchObject({ id: "q1", principalSubject: "phone", effectivePermissionMode: "auto", priority: 2 });+ expect(record).toMatchObject({+ id: "q1",+ principalSubject: "phone",+ effectivePermissionMode: "auto",+ priority: 2,+ });expect(record?.createdAt).toBe(Date.parse("2026-09-18T00:00:00.000Z"));- await store.push({ ...record!, attachments: [{ path: "/x", name: "x", kind: "file" }] });- expect(calls.at(-1)?.params).toMatchObject({ id: "q1", principal: "phone", permissionMode: "auto" });+ await store.push({+ ...record!,+ attachments: [{ path: "/x", name: "x", kind: "file" }],+ });+ expect(calls.at(-1)?.params).toMatchObject({+ id: "q1",+ principal: "phone",+ permissionMode: "auto",+ });expect(await store.remove("q1")).toBe(true);expect(await store.reorder!("q1", "up")).toBe(false);- expect(fromHostQueueEntry({ id: "q", sessionId: "s", principal: "p", inputHash: "h", content: "c", permissionMode: "nope", position: 1, createdAt: "bad" })).toMatchObject({+ expect(+ fromHostQueueEntry({+ id: "q",+ sessionId: "s",+ principal: "p",+ inputHash: "h",+ content: "c",+ permissionMode: "nope",+ position: 1,+ createdAt: "bad",+ }),+ ).toMatchObject({effectivePermissionMode: "ask",createdAt: 0,});@@ -112,6 +193,8 @@ describe("host ports", () => {it("fails closed when the host is gone", async () => {const store = createHostQueueStore(() => null);expect(await store.listAll()).toEqual([]);- await expect(store.remove("q1")).rejects.toMatchObject({ code: "AGENT_UNAVAILABLE" });+ await expect(store.remove("q1")).rejects.toMatchObject({+ code: "AGENT_UNAVAILABLE",+ });});});diff --git a/packages/host-runtime/src/host-ports.ts b/packages/host-runtime/src/host-ports.tsindex 4ab6f1ebc..250bdd6db 100644--- a/packages/host-runtime/src/host-ports.ts+++ b/packages/host-runtime/src/host-ports.ts@@ -9,11 +9,19 @@ import type {SessionSummary,} from "@pi-desktop/agent-host";import { RacpError } from "@pi-desktop/agent-host";-import type { RacpItemSummary, RacpPermissionMode, UiMessage, VoiceOrigin } from "@pi-desktop/shared";+import type {+ RacpItemSummary,+ RacpPermissionMode,+ UiMessage,+ VoiceOrigin,+} from "@pi-desktop/shared";/** Rust host-core over stdio JSON-RPC, as the ports below need it. */export type HostRpc = {- call<T = unknown>(method: string, params?: Record<string, unknown>): Promise<T>;+ call<T = unknown>(+ method: string,+ params?: Record<string, unknown>,+ ): Promise<T>;};export type HostSessionRecord = {@@ -30,25 +38,39 @@ export type HostSessionRecord = {};/** Opaque Main/Host authorization fingerprint; never send the source identity to the renderer or model. */-export function sessionWorkspaceIdentity(input: { projectId?: unknown; projectPath?: unknown }): string | null {- const projectId = typeof input.projectId === "string" ? input.projectId.trim() : "";- const projectPath = typeof input.projectPath === "string" ? input.projectPath.trim() : "";+export function sessionWorkspaceIdentity(input: {+ projectId?: unknown;+ projectPath?: unknown;+}): string | null {+ const projectId =+ typeof input.projectId === "string" ? input.projectId.trim() : "";+ const projectPath =+ typeof input.projectPath === "string" ? input.projectPath.trim() : "";if (!projectId && !projectPath) return null;- return createHash("sha256").update(JSON.stringify([projectId, projectPath])).digest("hex");+ return createHash("sha256")+ .update(JSON.stringify([projectId, projectPath]))+ .digest("hex");}export function requireHostRpc(getHost: () => HostRpc | null): HostRpc {const host = getHost();- if (!host) throw new RacpError("AGENT_UNAVAILABLE", "host is not running", { retriable: true });+ if (!host)+ throw new RacpError("AGENT_UNAVAILABLE", "host is not running", {+ retriable: true,+ });return host;}export function toSessionSummary(record: HostSessionRecord): SessionSummary {- const mode = record.mode === "plan" || record.mode === "goal" ? record.mode : "agent";+ const mode =+ record.mode === "plan" || record.mode === "goal" ? record.mode : "agent";const permissionMode: RacpPermissionMode =- record.permissionMode === "accept-edits" || record.permissionMode === "auto" ? record.permissionMode : "ask";+ record.permissionMode === "accept-edits" || record.permissionMode === "auto"+ ? record.permissionMode+ : "ask";const planningState =- record.planningState === "planning" || record.planningState === "awaiting_approval"+ record.planningState === "planning" ||+ record.planningState === "awaiting_approval"? record.planningState: "inactive";return {@@ -56,12 +78,15 @@ export function toSessionSummary(record: HostSessionRecord): SessionSummary {title: record.title ?? "",...(record.projectId ? { projectId: record.projectId } : {}),workspaceIdentity: sessionWorkspaceIdentity(record),- ...(record.projectPath ? { workspaceLabel: basename(record.projectPath) } : {}),+ ...(record.projectPath+ ? { workspaceLabel: basename(record.projectPath) }+ : {}),mode,permissionMode,planningState,createdAt: record.createdAt ?? new Date(0).toISOString(),- updatedAt: record.updatedAt ?? record.createdAt ?? new Date(0).toISOString(),+ updatedAt:+ record.updatedAt ?? record.createdAt ?? new Date(0).toISOString(),};}@@ -73,34 +98,85 @@ export function toRacpItem(message: UiMessage): RacpItemSummary {itemType: "message",status: message.status === "streaming" ? "streaming" : "completed",createdAt: message.createdAt,- ...(message.parentToolCallId ? { parentToolCallId: message.parentToolCallId } : {}),- ...(message.nestedParentToolCallId ? { nestedParentToolCallId: message.nestedParentToolCallId } : {}),+ ...(message.parentToolCallId+ ? { parentToolCallId: message.parentToolCallId }+ : {}),+ ...(message.nestedParentToolCallId+ ? { nestedParentToolCallId: message.nestedParentToolCallId }+ : {}),...(message.agentName ? { agentName: message.agentName } : {}),content: message,};}+/**+ * host-core keys a session by its project path; RACP exposes the project id+ * (spec §5.1), so summaries are decorated from the projects table. A path+ * with no row (a session whose project was removed) simply has no id.+ */+export async function withSessionProjectIds(+ host: HostRpc,+ records: HostSessionRecord[],+): Promise<SessionSummary[]> {+ const needsLookup = records.some((record) => record.projectPath);+ const byPath = new Map<string, string>();+ if (needsLookup) {+ const { projects } = await host.call<{ projects?: ProjectRow[] }>(+ "projects.list",+ {},+ );+ for (const project of projects ?? [])+ byPath.set(project.path, String(project.id));+ }+ return records.map((record) => {+ const summary = toSessionSummary(record);+ const projectId = record.projectPath+ ? byPath.get(record.projectPath)+ : undefined;+ return projectId ? { ...summary, projectId } : summary;+ });+}++type ProjectRow = { id: number; path: string; name?: string };+/** Session metadata and transcript pages straight from host `session.get`. */-export function createHostSessionPort(getHost: () => HostRpc | null): SessionPort {+export function createHostSessionPort(+ getHost: () => HostRpc | null,+): SessionPort {// `messageLimit` bounds the transcript read; metadata lookups need no messages.- async function fetchSession(sessionId: string, messageLimit?: number): Promise<HostSessionRecord | null> {+ async function fetchSession(+ sessionId: string,+ messageLimit?: number,+ ): Promise<HostSessionRecord | null> {const host = getHost();if (!host) return null;- const result = await host.call<{ session?: HostSessionRecord | null }>("session.get", {- id: sessionId,- ...(messageLimit === undefined ? {} : { messageLimit }),- });+ const result = await host.call<{ session?: HostSessionRecord | null }>(+ "session.get",+ {+ id: sessionId,+ ...(messageLimit === undefined ? {} : { messageLimit }),+ },+ );return result.session ?? null;}return {async get(sessionId) {const record = await fetchSession(sessionId, 1);- return record ? toSessionSummary(record) : null;+ if (!record) return null;+ // Attach consumers replace their cached summary with this one, so the+ // project id must survive the same decoration as `session/list` (the+ // renderer groups rows by it; a bare record drops the row from its+ // project group).+ const host = getHost();+ if (!host) return toSessionSummary(record);+ return (await withSessionProjectIds(host, [record]))[0] ?? null;},async history(sessionId, { limit, beforeItemId }) {const record = await fetchSession(sessionId);const messages = record?.messages ?? [];- const end = beforeItemId ? messages.findIndex((message) => message.id === beforeItemId) : messages.length;+ const end = beforeItemId+ ? messages.findIndex((message) => message.id === beforeItemId)+ : messages.length;const cut = end === -1 ? messages.length : end;const start = Math.max(0, cut - limit);return {@@ -131,17 +207,23 @@ export type HostQueueEntry = {export function fromHostQueueEntry(entry: HostQueueEntry): QueuedTurnRecord {const permissionMode: RacpPermissionMode =- entry.permissionMode === "accept-edits" || entry.permissionMode === "auto" ? entry.permissionMode : "ask";+ entry.permissionMode === "accept-edits" || entry.permissionMode === "auto"+ ? entry.permissionMode+ : "ask";return {id: entry.id,sessionId: entry.sessionId,principalSubject: entry.principal,content: entry.content,startGoal: entry.startGoal === true,- ...(entry.sessionMessageId ? { sessionMessageId: entry.sessionMessageId } : {}),+ ...(entry.sessionMessageId+ ? { sessionMessageId: entry.sessionMessageId }+ : {}),...(entry.userMessageId ? { userMessageId: entry.userMessageId } : {}),...(entry.voiceOrigin ? { voiceOrigin: entry.voiceOrigin } : {}),- ...(Array.isArray(entry.attachments) ? { attachments: entry.attachments as QueuedTurnRecord["attachments"] } : {}),+ ...(Array.isArray(entry.attachments)+ ? { attachments: entry.attachments as QueuedTurnRecord["attachments"] }+ : {}),effectivePermissionMode: permissionMode,...(entry.idempotencyKey ? { idempotencyKey: entry.idempotencyKey } : {}),inputHash: entry.inputHash,@@ -151,12 +233,17 @@ export function fromHostQueueEntry(entry: HostQueueEntry): QueuedTurnRecord {}/** The Host-owned turn queue persisted by host-core (schema v15, ADR 0213). */-export function createHostQueueStore(getHost: () => HostRpc | null): QueueStore {+export function createHostQueueStore(+ getHost: () => HostRpc | null,+): QueueStore {return {async listAll() {const host = getHost();if (!host) return [];- const result = await host.call<{ entries?: HostQueueEntry[] }>("session.queueList", {});+ const result = await host.call<{ entries?: HostQueueEntry[] }>(+ "session.queueList",+ {},+ );return (result.entries ?? []).map(fromHostQueueEntry);},async push(record) {@@ -164,29 +251,41 @@ export function createHostQueueStore(getHost: () => HostRpc | null): QueueStoreid: record.id,sessionId: record.sessionId,principal: record.principalSubject,- ...(record.idempotencyKey ? { idempotencyKey: record.idempotencyKey } : {}),+ ...(record.idempotencyKey+ ? { idempotencyKey: record.idempotencyKey }+ : {}),inputHash: record.inputHash,content: record.content,...(record.startGoal ? { startGoal: true } : {}),- ...(record.sessionMessageId ? { sessionMessageId: record.sessionMessageId } : {}),- ...(record.userMessageId ? { userMessageId: record.userMessageId } : {}),+ ...(record.sessionMessageId+ ? { sessionMessageId: record.sessionMessageId }+ : {}),+ ...(record.userMessageId+ ? { userMessageId: record.userMessageId }+ : {}),...(record.voiceOrigin ? { voiceOrigin: record.voiceOrigin } : {}),...(record.attachments ? { attachments: record.attachments } : {}),permissionMode: record.effectivePermissionMode,});},async remove(id) {- const result = await requireHostRpc(getHost).call<{ removed?: boolean }>("session.queueRemove", { id });+ const result = await requireHostRpc(getHost).call<{ removed?: boolean }>(+ "session.queueRemove",+ { id },+ );return result.removed === true;},async prioritize(id) {await requireHostRpc(getHost).call("session.queuePrioritize", { id });},async reorder(id, direction) {- const result = await requireHostRpc(getHost).call<{ moved?: boolean }>("session.queueReorder", {- id,- direction,- });+ const result = await requireHostRpc(getHost).call<{ moved?: boolean }>(+ "session.queueReorder",+ {+ id,+ direction,+ },+ );return result.moved === true;},};@@ -199,8 +298,11 @@ export async function listPendingToolRequests(): Promise<PendingToolRequest[]> {const host = getHost();if (!host) return [];- const result = await host.call<{ requests?: PendingToolRequest[] }>("permissions.pending", {- ...(sessionId ? { sessionId } : {}),- });+ const result = await host.call<{ requests?: PendingToolRequest[] }>(+ "permissions.pending",+ {+ ...(sessionId ? { sessionId } : {}),+ },+ );return result.requests ?? [];}