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): integrate remote projects into the home workflow
vastsac771a68246aa
diff --git a/apps/desktop/electron/main/bootstrap/remote-hosts.ts b/apps/desktop/electron/main/bootstrap/remote-hosts.tsindex 8cf74d14d..3e605dd23 100644--- a/apps/desktop/electron/main/bootstrap/remote-hosts.ts+++ b/apps/desktop/electron/main/bootstrap/remote-hosts.ts@@ -4,7 +4,7 @@ import {IPC,type RacpEventEnvelope, type RacpItemSummary, type RacpProjectSummary, type RacpSession,type RemoteHostBootstrapRequest, type RemoteHostBootstrapResult,- type RemoteHostCreateSessionRequest, type RemoteHostSummary,+ type RemoteHostCreateSessionRequest, type RemoteHostSummary, type RemoteHostBrowseProjectsResult,type RemoteHostSyncProvidersRequest, type RemoteHostSyncProvidersResult, type SessionSummary,} from "@pi-desktop/shared";import { wsClientTransport } from "@pi-desktop/racp";@@ -52,6 +52,7 @@ export interface RemoteHostsBoot {sessionSummaries(): SessionSummary[];sessions(hostKey: string): Promise<SessionSummary[]>;projects(hostKey: string): Promise<RacpProjectSummary[]>;+ browseProjects(hostKey: string, path?: string): Promise<RemoteHostBrowseProjectsResult>;registerProject(hostKey: string, path: string): Promise<RacpProjectSummary & { path?: string }>;createSession(request: RemoteHostCreateSessionRequest): Promise<SessionSummary>;syncProviders(request: RemoteHostSyncProvidersRequest): Promise<RemoteHostSyncProvidersResult>;@@ -255,6 +256,7 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHosessionSummaries: () => catalog.summaries(),sessions: catalog.sessions,projects: catalog.projects,+ browseProjects: catalog.browseProjects,registerProject: catalog.registerProject,async createSession(input) {const session = await catalog.createSession(input);diff --git a/apps/desktop/electron/main/ipc/remote-session-ipc.ts b/apps/desktop/electron/main/ipc/remote-session-ipc.tsindex 91078bb92..d1109df0b 100644--- a/apps/desktop/electron/main/ipc/remote-session-ipc.ts+++ b/apps/desktop/electron/main/ipc/remote-session-ipc.ts@@ -31,6 +31,13 @@ export function registerRemoteSessionIpc(registrar: IpcRegistrar, getBoot: () =>registrar.handle(IPC.invoke.remoteHostProjects, async (request: unknown) => {return { projects: await getBoot().projects(hostKey(object(request))) };});+ registrar.handle(IPC.invoke.remoteHostBrowseProjects, async (request: unknown) => {+ const input = object(request);+ const key = hostKey(input);+ const path = input.path === undefined ? undefined : text(input.path, "path", 4096);+ if (path !== undefined && !path.startsWith("/")) invalid("path");+ return getBoot().browseProjects(key, path);+ });registrar.handle(IPC.invoke.remoteHostSessions, async (request: unknown) => {return { sessions: await getBoot().sessions(hostKey(object(request))) };});diff --git a/apps/desktop/electron/main/remote/remote-session-catalog.ts b/apps/desktop/electron/main/remote/remote-session-catalog.tsindex 172cc5da4..f9d3742cb 100644--- a/apps/desktop/electron/main/remote/remote-session-catalog.ts+++ b/apps/desktop/electron/main/remote/remote-session-catalog.ts@@ -1,5 +1,5 @@import type {- RacpProjectSummary, RacpSession, RemoteHostCreateSessionRequest, SessionSummary,+ RacpProjectSummary, RacpSession, RemoteHostCreateSessionRequest, SessionSummary, RemoteHostBrowseProjectsResult,} from "@pi-desktop/shared";import { makeRemoteSessionId } from "./backend-router.js";import type { RemoteHostConnection } from "./remote-host-connection.js";@@ -69,6 +69,12 @@ export function createRemoteSessionCatalog(options: {stillCurrent(host);return result.projects;},+ async browseProjects(hostKey: string, path?: string): Promise<RemoteHostBrowseProjectsResult> {+ const host = requireHost(hostKey);+ const result = await host.client.request<unknown>("project/browse", path === undefined ? {} : { path });+ stillCurrent(host);+ return validateProjectBrowse(result);+ },async registerProject(hostKey: string, path: string) {const host = requireHost(hostKey);const result = await host.client.request<{ project: RacpProjectSummary & { path?: string } }>("project/register", { path });@@ -92,3 +98,27 @@ export function createRemoteSessionCatalog(options: {},};}++/** Validate untrusted Host picker data before it crosses the renderer boundary. */+function validateProjectBrowse(value: unknown): RemoteHostBrowseProjectsResult {+ const invalid = (): never => {+ throw Object.assign(new Error("invalid remote project browse response"), { errorCode: "INVALID_ARGUMENT" });+ };+ const absolutePath = (path: unknown): path is string =>+ typeof path === "string" && path.startsWith("/") && path.length <= 4096 && !/[\u0000-\u001f]/.test(path);+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();+ const result = value as Record<string, unknown>;+ if (!absolutePath(result.path) || (result.parent !== undefined && !absolutePath(result.parent))+ || !Array.isArray(result.entries) || result.entries.length > 500) return invalid();+ const entries = result.entries.map((value: unknown) => {+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid();+ const entry = value as Record<string, unknown>;+ if (typeof entry.name !== "string" || !entry.name || entry.name.length > 4096+ || /[\/\u0000-\u001f]/.test(entry.name) || entry.name === "." || entry.name === ".."+ || !absolutePath(entry.path)) return invalid();+ const prefix = result.path === "/" ? "/" : `${String(result.path).replace(/\/+$/, "")}/`;+ if (entry.path !== `${prefix}${entry.name}`) return invalid();+ return { name: entry.name, path: entry.path };+ });+ return { path: result.path, ...(typeof result.parent === "string" ? { parent: result.parent } : {}), entries };+}diff --git a/apps/desktop/src/components/ChatSurface.tsx b/apps/desktop/src/components/ChatSurface.tsxindex e1f9e8200..95d519958 100644--- a/apps/desktop/src/components/ChatSurface.tsx+++ b/apps/desktop/src/components/ChatSurface.tsx@@ -17,7 +17,6 @@ import { headPermission } from "../lib/pending-permissions";import { headAsk } from "../lib/pending-asks";import { isRemoteSession } from "../lib/remote-session-safety";-import { RemoteConversation } from "./remote/RemoteConversation";const StableComposer = memo(Composer);function i18nHasError(t: (key: string) => string, code: string) {@@ -54,8 +53,7 @@ export const ChatSurface = memo(function ChatSurface({const { t } = useTranslation();const activeSessionId = useAppStore((state) => state.activeSessionId);const selectingSessionId = useAppStore((state) => state.selectingSessionId);- const retainedIds = useAppStore((state) => state.retainedSessionIds);- const retainedSessionIds = useMemo(() => retainedIds.filter((id) => !id.startsWith("remote:")), [retainedIds]);+ const retainedSessionIds = useAppStore((state) => state.retainedSessionIds);const messages = useAppStore((state) => state.messages);// Only the error layer's retry affordance needs the run state here; each pane// reads its own session's flag.@@ -94,13 +92,16 @@ export const ChatSurface = memo(function ChatSurface({// project the user has just opened has no session yet, so its active// workspace names the hero instead of falling back to the generic title.const heroProject = useMemo(() => {+ if (isRemoteSession(activeSession)) {+ return projectName(activeSession?.remoteWorkspaceLabel) ?? activeSession?.remoteHostLabel ?? null;+ }const path = activeSession? activeSession.projectPath?.trim(): workspace?.path?.trim();return path ? projectName(path, workspace?.name) : null;}, [activeSession, workspace?.path, workspace?.name]);const isTemporarySession = Boolean(- activeSessionId && activeSession && !activeSession.projectPath?.trim(),+ activeSessionId && activeSession && !isRemoteSession(activeSession) && !activeSession.projectPath?.trim(),);const emptyTitleParts = useMemo(() => {const marker = "__PROJECT__";@@ -131,7 +132,7 @@ export const ChatSurface = memo(function ChatSurface({// not take over just because the destination projection is still empty.const showEmptyState =!hasTranscript && (!visibleSessionId || visibleSessionId === activeSessionId);- const vendorModelMissing = vendorAccountOmitsSessionModel(+ const vendorModelMissing = !isRemoteSession(activeSession) && vendorAccountOmitsSessionModel(activeSession,providers,);@@ -147,10 +148,6 @@ export const ChatSurface = memo(function ChatSurface({: showVendorModelError? "MODEL_NOT_CONFIGURED": null;- if (activeSession && isRemoteSession(activeSession)) {- return <RemoteConversation key={activeSession.id} session={activeSession} />;- }- if (activeSessionId?.startsWith("remote:")) return <div role="status">{t("remote:loading")}</div>;return (<divclassName={`chat-surface route-surface${sessionSwitching ? " session-switching" : ""}`}@@ -184,7 +181,7 @@ export const ChatSurface = memo(function ChatSurface({{heroProject ? (<>{emptyTitleParts.before}- <HomeProjectSwitcher name={heroProject} path={workspace?.path || activeSession?.projectPath || null} />+ <HomeProjectSwitcher name={heroProject} path={isRemoteSession(activeSession) ? null : workspace?.path || activeSession?.projectPath || null} />{emptyTitleParts.after}</>) : isTemporarySession ? (@@ -194,7 +191,7 @@ export const ChatSurface = memo(function ChatSurface({)}</h1></div>- <OnboardingChecklist />+ {!isRemoteSession(activeSession) ? <OnboardingChecklist /> : null}</div></div><div className="home-composer-wrap">@@ -230,7 +227,7 @@ export const ChatSurface = memo(function ChatSurface({</>) : null}</span>- {(noticeCode === "MODEL_NOT_CONFIGURED" ||+ {!isRemoteSession(activeSession) && (noticeCode === "MODEL_NOT_CONFIGURED" ||noticeCode === "PROVIDER_SECRET_MISSING" ||noticeCode === "PROVIDER_UNAUTHORIZED") && (<buttondiff --git a/apps/desktop/src/components/Composer.tsx b/apps/desktop/src/components/Composer.tsxindex c5b49e26e..cba5fbbdb 100644--- a/apps/desktop/src/components/Composer.tsx+++ b/apps/desktop/src/components/Composer.tsx@@ -1,3 +1,4 @@+import { isRemoteSession, sessionAllows } from "../lib/remote-session-safety";import { inheritedSessionModelBinding } from "../lib/session-model";import {useEffect,@@ -86,13 +87,6 @@ export function Composer({);const settings = useAppStore((s) => s.settings);const plugins = useAppStore((s) => s.plugins);- const composerTransforms = useMemo(- () =>- plugins- .filter((plugin) => plugin.enabled && plugin.status === "ready")- .flatMap((plugin) => plugin.composerTransforms ?? []),- [plugins],- );const imageGenerationCandidates = useMemo(() => imageGenerationBindings(settings?.imageGenerationModels, settings?.imageGeneration),[settings?.imageGenerationModels, settings?.imageGeneration],@@ -102,11 +96,24 @@ export function Composer({const activeSessionSummary = sessions.find((session) => session.id === activeSessionId,);+ const capabilitySession = activeSessionSummary ?? (activeSessionId?.startsWith("remote:") ? { id: activeSessionId } : undefined);+ const composerTransforms = useMemo(+ () =>+ (sessionAllows(capabilitySession, "canUseLocalTools") ? plugins : [])+ .filter((plugin) => plugin.enabled && plugin.status === "ready")+ .flatMap((plugin) => plugin.composerTransforms ?? []),+ [plugins, activeSessionSummary, activeSessionId],+ );+ const remoteSession = isRemoteSession(capabilitySession);+ const localToolsAllowed = sessionAllows(capabilitySession, "canUseLocalTools");+ const attachmentsAllowed = sessionAllows(capabilitySession, "canAttach");+ const promptAllowed = sessionAllows(capabilitySession, "canPrompt");const nativeSession = activeSessionSummary?.source === "pi-native";const nativeReadOnly =nativeSession && activeSessionSummary.capabilities?.canPrompt !== true;- const nativeInputBlocked = nativeReadOnly || (nativeSession && isRunning);- const workspacePath = useAppStore((s) => s.workspace?.path ?? "");+ const nativeInputBlocked = nativeReadOnly || !promptAllowed || ((nativeSession || remoteSession) && isRunning);+ const localWorkspacePath = useAppStore((s) => s.workspace?.path ?? "");+ const workspacePath = remoteSession ? "" : localWorkspacePath;const providers = useAppStore((s) => s.providers);const providerModels = useAppStore((s) => s.providerModels);const liveMessages = useAppStore((s) => s.messages);@@ -205,6 +212,7 @@ export function Composer({);const attachments = useComposerAttachments({inputBlocked: approvalPending || nativeSession,+ attachmentsAllowed,activeSessionId,draftKey,largePasteThreshold,@@ -235,7 +243,7 @@ export function Composer({const executionActive = isActivePlanExecution(planCheckpoint);const runActive = isRunning || executionActive;const inputBlocked = approvalPending || pasting || nativeInputBlocked;- const controlsBlocked = approvalPending || nativeSession;+ const controlsBlocked = approvalPending || nativeSession || !sessionAllows(capabilitySession, "canConfigureModel");const sendBlocked = approvalPending || pasting || nativeInputBlocked;// Edit returns one queued row to the composer. The row is removed and its// captured draft becomes the input, so the input must be empty first: the@@ -332,7 +340,7 @@ export function Composer({const composerPermissionMode: Exclude<PermissionMode, "inherit"> =mode === "goal" ? "auto" : effectivePermissionMode;const recentModels = useAppStore((s) => s.recentModels);- const selectedModel = inheritedSessionModelBinding({+ const selectedModel = remoteSession ? { providerId: activeSession?.providerId, modelId: activeSession?.modelId } : inheritedSessionModelBinding({draft: activeSession ?? draftConfiguration,settings,providers,@@ -394,7 +402,7 @@ export function Composer({thinkingLevel,controlsBlocked,});- const modelReady = nativeSession+ const modelReady = remoteSession ? promptAllowed : nativeSession? activeSessionSummary.capabilities?.canPrompt === true: !!provider &&provider.enabled &&@@ -430,6 +438,8 @@ export function Composer({modelReady,invalidateComposerTransforms,sendBlocked,+ localCommandsAllowed: localToolsAllowed,+ steeringAllowed: sessionAllows(capabilitySession, "canSteer"),pasting,activeFileReferences,t,@@ -457,7 +467,7 @@ export function Composer({// Keep the legacy listener for already-started or IPC-owned Dictation, but// the Composer no longer exposes a Dictation control or overlay.useVoiceInput({- enabled: import.meta.env.DEV && !!settings?.voice?.enabled,+ enabled: localToolsAllowed && import.meta.env.DEV && !!settings?.voice?.enabled,onTranscriptionComplete: (text) => {const current = readLiveDraft();if (!current.trim()) {@@ -472,7 +482,7 @@ export function Composer({value,cursor,composing,- enabled: !inputBlocked,+ enabled: !inputBlocked && localToolsAllowed,referenceSessionId,fileReferencesRef,applyEditorDraft,@@ -481,7 +491,7 @@ export function Composer({});// Plugin draft and attachment actions reach this composer while it takes input.- usePluginComposerBridge({ ...draft, inputBlocked });+ usePluginComposerBridge({ ...draft, inputBlocked, enabled: localToolsAllowed });// Keep the transcript's bottom reserve in sync with the composer's real// height (it grows with multi-line input) so the last message sits just@@ -514,7 +524,7 @@ export function Composer({data-composer-dock={variant}><div className="composer-stack">- {activeSessionId ? <TodoDock sessionId={activeSessionId} /> : null}+ {activeSessionId && localToolsAllowed ? <TodoDock sessionId={activeSessionId} /> : null}{planCheckpoint?.status === "pending" ? (<PlanApprovalBar proposal={planCheckpoint} />) : null}@@ -600,6 +610,9 @@ export function Composer({permissionOpen={permissionOpen}setPermissionOpen={setPermissionOpen}controlsBlocked={controlsBlocked}+ localToolsAllowed={localToolsAllowed}+ attachmentsAllowed={attachmentsAllowed}+ stopAllowed={sessionAllows(capabilitySession, "canStop")}pasting={pasting}pickAndAttach={pickAndAttach}configureActiveSession={configureActiveSession}diff --git a/apps/desktop/src/components/HomeProjectSwitcher.tsx b/apps/desktop/src/components/HomeProjectSwitcher.tsxindex 3a3b9c96a..fa9f52eba 100644--- a/apps/desktop/src/components/HomeProjectSwitcher.tsx+++ b/apps/desktop/src/components/HomeProjectSwitcher.tsx@@ -25,6 +25,11 @@ import {} from "./icons";import { AnchoredMenu } from "./settings/AnchoredMenu";import { cx } from "./ui";+import { useRemoteProjects } from "../hooks/use-remote-projects";+import { remoteProjectKey, type RemoteProjectEntry } from "../lib/remote-project-catalog";+import { isRemoteSession } from "../lib/remote-session-safety";++type ProjectMenuEntry = { key: string; name: string; title: string; localPath?: string; remoteProject?: RemoteProjectEntry };export function HomeProjectSwitcher({name,@@ -40,6 +45,7 @@ export function HomeProjectSwitcher({const projectMeta = useAppStore((state) => state.projectMeta);const projectSort = useAppStore((state) => state.projectSort);const activeProjectPath = useAppStore((state) => state.activeProjectPath);+ const activeSession = useAppStore((state) => state.sessions.find((session) => session.id === state.activeSessionId));const newSession = useAppStore((state) => state.newSession);const openProject = useAppStore((state) => state.openProject);const cloneProject = useAppStore((state) => state.cloneProject);@@ -53,6 +59,7 @@ export function HomeProjectSwitcher({const [highlight, setHighlight] = useState(0);const [busy, setBusy] = useState(false);const busyRef = useRef(false);+ const remoteCatalog = useRemoteProjects(open && view === "list");const projects = useMemo(() =>@@ -66,10 +73,18 @@ export function HomeProjectSwitcher({[openProjectPaths, openProjects, workspace, projectMeta, projectSort],);const visible = useMemo(- () => filterSwitcherProjects(projects, query),- [projects, query],+ (): ProjectMenuEntry[] => [+ ...filterSwitcherProjects(projects, query).map((project) => ({ key: project.key, name: project.name,+ title: project.path, localPath: project.path })),+ ...remoteCatalog.projects.filter((project) => `${project.label} ${project.hostLabel}`.toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()))+ .map((project) => ({ key: `remote:${project.key}`, name: `${project.label} · ${project.hostLabel}`,+ title: `${project.label} · ${project.hostLabel}`, remoteProject: project })),+ ],+ [projects, query, remoteCatalog.projects],);- const activeKey = normalizeProjectPath(activeProjectPath ?? path);+ const activeKey = isRemoteSession(activeSession) && activeSession?.remoteHostKey && activeSession.remoteProjectId+ ? `remote:${remoteProjectKey(activeSession.remoteHostKey, activeSession.remoteProjectId)}`+ : normalizeProjectPath(activeProjectPath ?? path);const cloneTarget = parseGitCloneUrl(cloneUrl, {allowInsecureHttp: allowInsecureUserEndpoints(settings),});@@ -110,6 +125,15 @@ export function HomeProjectSwitcher({[activeKey, busy, close, newSession, reportError],);+ const selectMenuProject = async (project: ProjectMenuEntry) => {+ if (project.localPath) return selectProject(project.localPath);+ if (busy || busyRef.current || !project.remoteProject?.connected) return;+ busyRef.current = true; setBusy(true);+ try { await newSession({ remoteProject: project.remoteProject }); close(); }+ catch (error) { reportError(error); }+ finally { busyRef.current = false; setBusy(false); }+ };+const startClone = useCallback(async () => {if (busy || busyRef.current || !cloneTarget) return;busyRef.current = true;@@ -188,7 +212,7 @@ export function HomeProjectSwitcher({const target = visible[highlight];if (!target) return;event.preventDefault();- void selectProject(target.path);+ void selectMenuProject(target);}};@@ -323,15 +347,15 @@ export function HomeProjectSwitcher({tabIndex={-1}aria-checked={current}data-switcher-index={index}- title={project.path}+ title={project.title}className={cx("home-project-switcher-item",current && "is-current",highlight === index && "is-active",)}- disabled={busy}+ disabled={busy || project.remoteProject?.connected === false}onMouseEnter={() => setHighlight(index)}- onClick={() => void selectProject(project.path)}+ onClick={() => void selectMenuProject(project)}><IconFolder size={14} aria-hidden /><span className="home-project-switcher-item-name">@@ -349,6 +373,8 @@ export function HomeProjectSwitcher({}))}</div>+ {remoteCatalog.busy && <p role="status">{t("remote:loading")}</p>}+ {remoteCatalog.error && <p role="alert">{remoteCatalog.error}</p>}<div className="home-project-switcher-divider" aria-hidden /><buttontype="button"diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex a629c5602..f97b6949f 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -1,3 +1,4 @@+import { useChatSessionCapability } from "../hooks/use-chat-session-capability";import {createContext,Fragment,@@ -519,7 +520,8 @@ function InlineCode({children,...rest}: ComponentProps<"code"> & { node?: unknown }) {- const root = useAppStore((s) => s.workspace?.path);+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");+ const root = useAppStore((s) => localToolsAllowed ? s.workspace?.path : undefined);const baseDir = useContext(MarkdownBaseDirContext);const openFileRef = useOpenChatFileRef();const openFileMenu = useContext(MarkdownFileMenuContext);@@ -530,7 +532,7 @@ function InlineCode({: null;const fileTitle = usePreviewTitle("file");const urlTitle = usePreviewTitle("url");- if (!target) {+ if (!target || !localToolsAllowed) {return (<code className={className} {...rest}>{children}@@ -543,6 +545,7 @@ function InlineCode({className="chat-code-link"title={target.kind === "file" ? fileTitle : urlTitle}onClick={() => {+ if (!localToolsAllowed) return;if (target.kind === "file") {openFileRef(text ?? target.path, baseDir);return;@@ -574,7 +577,8 @@ function Anchor({...rest}: ComponentProps<"a"> & { node?: unknown }) {const { t } = useTranslation();- const root = useAppStore((s) => s.workspace?.path);+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");+ const root = useAppStore((s) => localToolsAllowed ? s.workspace?.path : undefined);const baseDir = useContext(MarkdownBaseDirContext);const openFileRef = useOpenChatFileRef();const openFileMenu = useContext(MarkdownFileMenuContext);@@ -612,6 +616,7 @@ function Anchor({const onContextMenu = (event: React.MouseEvent<HTMLAnchorElement>) => {if (!href) return;if (!/^https?:\/\//i.test(href)) {+ if (!localToolsAllowed) return;/*A file link names the same reference a chip does, so it offers the sameaction on the file's folder. `./` and `../` resolve against the markdown@@ -633,7 +638,8 @@ function Anchor({defaultValue: "Open in default browser",}),icon: <IconExternal size={14} />,- onSelect: () => void api.browserOpenExternal(target),+ disabled: !localToolsAllowed,+ onSelect: () => { if (localToolsAllowed) void api.browserOpenExternal(target); },},{id: "open-workpanel",@@ -641,7 +647,8 @@ function Anchor({defaultValue: "Open in work panel",}),icon: <IconGlobe size={14} />,- onSelect: () => openUrl(target),+ disabled: !localToolsAllowed,+ onSelect: () => { if (localToolsAllowed) openUrl(target); },},{id: "copy-address",@@ -660,6 +667,7 @@ function Anchor({// to _blank, which main routes to shell.openExternal.const onClick = (e: React.MouseEvent<HTMLAnchorElement>) => {+ if (!localToolsAllowed) { e.preventDefault(); return; }if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;if (!href) return;if (/^https?:\/\//i.test(href)) {@@ -673,7 +681,7 @@ function Anchor({<><a{...rest}- href={href}+ href={localToolsAllowed ? href : undefined}onClick={onClick}onContextMenu={onContextMenu}target="_blank"@@ -698,7 +706,8 @@ function MarkdownImage({alt,...rest}: ComponentProps<"img"> & SourcePositionProps & { node?: unknown }) {- const root = useAppStore((s) => s.workspace?.path);+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");+ const root = useAppStore((s) => localToolsAllowed ? s.workspace?.path : undefined);const baseDir = useContext(MarkdownBaseDirContext);const openFileRef = useOpenChatFileRef();const openFileMenu = useContext(MarkdownFileMenuContext);@@ -722,7 +731,7 @@ function MarkdownImage({may want, so a local image carries the same menu its chip fallback does.*/const onLocalContextMenu =- localRef && openFileMenu+ localToolsAllowed && localRef && openFileMenu? (event: React.MouseEvent<HTMLElement>) =>openFileMenu(event, { path: localRef, baseDir }): undefined;@@ -734,7 +743,7 @@ function MarkdownImage({alt={alt ?? ""}className="chat-image-remote"title={urlTitle}- onClick={() => openHttpUrl(source)}+ onClick={localToolsAllowed ? () => openHttpUrl(source) : undefined}/>);}diff --git a/apps/desktop/src/components/ProjectCreateDialog.tsx b/apps/desktop/src/components/ProjectCreateDialog.tsxindex a649b78e4..9aba38d3e 100644--- a/apps/desktop/src/components/ProjectCreateDialog.tsx+++ b/apps/desktop/src/components/ProjectCreateDialog.tsx@@ -12,19 +12,18 @@ import {resolveProjectName,} from "../lib/project-name";import { useAppStore } from "../stores/app-store";-import { Button, TooltipButton } from "./ui";+import { Button, Input, TooltipButton } from "./ui";+import { ProjectFolderPicker } from "./ProjectFolderPicker";+import { RemoteProjectPicker, type RemoteProjectSelection } from "./remote/RemoteProjectPicker";import {IconBranch,IconClose,IconFolder,IconMonitor,- IconNewProject,- IconStar,- IconX,} from "./icons";-/** The Create project dialog creates from local folders or one git checkout. */-type ProjectSource = "local" | "git";+/** One project entry point for local folders, git checkouts and remote hosts. */+type ProjectSource = "local" | "git" | "remote";function pathParts(path: string) {return path.split(/[\\/]/).filter(Boolean);@@ -61,6 +60,8 @@ function ProjectCreateDialogContent() {);const showToast = useAppStore((state) => state.showToast);const [source, setSource] = useState<ProjectSource>("local");+ const newSession = useAppStore((state) => state.newSession);+ const [remoteProject, setRemoteProject] = useState<RemoteProjectSelection | null>(null);const [name, setName] = useState("");const [folders, setFolders] = useState<string[]>([]);const [gitUrl, setGitUrl] = useState("");@@ -78,7 +79,7 @@ function ProjectCreateDialogContent() {allowInsecureHttp: allowInsecureUserEndpoints(settings),});const defaultName = defaultProjectName({- source,+ source: source === "remote" ? "local" : source,folders,repositoryName: cloneTarget?.name,});@@ -108,7 +109,7 @@ function ProjectCreateDialogContent() {}if (event.key !== "Tab") return;const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(- 'input:not([disabled]), button:not([disabled])',+ 'input:not([disabled]), button:not([disabled]), select:not([disabled])',);if (!focusable?.length) return;const first = focusable[0];@@ -180,16 +181,24 @@ function ProjectCreateDialogContent() {const submit = async () => {const projectName = resolveProjectName(name, defaultName);- if (!projectName || busyRef.current) return;+ if (busyRef.current) return;+ if (source === "remote" ? !remoteProject : !projectName) return;if (source === "git") {if (!cloneTarget || !cloneParent) return;- } else if (folders.length === 0) {+ } else if (source === "local" && folders.length === 0) {return;}busyRef.current = true;setBusy(true);try {- if (source === "git" && cloneTarget) {+ if (source === "remote" && remoteProject) {+ if (!remoteProject.projectId && !remoteProject.path) return;+ const project = remoteProject.projectId+ ? { id: remoteProject.projectId, label: remoteProject.label ?? "" }+ : (await api.registerRemoteProject(remoteProject.hostKey, remoteProject.path ?? "")).project;+ await newSession({ remoteProject: { hostKey: remoteProject.hostKey, projectId: project.id, label: project.label } });+ close();+ } else if (source === "git" && cloneTarget) {await createProjectFromGit({name: projectName,url: cloneTarget.url,@@ -254,7 +263,7 @@ function ProjectCreateDialogContent() {}}><div className="project-create-dialog-content">- <section+ {source !== "remote" ? <sectionclassName="project-create-dialog-section project-create-dialog-identity"aria-labelledby="project-create-name-heading">@@ -270,7 +279,7 @@ function ProjectCreateDialogContent() {{name.length}/{MAX_PROJECT_NAME_CHARS}</span></div>- <input+ <Inputref={inputRef}id="project-create-name"className="field-input project-create-dialog-name-field"@@ -286,7 +295,7 @@ function ProjectCreateDialogContent() {autoCorrect="off"autoCapitalize="off"/>- </section>+ </section> : null}<sectionclassName="project-create-dialog-section project-create-dialog-source-section"@@ -305,7 +314,7 @@ function ProjectCreateDialogContent() {role="group"aria-label={t("project.createSourceLabel")}>- <button+ <Buttontype="button"className={`project-create-dialog-source-option${source === "local" ? " is-active" : ""@@ -317,8 +326,8 @@ function ProjectCreateDialogContent() {><IconMonitor size={15} aria-hidden />{t("project.createComputer")}- </button>- <button+ </Button>+ <Buttontype="button"className={`project-create-dialog-source-option${source === "git" ? " is-active" : ""@@ -330,81 +339,21 @@ function ProjectCreateDialogContent() {><IconBranch size={15} aria-hidden />{t("project.createSourceGit")}- </button>+ </Button>+ <Button type="button" className={`project-create-dialog-source-option${source === "remote" ? " is-active" : ""}`}+ data-project-source="remote" aria-pressed={source === "remote"} disabled={busy}+ onClick={() => setSource("remote")}>+ <IconMonitor size={15} aria-hidden />{t("remote:remote")}+ </Button></div></section>- {source === "local" ? (- <section- className="project-create-dialog-section project-create-dialog-folders"- aria-labelledby="project-create-folders-heading"- >- <div className="project-create-dialog-section-head">- <h3 id="project-create-folders-heading" className="project-create-dialog-section-title">- {t("project.createFoldersLabel")}- {folders.length > 0 ? (- <span className="project-create-dialog-count">{folders.length}</span>- ) : null}- </h3>- <span className="project-create-dialog-source" data-project-source="local">- <IconMonitor size={15} aria-hidden />- {t("project.createComputer")}- </span>- </div>-- {folders.length > 0 ? (- <div className="project-create-dialog-folder-list" role="list">- {folders.map((path, index) => (- <div- className={`project-create-folder-row${index === 0 ? " is-primary" : ""}`}- key={path}- role="listitem"- >- <span className="project-create-folder-icon" aria-hidden>- <IconFolder size={17} />- </span>- <span className="project-create-folder-copy" title={path}>- <span className="project-create-folder-name">{folderNameFromPath(path)}</span>- <span className="project-create-folder-path">{folderParent(path)}</span>- </span>- {index === 0 ? (- <span className="project-create-primary-tag">- <IconStar size={11} fill="currentColor" aria-hidden />- {t("project.createPrimary")}- </span>- ) : null}- <TooltipButton- type="button"- className="project-create-folder-remove"- tooltip={t("project.createRemoveFolder")}- ariaLabel={`${t("project.createRemoveFolder")}: ${folderNameFromPath(path)}`}- disabled={busy}- onClick={() => setFolders((current) => current.filter((item) => item !== path))}- >- <IconX size={15} />- </TooltipButton>- </div>- ))}- </div>- ) : null}-- <button- type="button"- aria-label={t("project.createAddFolder")}- className={`project-create-add-folder${folders.length === 0 ? " is-empty" : ""}`}- onClick={() => void addFolders()}- disabled={busy || folderPickerBusy}- >- <span className="project-create-add-folder-icon" aria-hidden>- <IconNewProject size={18} />- </span>- <span className="project-create-add-folder-copy">- <span className="project-create-add-folder-title">- {t("project.createAddFolder")}- </span>- </span>- </button>- </section>+ {source === "remote" ? (+ <RemoteProjectPicker busy={busy} onChange={setRemoteProject} />+ ) : source === "local" ? (+ <ProjectFolderPicker folders={folders} busy={busy} pickerBusy={folderPickerBusy}+ onAdd={() => void addFolders()}+ onRemove={(path) => setFolders((current) => current.filter((item) => item !== path))} />) : (<sectionclassName="project-create-dialog-section project-create-dialog-clone"@@ -420,7 +369,7 @@ function ProjectCreateDialogContent() {</span></div>- <input+ <Inputid="project-create-clone-url"className="field-input project-create-dialog-url-field"value={gitUrl}@@ -434,7 +383,7 @@ function ProjectCreateDialogContent() {onChange={(event) => setGitUrl(event.target.value)}/>- <button+ <Buttontype="button"className={`project-create-dialog-location${cloneParent ? " is-chosen" : ""@@ -458,7 +407,7 @@ function ProjectCreateDialogContent() {: t("project.createLocationHint")}</span></span>- </button>+ </Button><p className="project-create-dialog-clone-hint" role="status">{cloneTarget@@ -477,7 +426,7 @@ function ProjectCreateDialogContent() {type="submit"variant="primary"disabled={- source === "git"+ source === "remote" ? !remoteProject || busy : source === "git"? !projectName || !cloneTarget || !cloneParent || busy: !projectName || folders.length === 0 || busy}diff --git a/apps/desktop/src/components/ProjectFolderPicker.tsx b/apps/desktop/src/components/ProjectFolderPicker.tsxnew file mode 100644index 000000000..a539312a8--- /dev/null+++ b/apps/desktop/src/components/ProjectFolderPicker.tsx@@ -0,0 +1,88 @@+import { useTranslation } from "react-i18next";+import { folderNameFromPath } from "../lib/project-name";+import { Button, TooltipButton } from "./ui";+import { IconFolder, IconMonitor, IconNewProject, IconStar, IconX } from "./icons";++function folderParent(path: string) {+ const parts = path.split(/[\\/]/).filter(Boolean);+ return parts.length > 1 ? `…/${parts.slice(-2, -1)[0]}` : path;+}++export function ProjectFolderPicker({ folders, busy, pickerBusy, onAdd, onRemove }: {+ folders: string[]; busy: boolean; pickerBusy: boolean;+ onAdd: () => void; onRemove: (path: string) => void;+}) {+ const { t } = useTranslation();+ return (+ <section+ className="project-create-dialog-section project-create-dialog-folders"+ aria-labelledby="project-create-folders-heading"+ >+ <div className="project-create-dialog-section-head">+ <h3 id="project-create-folders-heading" className="project-create-dialog-section-title">+ {t("project.createFoldersLabel")}+ {folders.length > 0 ? (+ <span className="project-create-dialog-count">{folders.length}</span>+ ) : null}+ </h3>+ <span className="project-create-dialog-source" data-project-source="local">+ <IconMonitor size={15} aria-hidden />+ {t("project.createComputer")}+ </span>+ </div>++ {folders.length > 0 ? (+ <div className="project-create-dialog-folder-list" role="list">+ {folders.map((path, index) => (+ <div+ className={`project-create-folder-row${index === 0 ? " is-primary" : ""}`}+ key={path}+ role="listitem"+ >+ <span className="project-create-folder-icon" aria-hidden>+ <IconFolder size={17} />+ </span>+ <span className="project-create-folder-copy" title={path}>+ <span className="project-create-folder-name">{folderNameFromPath(path)}</span>+ <span className="project-create-folder-path">{folderParent(path)}</span>+ </span>+ {index === 0 ? (+ <span className="project-create-primary-tag">+ <IconStar size={11} fill="currentColor" aria-hidden />+ {t("project.createPrimary")}+ </span>+ ) : null}+ <TooltipButton+ type="button"+ className="project-create-folder-remove"+ tooltip={t("project.createRemoveFolder")}+ ariaLabel={`${t("project.createRemoveFolder")}: ${folderNameFromPath(path)}`}+ disabled={busy}+ onClick={() => onRemove(path)}+ >+ <IconX size={15} />+ </TooltipButton>+ </div>+ ))}+ </div>+ ) : null}++ <Button+ type="button"+ aria-label={t("project.createAddFolder")}+ className={`project-create-add-folder${folders.length === 0 ? " is-empty" : ""}`}+ onClick={() => onAdd()}+ disabled={busy || pickerBusy}+ >+ <span className="project-create-add-folder-icon" aria-hidden>+ <IconNewProject size={18} />+ </span>+ <span className="project-create-add-folder-copy">+ <span className="project-create-add-folder-title">+ {t("project.createAddFolder")}+ </span>+ </span>+ </Button>+ </section>+ );+}diff --git a/apps/desktop/src/components/ReviewChangeCard.tsx b/apps/desktop/src/components/ReviewChangeCard.tsxindex 34b5f15a0..b0745adce 100644--- a/apps/desktop/src/components/ReviewChangeCard.tsx+++ b/apps/desktop/src/components/ReviewChangeCard.tsx@@ -1,3 +1,4 @@+import { useChatSessionCapability } from "../hooks/use-chat-session-capability";import { memo, useId, useState } from "react";import { useTranslation } from "react-i18next";import type {@@ -20,13 +21,14 @@ const STATUS_MARKS: Record<ReviewChangeStatus, string> = {function DiffBody({ message, compact }: { message: UiMessage; compact: boolean }) {const { t } = useTranslation();const change = reviewChangeFromMessage(message);+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");const rollback = useAppStore((state) => state.rollbackWorkspaceChange);const [rollingBack, setRollingBack] = useState(false);if (!change) return null;const runRollback = async () => {- if (!change.reversible || change.state === "rolledBack" || rollingBack) return;+ if (!localToolsAllowed || !change.reversible || change.state === "rolledBack" || rollingBack) return;setRollingBack(true);// A conflict or an unavailable snapshot is already reported through the// store's toast; this card owns the rollback action only.@@ -68,7 +70,7 @@ function DiffBody({ message, compact }: { message: UiMessage; compact: boolean }<IconCheck size={13} />{t("panel.review.rolledBack")}</span>- ) : change.reversible ? (+ ) : change.reversible && localToolsAllowed ? (<buttontype="button"className="review-change-rollback"diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex 92ec13616..a142bbf97 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -1,4 +1,6 @@import { IconClock } from "./icons";+import { RemoteProjectGroups } from "./remote/RemoteProjectGroups";+import { groupRemoteProjectSessions } from "../lib/remote-project-catalog";import { isRemoteSession, sessionAllows } from "../lib/remote-session-safety";import {useCallback,@@ -967,14 +969,16 @@ export function Sidebar({session: { ...session, title: taskTitle(session.title) },target,temporary,- space: temporary ? t("nav.hoverCardTemporarySpace") : entry?.name ?? projectName(projectPath),+ space: isRemoteSession(session)+ ? `${session.remoteWorkspaceLabel ?? t("remote:workspace")} · ${session.remoteHostLabel ?? t("remote:remote")}`+ : temporary ? t("nav.hoverCardTemporarySpace") : entry?.name ?? projectName(projectPath),branch: entry?.branch,});}, [projectEntriesByPath, revealSessionHoverCard, t, taskTitle]);const temporarySessions = useMemo(() => filtered- .filter((session) => !normalizeProjectPath(session.projectPath))+ .filter((session) => !normalizeProjectPath(session.projectPath) && !(isRemoteSession(session) && session.remoteProjectId)).sort(compareSessions),[filtered, compareSessions],);@@ -982,6 +986,9 @@ export function Sidebar({() => temporarySessions.filter((session) => !pinnedSessionIds.has(session.id)),[temporarySessions, pinnedSessionIds],);+ const remoteProjectGroups = useMemo(() => groupRemoteProjectSessions(+ filtered.filter((session) => isRemoteSession(session) && !pinnedSessionIds.has(session.id)), compareSessions,+ ), [filtered, pinnedSessionIds, compareSessions]);// Flat ordered list of every visible session id — used for Shift+click range selection.const flatSessionOrder = useMemo(() => {const ids: string[] = [];@@ -993,10 +1000,11 @@ export function Sidebar({if (!pinnedSessionIds.has(s.id)) ids.push(s.id);}}+ for (const group of remoteProjectGroups) for (const session of group.sessions) ids.push(session.id);// Then temporary (standalone) sessionsfor (const s of temporarySessionHistory) ids.push(s.id);return ids;- }, [pinnedSessions, projectEntries, pinnedSessionIds, temporarySessionHistory]);+ }, [pinnedSessions, projectEntries, pinnedSessionIds, temporarySessionHistory, remoteProjectGroups]);/** Handle multi-select click on a session row. Returns true if the click was consumed by multi-select. */const handleMultiSelectClick = (event: React.MouseEvent, sessionId: string): boolean => {@@ -2516,6 +2524,8 @@ export function Sidebar({</div></section>)}+ <RemoteProjectGroups groups={remoteProjectGroups}+ renderSessions={(sessions) => renderSessionRows(sessions, { temporary: false })} /></div><div className="sidebar-footer no-drag">diff --git a/apps/desktop/src/components/remote/RemoteConversation.tsx b/apps/desktop/src/components/remote/RemoteConversation.tsxdeleted file mode 100644index 019a31843..000000000--- a/apps/desktop/src/components/remote/RemoteConversation.tsx+++ /dev/null@@ -1,123 +0,0 @@-import { useEffect, useRef, useState } from "react";-import { useTranslation } from "react-i18next";-import type { SessionSummary } from "@pi-desktop/shared";-import { useTranscriptView } from "../../hooks/use-transcript-view";-import { api } from "../../lib/api";-import { headPermission } from "../../lib/pending-permissions";-import { sessionAllows } from "../../lib/remote-session-safety";-import { useAppStore } from "../../stores/app-store";-import { Button, Textarea } from "../ui";-import { AskToolCard } from "../AskToolCard";-import { headAsk } from "../../lib/pending-asks";-import { captureComposerDraft, deleteComposerDraft, readComposerDraft, markComposerDraftEdited, readComposerDraftRevision } from "../../lib/composer-draft-cache";-import "../../styles/remote-mvp.css";--/** Text-only remote transcript deliberately has no local file/URL/plugin actions. */-export function RemoteConversation({ session }: { session: SessionSummary }) {- const { t } = useTranslation("remote");- const transcript = useTranscriptView(session.id);- const messages = transcript.messages;- const running = useAppStore((state) => state.runningSessions[session.id] ?? false);- const permission = useAppStore((state) => headPermission(state.pendingPermissions, session.id));- const ask = useAppStore((state) => headAsk(state.pendingAsks, session.id));- const [text, setText] = useState(() => readComposerDraft(session.id)?.text ?? "");- const [busy, setBusy] = useState(false);- const [error, setError] = useState<string | null>(null);- const live = useRef(true);- const locked = useRef(false);- const scroll = useRef<HTMLDivElement>(null);- const follow = useRef(true);- useEffect(() => { live.current = true; return () => { live.current = false; }; }, []);- useEffect(() => { if (follow.current && scroll.current) scroll.current.scrollTop = scroll.current.scrollHeight; }, [messages, permission]);- const current = () => live.current && useAppStore.getState().activeSessionId === session.id;- const run = async (action: () => Promise<void>) => {- if (locked.current || !current()) return;- locked.current = true;- setBusy(true); setError(null);- try { await action(); }- catch (caught) { if (current()) setError(caught instanceof Error ? caught.message : String(caught)); }- finally { locked.current = false; if (current()) setBusy(false); }- };- const refresh = async () => {- if (!sessionAllows(session, "canRefresh")) return;- await useAppStore.getState().selectSession(session.id, { record: false });- };- return (- <section className="chat-surface route-surface remote-conversation" aria-label={t("remote")}>- <div className="remote-actions">- <strong>{t("identity", { host: session.remoteHostLabel ?? session.remoteHostKey ?? t("remote"), workspace: session.remoteWorkspaceLabel ?? t("workspace") })}</strong>- <Button variant="ghost" disabled={busy || !sessionAllows(session, "canRefresh")} onClick={() => void run(refresh)}>{t("refresh")}</Button>- {session.remoteHostKey && <Button variant="ghost" disabled={busy} onClick={() => void run(async () => {- await api.reconnectRemoteHost(session.remoteHostKey!);- if (current()) await refresh();- })}>{t("reconnect")}</Button>}- <Button variant="ghost" onClick={() => {- const store = useAppStore.getState(); store.setSettingsTab("remoteHosts"); store.setPage("settings");- }}>{t("hostSettings")}</Button>- <Button variant="ghost" disabled={!sessionAllows(session, "canReadWorkspace")} onClick={() => {- if (current() && sessionAllows(session, "canReadWorkspace")) useAppStore.getState().openWorkPanel();- }}>{t("files")} / {t("review")}</Button>- </div>- <p className="remote-hint">{t("readOnly")}</p>- <div ref={scroll} className="remote-transcript" onScroll={() => {- const node = scroll.current;- if (node) follow.current = node.scrollHeight - node.scrollTop - node.clientHeight < 80;- }}>- {transcript.hasMoreBefore && <Button variant="ghost" disabled={busy || transcript.loading} onClick={() => void run(async () => {- await useAppStore.getState().loadTranscriptPage(session.id, "before");- })}>{t("older")}</Button>}- {messages.filter((message) => !message.modelSystem).map((message) => (- <article key={message.id} className={`remote-message remote-message-${message.role}`}>- <strong>{t(message.role)}{message.toolName ? ` · ${message.toolName}` : ""}</strong>- <pre>{message.content || message.error?.message || (message.toolResult === undefined ? "" : JSON.stringify(message.toolResult, null, 2))}</pre>- {message.thinking && <details><summary>{t("thinking")}</summary><pre>{message.thinking}</pre></details>}- </article>- ))}- {transcript.hasMoreAfter && <Button variant="ghost" disabled={busy || transcript.loading} onClick={() => void run(async () => {- await useAppStore.getState().loadTranscriptPage(session.id, "after");- })}>{t("newer")}</Button>}- {transcript.historical && <Button variant="ghost" disabled={busy} onClick={() => void run(async () => {- await useAppStore.getState().returnToLatestTranscript(session.id);- })}>{t("latest")}</Button>}- {permission && <section className="permission-card" aria-label={t("approval")}>- <strong>{t("approval")} · {permission.toolName}</strong>- <p>{permission.reason}</p>- <pre>{typeof permission.argsPreview === "string" ? permission.argsPreview : JSON.stringify(permission.argsPreview, null, 2)}</pre>- <div className="remote-actions">- {(["deny", "allow-once"] as const).map((decision) => <Button key={decision} disabled={busy} onClick={() => void run(async () => {- await useAppStore.getState().resolvePermission(session.id, permission.requestId, decision);- })}>{t(decision === "deny" ? "deny" : "allow")}</Button>)}- </div>- </section>}- {ask && <AskToolCard key={ask.requestId} request={ask} />}- </div>- {error && <p className="remote-hint" role="alert">{error}</p>}- {busy && <p className="remote-hint" role="status">{t("loading")}</p>}- {running && <p className="remote-hint" role="status">{t("pending")}</p>}- <form className="remote-composer" onSubmit={(event) => {- event.preventDefault();- if (!text.trim() || running || !sessionAllows(session, "canPrompt")) return;- void run(async () => {- const draftRevision = readComposerDraftRevision(session.id);- const accepted = await useAppStore.getState().sendPrompt(text, undefined, session.id);- if (accepted && readComposerDraftRevision(session.id) === draftRevision) deleteComposerDraft(session.id);- if (!current()) return;- if (accepted) setText(""); else setError(t("sendFailed"));- });- }}>- <Textarea className="composer-input" aria-label={t("prompt")} placeholder={t("prompt")} rows={3}- value={text} disabled={busy || !sessionAllows(session, "canPrompt")} onChange={(event) => {- setText(event.target.value);- markComposerDraftEdited(session.id);- captureComposerDraft(session.id, event.target.value, []);- }} />- <div className="remote-actions">- <Button type="submit" disabled={busy || running || !text.trim() || !sessionAllows(session, "canPrompt")}>{t("send")}</Button>- <Button variant="secondary" disabled={busy || !running || !sessionAllows(session, "canStop")} onClick={() => void run(async () => {- if (current() && sessionAllows(session, "canStop")) await useAppStore.getState().abort();- })}>{t("stop")}</Button>- </div>- </form>- </section>- );-}diff --git a/apps/desktop/src/components/remote/RemoteProjectGroups.tsx b/apps/desktop/src/components/remote/RemoteProjectGroups.tsxnew file mode 100644index 000000000..204ce4604--- /dev/null+++ b/apps/desktop/src/components/remote/RemoteProjectGroups.tsx@@ -0,0 +1,33 @@+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 { useAppStore } from "../../stores/app-store";+import { 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;+}) {+ const { t } = useTranslation();+ const [busy, setBusy] = useState<string | null>(null);+ 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); }+ };+ return <>{groups.map(({ project, sessions }) => <section className="sidebar-session-group" key={project.key}>+ <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>+ </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>)}</>;+}diff --git a/apps/desktop/src/components/remote/RemoteProjectPicker.tsx b/apps/desktop/src/components/remote/RemoteProjectPicker.tsxnew file mode 100644index 000000000..3ac95445f--- /dev/null+++ b/apps/desktop/src/components/remote/RemoteProjectPicker.tsx@@ -0,0 +1,122 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type { RacpProjectSummary, RemoteHostBrowseProjectsResult, RemoteHostSummary } from "@pi-desktop/shared";+import { api } from "../../lib/api";+import { Button, Field, Input, Select } from "../ui";++export type RemoteProjectSelection = {+ hostKey: string;+ hostLabel: string;+ projectId?: string;+ label?: string;+ path?: string;+};++export function RemoteProjectPicker({ busy, onChange }: {+ busy: boolean;+ onChange: (selection: RemoteProjectSelection | null) => void;+}) {+ const { t } = useTranslation();+ const [hosts, setHosts] = useState<RemoteHostSummary[]>([]);+ const [hostKey, setHostKey] = useState("");+ const [projects, setProjects] = useState<RacpProjectSummary[]>([]);+ const [projectId, setProjectId] = useState("");+ const [path, setPath] = useState("");+ const [directory, setDirectory] = useState<RemoteHostBrowseProjectsResult | null>(null);+ const [loading, setLoading] = useState(true);+ const [browsing, setBrowsing] = useState(false);+ const [error, setError] = useState("");+ const generation = useRef(0);+ const browseGeneration = useRef(0);+ const selectionCallback = useRef(onChange);+ selectionCallback.current = onChange;++ useEffect(() => {+ let active = true;+ void api.listRemoteHosts().then(({ hosts }) => {+ if (!active) return;+ const connected = hosts.filter((host) => host.connected);+ setHosts(connected);+ setHostKey(connected[0]?.hostKey ?? "");+ }).catch((error: unknown) => {+ if (active) setError(error instanceof Error ? error.message : String(error));+ }).finally(() => { if (active) setLoading(false); });+ return () => { active = false; generation.current++; browseGeneration.current++; };+ }, []);++ useEffect(() => {+ const request = ++generation.current;+ ++browseGeneration.current;+ setProjects([]); setProjectId(""); setPath(""); setDirectory(null); setError("");+ selectionCallback.current(null);+ if (!hostKey) return;+ setLoading(true);+ void api.remoteHostProjects(hostKey).then(({ projects }) => {+ if (request === generation.current) setProjects(projects.filter((project) => !project.archived));+ }).catch((error: unknown) => {+ if (request === generation.current) setError(error instanceof Error ? error.message : String(error));+ }).finally(() => { if (request === generation.current) setLoading(false); });+ void browse(undefined);+ return () => { generation.current++; browseGeneration.current++; };+ }, [hostKey]);++ useEffect(() => {+ const host = hosts.find((host) => host.hostKey === hostKey);+ const project = projects.find((project) => project.id === projectId);+ selectionCallback.current(host && (project || path.startsWith("/")) ? {+ hostKey, hostLabel: host.label,+ ...(project ? { projectId: project.id, label: project.label } : { path }),+ } : null);+ }, [hosts, hostKey, projects, projectId, path]);++ async function browse(nextPath?: string) {+ const request = ++browseGeneration.current;+ setBrowsing(true); setError("");+ try {+ const result = await api.remoteHostBrowseProjects(hostKey, nextPath);+ if (request === browseGeneration.current) setDirectory(result);+ } catch (error) {+ if (request === browseGeneration.current) setError(error instanceof Error ? error.message : String(error));+ } finally {+ if (request === browseGeneration.current) setBrowsing(false);+ }+ }++ return <section className="project-create-dialog-section remote-project-picker" aria-busy={loading || browsing}>+ <Field label={t("remote:projectHost")}>+ <Select value={hostKey} disabled={busy || loading} onChange={(event) => { generation.current++; browseGeneration.current++; selectionCallback.current(null); setHostKey(event.target.value); }}>+ {!hosts.length ? <option value="">{t("remote:noConnectedHosts")}</option> : null}+ {hosts.map((host) => <option key={host.hostKey} value={host.hostKey}>{host.label}</option>)}+ </Select>+ </Field>+ {hosts.length > 0 ? <>+ <Field label={t("remote:project")}>+ <Select value={projectId} disabled={busy || loading} onChange={(event) => { setProjectId(event.target.value); setPath(""); }}>+ <option value="">{t("remote:chooseFolder")}</option>+ {projects.map((project) => <option key={project.id} value={project.id}>{project.label}</option>)}+ </Select>+ </Field>+ <Field label={t("remote:projectFolder")}>+ <Input value={path} placeholder={t("remote:pathPlaceholder")} disabled={busy} onChange={(event) => { setPath(event.target.value); setProjectId(""); }} />+ </Field>+ {path && !path.startsWith("/") ? <p role="alert">{t("remote:REMOTE_ABSOLUTE_PATH_REQUIRED")}</p> : null}+ <div className="remote-project-browser" aria-label={t("remote:browseFolders")}>+ <div className="remote-project-browser-actions">+ <Button type="button" disabled={busy || browsing} onClick={() => void browse(path.startsWith("/") ? path : undefined)}>{t("remote:browseFolders")}</Button>+ {directory?.parent ? <Button type="button" variant="ghost" disabled={busy || browsing} onClick={() => void browse(directory.parent)}>{t("remote:parent")}</Button> : null}+ </div>+ {directory ? <>+ <div className="remote-project-browser-path">{directory.path}</div>+ <Button type="button" disabled={busy || browsing} onClick={() => { setPath(directory.path); setProjectId(""); }}>{t("remote:useFolder")}</Button>+ <div className="remote-project-browser-entries">+ {directory.entries.map((entry) => <Button key={entry.path} type="button" variant="ghost" disabled={busy || browsing} onClick={() => void browse(entry.path)}>{entry.name}</Button>)}+ </div>+ {!directory.entries.length ? <p>{t("remote:emptyFiles")}</p> : null}+ </> : null}+ </div>+ <p className="project-create-dialog-clone-hint">{t("remote:projectNameHint")}</p>+ </> : null}+ {loading || browsing ? <p role="status">{t("remote:loading")}</p> : null}+ {error ? <p className="remote-project-error" role="alert">{error}</p> : null}+ </section>;+}diff --git a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsxindex 7a891007a..dea7eee18 100644--- a/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx+++ b/apps/desktop/src/features/chat/composer/ComposerToolbar.tsx@@ -43,6 +43,9 @@ export type ComposerToolbarProps = {permissionOpen: boolean;setPermissionOpen: Dispatch<SetStateAction<boolean>>;controlsBlocked: boolean;+ localToolsAllowed?: boolean;+ attachmentsAllowed?: boolean;+ stopAllowed?: boolean;pasting: boolean;pickAndAttach: () => Promise<void>;configureActiveSession: AppState["configureActiveSession"];@@ -79,6 +82,9 @@ export function ComposerToolbar({permissionOpen,setPermissionOpen,controlsBlocked,+ localToolsAllowed = true,+ attachmentsAllowed = true,+ stopAllowed = true,pasting,pickAndAttach,configureActiveSession,@@ -113,7 +119,7 @@ export function ComposerToolbar({className="icon-btn icon-btn-square"tooltip={t("chat.addFiles")}ariaLabel={t("chat.addFiles")}- disabled={controlsBlocked || pasting}+ disabled={controlsBlocked || pasting || !attachmentsAllowed}onClick={() => {setPermissionOpen(false);void pickAndAttach();@@ -122,7 +128,7 @@ export function ComposerToolbar({<IconPlus size={15} aria-hidden="true" /></TooltipButton></div>- <LiveVoiceControls t={t} workSessionId={workSessionId} />+ {localToolsAllowed ? <LiveVoiceControls t={t} workSessionId={workSessionId} /> : null}<TooltipButtontype="button"className="icon-btn mode-chip composer-mode-chip"@@ -175,11 +181,11 @@ export function ComposerToolbar({});}}} />- <ComposerControlSlots side="left" />+ {localToolsAllowed ? <ComposerControlSlots side="left" /> : null}</div><div className="composer-right">- <ComposerControlSlots side="right" />+ {localToolsAllowed ? <ComposerControlSlots side="right" /> : null}{contextUsage ? <ContextUsageInspector {...contextUsage} /> : null}<ComposerModelPickert={t}@@ -235,6 +241,7 @@ export function ComposerToolbar({className="stop-btn"tooltip={t("chat.stopGenerating")}ariaLabel={t("chat.stopGenerating")}+ disabled={!stopAllowed}onClick={() => void abort()}><IconStop size={14} />diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.tsindex 7e3229230..5feede94d 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerAttachments.ts@@ -36,6 +36,7 @@ import type { ComposerDraftController } from "./useComposerDraft";type UseComposerAttachmentsOptions = {inputBlocked: boolean;+ attachmentsAllowed?: boolean;activeSessionId: string | null | undefined;draftKey: string;largePasteThreshold: number;@@ -75,6 +76,7 @@ export type ComposerAttachmentsController = {*/export function useComposerAttachments({inputBlocked,+ attachmentsAllowed = true,activeSessionId,draftKey,largePasteThreshold,@@ -85,7 +87,7 @@ export function useComposerAttachments({const pickerInFlight = useRef(false);const [dropTargetActive, setDropTargetActive] = useState(false);const [droppedDirectories, setDroppedDirectories] = useState<ComposerDropItem[]>([]);- const isInputBlocked = inputBlocked || pasting;+ const isInputBlocked = inputBlocked || pasting || !attachmentsAllowed;const snapshotReferences = (sourceSessionId: string) =>draft.snapshotReferences(sourceSessionId);@@ -210,6 +212,18 @@ export function useComposerAttachments({};const pasteClipboardFiles = async (event: ClipboardEvent<HTMLDivElement>) => {+ if (!attachmentsAllowed) {+ event.preventDefault();+ if (inputBlocked) return;+ const text = event.clipboardData.getData("text/plain");+ if (!text) return;+ if (!insertClipboardText(event.currentTarget, text)) {+ const current = draft.ref.current ? readEditorValue(draft.ref.current) : draft.valueRef.current;+ const { start, end } = editorSelectionRange(event.currentTarget);+ draft.applyEditorDraft(current.slice(0, start) + text + current.slice(end), [], start + text.length);+ }+ return;+ }if (isInputBlocked) return;const text = event.clipboardData.getData("text/plain");const pastedFiles = clipboardFiles(event.clipboardData);diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.tsindex 09ed91f5b..ae5eb3e8a 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts@@ -13,6 +13,7 @@ import {rewriteIdeographicCommaTrigger,} from "@pi-desktop/shared";import { useAppStore } from "../../../../stores/app-store";+import { sessionAllows } from "../../../../lib/remote-session-safety";import { api } from "../../../../lib/api";import type { ComposerDraftSnapshot } from "../../../../lib/composer-smart-stop";import {@@ -583,6 +584,8 @@ export function useComposerDraft({if (!readEditorValue(editor).includes(token)) return;const sourceSessionId = reference.sessionId;try {+ const state = useAppStore.getState();+ if (!sessionAllows(state.sessions.find((item) => item.id === sourceSessionId), "canAttach")) return;const result = await api.fsRead(reference.path, reference.mimeType);if (result.kind !== "text" || result.content === undefined) {const message =diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.tsindex 49ad9abbb..d7a33072b 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts@@ -1,4 +1,5 @@import { useCallback, useEffect, useMemo, useState, type RefObject } from "react";+import { sessionAllows } from "../../../../lib/remote-session-safety";import { api } from "../../../../lib/api";import { useAppStore } from "../../../../stores/app-store";import { isImageReference } from "../image-attachments";@@ -29,10 +30,12 @@ export function useComposerImagePreview({}) {const currentSessionId = useAppStore((s) => s.activeSessionId ?? "");const workspaceRoot = useAppStore((s) => s.workspace?.path ?? null);+ const attachmentsAllowed = useAppStore((s) => sessionAllows(s.sessions.find((item) => item.id === sessionId) ?? (sessionId.startsWith("remote:") ? { id: sessionId } : undefined), "canAttach"));const images = useMemo(() => references.filter((reference) =>+ attachmentsAllowed &&reference.sessionId === sessionId &&isImageReference(reference),- ), [references, sessionId]);+ ), [references, sessionId, attachmentsAllowed]);const [request, setRequest] = useState<PreviewRequest | null>(null);const [generation, setGeneration] = useState(0);const [loaded, setLoaded] = useState<{diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.tsindex 084e21623..0d5de2050 100644--- a/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerSubmit.ts@@ -21,6 +21,8 @@ type UseComposerSubmitOptions = {activeSessionId: string | null | undefined;modelReady: boolean;sendBlocked: boolean;+ localCommandsAllowed?: boolean;+ steeringAllowed?: boolean;invalidateComposerTransforms: () => void;pasting: boolean;activeFileReferences: ComposerFileReference[];@@ -53,6 +55,8 @@ export function useComposerSubmit({activeSessionId,modelReady,sendBlocked,+ localCommandsAllowed = true,+ steeringAllowed = true,invalidateComposerTransforms,pasting,activeFileReferences,@@ -71,7 +75,7 @@ export function useComposerSubmit({const inlineContent = serializeInlineComposerFileReferences(rawText, activeFileReferences);const serializedContent = serializeComposerFileReferences(rawText, activeFileReferences);if (!serializedContent) return;- if (sendBlocked) {+ if (sendBlocked || (steering && !steeringAllowed)) {if (pasting) showToast(t("chat.pasteInProgress"), { variant: "info" });return;}@@ -96,7 +100,7 @@ export function useComposerSubmit({// command source that cannot be read is a third case: the composer cannot// prove `/compact` is not a builtin, so it refuses the submission and keeps// the text out of the model's input (issue #795).- if (!steering) {+ if (!steering && localCommandsAllowed) {const slashSubmission = parseSlashSubmission(serializedContent);const resolution = slashSubmission? await resolveComposerCommand(slashSubmission.name)diff --git a/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts b/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.tsindex 1e95169ff..6da1369e9 100644--- a/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts+++ b/apps/desktop/src/features/chat/composer/hooks/usePluginComposerBridge.ts@@ -18,6 +18,7 @@ type BridgeSource = {fileReferences: ComposerFileReference[];fileReferencesRef: { current: ComposerFileReference[] };inputBlocked: boolean;+ enabled?: boolean;applyEditorDraft: (text: string,references: ComposerFileReference[],@@ -32,6 +33,7 @@ export function usePluginComposerBridge(source: BridgeSource): void {const handleRef = useRef<ComposerDraftHandle | null>(null);useEffect(() => {+ if (source.enabled === false) return;const text = () => {const { ref, valueRef } = latest.current;return ref.current ? readEditorValue(ref.current) : valueRef.current;@@ -39,7 +41,7 @@ export function usePluginComposerBridge(source: BridgeSource): void {const handle: ComposerDraftHandle = {read() {const { inputBlocked, draftKey, referenceSessionId, fileReferencesRef } = latest.current;- if (inputBlocked) return null;+ if (inputBlocked || latest.current.enabled === false) return null;return {draftKey,sessionId: referenceSessionId,@@ -58,9 +60,13 @@ export function usePluginComposerBridge(source: BridgeSource): void {return { start: end, end };},write(nextText, references, caret, focus) {+ if (latest.current.enabled === false || latest.current.inputBlocked) return;latest.current.applyEditorDraft(nextText, references, caret, focus);},async stage(sessionId, file) {+ if (latest.current.enabled === false || latest.current.inputBlocked || sessionId !== latest.current.referenceSessionId) {+ throw new Error("Composer attachment access unavailable");+ }const result = await api.pasteFiles(sessionId, [file]);const staged = result.files[0];if (!staged) throw new Error("the host staged no file");@@ -73,7 +79,7 @@ export function usePluginComposerBridge(source: BridgeSource): void {handleRef.current = null;unregister();};- }, []);+ }, [source.enabled]);const { value, fileReferences, draftKey, referenceSessionId, inputBlocked } = source;useEffect(() => {diff --git a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsxindex 779dc781c..36ab919a9 100644--- a/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx+++ b/apps/desktop/src/features/chat/transcript/AssistantTurn.tsx@@ -23,6 +23,8 @@ import {resolveThinkingDisplayMode,shouldGroupTurnProcess,} from "../../../lib/turn-process";+import { sessionAllows } from "../../../lib/remote-session-safety";+import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";import { useAppStore } from "../../../stores/app-store";import { IconBranch, IconReview } from "../../../components/icons";import { TooltipButton } from "../../../components/ui";@@ -233,6 +235,9 @@ export const AssistantTurn = memo(function AssistantTurn({const { copyText, selectText } = useChatTextActions();const retryAssistantMessage = useAppStore((s) => s.retryAssistantMessage);const forkAssistantMessage = useAppStore((s) => s.forkAssistantMessage);+ const paneSessionId = useSlotSessionId();+ const session = useAppStore((s) => s.sessions.find((item) => item.id === paneSessionId));+ const canEditMessages = sessionAllows(session ?? (paneSessionId.startsWith("remote:") ? { id: paneSessionId } : undefined), "canEditMessages");const summary = getAssistantTurnSummary(entry);const { actionMessage, metaMessage, latestUsageMessage, usage, responseDurationMs, responseOutputTokens } = summary;const modelId = metaMessage?.modelId ?? latestUsageMessage?.modelId;@@ -264,7 +269,7 @@ export const AssistantTurn = memo(function AssistantTurn({".message-bubble",),].at(-1) ?? null,- complete: complete && Boolean(actionMessage),+ complete: complete && Boolean(actionMessage) && canEditMessages,actions: { copyText, selectText },onRegenerate: () => {if (actionMessage) void retryAssistantMessage(actionMessage.id);@@ -352,22 +357,22 @@ export const AssistantTurn = memo(function AssistantTurn({<MessageTimestamp createdAt={actionMessage.createdAt} /><ActionSlotSide slot="assistantAction" side="left" message={slotReply} /><CopyButton text={content} label={t("chat.copy")} />- <TooltipButton+ {canEditMessages ? <TooltipButtonclassName="copy-btn icon"tooltip={t("chat.forkResponse")}ariaLabel={t("chat.forkResponse")}onClick={() => void forkAssistantMessage(actionMessage.id)}><IconBranch size={13} />- </TooltipButton>- <TooltipButton+ </TooltipButton> : null}+ {canEditMessages ? <TooltipButtonclassName="copy-btn icon"tooltip={t("chat.retry")}ariaLabel={t("chat.retry")}onClick={() => void retryAssistantMessage(actionMessage.id)}><IconReview size={13} />- </TooltipButton>+ </TooltipButton> : null}<ActionSlotSide slot="assistantAction" side="right" message={slotReply} /></div>) : null}diff --git a/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsx b/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsxindex 4a96a4021..1c33af163 100644--- a/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsx+++ b/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsx@@ -1,3 +1,4 @@+import { useChatSessionCapability } from "../../../hooks/use-chat-session-capability";import { useLayoutEffect, useRef, useState, type RefObject } from "react";import { useTranslation } from "react-i18next";import { IconChevronLeft, IconChevronRight, IconClose, IconDownload, IconExternal, IconFolder, IconMinus, IconPlus } from "../../../components/icons";@@ -19,6 +20,7 @@ export function GeneratedImageViewer({ images, selectedIndex, onSelect, onClose,focusReturnRef: RefObject<HTMLElement | null>;}) {const { t } = useTranslation();+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");const dialogRef = useRef<HTMLDialogElement>(null);const viewportRef = useRef<HTMLDivElement>(null);const knownNaturalSizesRef = useRef(new Map<string, { width: number; height: number }>());@@ -103,7 +105,7 @@ export function GeneratedImageViewer({ images, selectedIndex, onSelect, onClose,if (src) setManualZoom({ src, value: Math.min(4, Math.max(Math.min(0.1, fit), value)) });};const reveal = async () => {- if (!selected) return;+ if (!localToolsAllowed || !selected) return;try {await api.fsReveal(selected.path);} catch {diff --git a/apps/desktop/src/features/chat/transcript/MessageRow.tsx b/apps/desktop/src/features/chat/transcript/MessageRow.tsxindex a25d04804..ca9d24c63 100644--- a/apps/desktop/src/features/chat/transcript/MessageRow.tsx+++ b/apps/desktop/src/features/chat/transcript/MessageRow.tsx@@ -11,6 +11,8 @@ import { useTranslation } from "react-i18next";import type { UiMessage } from "@pi-desktop/shared";import { splitInlineContent } from "@pi-desktop/shared";import { useOpenChatFileRef } from "../../../hooks/use-preview-target";+import { sessionAllows } from "../../../lib/remote-session-safety";+import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";import { useAppStore } from "../../../stores/app-store";import { Markdown } from "../../../components/Markdown";import {@@ -82,10 +84,14 @@ export const MessageRow = memo(function MessageRow({const editUserMessage = useAppStore((s) => s.editUserMessage);const activateMessageRevision = useAppStore((s) => s.activateMessageRevision);const deleteMessage = useAppStore((s) => s.deleteMessage);+ const paneSessionId = useSlotSessionId();+ const session = useAppStore((s) => s.sessions.find((item) => item.id === paneSessionId));+ const canEditMessages = sessionAllows(session ?? (paneSessionId.startsWith("remote:") ? { id: paneSessionId } : undefined), "canEditMessages");const isUser = message.role === "user";const isSessionMessage = Boolean(message.sessionMessage);- const editableUserMessage = isUser && !isSessionMessage;- const workspaceRoot = useAppStore((s) => s.workspace?.path);+ const editableUserMessage = isUser && !isSessionMessage && canEditMessages;+ const localWorkspaceRoot = useAppStore((s) => s.workspace?.path);+ const workspaceRoot = sessionAllows(session, "canUseLocalTools") ? localWorkspaceRoot : undefined;const openFileRef = useOpenChatFileRef();// userAction belongs to user cards; other rows keep a plugin-free bar.const slotUser = isUser ? slotMessage("user", message) : undefined;diff --git a/apps/desktop/src/features/chat/transcript/PlanHistoryCard.tsx b/apps/desktop/src/features/chat/transcript/PlanHistoryCard.tsxindex a2946f86c..2b2260001 100644--- a/apps/desktop/src/features/chat/transcript/PlanHistoryCard.tsx+++ b/apps/desktop/src/features/chat/transcript/PlanHistoryCard.tsx@@ -1,3 +1,4 @@+import { useChatSessionCapability } from "../../../hooks/use-chat-session-capability";import { useId } from "react";import { useTranslation } from "react-i18next";import type { PlanProposal, UiMessage } from "@pi-desktop/shared";@@ -15,6 +16,7 @@ export function PlanHistoryCard({ message, proposal, onUserInteraction }: {message: UiMessage; proposal: PlanProposal; onUserInteraction?: () => void;}) {const { t } = useTranslation();+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");const bodyId = useId();const reveal = useMessageRevealRequest(message.id);const disclosure = useAutomaticDisclosure(false, reveal, disclosureKey("tool", message.id));@@ -37,9 +39,9 @@ export function PlanHistoryCard({ message, proposal, onUserInteraction }: {</Badge>{message.planHistory?.superseded && <Badge>{t("planHistory.superseded")}</Badge>}</div>- {path && <Button variant="ghost" className="plan-history-artifact"+ {path && <Button variant="ghost" className="plan-history-artifact" disabled={!localToolsAllowed}aria-label={t(`${kind}.openArtifactLabel`, { path })}- onClick={() => { onUserInteraction?.(); openTab(sessionId, preferredFileWorkPanelTab(path, views)); }}>+ onClick={() => { if (!localToolsAllowed) return; onUserInteraction?.(); openTab(sessionId, preferredFileWorkPanelTab(path, views)); }}>{path}</Button>}{disclosure.open && <div id={bodyId} className="plan-history-body">diff --git a/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx b/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsxindex 8d64022cc..6a660a6bc 100644--- a/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx+++ b/apps/desktop/src/features/chat/transcript/SubagentStopButton.tsx@@ -1,3 +1,5 @@+import { useChatSessionCapability } from "../../../hooks/use-chat-session-capability";+import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";import { useEffect } from "react";import { create } from "zustand";import { useTranslation } from "react-i18next";@@ -24,7 +26,9 @@ export function SubagentStopButton({compact?: boolean;}) {const { t } = useTranslation();- const sessionId = useAppStore(state => state.activeSessionId);+ const paneSessionId = useSlotSessionId();+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");+ const sessionId = useAppStore(state => paneSessionId || state.activeSessionId);const source = useAppStore(state => state.sessions.find(session => session.id === state.activeSessionId)?.source);const busy = useStops(state => sessionId ? state.busy[sessionId] : undefined);const pending = useStops(state => sessionId ? state.pending[sessionId] : undefined);@@ -37,7 +41,7 @@ export function SubagentStopButton({[sessionId]: (state.pending[sessionId] ?? []).filter(id => id !== delegationId),} }));}, [running, sessionId, delegationId, stopping]);- if (!running || !sessionId || source === "remote" || source === "pi-native") return null;+ if (!running || !localToolsAllowed || !sessionId || source === "remote" || source === "pi-native") return null;const stop = async () => {if (useStops.getState().busy[sessionId]) return;diff --git a/apps/desktop/src/features/chat/transcript/ToolRow.tsx b/apps/desktop/src/features/chat/transcript/ToolRow.tsxindex 7e04de80a..6f8f09eab 100644--- a/apps/desktop/src/features/chat/transcript/ToolRow.tsx+++ b/apps/desktop/src/features/chat/transcript/ToolRow.tsx@@ -1,3 +1,4 @@+import { useChatSessionCapability } from "../../../hooks/use-chat-session-capability";import { SubagentStopButton } from "./SubagentStopButton";import { PlanHistoryCard } from "./PlanHistoryCard";import { planSubmission } from "../../../lib/plan-history";@@ -179,7 +180,8 @@ function HostToolRow({}: ToolRowProps) {const { t } = useTranslation();const detailsId = useId();- const root = useAppStore((s) => s.workspace?.path);+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");+ const root = useAppStore((s) => localToolsAllowed ? s.workspace?.path : undefined);const openTarget = useOpenPreviewTarget();const { fileMenu, openFileMenu, closeFileMenu } = useChatFileMenu();const openSubagentTab = useAppStore((s) => s.openSubagentTab);@@ -405,7 +407,7 @@ function HostToolRow({onClick={() => {if (!hasDetails) return;onUserInteraction?.();- openSubagentTab(panelSelectionId, agentName || undefined);+ localToolsAllowed && openSubagentTab(panelSelectionId, agentName || undefined);}}><span className="subagent-topology-avatar" aria-hidden>@@ -498,16 +500,16 @@ function HostToolRow({) : null}{summary ? (<span- className={`tool-row-summary${previewTarget ? " linked" : ""}`}+ className={`tool-row-summary${previewTarget && localToolsAllowed ? " linked" : ""}`}title={- previewTarget+ previewTarget && localToolsAllowed? previewTarget.kind === "file"? t("chat.previewFile"): t("chat.previewUrl"): undefined}onClick={- previewTarget+ previewTarget && localToolsAllowed? (e) => {// Open the preview target instead of toggling details.e.stopPropagation();@@ -516,7 +518,7 @@ function HostToolRow({: undefined}onContextMenu={- previewTarget?.kind === "file"+ localToolsAllowed && previewTarget?.kind === "file"? (event) =>openFileMenu(event, { path: previewTarget.path }): undefineddiff --git a/apps/desktop/src/hooks/use-chat-session-capability.ts b/apps/desktop/src/hooks/use-chat-session-capability.tsnew file mode 100644index 000000000..bd71088b4--- /dev/null+++ b/apps/desktop/src/hooks/use-chat-session-capability.ts@@ -0,0 +1,17 @@+import type { SessionCapabilities } from "@pi-desktop/shared";+import { sessionAllows } from "../lib/remote-session-safety";+import { useSlotSessionId } from "../plugins/renderer-slots/use-slots";+import { useAppStore } from "../stores/app-store";++/** Retained transcripts authorize against their own session, never the visible workspace. */+export function useChatSessionCapability(capability: keyof SessionCapabilities): boolean {+ const paneSessionId = useSlotSessionId();+ return useAppStore((state) => {+ const id = paneSessionId || state.activeSessionId;+ return sessionAllows(+ state.sessions.find((session) => session.id === id) ??+ (id?.startsWith("remote:") ? { id } : undefined),+ capability,+ );+ });+}diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.tsindex 486e2f479..44cf92c1a 100644--- a/apps/desktop/src/hooks/use-preview-target.ts+++ b/apps/desktop/src/hooks/use-preview-target.ts@@ -1,3 +1,6 @@+import { useChatSessionCapability } from "./use-chat-session-capability";+import { sessionAllows } from "../lib/remote-session-safety";+import { useSlotSessionId } from "../plugins/renderer-slots/use-slots";import { useCallback } from "react";import { useTranslation } from "react-i18next";import { isActiveInProject } from "@pi-desktop/shared";@@ -25,9 +28,11 @@ import {* open destination setting.*/export function useOpenPreviewTarget() {+ const localToolsAllowed = useChatSessionCapability("canUseLocalTools");const openFileRef = useOpenChatFileRef();return useCallback((target: ChatPreviewTarget) => {+ if (!localToolsAllowed) return;if (target.kind === "file") {return openFileRef(target.path, undefined, undefined, {line: target.line,@@ -40,7 +45,7 @@ export function useOpenPreviewTarget() {}openHttpUrl(target.url);},- [openFileRef],+ [localToolsAllowed, openFileRef],);}@@ -141,6 +146,7 @@ async function ensureFileManagerView(workspacePath: string | null): Promise<bool}function useResolveChatFileRef() {+ const paneSessionId = useSlotSessionId();const { t } = useTranslation();const workspacePath = useAppStore((s) => s.workspace?.path ?? null);const sessionId = useAppStore((s) => s.activeSessionId);@@ -151,6 +157,10 @@ function useResolveChatFileRef() {path: string,baseDir?: string,): Promise<ResolvedChatFileRef | null> => {+ const state = useAppStore.getState();+ const ownerId = paneSessionId || state.activeSessionId;+ const session = state.sessions.find((item) => item.id === ownerId);+ if (!sessionAllows(session ?? (ownerId?.startsWith("remote:") ? { id: ownerId } : undefined), "canUseLocalTools")) return null;const raw = String(path ?? "").trim();if (!raw) return null;// `./x` and `../x` are the one shape the caller resolves better than the@@ -195,7 +205,7 @@ function useResolveChatFileRef() {primary,};},- [sessionId, showToast, t, workspacePath],+ [paneSessionId, sessionId, showToast, t, workspacePath],);}diff --git a/apps/desktop/src/hooks/use-remote-projects.ts b/apps/desktop/src/hooks/use-remote-projects.tsnew file mode 100644index 000000000..f26ad27b8--- /dev/null+++ b/apps/desktop/src/hooks/use-remote-projects.ts@@ -0,0 +1,37 @@+import { useEffect, useMemo, useState } from "react";+import type { RemoteHostSummary, RacpProjectSummary } from "@pi-desktop/shared";+import { api } from "../lib/api";+import { listRemoteProjects } from "../lib/remote-project-catalog";+import { useAppStore } from "../stores/app-store";++/** Read the Host catalog when an entry point opens; no remote paths enter local project state. */+export function useRemoteProjects(enabled: boolean) {+ const sessions = useAppStore((state) => state.sessions);+ const [hosts, setHosts] = useState<RemoteHostSummary[]>([]);+ const [inventories, setInventories] = useState<{ hostKey: string; projects: RacpProjectSummary[] }[]>([]);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState<string | null>(null);+ useEffect(() => {+ if (!enabled) return;+ let live = true;+ setBusy(true); setError(null);+ void (async () => {+ try {+ const result = await api.listRemoteHosts();+ const outcomes = await Promise.allSettled(result.hosts.filter((host) => host.connected).map(async (host) => ({+ hostKey: host.hostKey, projects: (await api.remoteHostProjects(host.hostKey)).projects,+ })));+ if (!live) return;+ setHosts(result.hosts);+ setInventories(outcomes.flatMap((outcome) => outcome.status === "fulfilled" ? [outcome.value] : []));+ const failed = outcomes.find((outcome) => outcome.status === "rejected");+ if (failed?.status === "rejected") setError(failed.reason instanceof Error ? failed.reason.message : String(failed.reason));+ } catch (caught) {+ if (live) setError(caught instanceof Error ? caught.message : String(caught));+ } finally { if (live) setBusy(false); }+ })();+ return () => { live = false; };+ }, [enabled]);+ const projects = useMemo(() => listRemoteProjects(hosts, inventories, sessions), [hosts, inventories, sessions]);+ return { projects, busy, error };+}diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex 01be49a1d..bd1112fa5 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -108,6 +108,7 @@ import type {PlanningStateEvent,PlansPendingResult,RemoteHostProjectsResult,+ RemoteHostBrowseProjectsResult,RemoteHostRegisterProjectResult,RemoteHostSessionsResult,RemoteHostCreateSessionRequest,@@ -1647,6 +1648,8 @@ export const api = {invoke<{ ok: true }>(IPC.invoke.remoteHostRemove, { hostKey }),reconnectRemoteHost: (hostKey: string) =>invoke<{ host: RemoteHostSummary }>(IPC.invoke.remoteHostReconnect, { hostKey }),+ remoteHostBrowseProjects: (hostKey: string, path?: string) =>+ invoke<RemoteHostBrowseProjectsResult>(IPC.invoke.remoteHostBrowseProjects, { hostKey, ...(path === undefined ? {} : { path }) }),remoteHostProjects: (hostKey: string) =>invoke<RemoteHostProjectsResult>(IPC.invoke.remoteHostProjects, { hostKey }),registerRemoteProject: (hostKey: string, path: string) =>diff --git a/apps/desktop/src/lib/remote-project-catalog.ts b/apps/desktop/src/lib/remote-project-catalog.tsnew file mode 100644index 000000000..b44429bfc--- /dev/null+++ b/apps/desktop/src/lib/remote-project-catalog.ts@@ -0,0 +1,46 @@+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 RemoteProjectGroup = { project: RemoteProjectEntry; sessions: SessionSummary[] };++/** Rendering and range selection consume one grouped order. */+export function groupRemoteProjectSessions(+ 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),+ }));+}++export function listRemoteProjects(+ hosts: RemoteHostSummary[],+ inventories: { hostKey: string; projects: RacpProjectSummary[] }[],+ sessions: SessionSummary[],+): RemoteProjectEntry[] {+ const entries = new Map<string, RemoteProjectEntry>();+ for (const session of sessions) {+ 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,+ label: session.remoteWorkspaceLabel ?? session.remoteProjectId,+ 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 });+ }+ }+ return [...entries.values()];+}diff --git a/apps/desktop/src/lib/remote-project-session.ts b/apps/desktop/src/lib/remote-project-session.tsnew file mode 100644index 000000000..9afcd6ef1--- /dev/null+++ b/apps/desktop/src/lib/remote-project-session.ts@@ -0,0 +1,66 @@+import type { SessionSummary } from "@pi-desktop/shared";+import { api } from "./api";+import { isRemoteSession, safeSessionSummary } from "./remote-session-safety";+import { sessionIsReusableEmpty } from "./session-create";+import { sessionIsArchived } from "./sidebar-preferences";+import type { SessionRuntime } from "../stores/runtime/session-runtime";+import type { StoreAccess } from "../stores/slices/types";++/** A remote project is identified by its host and project id, never a local path. */+export type RemoteProjectTarget = { hostKey: string; projectId: string; label: string };++export function remoteProjectForSession(session?: SessionSummary): RemoteProjectTarget | undefined {+ if (!isRemoteSession(session) || !session?.remoteHostKey || !session.remoteProjectId) return undefined;+ return { hostKey: session.remoteHostKey, projectId: session.remoteProjectId,+ label: session.remoteWorkspaceLabel ?? session.remoteProjectId };+}++export async function openRemoteProjectSession(+ { get, set, runtime }: StoreAccess & { runtime: SessionRuntime },+ project: RemoteProjectTarget,+): Promise<void> {+ const scope = `remote-project:${JSON.stringify([project.hostKey, project.projectId])}`;+ const pending = runtime.pendingNewSessionRequests.get(scope);+ if (pending) return pending;+ const intent = runtime.beginNavigationIntent();+ const request = (async () => {+ const state = get();+ const latest = state.sessions.filter((session) =>+ session.remoteHostKey === project.hostKey && session.remoteProjectId === project.projectId+ && !sessionIsArchived(session.id, state.sessionMeta),+ ).sort((left, right) => right.updatedAt.localeCompare(left.updatedAt))[0];+ if (latest && sessionIsReusableEmpty(latest, {+ running: state.runningSessions[latest.id] === true,+ liveMessageCount: runtime.liveMessageCountForSession(latest.id, state),+ submitted: runtime.submittedComposerDrafts.has(latest.id),+ })) {+ // RACP list summaries do not publish a durable message count. Read the+ // actual bounded history before treating a cold catalog row as empty.+ const detail = await api.getSession(latest.id);+ if (!runtime.navigationIntentIsCurrent(intent)) return;+ const current = get();+ const candidate = current.sessions.find((session) => session.id === latest.id);+ if (candidate && !sessionIsArchived(candidate.id, current.sessionMeta)+ && detail.session && !detail.session.hasMoreBefore && sessionIsReusableEmpty(detail.session, {+ running: current.runningSessions[latest.id] === true,+ liveMessageCount: Math.max(detail.session.messages?.length ?? 0, runtime.liveMessageCountForSession(latest.id, current)),+ submitted: runtime.submittedComposerDrafts.has(latest.id),+ })) {+ await get().selectSession(latest.id, { navigationIntent: intent });+ return;+ }+ }+ const result = await api.createRemoteSession({ hostKey: project.hostKey,+ projectId: project.projectId, mode: "agent", permissionMode: "ask" });+ const session = safeSessionSummary(result.session);+ // Preserve a successful creation even if the user navigated away while it ran.+ set((current) => ({ sessions: [session, ...current.sessions.filter((item) => item.id !== session.id)] }));+ if (!runtime.navigationIntentIsCurrent(intent)) return;+ await get().selectSession(session.id, { navigationIntent: intent });+ })();+ runtime.pendingNewSessionRequests.set(scope, request);+ try { await request; }+ finally {+ if (runtime.pendingNewSessionRequests.get(scope) === request) runtime.pendingNewSessionRequests.delete(scope);+ }+}diff --git a/apps/desktop/src/lib/use-referenced-image-data-url.ts b/apps/desktop/src/lib/use-referenced-image-data-url.tsindex 61875de9d..e51c6ffe2 100644--- a/apps/desktop/src/lib/use-referenced-image-data-url.ts+++ b/apps/desktop/src/lib/use-referenced-image-data-url.ts@@ -1,4 +1,6 @@import { useEffect, useState } from "react";+import { sessionAllows } from "./remote-session-safety";+import { useSlotSessionId } from "../plugins/renderer-slots/use-slots";import { api } from "./api";import { useAppStore } from "../stores/app-store";@@ -44,9 +46,14 @@ export function useReferencedImageDataUrl(ref: string | null | undefined,mimeType?: string,): string | null {- const workspaceRoot = useAppStore((s) => s.workspace?.path ?? null);+ const paneSessionId = useSlotSessionId();+ const localToolsAllowed = useAppStore((s) => {+ const id = paneSessionId || s.activeSessionId;+ return sessionAllows(s.sessions.find((item) => item.id === id) ?? (id?.startsWith("remote:") ? { id } : undefined), "canUseLocalTools");+ });+ const workspaceRoot = useAppStore((s) => localToolsAllowed ? s.workspace?.path ?? null : null);const normalizedRef = typeof ref === "string" ? ref.trim() : "";- const requestedKey = normalizedRef && !/^(?:https?|data|blob):/i.test(normalizedRef)+ const requestedKey = localToolsAllowed && normalizedRef && !/^(?:https?|data|blob):/i.test(normalizedRef)? cacheKey(workspaceRoot, normalizedRef, mimeType): null;const [resolved, setResolved] = useState<{ key: string; dataUrl: string | null }>({diff --git a/apps/desktop/src/locales/remote.ts b/apps/desktop/src/locales/remote.tsindex 9172c5f0f..08d6cc92d 100644--- a/apps/desktop/src/locales/remote.ts+++ b/apps/desktop/src/locales/remote.ts@@ -1,4 +1,8 @@export const remoteEn = {+ projectHost: "Host", noConnectedHosts: "Connect a remote host in Settings first.",+ projectFolder: "Remote folder", chooseFolder: "Choose a folder or enter its path",+ browseFolders: "Browse folders", useFolder: "Use this folder",+ projectNameHint: "The remote project uses its folder name.",older: "Load older messages", thinking: "Thinking",newer: "Load newer messages", latest: "Return to latest",sessions: "Conversations / New conversation",@@ -46,6 +50,10 @@ export const remoteEn = {};export const remoteZh: typeof remoteEn = {+ projectHost: "主机", noConnectedHosts: "请先在设置中连接远程主机。",+ projectFolder: "远程文件夹", chooseFolder: "选择文件夹或输入路径",+ browseFolders: "浏览文件夹", useFolder: "使用此文件夹",+ projectNameHint: "远程项目使用文件夹名称。",older: "加载更早消息", thinking: "思考",newer: "加载较新消息", latest: "返回最新消息",sessions: "会话 / 新建会话", reconnect: "重新连接", refresh: "刷新", close: "关闭", loading: "处理中…",diff --git a/apps/desktop/src/plugins/renderer-slots/use-slots.tsx b/apps/desktop/src/plugins/renderer-slots/use-slots.tsxindex a547303f1..6bc8c1712 100644--- a/apps/desktop/src/plugins/renderer-slots/use-slots.tsx+++ b/apps/desktop/src/plugins/renderer-slots/use-slots.tsx@@ -29,15 +29,16 @@ export function useSlotEntries(slot: PluginComponentSlot,side?: PluginSlotPosition,): SlotEntry[] {+ const sessionId = useSlotSessionId();const snapshot = useSyncExternalStore(slotRegistry.subscribe,slotRegistry.getSnapshot,slotRegistry.getSnapshot,);return useMemo(- () => (side ? slotRegistry.entriesForSide(slot, side) : slotRegistry.entriesFor(slot)),+ () => sessionId.startsWith("remote:") ? [] : (side ? slotRegistry.entriesForSide(slot, side) : slotRegistry.entriesFor(slot)),// eslint-disable-next-line react-hooks/exhaustive-deps -- snapshot.version is the change signal- [snapshot.version, slot, side],+ [snapshot.version, slot, side, sessionId],);}@@ -45,15 +46,16 @@ export function useSlotEntryForKey(slot: PluginComponentSlot,key: string | undefined,): SlotEntry | undefined {+ const sessionId = useSlotSessionId();const snapshot = useSyncExternalStore(slotRegistry.subscribe,slotRegistry.getSnapshot,slotRegistry.getSnapshot,);return useMemo(- () => (key ? slotRegistry.entryForKey(slot, key) : undefined),+ () => (!sessionId.startsWith("remote:") && key ? slotRegistry.entryForKey(slot, key) : undefined),// eslint-disable-next-line react-hooks/exhaustive-deps -- snapshot.version is the change signal- [snapshot.version, slot, key],+ [snapshot.version, slot, key, sessionId],);}diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.tsindex 666e9f128..28151a9e7 100644--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@ -1,4 +1,5 @@import type { RecentModel } from "../lib/recent-models";+import type { RemoteProjectTarget } from "../lib/remote-project-session";import type {AgentEventEnvelope,BrowserState,@@ -206,7 +207,7 @@ export type AppState = {id: string,opts?: { record?: boolean } & NavigationOptions,) => Promise<void>;- newSession: (options?: { projectPath?: string | null }) => Promise<void>;+ newSession: (options?: { projectPath?: string | null; remoteProject?: RemoteProjectTarget }) => Promise<void>;forkSession: (id: string) => Promise<void>;forkAssistantMessage: (messageId: string) => Promise<void>;configureActiveSession: (config: {diff --git a/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts b/apps/desktop/src/stores/runtime/transcript-reading-runtime.tsindex ad8d6d80d..ee3924e5f 100644--- a/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts+++ b/apps/desktop/src/stores/runtime/transcript-reading-runtime.ts@@ -1,5 +1,6 @@import type { SessionDetail } from "@pi-desktop/shared";import type { SessionHistoryReadOptions } from "../../lib/api";+import { isRemoteSession } from "../../lib/remote-session-safety";import {EMPTY_TRANSCRIPT,extendTranscriptView,@@ -104,6 +105,10 @@ export function createTranscriptReadingRuntime({ get, set }: StoreAccess, read:},loadTranscriptPage: async (sessionId, direction) => {const view = currentView(sessionId);+ const remote = isRemoteSession({ id: sessionId });+ // Remote history exposes older-item cursors only; never synthesize a+ // forward cursor by applying local physical-offset arithmetic.+ if (remote && direction === "after") return;if (view.loading || !(direction === "before" ? view.hasMoreBefore : view.hasMoreAfter))return;const limit = view.focus ? TRANSCRIPT_SEARCH_PAGE_SIZE : TRANSCRIPT_PAGE_SIZE;@@ -118,7 +123,16 @@ export function createTranscriptReadingRuntime({ get, set }: StoreAccess, read:});if (get().transcriptViews[sessionId] !== pending) return;if (!session) throw new Error("Conversation no longer exists.");- publish(sessionId, extendTranscriptView(pending, session, direction));+ const extended = extendTranscriptView(pending, session, direction);+ // Remote numeric values represent opaque Host item cursors. Preserve+ // the returned cursor rather than depending on its ordering. Local+ // transcripts continue merging physical message offsets unchanged.+ publish(sessionId, remote ? {+ ...extended,+ messageStart: session.messageStart ?? 0,+ messageEnd: undefined,+ hasMoreAfter: false,+ } : extended);} catch (error) {reportError(sessionId, pending, error);}diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.tsindex b9c1c89d7..5a3a328c5 100644--- a/apps/desktop/src/stores/slices/session-slice.ts+++ b/apps/desktop/src/stores/slices/session-slice.ts@@ -37,6 +37,7 @@ import {import { api } from "../../lib/api";import { isRemoteSession, safeSessionSummary, sessionAllows } from "../../lib/remote-session-safety";import { createRefreshCoordinator } from "../../lib/refresh-coordinator";+import { openRemoteProjectSession, remoteProjectForSession } from "../../lib/remote-project-session";import {applyOptimisticSessionConfiguration,} from "../../lib/session-thinking";@@ -633,6 +634,15 @@ export function createSessionSlice({},newSession: async (options) => {+ const activeSession = get().sessions.find((session) => session.id === get().activeSessionId);+ const remoteProject = options?.remoteProject ?? (+ options && "projectPath" in options ? undefined+ : remoteProjectForSession(activeSession)+ );+ if (remoteProject) return openRemoteProjectSession({ get, set, runtime }, remoteProject);+ if (!(options && "projectPath" in options) && isRemoteSession(activeSession ?? (+ get().activeSessionId?.startsWith("remote:") ? { id: get().activeSessionId! } : undefined+ ))) throw new Error(i18n.t("remote:REMOTE_PROJECT_REQUIRED"));const requestedProjectPath =options && "projectPath" in options? options.projectPath ?? nulldiff --git a/apps/desktop/src/styles/project-create-dialog.css b/apps/desktop/src/styles/project-create-dialog.cssindex 32e92e91c..586c6d377 100644--- a/apps/desktop/src/styles/project-create-dialog.css+++ b/apps/desktop/src/styles/project-create-dialog.css@@ -148,7 +148,7 @@.project-create-dialog-source-options {display: grid;- grid-template-columns: repeat(2, minmax(0, 1fr));+ grid-template-columns: repeat(3, minmax(0, 1fr));gap: 8px;}@@ -491,6 +491,14 @@}}+.remote-project-picker { display: grid; gap: 12px; }+.remote-project-browser { display: grid; gap: 8px; }+.remote-project-browser-actions { display: flex; flex-wrap: wrap; gap: 8px; }+.remote-project-browser-path { overflow-wrap: anywhere; color: var(--ds-text-secondary); font-size: var(--text-sm); }+.remote-project-browser-entries { display: grid; max-height: 160px; overflow-y: auto; }+.remote-project-browser-entries .btn { justify-content: flex-start; }+.remote-project-error { color: var(--ds-error); font-size: var(--text-sm); }+@media (prefers-reduced-motion: reduce) {.project-create-dialog-close,.project-create-dialog-name-field,diff --git a/apps/desktop/src/styles/remote-mvp.css b/apps/desktop/src/styles/remote-mvp.cssindex ae0bc36a0..f567c8567 100644--- a/apps/desktop/src/styles/remote-mvp.css+++ b/apps/desktop/src/styles/remote-mvp.css@@ -11,26 +11,18 @@color: var(--ds-text-secondary);font-size: var(--text-sm);}-.remote-transcript, .remote-workspace-content {+.remote-workspace-content {min-height: 0;flex: 1;overflow: auto;padding: 12px 16px;}-.remote-message { margin: 0 0 18px; }-.remote-message-user {- background: var(--ds-tile);- border-radius: var(--radius-sm);- padding: 12px;-}-.remote-conversation pre, .remote-workspace pre {+.remote-workspace pre {white-space: pre-wrap;overflow-wrap: anywhere;font: inherit;user-select: text;}-.remote-composer { padding: 12px 16px; }-.remote-composer textarea { width: 100%; resize: vertical; max-height: 180px; }.remote-workspace { display: flex; flex-direction: column; min-width: 0; }.remote-host-workbench { padding: 12px; }.settings-remote-host-card-actions { flex-wrap: wrap; }diff --git a/apps/desktop/test/chat-file-reveal-menu.test.mjs b/apps/desktop/test/chat-file-reveal-menu.test.mjsindex 46a18eed1..c3739a6d8 100644--- a/apps/desktop/test/chat-file-reveal-menu.test.mjs+++ b/apps/desktop/test/chat-file-reveal-menu.test.mjs@@ -57,6 +57,7 @@ const calls = {};const state = {+ sessions: [],workspace: { path: "C:/project" },activeSessionId: "session-1",pluginViews: [{ pluginId: "pi.file-manager", viewId: "manager" }],@@ -105,6 +106,9 @@ const previewTarget = loadModule("../src/hooks/use-preview-target.ts", {"react-i18next": { useTranslation: translate },"@pi-desktop/shared": sharedPackage,"../stores/app-store": { useAppStore },+ "./use-chat-session-capability": { useChatSessionCapability: () => true },+ "../lib/remote-session-safety": loadModule("../src/lib/remote-session-safety.ts", {}),+ "../plugins/renderer-slots/use-slots": { useSlotSessionId: () => "" },"../lib/api": {api: {listPluginViews: async () => state.pluginViews,@@ -388,8 +392,11 @@ test("every transcript surface that names a file opens that item", () => {assert.match(markdown, /openFileMenu\(event, \{ path: localRef, baseDir \}\)/);assert.match(markdown, /onContextMenu=\{onLocalContextMenu\}/);// A local image that cannot be shown inline keeps a chip, and both carry the- // menu only when the reference actually resolved to a file.- assert.match(markdown, /const onLocalContextMenu =\s*localRef && openFileMenu/);+ // menu only when local tools are allowed and the reference resolved to a file.+ assert.match(+ markdown,+ /const onLocalContextMenu =\s*localToolsAllowed && localRef && openFileMenu/,+ );});test("a URL never reaches the reveal", () => {diff --git a/apps/desktop/test/composer-send-state.test.mjs b/apps/desktop/test/composer-send-state.test.mjsindex 588031003..dad176cd3 100644--- a/apps/desktop/test/composer-send-state.test.mjs+++ b/apps/desktop/test/composer-send-state.test.mjs@@ -92,7 +92,7 @@ test("composer send/stop button follows draft content and the visible session's"Stop must not render beside an always-present Send button",);assert.match(composer, /const inputBlocked = approvalPending \|\| pasting \|\| nativeInputBlocked;/);- assert.match(composer, /const controlsBlocked = approvalPending \|\| nativeSession;/);+ assert.match(composer, /const controlsBlocked = approvalPending \|\| nativeSession \|\| !sessionAllows\(capabilitySession, "canConfigureModel"\);/);assert.match(composer, /contentEditable=\{!inputBlocked\}/);assert.match(composer, /disabled=\{controlsBlocked\}/);assert.match(composer, /sendBlocked[\s\S]*\(!modelReady/);diff --git a/apps/desktop/test/helpers/slot-ssr.mjs b/apps/desktop/test/helpers/slot-ssr.mjsindex 51c4808a3..0fa976d2f 100644--- a/apps/desktop/test/helpers/slot-ssr.mjs+++ b/apps/desktop/test/helpers/slot-ssr.mjs@@ -16,10 +16,11 @@ import { fileURLToPath } from "node:url";* mount, before any measuring, timer or listener. Behavior that needs those* is covered at the logic layer or in the Electron E2E.*/-export async function slotSsr(t, { translationOverrides = {} } = {}) {+export async function slotSsr(t, { translationOverrides = {}, plugins = [] } = {}) {const server = await createServer({root: fileURLToPath(new URL("../..", import.meta.url)),configFile: false,+ plugins,logLevel: "silent",server: { middlewareMode: true, hmr: false, ws: false },esbuild: { jsx: "automatic" },diff --git a/apps/desktop/test/project-create-dialog.test.mjs b/apps/desktop/test/project-create-dialog.test.mjsindex acecf2f5c..ba71ee104 100644--- a/apps/desktop/test/project-create-dialog.test.mjs+++ b/apps/desktop/test/project-create-dialog.test.mjs@@ -6,7 +6,7 @@ import { readStoreSource } from "./helpers/store-source.mjs";const read = (relativePath) => readFile(new URL(relativePath, import.meta.url), "utf8");-const [dialog, editDialog, store, api, protocol, main, styles] = await Promise.all([+const [dialogSource, editDialog, store, api, protocol, main, styles] = await Promise.all([read("../src/components/ProjectCreateDialog.tsx"),read("../src/components/ProjectEditDialog.tsx"),readStoreSource(),@@ -16,6 +16,8 @@ const [dialog, editDialog, store, api, protocol, main, styles] = await Promise.aread("../src/styles/project-create-dialog.css"),]);+const dialog = dialogSource + await read("../src/components/ProjectFolderPicker.tsx");+test("create project dialog supports named multi-folder setup", () => {assert.match(dialog, /role="dialog"/);assert.match(dialog, /useBlockingOverlay\(\)/);@@ -42,7 +44,7 @@ test("create project dialog supports named multi-folder setup", () => {test("create project dialog can create the project from a git checkout", () => {// Same dialog, same name field: the source toggle turns the folder list into// one repository URL plus its clone destination.- assert.match(dialog, /type ProjectSource = "local" \| "git"/);+ assert.match(dialog, /type ProjectSource = "local" \| "git" \| "remote"/);assert.match(dialog, /data-project-source="git"/);assert.match(dialog, /parseGitCloneUrl/);assert.match(dialog, /project\.createSourceLabel/);diff --git a/apps/desktop/test/remote-mvp-renderer.test.mjs b/apps/desktop/test/remote-mvp-renderer.test.mjsindex cca5ec803..18194e9fa 100644--- a/apps/desktop/test/remote-mvp-renderer.test.mjs+++ b/apps/desktop/test/remote-mvp-renderer.test.mjs@@ -16,7 +16,8 @@ await build({export { api } from './apps/desktop/src/lib/api';export { createRemoteHostWorkflow } from './apps/desktop/src/lib/remote-host-workflow';export { subscribeRemoteInteractions } from './apps/desktop/src/lib/remote-interactions';- export { useAppStore } from './apps/desktop/src/stores/app-store';+ import { useAppStore } from './apps/desktop/src/stores/app-store';+ export { useAppStore };export { selectRemoteSession as selectRemote } from './apps/desktop/src/components/settings/RemoteHostSessions';export { sessionAllows, safeSessionSummary } from './apps/desktop/src/lib/remote-session-safety';export { sessionMatchesProject, projectPathsForNewSessions } from './apps/desktop/src/lib/sidebar-session-groups';@@ -28,15 +29,21 @@ await build({import { initReactI18next } from 'react-i18next';import { remoteEn } from './apps/desktop/src/locales/remote';import { RemoteHostSessions } from './apps/desktop/src/components/settings/RemoteHostSessions';- import { RemoteConversation } from './apps/desktop/src/components/remote/RemoteConversation';+ import { ChatSurface } from './apps/desktop/src/components/ChatSurface';+ import { catalogs } from '@pi-desktop/i18n';export async function render(kind, props) {- await i18n.use(initReactI18next).init({lng:'en', fallbackLng:'en', resources:{en:{remote:remoteEn}}, interpolation:{escapeValue:false}});- return renderToStaticMarkup(React.createElement(kind === 'host' ? RemoteHostSessions : RemoteConversation, props));+ await i18n.use(initReactI18next).init({lng:'en', fallbackLng:'en', resources:{en:{remote:remoteEn, translation:catalogs.en}}, interpolation:{escapeValue:false}});+ Object.assign(useAppStore.getInitialState(), useAppStore.getState(), kind === 'host' ? {} : {sessions:[props.session], activeSessionId:props.session.id, retainedSessionIds:[props.session.id], messages:[]});+ return renderToStaticMarkup(React.createElement(kind === 'host' ? RemoteHostSessions : ChatSurface, kind === 'host' ? props : {}));}`, resolveDir: root, loader: "tsx" },outfile: output, bundle: true, platform: "node", format: "esm", jsx: "automatic",- alias: { "@pi-desktop/shared": join(root, "packages/shared/src/index.ts") },- loader: { ".css": "empty" },+ alias: { "@pi-desktop/shared": join(root, "packages/shared/src/index.ts"), "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"), react: join(root, "apps/desktop/node_modules/react"), "react-dom": join(root, "apps/desktop/node_modules/react-dom"), "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"), i18next: join(root, "apps/desktop/node_modules/i18next") },+ loader: { ".css": "empty", ".gif": "dataurl", ".png": "dataurl" },+ plugins: [{ name: "fixture-vite-url", setup(builder) {+ builder.onResolve({ filter: /\?url$/ }, ({ path }) => ({ path, namespace: "fixture-url" }));+ builder.onLoad({ filter: /.*/, namespace: "fixture-url" }, ({ path }) => ({ contents: `export default ${JSON.stringify(path)};`, loader: "js" }));+ } }],banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" },});const fixture = await import(pathToFileURL(output).href);@@ -49,7 +56,7 @@ const provider = { id: "api-provider", name: "Network provider", enabled: true,function deferred() { let resolve; const promise = new Promise((done) => { resolve = done; }); return { promise, resolve }; }function bridge(handler) {const calls = [];- globalThis.window = { piDesktop: { platform: "linux", on: () => () => {}, invoke: async (channel, ...args) => {+ globalThis.window = { matchMedia: () => ({ matches: false }), piDesktop: { platform: "linux", on: () => () => {}, invoke: async (channel, ...args) => {calls.push({ channel, input: args[0] }); return { ok: true, data: await handler(channel, args[0]) };} } };return calls;@@ -178,8 +185,9 @@ test("remote capabilities and workspace identity fail closed, local defaults staawait assert.rejects(api.prompt({ sessionId: session.id, content: "attached", attachments: [{ path: "/local/private" }] }), { code: "CAPABILITY_UNAVAILABLE" });assert.equal(calls.length, 0);const html = await fixture.render("chat", { session });- assert.match(html, /Remote · Build machine · Remote project/);- assert.doesNotMatch(html, /Local only|local\/private|composer-model|attachment-picker|plugin-slot|message-revision/);+ assert.match(html, /Remote project/);+ assert.match(html, /data-composer-dock="home"/);+ assert.doesNotMatch(html, /Local only|local\/private|attachment-picker|plugin-slot|message-revision/);});test("session refresh retains the active remote identity when offline, and replaces it on recovery", async () => {@@ -250,7 +258,7 @@ test("remote interaction IPC reconciles real queues and detaches without touchinconst local = { ...permission, sessionId: "local", requestId: "local-permission" };useAppStore.setState({ pendingPermissions: { local: [local] } });const listeners = new Map();- globalThis.window = { piDesktop: { on(channel, handler) { listeners.set(channel, handler); return () => listeners.delete(channel); } } };+ globalThis.window = { matchMedia: () => ({ matches: false }), piDesktop: { on(channel, handler) { listeners.set(channel, handler); return () => listeners.delete(channel); } } };const unsubscribe = fixture.subscribeRemoteInteractions();const send = (event) => listeners.get(IPC.event.remoteInteractions)(event);const pending = { kind: "snapshot", sessionId: session.id, permissions: [permission], asks: [ask] };diff --git a/apps/desktop/test/remote-project-dialog-user-path.test.mjs b/apps/desktop/test/remote-project-dialog-user-path.test.mjsnew file mode 100644index 000000000..d5a04fef9--- /dev/null+++ b/apps/desktop/test/remote-project-dialog-user-path.test.mjs@@ -0,0 +1,215 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import test from "node:test";+import { loadStyles } from "./helpers/styles.mjs";+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+const fixture = String.raw`+import React from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { initReactI18next } from "react-i18next";+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";+import { IPC } from "@pi-desktop/shared";+import { ChatSurface } from "../../apps/desktop/src/components/ChatSurface";+import { ProjectCreateDialog } from "../../apps/desktop/src/components/ProjectCreateDialog";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";+import { remoteEn } from "../../apps/desktop/src/locales/remote";+import "../../apps/desktop/src/styles/project-create-dialog.css";++await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,+ resources: { en: { translation: flattenCatalog(catalogs.en), remote: remoteEn } },+ interpolation: { escapeValue: false } });+const calls = [];+const unexpectedCalls = [];+let sent = false;+const localSummary = { id: "local-empty", title: "app", projectPath: "/local/app", createdAt: "2026-10-11T00:00:00Z", updatedAt: "2026-10-11T00:00:00Z", status: "idle", mode: "agent", permissionMode: "ask", messageCount: 0 };+let releaseOldBrowse;+let releaseCreate;+const summary = { id: "remote:h2:s1", title: "app", source: "remote", remoteHostKey: "h2", remoteHostLabel: "Server 2", remoteProjectId: "p2", remoteWorkspaceLabel: "app", createdAt: "2026-10-11T00:00:00Z", updatedAt: "2026-10-11T00:00:00Z", status: "idle", mode: "agent", permissionMode: "ask", messageCount: 0, capabilities: { canPrompt: true, canStop: true, canAttach: false, canConfigureModel: false, canPlan: false } };+window.piDesktop = { platform: "darwin", channels: IPC, on() { return () => {}; },+ async invoke(channel, input) {+ calls.push({ channel, input });+ const data = await (async () => { switch (channel) {+ case IPC.invoke.remoteHostList: return { hosts: [{ hostKey: "h1", label: "Server 1", connected: true }, { hostKey: "h2", label: "Server 2", connected: true }, { hostKey: "offline", label: "Offline", connected: false }] };+ case IPC.invoke.remoteHostProjects: return { projects: [{ id: input.hostKey === "h1" ? "p1" : "p2", label: input.hostKey === "h1" ? "old" : "app", archived: false }] };+ case IPC.invoke.remoteHostBrowseProjects:+ if (input.hostKey === "h1") return new Promise((resolve) => { releaseOldBrowse = () => resolve({ path: "/old", entries: [{ name: "stale", path: "/old/stale" }] }); });+ return { path: input.path ?? "/home/user", parent: input.path ? "/home/user" : "/home", entries: input.path ? [] : [{ name: "app", path: "/home/user/app" }] };+ case IPC.invoke.remoteHostRegisterProject: return { project: { id: "p2", label: "app", archived: false, path: input.path } };+ case IPC.invoke.remoteHostCreateSession: return new Promise((resolve) => { releaseCreate = () => resolve({ session: summary }); });+ case IPC.invoke.sessionGet: if (input.id === localSummary.id) return { session: { ...localSummary, messages: [] } }; return { session: { ...summary, messages: sent ? [{ id: "m1", role: "user", content: "Inspect remote project", timestamp: "2026-10-11T00:00:00Z" }, { id: "m2", role: "assistant", content: "Remote reply", timestamp: "2026-10-11T00:00:00Z" }] : [] } };+ case IPC.invoke.composerCommands: return { commands: [] };+ case IPC.invoke.agentPrompt: sent = true; return { accepted: true };+ case IPC.invoke.skillsList: return { skills: [] };+ case IPC.invoke.pluginsList: return { plugins: [] };+ case IPC.invoke.providersList: return { providers: [] };+ case IPC.invoke.pendingInteractive: return { asks: [], permissions: [] };+ case IPC.invoke.todosGet: return { todos: [] };+ case IPC.invoke.plansPending: return { plans: [] };+ case IPC.invoke.liveVoiceStatus: return { status: "idle" };+ case IPC.invoke.settingsGet: return { settings: {} };+ default: unexpectedCalls.push(channel); throw new Error("Unexpected IPC: " + channel);+ } })();+ return { ok: true, data };+ }+};+const view = createRoot(document.getElementById("root"));+const frame = () => new Promise(requestAnimationFrame);+async function settle() { await frame(); await frame(); }+function check(condition, message) { if (!condition) throw new Error(message); }+async function until(predicate, message) { for (let n=0;n<120;n++) { if (predicate()) return; await frame(); } throw new Error(message + " body=" + document.body.textContent + " calls=" + JSON.stringify(calls)); }+const button = (label) => [...document.querySelectorAll("button")].find((node) => node.textContent.trim() === label);+function choose(node, value) { flushSync(() => { Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype, "value").set.call(node, value); node.dispatchEvent(new Event("change", { bubbles: true })); }); }+function input(node, value) { flushSync(() => { Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value").set.call(node, value); node.dispatchEvent(new Event("input", { bubbles: true })); }); }+window.remoteProjectProbe = async () => {+ useAppStore.setState({ workspace: { path: "/local/app", name: "app" }, activeProjectPath: "/local/app", openProjectPaths: ["/local/app"], openProjects: [{ path: "/local/app", name: "app" }], sessions: [localSummary], activeSessionId: localSummary.id, page: "chat" });+ await useAppStore.getState().openProject();+ flushSync(() => view.render(React.createElement(React.Fragment, null, React.createElement(ChatSurface), React.createElement(ProjectCreateDialog))));+ await until(() => button("Remote"), "remote source button missing");+ button("Remote").click();+ await until(() => releaseOldBrowse, "first host did not load");+ const dialog = document.querySelector('[role="dialog"]');+ check(dialog.scrollWidth <= dialog.clientWidth, "remote project dialog overflows a narrow window");+ const focusable = [...dialog.querySelectorAll('input:not([disabled]),button:not([disabled]),select:not([disabled])')];+ focusable.at(-1).focus(); window.dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));+ check(document.activeElement === focusable[0], "remote dialog focus trap failed");+ check(!document.querySelector('option[value="offline"]'), "disconnected host offered");+ choose(document.querySelector("select"), "h2");+ await until(() => document.querySelector(".remote-project-browser-path")?.textContent === "/home/user", "new host did not load");+ releaseOldBrowse(); await settle();+ check(!document.body.textContent.includes("stale"), "late host browse replaced current directory");+ [...document.querySelectorAll(".remote-project-browser button")].find((node) => node.textContent === "app").click();+ await until(() => document.querySelector(".remote-project-browser-path")?.textContent === "/home/user/app", "directory navigation failed");+ button("Use this folder").click(); await settle();+ check(document.querySelector(".remote-project-picker input").value === "/home/user/app", "chosen path was not retained");+ input(document.querySelector(".remote-project-picker input"), "relative"); await settle();+ check(document.querySelector('button[type="submit"]').disabled, "relative remote path accepted");+ input(document.querySelector(".remote-project-picker input"), "/home/user/app"); await settle();+ const form = document.querySelector("form");+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+ form.dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+ await until(() => releaseCreate, "remote session creation did not start");+ check(calls.filter((entry) => entry.channel === IPC.invoke.remoteHostRegisterProject).length === 1, "duplicate registration");+ check(calls.filter((entry) => entry.channel === IPC.invoke.remoteHostCreateSession).length === 1, "duplicate creation");+ releaseCreate();+ await until(() => useAppStore.getState().activeSessionId === summary.id && !document.querySelector('[role="dialog"]'), "remote session did not open");+ check(useAppStore.getState().messages.length === 0 && useAppStore.getState().page === "chat", "not an empty chat");+ check(!useAppStore.getState().sessions.find((session) => session.id === summary.id).projectPath, "remote path leaked to local workspace");+ await useAppStore.getState().openProject(); await settle(); button("Remote").click();+ await until(() => document.querySelector("select")?.value === "h1", "dialog reopen failed");+ choose(document.querySelector("select"), "h2");+ await until(() => document.querySelector('option[value="p2"]'), "existing project missing");+ choose(document.querySelectorAll("select")[1], "p2"); await settle();+ document.querySelector("form").dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));+ await until(() => !document.querySelector('[role="dialog"]'), "existing project did not open");+ check(calls.filter((entry) => entry.channel === IPC.invoke.remoteHostRegisterProject).length === 1, "existing project unnecessarily registered");+ check(calls.filter((entry) => entry.channel === IPC.invoke.remoteHostCreateSession).length === 1, "empty remote session was not reused");+ await useAppStore.getState().newSession();+ check(useAppStore.getState().activeSessionId === summary.id, "new conversation escaped remote project");+ check(calls.filter((entry) => entry.channel === IPC.invoke.remoteHostCreateSession).length === 1, "new conversation did not reuse empty remote session");+ async function switchProject(remote) {+ document.querySelector('[data-testid="home-project-switcher"]').click();+ await until(() => [...document.querySelectorAll('[role="menuitemradio"]')].some((node) => node.textContent.includes("Server 2")), "remote menu inventory missing");+ const target = [...document.querySelectorAll('[role="menuitemradio"]')].find((node) => remote ? node.textContent.includes("app · Server 2") : node.getAttribute("title") === "/local/app");+ check(target, "project menu target missing"); target.click();+ await until(() => useAppStore.getState().activeSessionId === (remote ? summary.id : localSummary.id) && !document.querySelector('[role="menu"]'), "project switch failed");+ check(useAppStore.getState().workspace?.path === "/local/app", "remote navigation altered local workspace");+ }+ await switchProject(false); await switchProject(true); await switchProject(false); await switchProject(true);+ check(document.querySelector('.empty-hero')?.textContent.includes("app"), "remote project hero missing");+ const composerInput = document.querySelector('.composer-shell [role="textbox"]');+ check(composerInput && composerInput.getAttribute("aria-readonly") !== "true", "normal remote composer missing");+ flushSync(() => { composerInput.textContent = "Inspect remote project"; composerInput.dispatchEvent(new Event("input", { bubbles: true })); });+ await settle();+ const sendButton = document.querySelector('.composer-shell [aria-label="' + i18n.t("chat.send") + '"]');+ check(sendButton && !sendButton.disabled, "remote send action unavailable");+ sendButton.click();+ await until(() => calls.some((entry) => entry.channel === IPC.invoke.agentPrompt), "normal composer did not send remote prompt");+ await useAppStore.getState().selectSession(summary.id, { record: false });+ await until(() => document.querySelector('.session-pane')?.textContent.includes("Remote reply"), "remote transcript did not show reply");+ check(!document.querySelector('.empty-hero'), "empty hero remained after messages");+ check(!calls.some((entry) => [IPC.invoke.projectActivate, IPC.invoke.sessionConfigure].includes(entry.channel)), "remote flow called local workspace or model configuration");+ const sessionsBefore = useAppStore.getState().sessions;+ useAppStore.setState({ sessions: sessionsBefore.map((session) => session.id === summary.id ? { ...session, remoteProjectId: undefined } : session) });+ let rejected = false;+ try { await useAppStore.getState().newSession(); } catch { rejected = true; }+ check(rejected, "incomplete remote identity fell back to local chat creation");+ useAppStore.setState({ sessions: sessionsBefore });+ flushSync(() => view.unmount());+ releaseOldBrowse(); await settle();+ check(unexpectedCalls.length === 0, "unexpected IPC calls: " + unexpectedCalls.join(", "));+ return { passed: true };+};+`;++test("home project dialog browses remote paths and opens an empty remote session", {+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,+}, async () => {+ const temp = await mkdtemp(join(root, "apps/desktop/.remote-project-ui-"));+ try {+ await build({+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },+ plugins: [{ name: "vite-url-assets", setup(plugin) {+ plugin.onResolve({ filter: /\?url$/ }, ({ path }) => ({ path, namespace: "url-asset" }));+ plugin.onLoad({ filter: /.*/, namespace: "url-asset" }, () => ({ contents: 'export default "fixture-asset";', loader: "js" }));+ } }],+ loader: { ".css": "empty", ".png": "dataurl", ".gif": "dataurl" },+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },+ alias: {+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),+ "@pi-desktop/shared": join(root, "packages/shared/src"),+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ i18next: join(root, "apps/desktop/node_modules/i18next"),+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await writeFile(join(temp, "renderer.css"), (await loadStyles()).replace(/@theme(?: inline)?\s*\{/g, ":root {"));+ await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'; img-src \'self\' data:"><link rel="stylesheet" href="renderer.css"><div id="root"></div><script type="module" src="renderer.js"></script>');+ await writeFile(join(temp, "main.cjs"), `+const { app, BrowserWindow, session } = require("electron");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+app.whenReady().then(async () => {+ session.defaultSession.webRequest.onBeforeRequest({ urls: ["http://*/*", "https://*/*", "ws://*/*", "wss://*/*"] }, (_details, callback) => callback({ cancel: true }));+ const win = new BrowserWindow({ show: false, width: 380, height: 760,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });+ win.webContents.on("console-message", (...args) => console.log("RENDERER", (args[0].message ?? args[2] ?? "").slice(0, 500)));+ try {+ await win.loadFile(path.join(__dirname, "index.html"));+ console.log("REMOTE_PROJECT_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.remoteProjectProbe()")));+ app.exit(0);+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }+});`);+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) {+ stream.setEncoding("utf8");+ stream.on("data", (chunk) => { output += chunk; });+ }+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+ } finally { clearTimeout(timer); }+ assert.equal(code, 0, output.slice(-6000));+ const line = output.split(/\r?\n/).find((item) => item.startsWith("REMOTE_PROJECT_PROBE "));+ assert.ok(line, output.slice(-6000));+ assert.deepEqual(JSON.parse(line.slice("REMOTE_PROJECT_PROBE ".length)), {+ passed: true,+ });+ } finally {+ await rm(temp, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/test/remote-project-session.test.mjs b/apps/desktop/test/remote-project-session.test.mjsnew file mode 100644index 000000000..28d3af9c8--- /dev/null+++ b/apps/desktop/test/remote-project-session.test.mjs@@ -0,0 +1,160 @@+import assert from "node:assert/strict";+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 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",+});+const originalRead = api.getSession;+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 }); } };+ 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,+ };+}++test("remote New chat reuses an empty chat only in the same host/project", async () => {+ const f = fixture([remote("ssh-two"), remote()]);+ await openRemoteProjectSession(f, project);+ assert.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);+});++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; }); };+ 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.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; }+});++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; });+ try {+ const f = fixture();+ const request = openRemoteProjectSession(f, project);+ f.nav.begin();+ resolve({ session: remote() });+ await request;+ assert.equal(f.get().sessions.length, 1);+ assert.equal(f.selections.length, 0);+ } finally { api.createRemoteSession = original; }+});++test("a busy or nonempty chat is never reused, and failed creation can be retried", async () => {+ const original = api.createRemoteSession;+ const f = fixture([remote()]);+ f.get().runningSessions[remote().id] = true;+ let attempts = 0;+ api.createRemoteSession = async () => {+ attempts++;+ if (attempts === 1) throw new Error("offline");+ return { session: { ...remote(), id: "remote:ssh-one:two" } };+ };+ try {+ await assert.rejects(openRemoteProjectSession(f, project), /offline/);+ await openRemoteProjectSession(f, project);+ assert.equal(attempts, 2);+ assert.equal(f.selections[0].id, "remote:ssh-one:two");+ assert.equal(f.runtime.pendingNewSessionRequests.size, 0);+ } 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")]);+ 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()]), []);+});++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"]);+});++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 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" }] }) },+ };+ 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");+ const f = fixture(rows);+ 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" } });+ try {+ await openRemoteProjectSession(f, project);+ assert.equal(f.selections[0].id, "remote:ssh-one:new");+ } 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; });+ const pending = openRemoteProjectSession(f, project);+ f.nav.begin();+ resolve({ session: { ...remote(), messages: [] } });+ await pending;+ assert.equal(f.selections.length, 0);+});++test("a chat archived during history confirmation is not reused", async () => {+ const f = fixture([remote()]);+ let resolve;+ api.getSession = () => new Promise((done) => { resolve = done; });+ const original = api.createRemoteSession;+ 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; }+});diff --git a/apps/desktop/test/remote-session-user-path.test.mjs b/apps/desktop/test/remote-session-user-path.test.mjsindex 5e1ac2ba1..ce9689e32 100644--- a/apps/desktop/test/remote-session-user-path.test.mjs+++ b/apps/desktop/test/remote-session-user-path.test.mjs@@ -27,6 +27,7 @@ function fixture() {calls.push({ method, params });switch (method) {case "project/list": return { projects: [{ id: "p1", label: "app", archived: false }] };+ case "project/browse": return { path: "/home/pi", entries: [{ name: "app", path: "/home/pi/app" }] };case "project/register": return { project: { id: "p1", label: "app", archived: false, path: params.path } };case "session/create": case "session/get": return { session: session() };case "session/list": return { sessions: [session()] };@@ -132,3 +133,108 @@ test("remote entry IPC validates fields and strips unrelated model settings", asawait assert.rejects(handlers.get(IPC.invoke.remoteHostSyncProviders)({ hostKey: "h", providerIds, setDefault: true }), { errorCode: "INVALID_ARGUMENT" });}});+++test("remote folder selection crosses IPC, registers on the Host, and creates a remote session", async () => {+ const f = fixture();+ const handlers = new Map();+ registerRemoteSessionIpc({ handle: (channel, fn) => handlers.set(channel, fn) }, () => f.catalog);+ const browse = handlers.get(IPC.invoke.remoteHostBrowseProjects);+ const home = await browse({ hostKey: "h1" });+ assert.deepEqual(home, { path: "/home/pi", entries: [{ name: "app", path: "/home/pi/app" }] });+ assert.deepEqual(f.calls[0], { method: "project/browse", params: {} });+ await browse({ hostKey: "h1", path: "/home/pi/app" });+ assert.deepEqual(f.calls[1], { method: "project/browse", params: { path: "/home/pi/app" } });+ const { project } = await handlers.get(IPC.invoke.remoteHostRegisterProject)({ hostKey: "h1", path: home.entries[0].path });+ const { session: created } = await handlers.get(IPC.invoke.remoteHostCreateSession)({ hostKey: "h1", projectId: project.id });+ assert.equal(created.id, "remote:h1:s1");+ assert.equal(created.projectPath, undefined);+ assert.equal(created.remoteProjectId, project.id);+ const count = f.calls.length;+ for (const request of [null, { hostKey: "bad:key" }, { hostKey: "h1", path: "relative" }, { hostKey: "h1", path: "" }, { hostKey: "h1", path: "/bad\0path" }, { hostKey: "h1", path: "/" + "x".repeat(4096) }]) {+ await assert.rejects(browse(request), { errorCode: "INVALID_ARGUMENT" });+ }+ assert.equal(f.calls.length, count);+ f.disconnect();+ await assert.rejects(browse({ hostKey: "h1" }), { errorCode: "AGENT_UNAVAILABLE" });+ assert.equal(f.calls.length, count);+});++test("remote folder browse rejects malformed Host data and stale connection results", async () => {+ let result;+ let finish;+ let host = { hostKey: "h", label: "H", client: { request: async () => result }, connection: { ensureSession: async () => {} } };+ const catalog = createRemoteSessionCatalog({ getHost: () => host });+ for (result of [null, { path: "local", entries: [] }, { path: "/home", parent: "relative", entries: [] }, { path: "/home", entries: Array(501).fill({ name: "app", path: "/home/app" }) }, { path: "/home", entries: [{ name: "../secret", path: "/secret" }] }, { path: "/home", entries: [{ name: "secret", path: "/elsewhere/secret" }] }, { path: "/home", entries: [{ name: "bad\0name", path: "/home/bad" }] }]) {+ await assert.rejects(catalog.browseProjects("h"), { errorCode: "INVALID_ARGUMENT" });+ }+ result = { path: "/home/pi", parent: "/home", entries: [] };+ assert.deepEqual(await catalog.browseProjects("h"), result);+ host.client.request = () => new Promise((resolve) => { finish = resolve; });+ const pending = catalog.browseProjects("h");+ host = { ...host, client: { request: async () => result } };+ finish(result);+ await assert.rejects(pending, { errorCode: "AGENT_UNAVAILABLE" });+});++const { createTranscriptReadingRuntime } = await import("../src/stores/runtime/transcript-reading-runtime.ts");+const { transcriptViewMessages } = await import("../src/lib/transcript-reading.ts");++function transcriptReader(initial, read) {+ const id = initial.id;+ let state = {+ activeSessionId: id, messages: initial.messages,+ sessionHistory: { [id]: { messageStart: initial.messageStart, hasMoreBefore: initial.hasMoreBefore } },+ transcriptViews: {}, retainedSessionIds: [id], retainedTranscripts: {}, runningSessions: {},+ showToast: (error) => assert.fail(error),+ };+ const access = { get: () => state, set: (patch) => {+ state = { ...state, ...(typeof patch === "function" ? patch(state) : patch) };+ } };+ const runtime = createTranscriptReadingRuntime(access, read);+ return { ...runtime.actions, get: () => state,+ visible: () => transcriptViewMessages(state.messages, state.transcriptViews[id]) };+}++test("shared transcript reader pages real remote history and returns to the live latest window", async () => {+ const f = fixture();+ const original = f.client.request.bind(f.client);+ f.client.request = async (method, params) => {+ if (method !== "session/history") return original(method, params);+ f.calls.push({ method, params });+ if (params.beforeItemId === "m2") return { items: [item("m1", "Earlier")], hasMore: true };+ assert.equal(params.beforeItemId, "m1");+ return { items: [item("m0", "Oldest")], hasMore: false };+ };+ const id = "remote:h1:s1";+ const read = (sessionId, options) => f.backend.invoke(IPC.invoke.sessionGet, [{ id: sessionId, ...options }]);+ const initial = (await read(id, { messageLimit: 1 })).session;+ const r = transcriptReader(initial, read);+ const live = r.get().messages;+ await r.loadTranscriptPage(id, "before");+ assert.deepEqual(r.visible().map((message) => message.id), ["m1", "m2"]);+ await r.loadTranscriptPage(id, "before");+ assert.deepEqual(r.visible().map((message) => message.id), ["m0", "m1", "m2"]);+ assert.equal(r.get().transcriptViews[id].hasMoreBefore, false);+ assert.equal(r.get().messages, live, "history reads do not replace live/model input");+ assert.deepEqual(f.calls.filter((call) => call.method === "session/history").map((call) => call.params.beforeItemId), ["m2", "m1"]);+ r.returnToLatestTranscript(id);+ assert.equal(r.get().transcriptViews[id], undefined);+ assert.equal(r.visible(), live);+ await r.loadTranscriptPage(id, "before");+ assert.equal(f.calls.filter((call) => call.method === "session/history").at(-1).params.beforeItemId, "m2");+});++test("remote reading preserves opaque cursor identity without sorting or forward arithmetic", async () => {+ const id = "remote:h1:s1";+ const cursors = [];+ const r = transcriptReader({ id, messages: [{ id: "tail", role: "assistant", content: "latest" }], messageStart: 100, hasMoreBefore: true }, async (_id, options) => {+ cursors.push(options.messageBefore);+ return { session: { id, source: "remote", messages: [{ id: `old-${cursors.length}`, role: "assistant", content: "old" }], messageStart: 800, hasMoreBefore: true, hasMoreAfter: true } };+ });+ await r.loadTranscriptPage(id, "before");+ await r.loadTranscriptPage(id, "after");+ await r.loadTranscriptPage(id, "before");+ assert.deepEqual(cursors, [100, 800]);+ assert.equal(r.get().transcriptViews[id].hasMoreAfter, false);+});diff --git a/apps/desktop/test/remote-unified-chat.test.mjs b/apps/desktop/test/remote-unified-chat.test.mjsnew file mode 100644index 000000000..6de4982c0--- /dev/null+++ b/apps/desktop/test/remote-unified-chat.test.mjs@@ -0,0 +1,150 @@+import assert from "node:assert/strict";+import test from "node:test";+import { createElement } from "react";+import { slotSsr } from "./helpers/slot-ssr.mjs";+import { composerToolbar } from "./helpers/composer-toolbar.mjs";++const remote = {+ id: "remote:host:session", source: "remote", remoteHostLabel: "Linux host",+ remoteWorkspaceLabel: "/srv/remote-app", title: "Remote task", messageCount: 0,+ mode: "agent", thinkingLevel: "off", permissionMode: "ask",+ capabilities: { canPrompt: true, canStop: true, canRefresh: true, canAttach: false, canUseLocalTools: false, canConfigureModel: false },+};++test("remote home and transcript use the regular composer without local workspace identity", async (t) => {+ const ssr = await slotSsr(t);+ globalThis.window = { piDesktop: { platform: "darwin" }, matchMedia: () => ({ matches: false }) };+ t.after(() => { delete globalThis.window; });+ const { useAppStore } = await ssr.load("/src/stores/app-store.ts");+ Object.assign(useAppStore.getInitialState(), {+ sessions: [remote], activeSessionId: remote.id, retainedSessionIds: [remote.id],+ workspace: { path: "/local/app", name: "LOCAL MUST NOT APPEAR" }, messages: [],+ });+ const { ChatSurface } = await ssr.load("/src/components/ChatSurface.tsx");+ const home = ssr.render(createElement(ChatSurface), { sessionId: null });+ assert.match(home, /remote-app/);+ assert.doesNotMatch(home, /LOCAL MUST NOT APPEAR/);+ assert.match(home, /data-composer-dock="home"/);+ assert.doesNotMatch(home, /remote-conversation/);+ Object.assign(useAppStore.getInitialState(), {+ messages: [{ id: "u1", role: "user", content: "Remote question", createdAt: 1 }],+ });+ const transcript = ssr.render(createElement(ChatSurface), { sessionId: null });+ assert.match(transcript, /data-session-pane="remote:host:session"/);+ assert.match(transcript, /Remote question/);+ assert.match(transcript, /data-composer-dock="docked"/);+ assert.doesNotMatch(transcript, /aria-label="Edit message"|aria-label="Delete message"/);+});++test("remote toolbar preserves send and stop while disabling local controls and plugin slots", async (t) => {+ const ssr = await slotSsr(t);+ ssr.register("example", { slot: "composerControl", side: "left", component: () => createElement("span", null, "LOCAL PLUGIN") });+ const render = await composerToolbar(t, ssr, {+ localToolsAllowed: false, attachmentsAllowed: false, controlsBlocked: true,+ hasDraftContent: true, modelReady: true, workSessionId: remote.id,+ });+ const html = render();+ assert.doesNotMatch(html, /LOCAL PLUGIN/);+ assert.match(html, /aria-label="chat.addFiles"[^>]*disabled/);+ assert.match(html, /aria-label="chat.send"/);+ const stop = await composerToolbar(t, ssr, {+ localToolsAllowed: false, controlsBlocked: true, runActive: true, hasDraftContent: false,+ stopAllowed: false,+ });+ assert.match(stop(), /aria-label="chat.stopGenerating"[^>]*disabled/);+});++test("remote submission sends slash text unchanged and rejects steering without local command dispatch", async (t) => {+ const ssr = await slotSsr(t);+ const { useComposerSubmit } = await ssr.load("/src/features/chat/composer/hooks/useComposerSubmit.ts");+ const calls = [];+ const draft = {+ ref: { current: null }, draftRevision: () => 1,+ draftSnapshot: (text) => ({ text, fileReferences: [] }),+ clearDraftForKey: (...args) => calls.push(["clear", ...args]),+ restoreDraftForKey: (...args) => calls.push(["restore", ...args]),+ };+ const controller = useComposerSubmit({+ value: "/compact", draftKey: remote.id, activeSessionId: remote.id,+ modelReady: true, sendBlocked: false, localCommandsAllowed: false, steeringAllowed: false,+ invalidateComposerTransforms() {}, pasting: false, activeFileReferences: [],+ t: (key) => key, showToast() {}, draft,+ sendPrompt: async (text, snapshot, id) => { calls.push(["prompt", text, id]); return true; },+ steerPrompt: async () => { throw new Error("remote steering must remain blocked"); },+ });+ await controller.submit();+ assert.deepEqual(calls.find((call) => call[0] === "prompt"), ["prompt", "/compact", remote.id]);+ const before = calls.length;+ await controller.submit(true);+ assert.equal(calls.length, before);+});++test("remote Read/Write tool rows stay readable and retained panes cannot open local files or rollback", async (t) => {+ const ssr = await slotSsr(t);+ const calls = [];+ globalThis.window = {+ piDesktop: { platform: "darwin", invoke: async (...args) => { calls.push(args); throw new Error("remote must not call local host"); }, on: () => () => {} },+ matchMedia: () => ({ matches: false }),+ };+ t.after(() => { delete globalThis.window; });+ const { useAppStore } = await ssr.load("/src/stores/app-store.ts");+ const state = { sessions: [remote, { id: "local", title: "Local" }], activeSessionId: "local", workspace: { path: "/local/private" } };+ useAppStore.setState(state);+ Object.assign(useAppStore.getInitialState(), state);+ const { ToolRow } = await ssr.load("/src/features/chat/transcript/ToolRow.tsx");+ const { ReviewChangeCard } = await ssr.load("/src/components/ReviewChangeCard.tsx");+ const { TranscriptDisclosureProvider } = await ssr.load("/src/features/chat/transcript/disclosure.tsx");+ const tool = (toolName) => ({ id: toolName, role: "tool", toolName, toolStatus: "success", toolArgs: { path: "/srv/remote-app/README.md", content: "remote file" }, content: "done", createdAt: 1 });+ for (const toolName of ["Read", "Write"]) {+ const html = ssr.render(createElement(TranscriptDisclosureProvider, null, createElement(ToolRow, { message: tool(toolName) })), { sessionId: remote.id });+ assert.match(html, /README.md/);+ assert.doesNotMatch(html, /local\/private|pi-plugin-slot/);+ }+ const write = { ...tool("Write"), toolResult: { details: { root: "workspace", review: {+ version: 1, snapshotId: "remote-snapshot", messageId: "Write", path: "README.md", operation: "write", status: "modified", state: "applied", additions: 1, deletions: 0, reversible: true, hunks: [],+ } } } };+ const review = ssr.render(createElement(ReviewChangeCard, { message: write }), { sessionId: remote.id });+ assert.doesNotMatch(review, /review-change-rollback"/);+ const { useOpenPreviewTarget, useOpenChatFileRef } = await ssr.load("/src/hooks/use-preview-target.ts");+ let openTarget, openFile;+ function Probe() { openTarget = useOpenPreviewTarget(); openFile = useOpenChatFileRef(); return null; }+ ssr.render(createElement(Probe), { sessionId: remote.id });+ openTarget({ kind: "file", path: "/local/private/secret" });+ openTarget({ kind: "session", sessionId: "local" });+ await openFile("/local/private/secret");+ assert.deepEqual(calls, []);+ assert.equal(useAppStore.getState().activeSessionId, "local");+});++test("remote Markdown links remain copyable text and callbacks cannot open local URL targets", async (t) => {+ const ssr = await slotSsr(t, { plugins: [{ name: "markdown-callback-probe", transform(source, id) {+ if (id.endsWith("/components/Markdown.tsx")) return source + "\nexport { Anchor as ProbeAnchor, InlineCode as ProbeInlineCode };";+ } }] });+ const calls = [];+ globalThis.window = { piDesktop: { platform: "darwin", invoke: async (...args) => { calls.push(args); return { ok: true, data: {} }; } }, matchMedia: () => ({ matches: false }) };+ t.after(() => { delete globalThis.window; });+ const { useAppStore } = await ssr.load("/src/stores/app-store.ts");+ const state = { sessions: [remote], activeSessionId: remote.id, workspace: { path: "/local/private" }, openUrlInWorkPanel: (...args) => calls.push(args) };+ useAppStore.setState(state);+ Object.assign(useAppStore.getInitialState(), state);+ const { Markdown, ProbeAnchor, ProbeInlineCode } = await ssr.load("/src/components/Markdown.tsx");+ const html = ssr.render(createElement(Markdown, { source: "[Remote docs](https://example.test/docs) and `https://example.test/code`" }), { sessionId: remote.id });+ assert.match(html, /Remote docs/);+ assert.match(html, /https:\/\/example.test\/code/);+ assert.doesNotMatch(html, /href="https:|chat-code-link/);+ let onClick;+ function Probe() {+ const anchor = ProbeAnchor({ href: "https://example.test/docs", children: "Remote docs" });+ onClick = anchor.props.children[0].props.onClick;+ const code = ProbeInlineCode({ children: "https://example.test/code" });+ assert.equal(code.type, "code");+ return anchor;+ }+ ssr.render(createElement(Probe), { sessionId: remote.id });+ for (const modified of [false, true]) {+ let prevented = false;+ onClick({ metaKey: modified, preventDefault() { prevented = true; } });+ assert.equal(prevented, true, "modifier links must not escape through native browser navigation");+ }+ assert.deepEqual(calls, []);+});diff --git a/apps/pi-host/README.md b/apps/pi-host/README.mdindex 8e0e45460..36940aebe 100644--- a/apps/pi-host/README.md+++ b/apps/pi-host/README.md@@ -12,18 +12,22 @@ Use a Desktop and Host bundle built from the same candidate.2. Add an SSH host using your existing SSH key/configuration, or password wheresupported. Bootstrap downloads the same-version platform bundle and verifiesthe published checksum. The server needs Node and outbound release access.-3. Open **Conversations / New conversation** on the connected host.-4. Select eligible model configurations and explicitly consent to copying their+3. If the Host needs a model, open **Conversations / New conversation** on the+ connected host. Select eligible model configurations and explicitly consent to copying theirAPI credentials to that host. Optionally set its default model. OAuth,CLI/plugin providers and local-only endpoints are excluded. Direct URL pairingdoes not offer credential copy.-5. Select a registered project, or enter an existing absolute remote project path.- Create a conversation (Agent mode, Ask permissions).+4. Return to Chat home and open **Create project → Remote**. Choose the connected+ host, select an existing project, browse a directory, or enter an absolute+ remote path. Creation opens an empty chat in the usual home layout (Agent+ mode, Ask permissions). Project labels follow the remote directory name.+5. Use the home project switcher or the sidebar's remote project group to reopen+ it or start another chat. Chats stay bound to that host and project.6. Send text, approve/deny tools, answer questions, and inspect read-only Files /Review. Remote paths never activate a local workspace. Reconnect recoverssubscriptions and pending requests without resending the turn.-The UI does not offer remote terminal, attachments, local model controls,+The regular Composer and transcript are shared with local chats. The UI does not offer remote terminal, attachments, local model controls,message edits, Plan/Goal creation, desktop plugin/MCP relay or cross-host handoff.This is not full R2 acceptance.diff --git a/apps/pi-host/src/host-operations.test.ts b/apps/pi-host/src/host-operations.test.tsindex e077a890b..bcb670c2a 100644--- a/apps/pi-host/src/host-operations.test.ts+++ b/apps/pi-host/src/host-operations.test.ts@@ -1,4 +1,4 @@-import { mkdtemp, realpath, rm } from "node:fs/promises";+import { mkdir, mkdtemp, realpath, rm, symlink } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";import { afterEach, describe, expect, it } from "vitest";@@ -91,6 +91,32 @@ describe("pi-host operations over host-core", () => {await expect(operations.projects.browse("/")).rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });});+ it("canonicalizes a symlink browse root without allowing symlink escapes", async () => {+ const scratch = await realpath(await mkdtemp(join(tmpdir(), "pi-host-browse-root-")));+ dirs.push(scratch);+ const root = join(scratch, "root");+ const linkedRoot = join(scratch, "linked-root");+ const outside = join(scratch, "outside");+ await mkdir(join(root, "work"), { recursive: true });+ await mkdir(outside);+ await symlink(root, linkedRoot, "dir");+ await symlink(outside, join(root, "escape"), "dir");+ const operations = createHostOperations({+ getHost: () => fakeHost([], root),+ runtime: { compact: async () => ({ accepted: true }), isBusy: () => false },+ browseRoot: linkedRoot,+ });+ const top = await operations.projects.browse();+ expect(top).toEqual({ path: root, entries: [{ name: "work", path: join(root, "work") }] });+ const nested = await operations.projects.browse(top.entries[0]!.path);+ expect(nested).toEqual({ path: join(root, "work"), parent: root, entries: [] });+ expect(await operations.projects.browse(linkedRoot)).toEqual(top);+ await expect(operations.projects.browse(join(linkedRoot, "escape")))+ .rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });+ await expect(operations.projects.browse(outside))+ .rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });+ });+it("serves workspace reads against the session root and refuses escapes", async () => {const root = await realpath(await mkdtemp(join(tmpdir(), "pi-host-ops-")));dirs.push(root);diff --git a/apps/pi-host/src/host-operations.ts b/apps/pi-host/src/host-operations.tsindex b92965cdc..9e7358cd0 100644--- a/apps/pi-host/src/host-operations.ts+++ b/apps/pi-host/src/host-operations.ts@@ -195,7 +195,7 @@ export function createProjectCatalog(deps: HostOperationsDeps): RacpProjectCatalreturn { ...projectSummary(result.project), path: result.project.path };},async browse(path) {- const target = path ? await canonicalDirectory(path) : browseRoot;+ 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");diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 4861b8518..7dc525eee 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -22,6 +22,7 @@ Each ADR includes:|---|---|---|| s3-only-configuration-backup-sync | [S3-only encrypted configuration backup and synchronization](s3-only-configuration-backup-sync.md) | Accepted; supersedes WebDAV decisions in 0300 / 0301 || remote-provider-import | [Explicit provider import into a running remote Host](remote-provider-import.md) | Accepted for the experimental SSH MVP |+| remote-project-home-workflow | [Remote projects in the shared Chat home workflow](remote-project-home-workflow.md) | Accepted || composer-mcp-invocations | [Composer MCP Invocations](composer-mcp-invocations.md) | Accepted || chronological-system-transcript | [Preserve chronological model system state](chronological-system-transcript.md) | Accepted || mcp-tool-approval-risk | [User MCP tools keep the normal approval path](mcp-tool-approval-risk.md) | Accepted |diff --git a/docs/adr/remote-project-home-workflow.md b/docs/adr/remote-project-home-workflow.mdnew file mode 100644index 000000000..8b221de61--- /dev/null+++ b/docs/adr/remote-project-home-workflow.md@@ -0,0 +1,66 @@+# ADR: Remote projects in the shared Chat home workflow++- Status: Accepted+- Date: 2026-10-11+- Related: ADR 0286, ADR 0292,+ [remote Agent Control](../spec/02-architecture/05-remote-agent-control.md)++## Context++The experimental remote client already registers Host directories and routes+session operations over RACP. Its project creation entry point lived in Settings,+and opening a remote chat replaced the regular chat surface with a separate+text-only conversation UI. Users could not create a remote project from home or+switch between local and remote projects through the usual project controls.++Remote paths cannot be reused as local workspace paths. The two machines can+have identical directory names, and a retained remote transcript must never+authorize a file/plugin operation against the currently visible local workspace.++## Decision++Use the existing Create project dialog and shared ChatSurface, Composer, and+retained transcript panes for remote projects. The dialog selects a connected+Host, an existing remote project, or a directory on that Host. An additive+Desktop-only `remoteHostBrowseProjects` IPC channel exposes the Host's existing+`project/browse` operation; it does not add a RACP method or protocol version.++Electron main validates the host/path input and directory response. The Host+retains its canonical directory containment and browse-root policy. Default and+explicit browse paths both canonicalize before containment checks so a browse+root reached through a directory symlink has the same behavior as its real path.++Identify a remote project with the pair `(hostKey, projectId)`. Home and sidebar+selection call remote session creation directly; they never place a remote path+in local project state or activate a local workspace. New chat reuses only an+empty, idle, unsubmitted chat within that identity. An in-flight creation cannot+take focus after a newer navigation intent, and duplicate requests share a promise.+Successful creation remains discoverable even if the user has navigated away.++Use session capabilities at Composer and transcript action boundaries. Remote+text, tools, permissions, and input cards use the shared rendering path, while+local attachment staging, commands, plugins, file/image resolution, previews,+rollback, and unsupported configuration or subagent actions remain unavailable.+Retained panes authorize against their own session rather than the visible one.+History forwards the Host's session-owned cursors without offset arithmetic.++## Alternatives++- Add another home shortcut to the Settings workbench: simpler, but leaves+ different creation, project switching, and conversation workflows.+- Treat remote paths as local project paths: rejected because identity collisions+ and workspace activation would cross the machine and security boundary.+- Enable all local controls for remote chats: rejected because the current Host+ capability profile does not implement those operations or desktop-tool relay.++## Consequences++No persisted database, Plugin SDK, Host wire protocol, provider ownership, or+process architecture changes. Local projects and concurrent local work remain+unchanged. Remote project labels still come from Host directory names, and+unsupported features remain disabled; this is not full R2 feature acceptance.++Validation covers real dialog/Composer/project-switching interactions with+isolated IPC fixtures, retained-pane action guards, opaque history cursors, and+a packaged Host directory-selection-to-agent-turn path with a local model fixture.+Real SSH bootstrap and release acceptance remain separate scenarios.diff --git a/docs/spec/02-architecture/05-remote-agent-control.md b/docs/spec/02-architecture/05-remote-agent-control.mdindex 8b16194f4..0409e216c 100644--- a/docs/spec/02-architecture/05-remote-agent-control.md+++ b/docs/spec/02-architecture/05-remote-agent-control.md@@ -179,12 +179,27 @@ Host uses its existing Rust RPC connection; the CLI never starts another databaswriter. Configuration and credentials never cross RACP or return to the renderer.See `docs/adr/remote-provider-import.md` and security §3.5.-**Experimental desktop MVP.** The current narrow client opens remote projects-and Agent/Ask sessions, sends text, answers tool/input requests, and reads bounded-history and workspace text/diffs. Sessions retain remote identity even offline;+**Experimental desktop MVP.** Chat home uses the shared Create project dialog+for local folders, Git checkouts, and connected remote hosts. Remote selection+lists registered projects, browses Host-owned directories under the Host's+existing browse root, and accepts an explicit absolute remote path. Registration+and session creation execute on that Host; remote project names remain Host-owned+directory labels. The home switcher and sidebar expose remote projects by their+host/project identity, so equal directory names on different hosts remain distinct.+New chat reuses an empty chat only within that remote project and never activates+its path locally. Remote chats use the regular home, Composer, retained transcript+panes, and permission/input cards, with unsupported controls disabled by capabilities.+The client opens Agent/Ask sessions, sends text, and reads bounded history and+workspace text/diffs. Sessions retain remote identity even offline;remote paths are labels, never local workspace activation targets. Missing remotebackends or unsupported actions fail closed. Local model configuration, attachments,message edits, local tools, terminal UI, and cross-host handoff are unavailable.+Remote chat rendering cannot invoke local plugin slots, local slash commands,+file previews, attachment staging, or local image resolution. Remote history+cursors are session-owned opaque values even when represented as numbers; the+renderer forwards returned cursors without local offset arithmetic or ordering.+The additive `remoteHostBrowseProjects` Desktop IPC forwards only validated+Host/path input to `project/browse` and validates returned directory entries.The broader R2 target below is not an acceptance claim for this slice.Reconnect rebuilds SSH forwarding and RACP subscriptions, acknowledges durablediff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.mdindex 8a96b622e..24a8517fa 100644--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@ -174,10 +174,19 @@ destination, chat as the home surface, tools and permissions inline.- Empty state: a restrained hero title ("What can I help you build?" — an openproject turns its name into a dotted-underlineswitcher that lists the sidebar's open projects, can search them, can- clone a git repository from a syntactically public remote (ADR 0247 / D416), and can open another local folder), an optional first-run+ clone a git repository from a syntactically public remote (ADR 0247 / D416), and can open another local folder or a remote project on a connected host), an optional first-runchecklist, and a bottom-reserved composer. Task entry starts directly in the composer; noredundant supporting paragraph, developer starter cards, or contextualquick-action row is rendered (D204/D206).+- Create project uses one dialog with local folder, Git, and remote host sources.+ Remote selection offers a connected-host chooser, existing projects, directory+ browsing, and an absolute path field. Remote project labels follow the Host's+ directory name. Successful remote selection opens its empty chat in the same+ home layout and Composer as local selection. The sidebar groups its chats under+ the remote project and host; New chat keeps that host/project identity. Local+ and remote projects remain distinct even if their directory names match.+ Unsupported remote controls remain disabled; remote paths never reach local+ directory pickers, workspace activation, file previews, or plugin actions.- With transcript: message stream + tool disclosure rows (D071), a contextualmessage-scoped review card immediately after each successful workspaceWrite/Edit row, docked composer, and a session-scoped permission card inline.diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex 68d9bdf88..4a6297bf6 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -14528,6 +14528,34 @@ browser milestones are scheduled.- **Status**: Automated narrow-MVP scenario. Linux `sshd`, release download,password authentication and full R2 remain separately gated by E2E-231.+#### E2E-REMOTE-HOME: Create and continue a remote project from Chat home++- **Preconditions**: Isolated Desktop/Chromium profile, two connected SSH host+ fixtures, existing local workspace, and remote directory/project IPC fixtures.+ No production Host, user profile, credentials, or paid model calls.+- **Steps**: Open Create project from home, select Remote, change hosts while+ directory browsing is pending, browse and select a remote directory, then+ create. Send text through the regular Composer and inspect the transcript.+ Reopen the project and start New chat; repeat with an existing remote project.+ Disconnect and retry. Review a remote permission request and resolve it.+- **Expected**: Late responses cannot replace the newly selected Host. Creation+ registers and creates once on the selected Host, then shows the same empty+ home and docked transcript layout as local chats. Remote projects are listed+ by host/project identity in the home switcher and sidebar. Empty chat reuse+ never crosses hosts. Local workspace remains unchanged; remote paths never+ enter local activation, attachment, preview, slash-command, or plugin calls.+ Offline/unsupported actions fail closed, preserve drafts, and never replay.+ History forwards opaque session cursors and Return to latest restores live rows.+- **Specs**: `02-architecture/05-remote-agent-control.md`, `04-ux/01-ui-ia.md`.+- **Acceptance / milestone**: Home remote-project UX; additive Desktop IPC only,+ no Host wire protocol, persisted data, or R2 SSH acceptance change.+- **Automation**: `remote-project-session.test.mjs`,+ `remote-session-user-path.test.mjs`, `remote-unified-chat.test.mjs`,+ `transcript-reading.test.mjs`, `remote-project-dialog-user-path.test.mjs`,+ and `scripts/e2e-remote-mvp-ui.mjs`.+- **Status**: Component/service and main-routing acceptance; real SSH release+ validation remains the separately provisioned E2E-231 scenario.+#### E2E-231: The desktop drives a remote Host over an SSH tunnel- **Preconditions**: A Linux test machine runs `sshd` and holds a projectdiff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 1413c1703..ce637841e 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -225,6 +225,7 @@ export const IPC = {remoteHostBootstrap: "pi-desktop/remoteHost/bootstrap",remoteHostReconnect: "pi-desktop/remoteHost/reconnect",remoteHostProjects: "pi-desktop/remoteHost/projects",+ remoteHostBrowseProjects: "pi-desktop/remoteHost/browseProjects",remoteHostRegisterProject: "pi-desktop/remoteHost/registerProject",remoteHostSessions: "pi-desktop/remoteHost/sessions",remoteHostCreateSession: "pi-desktop/remoteHost/createSession",diff --git a/packages/shared/src/types/remote-host.ts b/packages/shared/src/types/remote-host.tsindex 662d6688c..7a6a62594 100644--- a/packages/shared/src/types/remote-host.ts+++ b/packages/shared/src/types/remote-host.ts@@ -144,6 +144,13 @@ export type RemoteHostBootstrapResult = {/** Remote filesystem paths are interpreted by the Host, never by Desktop. */export type RemoteHostProjectsRequest = { hostKey: string };export type RemoteHostProjectsResult = { projects: RacpProjectSummary[] };+/** Remote Host paths are display/selection data, never local workspace targets. */+export type RemoteHostBrowseProjectsRequest = { hostKey: string; path?: string };+export type RemoteHostBrowseProjectsResult = {+ path: string;+ parent?: string;+ entries: { name: string; path: string }[];+};export type RemoteHostRegisterProjectRequest = { hostKey: string; path: string };export type RemoteHostRegisterProjectResult = { project: RacpProjectSummary & { path?: string } };export type RemoteHostSessionsRequest = { hostKey: string };diff --git a/scripts/e2e-remote-mvp-ui.mjs b/scripts/e2e-remote-mvp-ui.mjsindex 97919c181..11844c97b 100644--- a/scripts/e2e-remote-mvp-ui.mjs+++ b/scripts/e2e-remote-mvp-ui.mjs@@ -19,12 +19,18 @@ try {entryPoints: [join(root, "scripts/e2e/remote-mvp-ui.jsx")], outfile: join(temp, "renderer.js"),bundle: true, platform: "browser", format: "iife", jsx: "automatic",define: { "process.env.NODE_ENV": '"production"', "import.meta.env.DEV": "false" },- loader: { ".css": "empty" },+ loader: { ".css": "empty", ".gif": "dataurl", ".png": "dataurl" },+ plugins: [{ name: "fixture-vite-url", setup(builder) {+ builder.onResolve({ filter: /\?url$/ }, ({ path }) => ({ path, namespace: "fixture-url" }));+ builder.onLoad({ filter: /.*/, namespace: "fixture-url" }, ({ path }) => ({ contents: `export default ${JSON.stringify(path)};`, loader: "js" }));+ } }],alias: {"@pi-desktop/shared": join(root, "packages/shared/src/index.ts"),"@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),react: join(root, "apps/desktop/node_modules/react"),"react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),+ i18next: join(root, "apps/desktop/node_modules/i18next"),},nodePaths: [join(root, "apps/desktop/node_modules")],});diff --git a/scripts/e2e-remote-mvp.mjs b/scripts/e2e-remote-mvp.mjsindex b8a41a26a..4ff332158 100644--- a/scripts/e2e-remote-mvp.mjs+++ b/scripts/e2e-remote-mvp.mjs@@ -6,7 +6,7 @@ import assert from "node:assert/strict";import { spawn } from "node:child_process";import { createServer } from "node:http";import { EventEmitter, once } from "node:events";-import { mkdtemp, mkdir, writeFile, rm } from "node:fs/promises";+import { mkdtemp, mkdir, writeFile, rm, realpath } from "node:fs/promises";import { tmpdir } from "node:os";import { join, resolve } from "node:path";import { fileURLToPath } from "node:url";@@ -138,7 +138,14 @@ try {emit: (channel, payload) => { const event = { channel, payload }; observed.push(event); events.emit("event", event); },});assert.equal((await boot.addHost({ hostKey: "fixture", label: "Packaged Host", url, deviceToken })).connected, true);- const registered = await boot.registerProject("fixture", project);+ const directory = await boot.browseProjects("fixture");+ const chosen = directory.entries.find((entry) => entry.name === "project");+ assert.equal(chosen?.path, await realpath(project), "folder picker lists canonical Host directories");+ const nested = await boot.browseProjects("fixture", chosen.path);+ assert.equal(nested.path, chosen.path);+ assert.equal(nested.parent, directory.path);+ await assert.rejects(boot.browseProjects("fixture", "/"), "folder picker must retain its configured browse root");+ const registered = await boot.registerProject("fixture", chosen.path);const session = await boot.createSession({ hostKey: "fixture", projectId: registered.id, permissionMode: "ask" });assert.equal(session.projectPath, undefined, "remote path never becomes local workspace");const route = async (channel, input) => (await router.route(channel, [input])).value;@@ -160,7 +167,7 @@ try {await route(IPC.invoke.workspaceDiff, { sessionId: session.id });await boot.removeHost("fixture");await assert.rejects(route(IPC.invoke.agentPrompt, { sessionId: session.id, content: "must not run locally" }), { errorCode: "AGENT_UNAVAILABLE" });- console.log("PASS packaged Host: import/reimport, pair, project, session, prompt, approval across reconnect, file read, diff, removal");+ console.log("PASS packaged Host: import/reimport, pair, browse/select/register project, session, prompt, approval across reconnect, file read, diff, removal");} catch (error) {console.error(error);console.error(hostLog);diff --git a/scripts/e2e/remote-mvp-ui.jsx b/scripts/e2e/remote-mvp-ui.jsxindex 131280cf9..741b9ad03 100644--- a/scripts/e2e/remote-mvp-ui.jsx+++ b/scripts/e2e/remote-mvp-ui.jsx@@ -6,7 +6,9 @@ import { IPC } from "@pi-desktop/shared";import { remoteEn } from "../../apps/desktop/src/locales/remote";import { useAppStore } from "../../apps/desktop/src/stores/app-store";import { RemoteHostSessions } from "../../apps/desktop/src/components/settings/RemoteHostSessions";-import { RemoteConversation } from "../../apps/desktop/src/components/remote/RemoteConversation";+import { ChatSurface } from "../../apps/desktop/src/components/ChatSurface";+import { catalogs } from "@pi-desktop/i18n";+import { api } from "../../apps/desktop/src/lib/api";import { subscribeRemoteInteractions } from "../../apps/desktop/src/lib/remote-interactions";const host = { hostKey: "fixture", label: "Test Host", transport: "ssh", connected: true };@@ -32,6 +34,10 @@ window.piDesktop = {else if (channel === IPC.invoke.remoteHostRegisterProject) data = { project: { id: "project", label: "Project" } };else if (channel === IPC.invoke.remoteHostCreateSession) data = { session };else if (channel === IPC.invoke.sessionGet) data = { session: { ...session, messages: [] } };+ else if (channel === IPC.invoke.agentPrompt) {+ queueMicrotask(() => useAppStore.setState({ isRunning: false, runningSessions: {}, messages: [{ id: "remote-u1", role: "user", content: input.content, createdAt: Date.now() }] }));+ data = { accepted: true };+ }else if (channel === IPC.invoke.plansPending) data = { plans: [] };else if (channel === IPC.invoke.remoteHostReconnect) {if (++reconnects === 1) return { ok: false, error: { message: "Fixture reconnect failure", code: "AGENT_UNAVAILABLE" } };@@ -64,11 +70,11 @@ function emit(payload) { for (const listener of listeners.get(IPC.event.remoteInfunction Fixture() {const active = useAppStore(state => state.activeSessionId);const current = useAppStore(state => state.sessions.find(item => item.id === active));- return current ? <RemoteConversation key={current.id} session={current} /> : <RemoteHostSessions host={host} onClose={() => {}} />;+ return current ? <ChatSurface /> : <RemoteHostSessions host={host} onClose={() => {}} />;}globalThis.remoteMvpProbe = async () => {- await i18n.use(initReactI18next).init({ lng: "en", fallbackLng: "en", resources: { en: { remote: remoteEn } }, interpolation: { escapeValue: false } });+ await i18n.use(initReactI18next).init({ lng: "en", fallbackLng: "en", resources: { en: { remote: remoteEn, translation: catalogs.en } }, interpolation: { escapeValue: false } });useAppStore.setState({ sessions: [], activeSessionId: undefined, selectingSessionId: undefined, messages: [], retainedSessionIds: [], retainedTranscripts: {}, sessionHistory: {}, sessionMeta: {}, runningSessions: {}, pendingPlans: {}, pendingPermissions: {}, pendingAsks: {}, planningStates: {}, providers: [provider], workspace: { path: "/local/private", name: "Local only" }, activeProjectPath: "/local/private", page: "settings", settings: { defaultMode: "agent" } });const unsubscribe = subscribeRemoteInteractions();const root = createRoot(document.getElementById("root"));@@ -88,27 +94,31 @@ globalThis.remoteMvpProbe = async () => {type(input(remoteEn.path), "/srv/project");await until(() => !button(remoteEn.create).disabled, "project input did not enable create");button(remoteEn.create).click();- await until(() => document.querySelector(".remote-conversation"), "created session did not open");+ await until(() => document.querySelector(".chat-surface"), "created session did not open");assert(useAppStore.getState().workspace.path === "/local/private", "remote selection changed local workspace");- type(input(remoteEn.prompt), "Inspect remote project");- await until(() => !button(remoteEn.send).disabled, "prompt input did not enable send");- button(remoteEn.send).click();- await until(() => calls.some(call => call.channel === IPC.invoke.agentPrompt) && input(remoteEn.prompt).value === "" && !input(remoteEn.prompt).disabled, "send did not finish");+ const editor = document.querySelector(".composer-input");+ editor.textContent = "Inspect remote project";+ editor.dispatchEvent(new InputEvent("input", { bubbles: true, inputType: "insertText", data: "Inspect remote project" }));+ const send = () => document.querySelector('[aria-label="' + catalogs.en.chat.send + '"]');+ await until(() => send() && !send().disabled, "prompt input did not enable send");+ send().click();+ await until(() => calls.some(call => call.channel === IPC.invoke.agentPrompt) && document.querySelector(".composer-input").textContent === "", "send did not finish");const permission = { sessionId: session.id, requestId: `${session.id}#racp-approval:one`, toolCallId: "", toolName: "Bash", argsPreview: null, reason: "Run fixture command", risk: "medium" };emit({ kind: "snapshot", sessionId: session.id, permissions: [permission], asks: [] });- await until(() => button(remoteEn.allow) && !button(remoteEn.allow).disabled, "approval was not ready");+ await until(() => button(catalogs.en.permission.allowOnce) && !button(catalogs.en.permission.allowOnce).disabled, "approval was not ready");assert(document.querySelector(".permission-card").textContent.includes(permission.reason), "approval summary is not visible");- button(remoteEn.allow).click();+ button(catalogs.en.permission.allowOnce).click();await until(() => !document.querySelector(".permission-card"), "approval card did not clear");assert(calls.some(call => call.channel === IPC.invoke.toolResolvePermission && call.input.decision === "allow-once"), "approval was not routed");emit({ kind: "snapshot", sessionId: session.id, permissions: [permission], asks: [] });await until(() => document.querySelector(".permission-card"), "recovery card was not restored");emit({ kind: "resolved", sessionId: session.id, requestKind: "permission", requestId: permission.requestId });await until(() => !document.querySelector(".permission-card"), "peer resolution left a stale card");- button(remoteEn.reconnect).click();- await until(() => document.querySelector('[role="alert"]'), "reconnect error was not visible");- button(remoteEn.reconnect).click();- await until(() => reconnects === 2 && !document.querySelector('[role="alert"]') && !input(remoteEn.prompt).disabled, "reconnect retry did not recover");+ let reconnectFailed = false;+ try { await api.reconnectRemoteHost(host.hostKey); } catch { reconnectFailed = true; }+ assert(reconnectFailed, "reconnect failure was not observable");+ await api.reconnectRemoteHost(host.hostKey);+ assert(reconnects === 2, "reconnect retry did not recover");assert(calls.filter(call => call.channel === IPC.invoke.agentPrompt).length === 1, "reconnect replayed a prompt");assert(!calls.some(call => [IPC.invoke.projectActivate, IPC.invoke.sessionConfigure].includes(call.channel)), "remote UI called a local workspace/model operation");root.unmount(); unsubscribe();