Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

feat(remote): keep the agent and model on Desktop for remote workspaces

vastsaabfe50a5af5f
diff --git a/apps/desktop/electron/main/bootstrap/remote-hosts.ts b/apps/desktop/electron/main/bootstrap/remote-hosts.ts
index 3e605dd23..cd3bd6f77 100644
--- a/apps/desktop/electron/main/bootstrap/remote-hosts.ts
+++ b/apps/desktop/electron/main/bootstrap/remote-hosts.ts
@@ -6,6 +6,8 @@ import {
type RemoteHostBootstrapRequest, type RemoteHostBootstrapResult,
type RemoteHostCreateSessionRequest, type RemoteHostSummary, type RemoteHostBrowseProjectsResult,
type RemoteHostSyncProvidersRequest, type RemoteHostSyncProvidersResult, type SessionSummary,
+ type CommandShellOption, isCommandShellOption,
+ type WorkspaceFilesRequest,
} from "@pi-desktop/shared";
import { wsClientTransport } from "@pi-desktop/racp";
import type { HostRpcPort } from "@pi-desktop/agent-host";
@@ -23,6 +25,11 @@ export { sshMetadataOf, sshHostRecord, transportOf } from "../remote/remote-host
export type { RemoteHostSummary };
export type RemoteHostAdapterFactory = (record: RemoteHostRecord) => RacpRemoteHostClient;
+export type RemoteWorkspaceToolInput = {
+ hostKey: string; path: string; sessionId: string; turnId: string;
+ toolCallId: string; toolName: string; args: unknown; timeoutMs?: number;
+ expectedCommandShellId?: string; expectedCommandShellDialect?: string;
+};
export type BootRemoteHostsOptions = {
dataDir: string;
encryption: EncryptionPort;
@@ -56,6 +63,10 @@ export interface RemoteHostsBoot {
registerProject(hostKey: string, path: string): Promise<RacpProjectSummary & { path?: string }>;
createSession(request: RemoteHostCreateSessionRequest): Promise<SessionSummary>;
syncProviders(request: RemoteHostSyncProvidersRequest): Promise<RemoteHostSyncProvidersResult>;
+ executeWorkspaceTool(request: RemoteWorkspaceToolInput): Promise<unknown>;
+ abortWorkspaceTool(request: { hostKey: string; sessionId: string; toolCallId: string }): Promise<void>;
+ workspaceCommandShell(hostKey: string): Promise<CommandShellOption>;
+ workspaceFiles(hostKey: string, input: WorkspaceFilesRequest): Promise<unknown>;
readonly registry: RemoteHostRegistry;
}
let activeRemoteHostsBoot: RemoteHostsBoot | null = null;
@@ -258,6 +269,61 @@ export function createRemoteHostsBoot(options: BootRemoteHostsOptions): RemoteHo
projects: catalog.projects,
browseProjects: catalog.browseProjects,
registerProject: catalog.registerProject,
+ async workspaceFiles(hostKey, input) {
+ const host = connectedHost(hostKey);
+ if (!host) throw unavailable();
+ const result = await host.adapter.client.request("workspace/files", input);
+ if (connectedHost(hostKey) !== host) throw unavailable();
+ return result;
+ },
+ async workspaceCommandShell(hostKey) {
+ const host = connectedHost(hostKey);
+ if (!host) throw unavailable();
+ const { shell } = await host.adapter.client.request<{ shell: unknown }>("workspace/toolShell", {});
+ if (connectedHost(hostKey) !== host) throw unavailable();
+ if (!isCommandShellOption(shell) || !shell.available) {
+ throw Object.assign(new Error("remote command shell unavailable"), { errorCode: "COMMAND_SHELL_INVALID" });
+ }
+ return shell;
+ },
+ async executeWorkspaceTool(input) {
+ const host = connectedHost(input.hostKey);
+ if (!host) throw unavailable();
+ const { hostKey: _hostKey, ...request } = input;
+ if (!request.path.startsWith("/") || request.path.includes("\0")
+ || !["Read", "Glob", "Grep", "Write", "Edit", "Bash"].includes(request.toolName)) {
+ throw Object.assign(new Error("invalid remote workspace tool"), { errorCode: "INVALID_ARGUMENT" });
+ }
+ const timeoutMs = input.timeoutMs ?? 60_000;
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 21_600_000) {
+ throw Object.assign(new Error("invalid remote tool timeout"), { errorCode: "INVALID_ARGUMENT" });
+ }
+ try {
+ const result = await host.adapter.client.request("workspace/toolExecute", request, timeoutMs + 15_000);
+ if (connectedHost(input.hostKey) !== host) throw unavailable();
+ if (!result || typeof result !== "object" || !("ok" in result)
+ || typeof result.ok !== "boolean" || !("content" in result)) {
+ throw Object.assign(new Error("remote host returned an invalid tool result"), { errorCode: "INVALID_ARGUMENT" });
+ }
+ return result;
+ } catch (error) {
+ // A timeout/disconnection never replays a side effect. Cancel on the
+ // original connection only; a replacement connection owns no such call.
+ if (connectedHost(input.hostKey) === host) {
+ try { await host.adapter.client.request("workspace/toolAbort", {
+ sessionId: input.sessionId, toolCallId: input.toolCallId,
+ }); } catch (abortError) { log("warn", "remote tool abort failed", { error: String(abortError) }); }
+ }
+ throw error;
+ }
+ },
+ async abortWorkspaceTool(input) {
+ const host = connectedHost(input.hostKey);
+ if (!host) throw unavailable();
+ await host.adapter.client.request("workspace/toolAbort", {
+ sessionId: input.sessionId, toolCallId: input.toolCallId,
+ });
+ },
async createSession(input) {
const session = await catalog.createSession(input);
changed();
diff --git a/apps/desktop/electron/main/chat-ref-resolve.ts b/apps/desktop/electron/main/chat-ref-resolve.ts
index 9d6afa874..eccea42ac 100644
--- a/apps/desktop/electron/main/chat-ref-resolve.ts
+++ b/apps/desktop/electron/main/chat-ref-resolve.ts
@@ -1,480 +1,2 @@
-import { lstat, readdir, realpath, stat } from "node:fs/promises";
-import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
-import type {
- FsChatRefMatch,
- FsChatRefMatchKind,
- FsChatRefProjectRoot,
- FsChatRefRoot,
-} from "@pi-desktop/shared";
-import { isAttachmentBlobRef, isIgnoredName, resolveRealPathWithinRoot } from "@pi-desktop/host-runtime";
-import { getWorkspaceFileIndex } from "./fs-index.js";
-
-/**
- * Partial-path completion for a file reference the agent printed in chat.
- *
- * An agent that works on `/root/dir/openimage.js` routinely names only
- * `openimage.js` in its prose. The transcript linkified that token against the
- * workspace root alone, so the click resolved to a path that does not exist and
- * the work panel painted an empty state instead of the file.
- *
- * Resolution order is the product contract:
- *
- * 1. an absolute reference only names that exact file inside a known root;
- * 2. an `attachments/<sha256>` blob names a stored file by hash rather than
- * by path, so it resolves against the attachment store directly;
- * 3. otherwise the roots are searched in priority order — the open project
- * first, the session's own scratch store second, the attachment blob
- * store last — and the first root that answers wins, so the project is
- * searched to exhaustion before the scratch store is considered;
- * 4. inside one root an exact path beats a shorthand, and among shorthands
- * the longest matching tail wins, then the shallowest path, so
- * `src/dir/a.ts` beats a second `dir/a.ts` buried deeper.
- */
-
-export type ChatRefRoots = {
- /**
- * Every folder of the open project, primary first (ADR 0249). A single-folder
- * project is a one-element list, so callers never special-case it.
- */
- project?: readonly FsChatRefProjectRoot[] | null;
- scratch?: string | null;
- /**
- * Roots an absolute reference may name without being searched by shorthand.
- *
- * A generated image lives in the scratch store of the session that produced
- * it, and the user clicks it from whatever conversation they are reading —
- * usually a later one. Every read guard (`fsRead`, `fsOpen`, the image
- * reader, `fsReveal`) already accepts the whole scratch store, so completing
- * against the session's own store alone reported a restriction for a file the
- * app can open. These entries widen the absolute-path check only: a shorthand
- * still searches the session's own root, so it never lands in another
- * session's files.
- */
- containment?: readonly ChatRefContainmentRoot[] | null;
- attachments?: string | null;
-};
-
-/** A root an absolute reference may name, though no shorthand searches it. */
-export type ChatRefContainmentRoot = { kind: FsChatRefRoot; path: string };
-
-/** A root to search, and — for a project folder — which folder it is. */
-type ChatRefRootEntry = {
- kind: FsChatRefRoot;
- path: string;
- projectRoot?: FsChatRefProjectRoot;
-};
-
-type CanonicalChatRefRoot = ChatRefRootEntry & { realPath: string | null };
-
-const MAX_REF_LENGTH = 512;
-const ATTACHMENT_HASH_PATTERN = /^[0-9a-f]{64}$/i;
-/** A tail longer than this is a user quoting a full path, not a shorthand. */
-const MAX_FUZZY_TAIL_SEGMENTS = 6;
-/** Bound for the scratch/attachment walk; those trees are small by design. */
-const MAX_ROOT_WALK_ENTRIES = 4000;
-
-/**
- * Windows and macOS compare filenames case-insensitively; Linux does not.
- * An exact-case match still wins on a tie, so this only widens the net.
- */
-const CASE_INSENSITIVE_FS =
- process.platform === "win32" || process.platform === "darwin";
-
-function toPosix(value: string): string {
- return String(value).replaceAll("\\", "/");
-}
-
-function matchesSegment(candidate: string, wanted: string): boolean {
- if (candidate === wanted) return true;
- return CASE_INSENSITIVE_FS && candidate.toLowerCase() === wanted.toLowerCase();
-}
-
-/** Strip the composer sigil, optional quotes, and a `:line[:col]` reference. */
-function cleanRef(raw: string): string {
- let value = stripRefDecorations(String(raw ?? ""));
- if (value.includes("\0")) return "";
- value = value.replace(/:\d+(?::\d+)?$/, "");
- return value;
-}
-
-function stripRefDecorations(raw: string): string {
- let value = raw.trim();
- if (value.startsWith("@")) value = value.slice(1).trim();
- if (value.length >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
- value = value.slice(1, -1).trim();
- }
- return value;
-}
-
-export type ParsedChatRef = {
- /** Path segments with `.` dropped and `..` collapsed. */
- segments: string[];
- /** Whether the original token anchored at a filesystem root. */
- absolute: boolean;
-};
-
-/**
- * Parse a chat file token. Returns null for `~`-prefixed home paths, empty
- * tokens, oversized tokens, and any token whose `..` walk leaves the start.
- */
-export function parseChatRef(raw: string): ParsedChatRef | null {
- const value = cleanRef(raw);
- if (!value || value.length > MAX_REF_LENGTH) return null;
- if (value.startsWith("~")) return null;
-
- const posix = toPosix(value);
- const absolute =
- posix.startsWith("/") ||
- /^[a-z]:\//i.test(posix) ||
- posix.startsWith("//");
-
- const segments: string[] = [];
- for (const segment of posix.split("/")) {
- if (!segment || segment === ".") continue;
- if (segment === "..") {
- if (segments.length === 0) return null;
- segments.pop();
- continue;
- }
- segments.push(segment);
- }
- if (segments.length === 0) return null;
- return { segments, absolute };
-}
-
-/**
- * Product priority: the open project first, then session scratch, then
- * attachments. Inside the project the order is the group's own order, primary
- * first, so the folder the agent's tools default to answers before its siblings
- * — and the first root that answers still wins outright.
- */
-function orderedRoots(roots: ChatRefRoots): ChatRefRootEntry[] {
- const list: ChatRefRootEntry[] = [];
- for (const root of roots.project ?? []) {
- const path = String(root?.path ?? "").trim();
- if (!path) continue;
- list.push({ kind: "workspace", path: resolve(path), projectRoot: root });
- }
- for (const kind of ["scratch", "attachments"] as const) {
- const value = roots[kind];
- if (typeof value !== "string" || !value.trim()) continue;
- list.push({ kind, path: resolve(value) });
- }
- return list;
-}
-
-/**
- * The containment-only roots, in the same vocabulary as the searched ones.
- *
- * They answer absolute references and nothing else: the shorthand walk below
- * keeps searching `orderedRoots`, so a reference is never completed from
- * another session's store.
- */
-function containmentEntries(roots: ChatRefRoots): ChatRefRootEntry[] {
- const list: ChatRefRootEntry[] = [];
- for (const root of roots.containment ?? []) {
- const path = String(root?.path ?? "").trim();
- if (!path) continue;
- list.push({ kind: root.kind, path: resolve(path) });
- }
- return list;
-}
-
-async function isRegularFile(target: string): Promise<boolean> {
- try {
- return (await stat(target)).isFile();
- } catch {
- return false;
- }
-}
-
-/** Root-relative POSIX path, or null when `absolute` is outside `rootPath`. */
-function relativeInside(rootPath: string, absolute: string): string | null {
- const rel = relative(rootPath, absolute);
- if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
- return null;
- }
- return toPosix(rel);
-}
-
-async function canonicalRoots(roots: ChatRefRootEntry[]): Promise<CanonicalChatRefRoot[]> {
- return Promise.all(roots.map(async (root) => {
- try {
- return { ...root, realPath: await realpath(root.path) };
- } catch {
- return { ...root, realPath: null };
- }
- }));
-}
-
-function couldShareVolume(target: string, roots: CanonicalChatRefRoot[]): boolean {
- if (process.platform !== "win32") return true;
- const volume = parse(target).root.toLowerCase();
- return roots.some((root) => [root.path, root.realPath].some(
- (path) => path && parse(path).root.toLowerCase() === volume,
- ));
-}
-
-async function canonicalPathOrMissingTail(path: string): Promise<string | null> {
- let ancestor = path;
- const tail: string[] = [];
- for (;;) {
- try {
- return resolve(await realpath(ancestor), ...tail);
- } catch {
- const parent = dirname(ancestor);
- if (parent === ancestor) return null;
- tail.unshift(basename(ancestor));
- ancestor = parent;
- }
- }
-}
-
-export async function isChatRefOutsideRoots(ref: string, roots: ChatRefRoots): Promise<boolean> {
- const parsed = parseChatRef(ref);
- if (!parsed?.absolute) return false;
- const cleaned = cleanRef(ref);
- if (!isAbsolute(cleaned)) return true;
- const absolutePath = resolve(cleaned);
- const rootList = await canonicalRoots([...orderedRoots(roots), ...containmentEntries(roots)]);
- if (!couldShareVolume(absolutePath, rootList)) return true;
- const targetPath = await canonicalPathOrMissingTail(absolutePath);
- if (!targetPath) return !rootList.some((root) => relativeInside(root.path, absolutePath) !== null);
- return !rootList.some((root) =>
- root.realPath && relativeInside(root.realPath, targetPath) !== null,
- );
-}
-
-function segmentsOf(path: string): string[] {
- return toPosix(path).split("/").filter(Boolean);
-}
-
-/** Fewer segments first, then a stable lexicographic order. */
-function compareCandidates(a: string, b: string): number {
- const depthDelta = segmentsOf(a).length - segmentsOf(b).length;
- if (depthDelta !== 0) return depthDelta;
- return a.localeCompare(b);
-}
-
-function endsWithTail(fileSegments: string[], tail: string[]): boolean {
- if (fileSegments.length < tail.length) return false;
- const offset = fileSegments.length - tail.length;
- for (let index = 0; index < tail.length; index += 1) {
- if (!matchesSegment(fileSegments[offset + index], tail[index])) return false;
- }
- return true;
-}
-
-type FuzzyCandidate = { relativePath: string; matchedBy: FsChatRefMatchKind };
-
-/**
- * Longest tail first, so a two-segment shorthand beats a bare leaf name.
- * Within one tail the shallowest file wins.
- */
-function fuzzyCandidates(
- files: readonly string[],
- tails: readonly string[][],
-): FuzzyCandidate[] {
- const parsedFiles = files.map((file) => ({
- file,
- segments: segmentsOf(file),
- }));
- const candidates: FuzzyCandidate[] = [];
- const seen = new Set<string>();
- for (const tail of tails) {
- const matches = parsedFiles
- .filter((entry) => endsWithTail(entry.segments, tail))
- .map((entry) => entry.file)
- .sort(compareCandidates);
- for (const file of matches) {
- if (seen.has(file)) continue;
- seen.add(file);
- candidates.push({
- relativePath: file,
- matchedBy: tail.length === 1 ? "basename" : "path-suffix",
- });
- }
- }
- return candidates;
-}
-
-async function isContainedRegularFile(root: string, relativePath: string): Promise<boolean> {
- const realPath = await resolveRealPathWithinRoot(root, relativePath);
- return realPath !== null && isRegularFile(realPath);
-}
-
-async function hasInvalidLinkAncestor(root: string, segments: readonly string[]): Promise<boolean> {
- for (let length = 1; length <= segments.length; length += 1) {
- const prefixSegments = segments.slice(0, length);
- try {
- if ((await lstat(join(root, ...prefixSegments))).isSymbolicLink()
- && !(await resolveRealPathWithinRoot(root, prefixSegments.join("/")))) return true;
- } catch (error) {
- const code = (error as NodeJS.ErrnoException).code;
- // Only ordinary missing paths can fall back to an indexed suffix match.
- if (code !== "ENOENT" && code !== "ENOTDIR") return true;
- }
- }
- return false;
-}
-
-/** Bounded walk for trees with no git index (session scratch, attachments). */
-async function walkRootFiles(
- rootPath: string,
- budget: number,
-): Promise<string[]> {
- const files: string[] = [];
- const queue: string[] = [""];
- while (queue.length > 0 && files.length < budget) {
- const rel = queue.shift() as string;
- let dirents;
- try {
- dirents = await readdir(join(rootPath, rel), { withFileTypes: true });
- } catch {
- continue;
- }
- for (const dirent of dirents) {
- if (isIgnoredName(dirent.name)) continue;
- const childRel = rel ? `${rel}/${dirent.name}` : dirent.name;
- if (dirent.isDirectory()) {
- queue.push(childRel);
- } else if (dirent.isFile()) {
- files.push(childRel);
- if (files.length >= budget) break;
- }
- }
- }
- return files;
-}
-
-/**
- * The project goes through the composer's cached index, which already carries
- * gitignore semantics and the files-tab ignore set; scratch and attachments
- * have no index and are walked directly.
- */
-async function listRootFiles(
- kind: FsChatRefRoot,
- rootPath: string,
-): Promise<string[]> {
- if (kind === "workspace") {
- const index = await getWorkspaceFileIndex(rootPath);
- return index.entries
- .filter((entry) => entry.kind === "file")
- .map((entry) => entry.path);
- }
- return walkRootFiles(rootPath, MAX_ROOT_WALK_ENTRIES);
-}
-
-/**
- * Resolve one chat file reference to the best existing file, or null when
- * nothing matches. Never throws: an unreadable root is simply not a match.
- */
-export async function resolveChatFileRef(
- ref: string,
- roots: ChatRefRoots,
-): Promise<FsChatRefMatch | null> {
- const parsed = parseChatRef(ref);
- if (!parsed) return null;
- const rootList = orderedRoots(roots);
- if (rootList.length === 0 && !(roots.containment ?? []).length) return null;
-
- const cleanedPosixRef = toPosix(cleanRef(ref));
- const isAttachmentRef = /^attachments(?:\/|$)/i.test(cleanedPosixRef);
-
- // Absolute references must not select an unrelated in-root file by suffix.
- if (parsed.absolute) {
- const cleaned = cleanRef(ref);
- if (!isAbsolute(cleaned)) return null;
- const absolutePath = resolve(cleaned);
- // An absolute reference may also name a store the app reads but no shorthand
- // searches, such as an image another session generated.
- const canonicalRootList = await canonicalRoots([
- ...rootList,
- ...containmentEntries(roots),
- ]);
- if (!couldShareVolume(absolutePath, canonicalRootList)) return null;
- let targetPath: string;
- try {
- targetPath = await realpath(absolutePath);
- } catch {
- return null;
- }
- if (!(await isRegularFile(targetPath))) return null;
- for (const root of canonicalRootList) {
- const relativePath = root.realPath ? relativeInside(root.realPath, targetPath) : null;
- if (!relativePath) continue;
- return {
- root: root.kind,
- relativePath,
- absolutePath,
- matchedBy: "exact-absolute",
- ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
- };
- }
- return null;
- }
-
- // 2. A content-addressed attachment blob (`attachments/<sha256>`) is not a
- // filesystem path: it names a stored blob by hash, and the files-tab
- // contract spells it that way. Resolve it against the attachment root
- // directly instead of searching for a path that cannot exist.
- if (isAttachmentRef) {
- if (!isAttachmentBlobRef(cleanedPosixRef)) return null;
- const attachmentsRoot = roots.attachments;
- if (!attachmentsRoot) return null;
- const blobHash = segmentsOf(cleanedPosixRef).at(-1);
- if (!blobHash || !ATTACHMENT_HASH_PATTERN.test(blobHash)) return null;
- const resolvedRoot = resolve(attachmentsRoot);
- const absolutePath = join(resolvedRoot, blobHash.toLowerCase());
- if (!absolutePath.startsWith(resolvedRoot + sep) && absolutePath !== resolvedRoot) {
- return null;
- }
- if (!(await isContainedRegularFile(resolvedRoot, blobHash.toLowerCase()))) return null;
- return {
- root: "attachments",
- relativePath: blobHash.toLowerCase(),
- absolutePath,
- matchedBy: "exact-relative",
- };
- }
-
- // 3. Roots in product priority order, and the first root that answers wins
- // outright: the open project is searched to exhaustion before the session
- // scratch store is considered at all. Inside one root the reference read
- // as a path verbatim outranks a tail match.
- const tails: string[][] = [];
- const longestTail = Math.min(parsed.segments.length, MAX_FUZZY_TAIL_SEGMENTS);
- for (let length = longestTail; length >= 1; length -= 1) {
- tails.push(parsed.segments.slice(parsed.segments.length - length));
- }
- for (const root of rootList) {
- const absolutePath = join(root.path, ...parsed.segments);
- if (await isRegularFile(absolutePath)) {
- if (!(await isContainedRegularFile(root.path, parsed.segments.join("/")))) return null;
- return {
- root: root.kind,
- relativePath: parsed.segments.join("/"),
- absolutePath,
- matchedBy: "exact-relative",
- ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
- };
- }
- if (await hasInvalidLinkAncestor(root.path, parsed.segments)) return null;
- const candidates = fuzzyCandidates(
- await listRootFiles(root.kind, root.path),
- tails,
- );
- for (const candidate of candidates) {
- if (!(await isContainedRegularFile(root.path, candidate.relativePath))) continue;
- return {
- root: root.kind,
- relativePath: candidate.relativePath,
- absolutePath: join(root.path, ...segmentsOf(candidate.relativePath)),
- matchedBy: candidate.matchedBy,
- ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
- };
- }
- }
-
- return null;
-}
+export { isChatRefOutsideRoots, parseChatRef, resolveChatFileRef } from "@pi-desktop/host-runtime";
+export type { ChatRefRoots, ChatRefContainmentRoot, ParsedChatRef } from "@pi-desktop/host-runtime";
diff --git a/apps/desktop/electron/main/fs-index.ts b/apps/desktop/electron/main/fs-index.ts
index 2bd0a79b3..bf41f117d 100644
--- a/apps/desktop/electron/main/fs-index.ts
+++ b/apps/desktop/electron/main/fs-index.ts
@@ -1,173 +1 @@
-import { spawn } from "node:child_process";
-import { readdir } from "node:fs/promises";
-import { join } from "node:path";
-import type { FsIndexEntry, FsIndexResult } from "@pi-desktop/shared";
-import { isIgnoredName } from "@pi-desktop/host-runtime";
-
-/**
- * Workspace file index for the composer "@" menu (D124, ADR 0024).
- *
- * Served from the main process like the files tab (ADR 0019): user-driven
- * browsing must not round-trip agent tools or permission prompts. The index
- * prefers `git ls-files` for exact gitignore semantics and falls back to a
- * bounded walk over the panel's ignore set. Fuzzy filtering happens in the
- * renderer; this only snapshots relative paths.
- */
-
-export const FS_INDEX_MAX_ENTRIES = 8000;
-const CACHE_TTL_MS = 15_000;
-const GIT_TIMEOUT_MS = 4000;
-const MAX_GIT_BUFFER = 32 * 1024 * 1024;
-
-type CacheSlot = { at: number; result: FsIndexResult };
-const cache = new Map<string, CacheSlot>();
-
-function hasIgnoredSegment(path: string): boolean {
- for (const segment of path.split("/")) {
- if (isIgnoredName(segment)) return true;
- }
- return false;
-}
-
-/** `git ls-files -co --exclude-standard -z`, null when git is unusable. */
-function gitListFiles(root: string): Promise<string[] | null> {
- return new Promise((resolve) => {
- const child = spawn(
- "git",
- ["ls-files", "-co", "--exclude-standard", "-z"],
- { cwd: root, env: process.env },
- );
- let out = "";
- let failed = false;
- const timer = setTimeout(() => {
- failed = true;
- child.kill();
- }, GIT_TIMEOUT_MS);
- child.stdout.on("data", (chunk) => {
- out += String(chunk);
- if (out.length > MAX_GIT_BUFFER) {
- failed = true;
- child.kill();
- }
- });
- child.on("error", () => {
- clearTimeout(timer);
- resolve(null);
- });
- child.on("close", (code) => {
- clearTimeout(timer);
- if (failed || code !== 0) return resolve(null);
- resolve(out.split("\0").filter((p) => p.length > 0));
- });
- });
-}
-
-/** Bounded recursive walk honoring the files-tab ignore set. */
-async function walkFiles(
- root: string,
- budget: number,
-): Promise<{ files: string[]; dirs: string[]; exhausted: boolean }> {
- const files: string[] = [];
- const dirs: string[] = [];
- let exhausted = false;
- const queue: string[] = [""];
- while (queue.length > 0) {
- const rel = queue.shift()!;
- let dirents;
- try {
- dirents = await readdir(join(root, rel), { withFileTypes: true });
- } catch {
- continue;
- }
- for (const dirent of dirents) {
- if (isIgnoredName(dirent.name)) continue;
- const childRel = rel ? `${rel}/${dirent.name}` : dirent.name;
- // Symlinks are skipped: the snapshot must never cycle or leave root.
- if (dirent.isDirectory()) {
- dirs.push(childRel);
- queue.push(childRel);
- } else if (dirent.isFile()) {
- files.push(childRel);
- }
- if (files.length + dirs.length >= budget) {
- exhausted = true;
- queue.length = 0;
- break;
- }
- }
- }
- return { files, dirs, exhausted };
-}
-
-function dirsFromFilePaths(files: string[]): string[] {
- const dirs = new Set<string>();
- for (const file of files) {
- let at = file.indexOf("/");
- while (at > 0) {
- dirs.add(file.slice(0, at));
- at = file.indexOf("/", at + 1);
- }
- }
- return [...dirs];
-}
-
-function depth(path: string): number {
- let count = 0;
- for (const ch of path) if (ch === "/") count += 1;
- return count;
-}
-
-/** Shallow entries first so truncation keeps the top-level tree visible. */
-function compareEntries(a: FsIndexEntry, b: FsIndexEntry): number {
- const depthDelta = depth(a.path) - depth(b.path);
- if (depthDelta !== 0) return depthDelta;
- return a.path.localeCompare(b.path);
-}
-
-async function buildIndex(root: string): Promise<FsIndexResult> {
- const viaGit = await gitListFiles(root);
- let files: string[];
- let dirs: string[];
- let exhausted = false;
- if (viaGit) {
- // -o lists untracked-but-not-ignored files; repos without a .gitignore
- // would still surface build output, so the panel ignore set applies too.
- files = viaGit.filter((p) => !hasIgnoredSegment(p));
- dirs = dirsFromFilePaths(files);
- } else {
- const walked = await walkFiles(root, FS_INDEX_MAX_ENTRIES + 1);
- files = walked.files;
- dirs = walked.dirs;
- exhausted = walked.exhausted;
- }
-
- const entries: FsIndexEntry[] = [
- ...dirs.map((path): FsIndexEntry => ({ path, kind: "dir" })),
- ...files.map((path): FsIndexEntry => ({ path, kind: "file" })),
- ].sort(compareEntries);
-
- if (entries.length > FS_INDEX_MAX_ENTRIES) {
- return { entries: entries.slice(0, FS_INDEX_MAX_ENTRIES), truncated: true };
- }
- return { entries, truncated: exhausted };
-}
-
-/** TTL-cached workspace index; concurrent calls share one build. */
-const pending = new Map<string, Promise<FsIndexResult>>();
-
-export async function getWorkspaceFileIndex(root: string): Promise<FsIndexResult> {
- const cached = cache.get(root);
- if (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.result;
- const inFlight = pending.get(root);
- if (inFlight) return inFlight;
- const build = buildIndex(root)
- .then((result) => {
- cache.set(root, { at: Date.now(), result });
- return result;
- })
- .finally(() => {
- pending.delete(root);
- });
- pending.set(root, build);
- return build;
-}
+export { FS_INDEX_MAX_ENTRIES, getWorkspaceFileIndex } from "@pi-desktop/host-runtime";
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.ts
index 0ea9a6ef3..face8cce2 100644
--- a/apps/desktop/electron/main/ipc/agent-ipc.ts
+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts
@@ -132,13 +132,14 @@ export function registerAgentIpc({
errorCode: ErrorCodes.TURN_NOT_FOUND,
});
}
- const context = await sidecar.call<{ projectPath?: string; supportsVision: boolean }>(
+ const context = await sidecar.call<{ projectPath?: string; remoteWorkspace?: unknown; supportsVision: boolean }>(
"agent.steeringContext", { sessionId: req.sessionId, expectedTurnId: req.expectedTurnId },
);
+ const localProjectPath = context.remoteWorkspace ? undefined : context.projectPath;
const mcpExpansion = /^\/mcp:\S/.test(req.content)
? expandMcpInvocation(
req.content,
- await composerCommandService.buildComposerCommands(context.projectPath ?? null),
+ await composerCommandService.buildComposerCommands(localProjectPath ?? null),
Boolean(req.attachments?.length),
)
: null;
@@ -146,7 +147,7 @@ export function registerAgentIpc({
// shows and where each image block sits in the prompt.
const steerContent = mcpExpansion?.expanded ?? req.content;
const prepared = await preparePromptAttachments(
- dataDir, req.sessionId, context.projectPath, req.attachments ?? [],
+ dataDir, req.sessionId, localProjectPath, req.attachments ?? [],
context.supportsVision, steerContent,
);
const session = await host.call<{ session?: { messages?: UiMessage[] } }>("session.get", {
@@ -232,7 +233,7 @@ export function registerAgentIpc({
? expandMcpInvocation(
req.content,
await composerCommandService.buildComposerCommands(
- typeof session.projectPath === "string" ? session.projectPath.trim() || null : null,
+ !session.remoteWorkspace && typeof session.projectPath === "string" ? session.projectPath.trim() || null : null,
),
Boolean(req.attachments?.length),
)
@@ -355,7 +356,7 @@ export function registerAgentIpc({
? req.content.slice(1, commandEnd === -1 ? undefined : commandEnd)
: "";
const commands = await composerCommandService.buildComposerCommands(
- launch.projectPath ?? root,
+ session.remoteWorkspace ? null : launch.projectPath ?? root,
);
const command = commands.find((item) => item.name === commandName);
const activeSkills = new Map(
@@ -407,7 +408,7 @@ export function registerAgentIpc({
preparedAttachments = await preparePromptAttachments(
dataDir,
req.sessionId,
- typeof session.projectPath === "string" && session.projectPath.trim()
+ !session.remoteWorkspace && typeof session.projectPath === "string" && session.projectPath.trim()
? session.projectPath.trim()
: undefined,
req.attachments ?? [],
diff --git a/apps/desktop/electron/main/ipc/workspace-ipc.ts b/apps/desktop/electron/main/ipc/workspace-ipc.ts
index 45160bcaf..666e4d925 100644
--- a/apps/desktop/electron/main/ipc/workspace-ipc.ts
+++ b/apps/desktop/electron/main/ipc/workspace-ipc.ts
@@ -11,11 +11,15 @@ import {
type FsChatRefProjectRoot,
type FsChatRefResolveResult,
type ProjectGroupRecord,
+ type RemoteWorkspace,
+ type WorkspaceFilesRequest,
} from "@pi-desktop/shared";
import {
loadComposerTemplates,
type ComposerTemplate,
} from "@pi-desktop/agent-runtime";
+import { remoteWorkspaceForFiles } from "../remote/workspace-file-scope";
+import { getActiveRemoteHostsBoot } from "../bootstrap/remote-hosts";
import { cloneGitRepository } from "../git-clone";
import {
importComposerFiles,
@@ -174,7 +178,7 @@ export function registerWorkspaceIpc({
errorCode: ErrorCodes.INVALID_ARGUMENT,
});
}
- const projectPath = resolve(requestedPath);
+ const projectPath = requestedPath.startsWith("remote-project:") ? requestedPath : resolve(requestedPath);
const listed = (await host.call("projects.list")) as {
projects?: Array<{ path?: string }>;
};
@@ -219,6 +223,22 @@ export function registerWorkspaceIpc({
}
return { workspace: await withGitBranch(res.workspace) };
});
+ handle(IPC.invoke.projectGroupCreateRemote, async (input: { name?: unknown; hostKey?: unknown; path?: unknown } = {}) => {
+ if (!host) throw new Error("host unavailable");
+ const name = typeof input.name === "string" ? input.name.trim() : "";
+ const hostKey = typeof input.hostKey === "string" ? input.hostKey.trim() : "";
+ const path = typeof input.path === "string" ? input.path.trim() : "";
+ if (!name || Array.from(name).length > 80 || !hostKey || hostKey.length > 200 || hostKey.includes(":")
+ || !path.startsWith("/") || path.length > 4096 || /[\u0000-\u001f]/.test(hostKey + path)) {
+ throw Object.assign(new Error("invalid remote project"), { errorCode: ErrorCodes.INVALID_ARGUMENT });
+ }
+ const boot = getActiveRemoteHostsBoot();
+ if (!boot) throw new Error("remote hosts unavailable");
+ const directory = await boot.browseProjects(hostKey, path);
+ const created = await host.call("project.group.createRemote", { name, remote: { hostKey, path: directory.path } });
+ void refreshProjectGroups(host);
+ return created;
+ });
handle(IPC.invoke.projectList, async () => {
if (!host) throw new Error("host unavailable");
return host.call("projects.list");
@@ -281,6 +301,11 @@ export function registerWorkspaceIpc({
errorCode: ErrorCodes.INVALID_ARGUMENT,
});
}
+ if (folders.every((path) => path.startsWith("remote-project:"))) {
+ const result = await host.call("project.group.update", { groupId, name, folders });
+ void refreshProjectGroups(host);
+ return result;
+ }
const safeFolders = [
...new Set(
folders
@@ -371,7 +396,7 @@ export function registerWorkspaceIpc({
const listed = (await host.call("projects.list")) as {
projects?: Array<{ path?: string }>;
};
- const projectPath = resolve(requestedPath);
+ const projectPath = requestedPath.startsWith("remote-project:") ? requestedPath : resolve(requestedPath);
const known = (listed.projects ?? []).some((project) => {
const candidate = String(project?.path ?? "").trim();
return candidate && resolve(candidate) === projectPath;
@@ -458,10 +483,10 @@ export function registerWorkspaceIpc({
);
handle(IPC.invoke.projectSet, async (path: string) => {
if (!host) throw new Error("host unavailable");
- setCurrentWorkspacePath(path);
const res = (await host.call("workspace.set", { path })) as {
workspace: { path: string; name: string } | null;
};
+ setCurrentWorkspacePath(res.workspace?.path ?? null);
return { workspace: await withGitBranch(res.workspace) };
});
handle(IPC.invoke.projectClear, async () => {
@@ -480,13 +505,13 @@ export function registerWorkspaceIpc({
if (!host) throw new Error("host unavailable");
// Deletion only touches host records, so a project whose folder was moved
// or deleted on disk stays deletable: deliberately no existence check.
- const projectPath = resolve(requestedPath);
+ const projectPath = requestedPath.startsWith("remote-project:") ? requestedPath : resolve(requestedPath);
const result = (await host.call("projects.remove", {
path: projectPath,
})) as { removed?: boolean; sessionsRemoved?: number };
const removed = Boolean(result?.removed);
const workspacePath = currentWorkspacePath();
- if (removed && workspacePath && resolve(workspacePath) === projectPath) {
+ if (removed && workspacePath && (workspacePath.startsWith("remote-project:") ? workspacePath : resolve(workspacePath)) === projectPath) {
// Leaving the host bound to a deleted project would re-create it on boot.
setCurrentWorkspacePath(null);
await host.call("workspace.clear");
@@ -620,7 +645,18 @@ export function registerWorkspaceIpc({
},
);
- handle(IPC.invoke.workspaceDiff, async () => {
+ const remoteFileWorkspace = (sessionId?: string) => remoteWorkspaceForFiles(getHost, sessionId);
+ const readRemoteFiles = (remote: RemoteWorkspace, operation: WorkspaceFilesRequest["operation"], ref?: string, mimeType?: string) => {
+ const boot = getActiveRemoteHostsBoot();
+ if (!boot) throw new Error("remote hosts unavailable");
+ return boot.workspaceFiles(remote.hostKey, { path: remote.path, operation, ...(ref ? { ref } : {}), ...(mimeType ? { mimeType } : {}) });
+ };
+ const localFileStores = [join(dataDir, "scratch"), join(dataDir, "attachments")];
+ const isLocalStoredFile = async (ref: string) => isAttachmentBlobRef(ref) || !!(await resolveRealOpenablePath(ref, null, localFileStores));
+
+ handle(IPC.invoke.workspaceDiff, async (input: { sessionId?: string } = {}) => {
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote) return readRemoteFiles(remote, "diff");
if (!host) throw new Error("host unavailable");
const res = (await host.call("workspace.get")) as {
workspace: { path: string } | null;
@@ -713,22 +749,21 @@ export function registerWorkspaceIpc({
return browserHost.getState();
});
- const requireWorkspaceRoot = async () => {
- if (!host) throw new Error("host unavailable");
- const res = (await host.call("workspace.get")) as {
- workspace: { path: string } | null;
- };
- const root = res.workspace?.path;
- if (!root) {
- throw Object.assign(new Error("workspace required"), {
- errorCode: ErrorCodes.INVALID_ARGUMENT,
- });
- }
+ const requireWorkspaceRoot = async (sessionId?: string) => {
+ const owner = getHost();
+ if (!owner) throw new Error("host unavailable");
+ const root = sessionId
+ ? (await owner.call<{ session?: { projectPath?: string } }>("session.get", { id: sessionId, messageLimit: 1 })).session?.projectPath
+ : (await owner.call<{ workspace?: { path: string } }>("workspace.get")).workspace?.path;
+ if (getHost() !== owner) throw Object.assign(new Error("host replaced"), { errorCode: ErrorCodes.HOST_UNAVAILABLE });
+ if (!root) throw Object.assign(new Error("workspace required"), { errorCode: ErrorCodes.INVALID_ARGUMENT });
return root;
};
- handle(IPC.invoke.fsList, async (input: { path?: string } = {}) => {
- const root = await requireWorkspaceRoot();
+ handle(IPC.invoke.fsList, async (input: { path?: string; sessionId?: string } = {}) => {
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote) return readRemoteFiles(remote, "list", input.path);
+ const root = await requireWorkspaceRoot(input.sessionId);
return { entries: await listDir(root, String(input.path ?? "")) };
});
@@ -806,9 +841,9 @@ export function registerWorkspaceIpc({
return [{ path: workspaceRoot, name, primary: true }];
};
- const optionalWorkspaceRoot = async (): Promise<string | null> => {
+ const optionalWorkspaceRoot = async (sessionId?: string): Promise<string | null> => {
try {
- return await requireWorkspaceRoot();
+ return await requireWorkspaceRoot(sessionId);
} catch {
return null;
}
@@ -816,11 +851,16 @@ export function registerWorkspaceIpc({
handle(
IPC.invoke.fsRead,
- async (input: { path?: string; mimeType?: string } = {}) => {
+ async (input: { path?: string; mimeType?: string; sessionId?: string } = {}) => {
const requested = String(input.path ?? "").trim();
+ if (await isLocalStoredFile(requested)) return readOpenableFile(requested, null, localFileStores, input.mimeType);
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote) {
+ return readRemoteFiles(remote, "read", requested, input.mimeType);
+ }
let workspaceRoot: string | null = null;
try {
- workspaceRoot = await requireWorkspaceRoot();
+ workspaceRoot = await requireWorkspaceRoot(input.sessionId);
} catch (error) {
if (!isAbsolute(requested) && !isAttachmentBlobRef(requested)) {
throw error;
@@ -837,8 +877,14 @@ export function registerWorkspaceIpc({
handle(
IPC.invoke.fsReadImageDataUrl,
- async (input: { ref?: string; mimeType?: string } = {}) => {
- const workspaceRoot = await optionalWorkspaceRoot();
+ async (input: { ref?: string; mimeType?: string; sessionId?: string } = {}) => {
+ const ref = String(input.ref ?? "").trim();
+ if (await isLocalStoredFile(ref)) return readOpenableImage(ref, null, localFileStores, input.mimeType);
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote) {
+ return readRemoteFiles(remote, "image", ref, input.mimeType);
+ }
+ const workspaceRoot = await optionalWorkspaceRoot(input.sessionId);
const requested = String(input.ref ?? "").trim();
return readOpenableImage(
requested,
@@ -849,11 +895,13 @@ export function registerWorkspaceIpc({
},
);
- handle(IPC.invoke.fsReveal, async (input: { path?: string } = {}) => {
+ handle(IPC.invoke.fsReveal, async (input: { path?: string; sessionId?: string } = {}) => {
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote && !(await isLocalStoredFile(String(input.path ?? "")))) throw Object.assign(new Error("remote paths cannot be revealed on this computer"), { errorCode: ErrorCodes.INVALID_ARGUMENT });
const requested = String(input.path ?? "").trim();
let workspaceRoot: string | null = null;
try {
- workspaceRoot = await requireWorkspaceRoot();
+ workspaceRoot = await requireWorkspaceRoot(input.sessionId);
} catch (error) {
if (!isAbsolute(requested) && !isAttachmentBlobRef(requested)) {
throw error;
@@ -873,8 +921,10 @@ export function registerWorkspaceIpc({
return { ok: true };
});
- handle(IPC.invoke.fsOpen, async (input: { path?: string; mimeType?: string } = {}) => {
- const workspaceRoot = await optionalWorkspaceRoot();
+ handle(IPC.invoke.fsOpen, async (input: { path?: string; mimeType?: string; sessionId?: string } = {}) => {
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote && !(await isLocalStoredFile(String(input.path ?? "")))) throw Object.assign(new Error("remote paths cannot be opened on this computer"), { errorCode: ErrorCodes.INVALID_ARGUMENT });
+ const workspaceRoot = await optionalWorkspaceRoot(input.sessionId);
const requested = String(input.path ?? "").trim();
const target = await resolveRealOpenablePath(
requested,
@@ -897,8 +947,10 @@ export function registerWorkspaceIpc({
return { ok: true };
});
- handle(IPC.invoke.fsIndex, async () => {
- const root = await optionalWorkspaceRoot();
+ handle(IPC.invoke.fsIndex, async (input: { sessionId?: string } = {}) => {
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote) return readRemoteFiles(remote, "index");
+ const root = await optionalWorkspaceRoot(input.sessionId);
if (!root) return { entries: [], truncated: false };
return getWorkspaceFileIndex(root);
});
@@ -918,7 +970,9 @@ export function registerWorkspaceIpc({
): Promise<FsChatRefResolveResult> => {
const ref = String(input.ref ?? "").trim();
if (!ref) return { match: null };
- const workspaceRoot = await optionalWorkspaceRoot();
+ const remote = await remoteFileWorkspace(input.sessionId);
+ if (remote && !(await isLocalStoredFile(ref))) return await readRemoteFiles(remote, "resolve", ref) as FsChatRefResolveResult;
+ const workspaceRoot = await optionalWorkspaceRoot(input.sessionId);
const roots = {
project: projectRootsFor(workspaceRoot),
scratch: await sessionScratchRoot(input.sessionId),
diff --git a/apps/desktop/electron/main/remote/racp-remote-host-client.ts b/apps/desktop/electron/main/remote/racp-remote-host-client.ts
index 4c272ab8f..816567eca 100644
--- a/apps/desktop/electron/main/remote/racp-remote-host-client.ts
+++ b/apps/desktop/electron/main/remote/racp-remote-host-client.ts
@@ -155,7 +155,7 @@ export function createRacpRemoteHostClient(
...(options.log ? { log: options.log } : {}),
});
const client: RemoteHostClient = {
- request: (method, params) => racp.request(method, params),
+ request: (method, params, timeoutMs) => racp.request(method, params, timeoutMs),
state: () => visibleState,
subscribeReconnect(listener) { reconnectListeners.add(listener); return () => { reconnectListeners.delete(listener); }; },
subscribeState(listener) { stateListeners.add(listener); return () => { stateListeners.delete(listener); }; },
diff --git a/apps/desktop/electron/main/remote/remote-backend.ts b/apps/desktop/electron/main/remote/remote-backend.ts
index 991f74e84..1ffe21baa 100644
--- a/apps/desktop/electron/main/remote/remote-backend.ts
+++ b/apps/desktop/electron/main/remote/remote-backend.ts
@@ -42,7 +42,7 @@ import { createRemoteHistory, type RemoteHistoryReadOptions } from "./remote-his
/** The subset of `RacpClient` this backend needs; kept minimal for testing. */
export type RemoteRacpClient = {
- request<T>(method: string, params?: unknown): Promise<T>;
+ request<T>(method: string, params?: unknown, timeoutMs?: number): Promise<T>;
};
export type RemoteBackendOptions = {
diff --git a/apps/desktop/electron/main/remote/remote-workspace-tools.ts b/apps/desktop/electron/main/remote/remote-workspace-tools.ts
new file mode 100644
index 000000000..3f0c0b79e
--- /dev/null
+++ b/apps/desktop/electron/main/remote/remote-workspace-tools.ts
@@ -0,0 +1,87 @@
+import type { RemoteHostsBoot } from "../bootstrap/remote-hosts";
+
+export type RemoteWorkspaceToolRequest = {
+ requestId: string;
+ sessionId: string;
+ turnId: string;
+ toolCallId: string;
+ toolName: string;
+ args: unknown;
+ remoteWorkspace: { hostKey: string; path: string };
+ timeoutMs?: number;
+ expectedCommandShellId?: string;
+ expectedCommandShellDialect?: string;
+};
+
+type HostReply = { call(method: string, params: Record<string, unknown>): Promise<unknown> };
+type Dependencies = {
+ getBoot: () => RemoteHostsBoot | null;
+ isCurrent: () => boolean;
+ isTurnDispatchable: (sessionId: string, turnId: string) => boolean;
+ log: (message: string, error: unknown) => void;
+};
+
+/** Local permission admission precedes this relay. No models or credentials cross it. */
+export function createRemoteWorkspaceToolRelay(host: HostReply, deps: Dependencies) {
+ const active = new Map<string, RemoteWorkspaceToolRequest>();
+ const cancelled = new Set<string>();
+ const keyFor = (request: Pick<RemoteWorkspaceToolRequest, "sessionId" | "toolCallId">) =>
+ JSON.stringify([request.sessionId, request.toolCallId]);
+ const failure = (error: unknown) => ({
+ ok: false, isError: true,
+ errorCode: error && typeof error === "object" && "errorCode" in error && typeof error.errorCode === "string"
+ ? error.errorCode : "REMOTE_TOOL_FAILED",
+ content: { error: error instanceof Error ? error.message : String(error) },
+ });
+ const abort = async (request: RemoteWorkspaceToolRequest) => {
+ await deps.getBoot()?.abortWorkspaceTool({ hostKey: request.remoteWorkspace.hostKey,
+ sessionId: request.sessionId, toolCallId: request.toolCallId });
+ };
+ return {
+ async execute(request: RemoteWorkspaceToolRequest) {
+ const key = keyFor(request);
+ let result: unknown;
+ let ownsActive = false;
+ try {
+ if (!deps.isCurrent() || !deps.isTurnDispatchable(request.sessionId, request.turnId)
+ || cancelled.has(key)) throw Object.assign(new Error("remote tool turn was cancelled"), { errorCode: "TOOL_ABORTED" });
+ const boot = deps.getBoot();
+ if (!boot) throw new Error("remote host is unavailable");
+ if (active.has(key)) throw new Error("duplicate remote tool dispatch");
+ active.set(key, request);
+ ownsActive = true;
+ result = await boot.executeWorkspaceTool({ ...request.remoteWorkspace,
+ sessionId: request.sessionId, turnId: request.turnId, toolCallId: request.toolCallId,
+ toolName: request.toolName, args: request.args,
+ ...(typeof request.timeoutMs === "number" ? { timeoutMs: request.timeoutMs } : {}),
+ ...(request.expectedCommandShellId ? { expectedCommandShellId: request.expectedCommandShellId } : {}),
+ ...(request.expectedCommandShellDialect ? { expectedCommandShellDialect: request.expectedCommandShellDialect } : {}),
+ });
+ if (!deps.isCurrent() || cancelled.has(key)) throw Object.assign(new Error("remote tool was cancelled"), { errorCode: "TOOL_ABORTED" });
+ } catch (error) {
+ result = failure(error);
+ } finally {
+ if (ownsActive) {
+ active.delete(key);
+ cancelled.delete(key);
+ }
+ }
+ if (!deps.isCurrent()) return;
+ try { await host.call("tools.remoteComplete", { requestId: request.requestId, result }); }
+ catch (error) { deps.log("remote tool completion failed", error); }
+ },
+ cancel(input: { sessionId: string; toolCallId: string }) {
+ const key = keyFor(input);
+ const request = active.get(key);
+ if (!request) return;
+ cancelled.add(key);
+ void abort(request).catch((error) => deps.log("remote tool cancellation failed", error));
+ },
+ dispose() {
+ for (const request of active.values()) {
+ cancelled.add(keyFor(request));
+ void abort(request).catch((error) => deps.log("remote tool shutdown failed", error));
+ }
+ },
+ };
+}
diff --git a/apps/desktop/electron/main/remote/workspace-file-scope.ts b/apps/desktop/electron/main/remote/workspace-file-scope.ts
new file mode 100644
index 000000000..d3b96a058
--- /dev/null
+++ b/apps/desktop/electron/main/remote/workspace-file-scope.ts
@@ -0,0 +1,25 @@
+import type { ProjectGroupRecord, RemoteWorkspace } from "@pi-desktop/shared";
+
+type FileHost = { call<T>(method: string, input?: unknown): Promise<T> };
+
+/** Retained file views authorize against their own durable session, not the selected project. */
+export async function remoteWorkspaceForFiles(getHost: () => FileHost | null, sessionId?: string): Promise<RemoteWorkspace | null> {
+ const owner = getHost();
+ if (!owner) throw new Error("host unavailable");
+ let path: string | undefined;
+ if (sessionId) {
+ const { session } = await owner.call<{ session?: { projectPath?: string } }>("session.get", { id: sessionId, messageLimit: 1 });
+ if (!session) throw Object.assign(new Error("session not found"), { errorCode: "NOT_FOUND" });
+ path = session.projectPath;
+ } else {
+ const { workspace } = await owner.call<{ workspace?: { path: string } }>("workspace.get");
+ path = workspace?.path;
+ }
+ if (getHost() !== owner) throw Object.assign(new Error("host replaced"), { errorCode: "HOST_UNAVAILABLE" });
+ if (!path?.startsWith("remote-project:")) return null;
+ const { groups } = await owner.call<{ groups: ProjectGroupRecord[] }>("project.groups.list");
+ if (getHost() !== owner) throw Object.assign(new Error("host replaced"), { errorCode: "HOST_UNAVAILABLE" });
+ const remote = groups.find((group) => group.primaryPath === path)?.remote;
+ if (!remote) throw Object.assign(new Error("remote workspace binding unavailable"), { errorCode: "NOT_FOUND" });
+ return remote;
+}
diff --git a/apps/desktop/electron/main/runtime/host.ts b/apps/desktop/electron/main/runtime/host.ts
index abf9bcb11..f726ae5d9 100644
--- a/apps/desktop/electron/main/runtime/host.ts
+++ b/apps/desktop/electron/main/runtime/host.ts
@@ -7,6 +7,8 @@ import type { PluginRuntime } from "../plugin-runtime";
import type { UserMcpRuntime } from "../user-mcp";
import type { RuntimeState } from "./context";
import type { FinishTurn } from "./plans";
+import { getActiveRemoteHostsBoot } from "../bootstrap/remote-hosts";
+import { createRemoteWorkspaceToolRelay, type RemoteWorkspaceToolRequest } from "../remote/remote-workspace-tools";
export type HostRuntimeDependencies = {
runtimeState: RuntimeState;
@@ -73,11 +75,25 @@ export function createHostRuntime({
startHost: () => Promise<void>;
} {
const wireHost = (h: HostProcess) => {
+ const remoteTools = createRemoteWorkspaceToolRelay(h, {
+ getBoot: getActiveRemoteHostsBoot,
+ isCurrent: () => runtimeState.host === h,
+ isTurnDispatchable: (sessionId, turnId) => isTurnDispatchable(sessionId, turnId),
+ log: (message, error) => logger.app("diagnostics", "warn", message, { data: String(error) }),
+ });
h.onNotification((method, params) => {
// Notifications from a previous host generation must never reach the
// current plugin/renderer bridge after a restart.
if (runtimeState.host !== h) return;
+ if (method === "tools.remoteExecute") {
+ void remoteTools.execute(params as RemoteWorkspaceToolRequest);
+ return;
+ }
+ if (method === "tools.remoteAbort") {
+ remoteTools.cancel(params as { sessionId: string; toolCallId: string });
+ return;
+ }
// An install reports itself, so the dialog that shows it can follow the
// phases, the mirror being tried and the bytes that have arrived. Nothing
// here decides anything: the request's own answer is still the outcome.
@@ -321,6 +337,7 @@ export function createHostRuntime({
}
});
h.onExit(({ code, signal, intentional }) => {
+ remoteTools.dispose();
if (runtimeState.host !== h) return;
logger.flushChild("host");
runtimeState.host = null;
diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.ts
index 968bfbdbe..7b0a4b9ef 100644
--- a/apps/desktop/electron/main/runtime/session-launch.ts
+++ b/apps/desktop/electron/main/runtime/session-launch.ts
@@ -41,6 +41,7 @@ import type { UserMcpRuntime } from "../user-mcp";
import type { RuntimeState } from "./context";
import type { RuntimeProvider } from "./provider-catalog";
import type { LoadedSkillDocument } from "../skill-document";
+import { getActiveRemoteHostsBoot } from "../bootstrap/remote-hosts";
const ErrorCodes = {
...SharedErrorCodes,
@@ -285,7 +286,12 @@ export function createSessionLaunchRuntime({
) {
if (!runtimeState.host) throw new Error("host unavailable");
await modelsDevCatalog.ensureLoaded();
- const commandShell = (await resolveEffectiveCommandShell()).effective!;
+ const remoteWorkspace = session.remoteWorkspace as { hostKey: string; path: string } | undefined;
+ const remoteBoot = remoteWorkspace ? getActiveRemoteHostsBoot() : null;
+ if (remoteWorkspace && !remoteBoot) throw new Error("remote host unavailable");
+ const commandShell = remoteWorkspace
+ ? await remoteBoot!.workspaceCommandShell(remoteWorkspace.hostKey)
+ : (await resolveEffectiveCommandShell()).effective!;
const providers = await runtimeState.host!.call<{ providers: RuntimeProvider[] }>(
"providers.list",
{ includeDisabled: false },
@@ -394,10 +400,11 @@ export function createSessionLaunchRuntime({
typeof session.projectPath === "string" && session.projectPath.trim()
? session.projectPath.trim()
: undefined;
- let projectInstructions = await loadInstructionChain(projectPath);
+ const localInstructionRoot = remoteWorkspace ? undefined : projectPath;
+ let projectInstructions = await loadInstructionChain(localInstructionRoot);
// pi-compatible SYSTEM.md / APPEND_SYSTEM.md (issue #542): resolved once
// per launch; a change retires the runtime through the reuse match.
- const customSystemPrompt = await loadCustomSystemPrompt(projectPath);
+ const customSystemPrompt = await loadCustomSystemPrompt(localInstructionRoot);
let projectMemory: string | undefined;
if (projectPath) {
try {
@@ -490,7 +497,7 @@ export function createSessionLaunchRuntime({
// pinned model is resolved here because credentials and the models.dev catalog
// live on this side. The user's own definitions (D202) are scope-filtered like the
// skills above; a delegate the model can see is one it will try to call.
- const subagentCatalog = await loadSubagentDefinitions(projectPath, {
+ const subagentCatalog = await loadSubagentDefinitions(localInstructionRoot, {
userDocuments: await activeUserSubagentDocuments(projectPath),
// A switched-off builtin is dropped from what this prompt may delegate to.
disabledBuiltins: await disabledBuiltinSubagents(),
@@ -667,6 +674,7 @@ export function createSessionLaunchRuntime({
scratchDir: join(dataDir, "scratch", sessionId),
attachmentsDir: join(dataDir, "attachments"),
projectPath,
+ ...(remoteWorkspace ? { remoteWorkspace } : {}),
customSystemPrompt,
projectInstructions,
projectMemory,
diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.ts
index c0b96949b..9edc060ae 100644
--- a/apps/desktop/electron/main/runtime/sidecar.ts
+++ b/apps/desktop/electron/main/runtime/sidecar.ts
@@ -367,7 +367,8 @@ export function createSidecarRuntime({
s.setProjectInstructionResolver(async ({ projectPath, path }) => {
// The root is registered by Electron main from the host-owned session
// record. The sidecar can provide a target path, never an arbitrary root.
- const instructions = await loadInstructionChain(projectPath, path);
+ const instructions = projectPath?.startsWith("remote-project:")
+ ? await loadInstructionChain(undefined) : await loadInstructionChain(projectPath, path);
if (!projectPath || !runtimeState.host) return instructions;
try {
const result = await runtimeState.host.call<{
diff --git a/apps/desktop/electron/main/workspace-git.ts b/apps/desktop/electron/main/workspace-git.ts
index d0770134b..4e1d1c7a8 100644
--- a/apps/desktop/electron/main/workspace-git.ts
+++ b/apps/desktop/electron/main/workspace-git.ts
@@ -5,7 +5,7 @@
export async function withGitBranch<T extends { path?: string; name?: string } | null | undefined>(
workspace: T,
): Promise<T> {
- if (!workspace || !workspace.path) return workspace;
+ if (!workspace || !workspace.path || workspace.path.startsWith("remote-project:")) return workspace;
try {
const { readFile } = await import("node:fs/promises");
const { join } = await import("node:path");
diff --git a/apps/desktop/src/components/HomeProjectSwitcher.tsx b/apps/desktop/src/components/HomeProjectSwitcher.tsx
index fa9f52eba..9b720e13a 100644
--- a/apps/desktop/src/components/HomeProjectSwitcher.tsx
+++ b/apps/desktop/src/components/HomeProjectSwitcher.tsx
@@ -75,12 +75,14 @@ export function HomeProjectSwitcher({
const visible = useMemo(
(): ProjectMenuEntry[] => [
...filterSwitcherProjects(projects, query).map((project) => ({ key: project.key, name: project.name,
- title: project.path, localPath: project.path })),
+ title: openProjects.find((item) => item.path === project.path)?.remote?.path
+ ?? (workspace?.path === project.path ? workspace.remote?.path : undefined)
+ ?? 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],
+ [projects, query, remoteCatalog.projects, openProjects, workspace],
);
const activeKey = isRemoteSession(activeSession) && activeSession?.remoteHostKey && activeSession.remoteProjectId
? `remote:${remoteProjectKey(activeSession.remoteHostKey, activeSession.remoteProjectId)}`
@@ -237,7 +239,7 @@ export function HomeProjectSwitcher({
aria-haspopup="menu"
aria-expanded={open}
aria-label={`${t("project.switchProject")}: ${name}`}
- title={path || t("project.switchProject")}
+ title={(workspace?.path === path ? workspace?.remote?.path : undefined) || path || t("project.switchProject")}
disabled={busy}
onClick={() => {
if (open) {
diff --git a/apps/desktop/src/components/ProjectCreateDialog.tsx b/apps/desktop/src/components/ProjectCreateDialog.tsx
index 9aba38d3e..41b39c1e5 100644
--- a/apps/desktop/src/components/ProjectCreateDialog.tsx
+++ b/apps/desktop/src/components/ProjectCreateDialog.tsx
@@ -60,7 +60,8 @@ function ProjectCreateDialogContent() {
);
const showToast = useAppStore((state) => state.showToast);
const [source, setSource] = useState<ProjectSource>("local");
- const newSession = useAppStore((state) => state.newSession);
+ const createProjectFromRemote = useAppStore((state) => state.createProjectFromRemote);
+ const [remoteBrowseOpen, setRemoteBrowseOpen] = useState(false);
const [remoteProject, setRemoteProject] = useState<RemoteProjectSelection | null>(null);
const [name, setName] = useState("");
const [folders, setFolders] = useState<string[]>([]);
@@ -80,7 +81,7 @@ function ProjectCreateDialogContent() {
});
const defaultName = defaultProjectName({
source: source === "remote" ? "local" : source,
- folders,
+ folders: source === "remote" && remoteProject ? [remoteProject.path] : folders,
repositoryName: cloneTarget?.name,
});
const projectName = resolveProjectName(name, defaultName);
@@ -182,7 +183,7 @@ function ProjectCreateDialogContent() {
const submit = async () => {
const projectName = resolveProjectName(name, defaultName);
if (busyRef.current) return;
- if (source === "remote" ? !remoteProject : !projectName) return;
+ if (!projectName || (source === "remote" && !remoteProject)) return;
if (source === "git") {
if (!cloneTarget || !cloneParent) return;
} else if (source === "local" && folders.length === 0) {
@@ -192,12 +193,7 @@ function ProjectCreateDialogContent() {
setBusy(true);
try {
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();
+ await createProjectFromRemote({ name: projectName, hostKey: remoteProject.hostKey, path: remoteProject.path });
} else if (source === "git" && cloneTarget) {
await createProjectFromGit({
name: projectName,
@@ -233,7 +229,9 @@ function ProjectCreateDialogContent() {
ref={dialogRef}
className="dialog project-create-dialog"
role="dialog"
- aria-modal="true"
+ aria-modal={remoteBrowseOpen ? undefined : true}
+ aria-hidden={remoteBrowseOpen || undefined}
+ inert={remoteBrowseOpen || undefined}
aria-labelledby="project-create-dialog-title"
onClick={(event) => event.stopPropagation()}
>
@@ -263,7 +261,7 @@ function ProjectCreateDialogContent() {
}}
>
<div className="project-create-dialog-content">
- {source !== "remote" ? <section
+ <section
className="project-create-dialog-section project-create-dialog-identity"
aria-labelledby="project-create-name-heading"
>
@@ -295,7 +293,7 @@ function ProjectCreateDialogContent() {
autoCorrect="off"
autoCapitalize="off"
/>
- </section> : null}
+ </section>
<section
className="project-create-dialog-section project-create-dialog-source-section"
@@ -349,7 +347,7 @@ function ProjectCreateDialogContent() {
</section>
{source === "remote" ? (
- <RemoteProjectPicker busy={busy} onChange={setRemoteProject} />
+ <RemoteProjectPicker busy={busy} onChange={setRemoteProject} onBrowsingChange={setRemoteBrowseOpen} />
) : source === "local" ? (
<ProjectFolderPicker folders={folders} busy={busy} pickerBusy={folderPickerBusy}
onAdd={() => void addFolders()}
@@ -426,7 +424,7 @@ function ProjectCreateDialogContent() {
type="submit"
variant="primary"
disabled={
- source === "remote" ? !remoteProject || busy : source === "git"
+ source === "remote" ? !projectName || !remoteProject || busy : source === "git"
? !projectName || !cloneTarget || !cloneParent || busy
: !projectName || folders.length === 0 || busy
}
diff --git a/apps/desktop/src/components/ProjectEditDialog.tsx b/apps/desktop/src/components/ProjectEditDialog.tsx
index 9fee33a42..5a418e532 100644
--- a/apps/desktop/src/components/ProjectEditDialog.tsx
+++ b/apps/desktop/src/components/ProjectEditDialog.tsx
@@ -5,7 +5,7 @@ import { useTranslation } from "react-i18next";
import type { ProjectGroupRecord, ProjectGroupRoot } from "@pi-desktop/shared";
import { api } from "../lib/api";
import { MAX_PROJECT_NAME_CHARS } from "../lib/sidebar-preferences";
-import { Button, TooltipButton } from "./ui";
+import { Button, Input, TooltipButton } from "./ui";
import {
IconClose,
IconFolder,
@@ -145,6 +145,7 @@ export function ProjectEditDialog({
}, [onClose]);
const addFolders = async () => {
+ if (group?.remote) return;
if (busyRef.current || folderPickerInFlightRef.current) return;
folderPickerInFlightRef.current = true;
setFolderPickerBusy(true);
@@ -172,7 +173,9 @@ export function ProjectEditDialog({
busyRef.current = true;
setBusy(true);
try {
- const result = await api.updateProjectGroup(group.id, trimmedName, folders);
+ const result = group.remote
+ ? await api.renameProjectGroup(group.id, trimmedName)
+ : await api.updateProjectGroup(group.id, trimmedName, folders);
onSaved(result.group);
onClose();
} catch (error) {
@@ -242,7 +245,7 @@ export function ProjectEditDialog({
{name.length}/{MAX_PROJECT_NAME_CHARS}
</span>
</div>
- <input
+ <Input
ref={inputRef}
id="project-edit-name"
className="field-input project-create-dialog-name-field"
@@ -268,16 +271,17 @@ export function ProjectEditDialog({
<span className="project-create-dialog-count">{folders.length}</span>
) : null}
</h3>
- <span className="project-create-dialog-source" data-project-source="local">
+ <span className="project-create-dialog-source" data-project-source={group?.remote ? "remote" : "local"}>
<IconMonitor size={15} aria-hidden />
- {t("project.createComputer")}
+ {group?.remote ? t("remote:remote") : t("project.createComputer")}
</span>
</div>
- {folders.length > 0 ? (
+ {!loading && folders.length > 0 ? (
<div className="project-create-dialog-folder-list" role="list">
{folders.map((path) => {
const primary = samePath(path, primaryPath);
+ const displayPath = group?.remote?.path ?? path;
return (
<div
className={`project-create-folder-row${primary ? " is-primary" : ""}`}
@@ -287,9 +291,9 @@ export function ProjectEditDialog({
<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">{folderName(path)}</span>
- <span className="project-create-folder-path">{folderParent(path)}</span>
+ <span className="project-create-folder-copy" title={displayPath}>
+ <span className="project-create-folder-name">{folderName(displayPath)}</span>
+ <span className="project-create-folder-path">{group?.remote ? displayPath : folderParent(displayPath)}</span>
</span>
{primary ? (
<span className="project-create-primary-tag">
@@ -309,7 +313,7 @@ export function ProjectEditDialog({
primary
? t("project.editPrimaryLocked")
: t("project.createRemoveFolder")
- }: ${folderName(path)}`}
+ }: ${folderName(displayPath)}`}
disabled={loading || busy || primary}
onClick={() =>
setFolders((current) =>
@@ -325,7 +329,7 @@ export function ProjectEditDialog({
</div>
) : null}
- <button
+ {!group?.remote ? <Button
type="button"
aria-label={t("project.createAddFolder")}
className={`project-create-add-folder${folders.length === 0 ? " is-empty" : ""}`}
@@ -340,7 +344,7 @@ export function ProjectEditDialog({
{t("project.createAddFolder")}
</span>
</span>
- </button>
+ </Button> : null}
</section>
</div>
diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsx
index 7efb738ca..e44752f13 100644
--- a/apps/desktop/src/components/Sidebar.tsx
+++ b/apps/desktop/src/components/Sidebar.tsx
@@ -101,6 +101,7 @@ import {
type ProjectEntry = {
path: string;
+ displayPath?: string;
key: string;
name: string;
sessions: SessionSummary[];
@@ -708,6 +709,8 @@ export function Sidebar({
const meta = projectMetaFor(rawPath, projectMeta);
byPath.set(normalized, {
path: rawPath,
+ displayPath: openProjects.find((project) => normalizeProjectPath(project.path) === normalized)?.remote?.path
+ ?? (normalizeProjectPath(workspace?.path) === normalized ? workspace?.remote?.path : undefined),
key: normalized,
name: projectName(rawPath, meta.name ?? name),
sessions: [],
@@ -1941,7 +1944,7 @@ export function Sidebar({
type="button"
id={projectId}
className="sidebar-session-group-title project-toggle"
- tooltip={entry.path}
+ tooltip={entry.displayPath ?? entry.path}
tooltipDelayMs={500}
tooltipClassName="ui-tooltip-path"
ariaLabel={entry.name}
@@ -1983,7 +1986,7 @@ export function Sidebar({
{entry.active ? <span className="sidebar-project-active-dot" aria-label={t("project.active", { defaultValue: "Active" })} /> : null}
</TooltipButton>
<span id={`${projectId}-path-description`} className="sr-only">
- {entry.path}
+ {entry.displayPath ?? entry.path}
{". "}
{t("project.reorder", { name: entry.name, defaultValue: "Reorder {{name}}" })}
</span>
diff --git a/apps/desktop/src/components/remote/RemoteFolderDialog.tsx b/apps/desktop/src/components/remote/RemoteFolderDialog.tsx
new file mode 100644
index 000000000..6b243f8da
--- /dev/null
+++ b/apps/desktop/src/components/remote/RemoteFolderDialog.tsx
@@ -0,0 +1,124 @@
+import { useEffect, useRef, useState } from "react";
+import { createPortal } from "react-dom";
+import { useTranslation } from "react-i18next";
+import type { RemoteHostBrowseProjectsResult } from "@pi-desktop/shared";
+import { api } from "../../lib/api";
+import { useBlockingOverlay } from "../../lib/blocking-overlay";
+import { Button, Field, Input, TooltipButton } from "../ui";
+import { IconChevronRight, IconClose, IconFolder } from "../icons";
+
+/** Directory navigation belongs to a separate modal, never the project form. */
+export function RemoteFolderDialog({ hostKey, hostLabel, initialPath, onChoose, onClose }: {
+ hostKey: string; hostLabel: string; initialPath: string;
+ onChoose: (path: string) => void; onClose: () => void;
+}) {
+ useBlockingOverlay();
+ const { t } = useTranslation();
+ const [directory, setDirectory] = useState<RemoteHostBrowseProjectsResult | null>(null);
+ const [path, setPath] = useState(initialPath);
+ const [browsing, setBrowsing] = useState(true);
+ const [error, setError] = useState("");
+ const generation = useRef(0);
+ const initialFocus = useRef(true);
+ const dialogRef = useRef<HTMLDivElement>(null);
+ const pathRef = useRef<HTMLInputElement>(null);
+ const closeRef = useRef(onClose);
+ closeRef.current = onClose;
+
+ async function browse(nextPath?: string) {
+ const request = ++generation.current;
+ setBrowsing(true);
+ setError("");
+ try {
+ const result = await api.remoteHostBrowseProjects(hostKey, nextPath);
+ if (request !== generation.current) return;
+ setDirectory(result);
+ setPath(result.path);
+ } catch (error) {
+ if (request === generation.current) setError(error instanceof Error ? error.message : String(error));
+ } finally {
+ if (request === generation.current) setBrowsing(false);
+ }
+ }
+
+ useEffect(() => {
+ const previouslyFocused = document.activeElement as HTMLElement | null;
+ const frame = requestAnimationFrame(() => dialogRef.current?.querySelector<HTMLButtonElement>("button:not([disabled])")?.focus());
+ void browse(initialPath.startsWith("/") ? initialPath : undefined);
+ return () => {
+ generation.current++;
+ cancelAnimationFrame(frame);
+ // The parent removes its inert state before focus is restored.
+ requestAnimationFrame(() => { if (previouslyFocused?.isConnected) previouslyFocused.focus(); });
+ };
+ }, [hostKey]);
+
+ useEffect(() => {
+ if (browsing || !initialFocus.current) return;
+ initialFocus.current = false;
+ pathRef.current?.focus();
+ }, [browsing]);
+
+ const choose = () => {
+ if (!directory || browsing || error || path !== directory.path) return;
+ onChoose(directory.path);
+ };
+ const dialog = <div className="overlay remote-folder-dialog-overlay" role="presentation"
+ onClick={(event) => { if (event.target === event.currentTarget) closeRef.current(); }}>
+ <div ref={dialogRef} className="dialog remote-folder-dialog" role="dialog" aria-modal="true"
+ aria-labelledby="remote-folder-dialog-title" aria-describedby="remote-folder-dialog-host"
+ onKeyDown={(event) => {
+ // The project dialog also traps focus; only this foreground modal handles keys.
+ event.stopPropagation();
+ if (event.key === "Escape") { event.preventDefault(); closeRef.current(); }
+ if (event.key !== "Tab") return;
+ const controls = dialogRef.current?.querySelectorAll<HTMLElement>('input:not([disabled]), button:not([disabled])');
+ if (!controls?.length) return;
+ const first = controls[0]; const last = controls[controls.length - 1];
+ if (event.shiftKey && document.activeElement === first) { event.preventDefault(); last.focus(); }
+ else if (!event.shiftKey && document.activeElement === last) { event.preventDefault(); first.focus(); }
+ }}>
+ <div className="project-create-dialog-head">
+ <div className="project-create-dialog-heading">
+ <h2 id="remote-folder-dialog-title" className="project-create-dialog-title">{t("remote:folderPickerTitle")}</h2>
+ <p id="remote-folder-dialog-host" className="project-edit-dialog-description">{hostLabel}</p>
+ </div>
+ <TooltipButton type="button" className="project-create-dialog-close" tooltip={t("project.createCancel")}
+ ariaLabel={t("project.createCancel")} onClick={onClose}><IconClose size={17} /></TooltipButton>
+ </div>
+ <form className="remote-folder-dialog-navigation" onSubmit={(event) => { event.preventDefault(); event.stopPropagation(); if (path.startsWith("/") && !browsing) void browse(path); }}>
+ <Field label={t("remote:folderPath")}>
+ <div className="remote-folder-dialog-path-entry">
+ <Input ref={pathRef} value={path} aria-label={t("remote:folderPath")} placeholder={t("remote:pathPlaceholder")}
+ autoComplete="off" spellCheck={false} disabled={browsing} onChange={(event) => setPath(event.target.value)} />
+ <Button type="submit" disabled={browsing || !path.startsWith("/")}>{t("remote:goToFolder")}</Button>
+ </div>
+ </Field>
+ {path && !path.startsWith("/") ? <p className="remote-project-error" role="alert">{t("remote:REMOTE_ABSOLUTE_PATH_REQUIRED")}</p> : null}
+ <Button type="button" variant="ghost" disabled={browsing || !directory?.parent}
+ onClick={() => void browse(directory?.parent)}>{t("remote:parent")}</Button>
+ </form>
+ <div className="remote-folder-dialog-directory" aria-busy={browsing}>
+ {browsing ? <p role="status">{t("remote:loading")}</p> : null}
+ {error ? <p className="remote-project-error" role="alert">{error}</p> : null}
+ {!browsing && directory && !error ? <>
+ <p className="remote-project-browser-path" title={directory.path}>{directory.path}</p>
+ <div className="remote-folder-dialog-entries" role="list" aria-label={t("remote:browseFolders")}>
+ {directory.entries.map((entry) => <div role="listitem" key={entry.path}>
+ <Button type="button" variant="ghost" className="remote-folder-dialog-entry"
+ aria-label={t("remote:openFolder", { name: entry.name })} title={entry.path} onClick={() => void browse(entry.path)}>
+ <IconFolder size={18} aria-hidden /><span>{entry.name}</span><IconChevronRight size={16} aria-hidden />
+ </Button>
+ </div>)}
+ </div>
+ {!directory.entries.length ? <p className="project-edit-dialog-description">{t("remote:emptyFolders")}</p> : null}
+ </> : null}
+ </div>
+ <div className="project-create-dialog-actions">
+ <Button type="button" variant="ghost" onClick={onClose}>{t("project.createCancel")}</Button>
+ <Button type="button" variant="primary" disabled={!directory || browsing || !!error || path !== directory.path} onClick={choose}>{t("remote:useFolder")}</Button>
+ </div>
+ </div>
+ </div>;
+ return createPortal(dialog, document.body);
+}
diff --git a/apps/desktop/src/components/remote/RemoteProjectPicker.tsx b/apps/desktop/src/components/remote/RemoteProjectPicker.tsx
index 3ac95445f..b358275c3 100644
--- a/apps/desktop/src/components/remote/RemoteProjectPicker.tsx
+++ b/apps/desktop/src/components/remote/RemoteProjectPicker.tsx
@@ -1,35 +1,29 @@
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
-import type { RacpProjectSummary, RemoteHostBrowseProjectsResult, RemoteHostSummary } from "@pi-desktop/shared";
+import type { RemoteHostSummary } from "@pi-desktop/shared";
import { api } from "../../lib/api";
import { Button, Field, Input, Select } from "../ui";
+import { RemoteFolderDialog } from "./RemoteFolderDialog";
-export type RemoteProjectSelection = {
- hostKey: string;
- hostLabel: string;
- projectId?: string;
- label?: string;
- path?: string;
-};
+export type RemoteProjectSelection = { hostKey: string; hostLabel: string; path: string };
-export function RemoteProjectPicker({ busy, onChange }: {
+export function RemoteProjectPicker({ busy, onChange, onBrowsingChange }: {
busy: boolean;
onChange: (selection: RemoteProjectSelection | null) => void;
+ onBrowsingChange: (open: boolean) => 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 [browseOpen, setBrowseOpen] = useState(false);
const [error, setError] = useState("");
- const generation = useRef(0);
- const browseGeneration = useRef(0);
const selectionCallback = useRef(onChange);
selectionCallback.current = onChange;
+ const browsingCallback = useRef(onBrowsingChange);
+ browsingCallback.current = onBrowsingChange;
+ const host = hosts.find((item) => item.hostKey === hostKey);
useEffect(() => {
let active = true;
@@ -41,82 +35,36 @@ export function RemoteProjectPicker({ busy, onChange }: {
}).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++; };
+ return () => { active = false; selectionCallback.current(null); browsingCallback.current(false); };
}, []);
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);
- }
- }
+ selectionCallback.current(host && path.trim().startsWith("/") ? { hostKey, hostLabel: host.label, path: path.trim() } : null);
+ }, [host, hostKey, path]);
- return <section className="project-create-dialog-section remote-project-picker" aria-busy={loading || browsing}>
+ const setBrowsing = (open: boolean) => { setBrowseOpen(open); browsingCallback.current(open); };
+ return <section className="project-create-dialog-section remote-project-picker" aria-busy={loading}>
<Field label={t("remote:projectHost")}>
- <Select value={hostKey} disabled={busy || loading} onChange={(event) => { generation.current++; browseGeneration.current++; selectionCallback.current(null); setHostKey(event.target.value); }}>
+ <Select aria-label={t("remote:projectHost")} value={hostKey} disabled={busy || loading} onChange={(event) => {
+ selectionCallback.current(null); setPath(""); setHostKey(event.target.value); setBrowsing(false);
+ }}>
{!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>
+ {host ? <>
<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 className="remote-folder-dialog-path-entry">
+ <Input value={path} aria-label={t("remote:projectFolder")} placeholder={t("remote:pathPlaceholder")} disabled={busy}
+ autoComplete="off" spellCheck={false} onChange={(event) => setPath(event.target.value)} />
+ <Button type="button" disabled={busy} onClick={(event) => { event.currentTarget.focus(); setBrowsing(true); }}>{t("remote:browseFolders")}</Button>
</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>
+ </Field>
+ {path && !path.trim().startsWith("/") ? <p className="remote-project-error" role="alert">{t("remote:REMOTE_ABSOLUTE_PATH_REQUIRED")}</p> : null}
</> : null}
- {loading || browsing ? <p role="status">{t("remote:loading")}</p> : null}
+ {loading ? <p role="status">{t("remote:loading")}</p> : null}
{error ? <p className="remote-project-error" role="alert">{error}</p> : null}
+ {browseOpen && host ? <RemoteFolderDialog key={hostKey} hostKey={hostKey} hostLabel={host.label} initialPath={path}
+ onChoose={(selected) => { setPath(selected); setBrowsing(false); }} onClose={() => setBrowsing(false)} /> : null}
</section>;
}
diff --git a/apps/desktop/src/components/settings/RemoteHostSessions.tsx b/apps/desktop/src/components/settings/RemoteHostSessions.tsx
index 93ed2a1d0..e8d2b010e 100644
--- a/apps/desktop/src/components/settings/RemoteHostSessions.tsx
+++ b/apps/desktop/src/components/settings/RemoteHostSessions.tsx
@@ -1,11 +1,10 @@
-import { useEffect, useMemo, useState, useSyncExternalStore } from "react";
+import { useEffect, useMemo, useSyncExternalStore } from "react";
import { useTranslation } from "react-i18next";
-import { isSyncableProvider, type RemoteHostSummary, type SessionSummary } from "@pi-desktop/shared";
+import { type RemoteHostSummary, type SessionSummary } from "@pi-desktop/shared";
import { createRemoteHostWorkflow } from "../../lib/remote-host-workflow";
import { api } from "../../lib/api";
import { useAppStore } from "../../stores/app-store";
-import { Button, Checkbox, CheckboxGroup, Field, Input } from "../ui";
-import { SettingsMenuSelect } from "./SettingsMenuSelect";
+import { Button } from "../ui";
export async function selectRemoteSession(session: SessionSummary) {
useAppStore.setState((state) => ({ sessions: [session, ...state.sessions.filter((item) => item.id !== session.id)] }));
@@ -21,16 +20,8 @@ export async function selectRemoteSession(session: SessionSummary) {
/** Inline workbench: the Settings rail remains usable, without a nested modal. */
export function RemoteHostSessions({ host, onClose }: { host: RemoteHostSummary; onClose: () => void }) {
const { t } = useTranslation("remote");
- const providers = useAppStore((state) => state.providers);
const workflow = useMemo(() => createRemoteHostWorkflow(host, selectRemoteSession), [host]);
const view = useSyncExternalStore(workflow.subscribe, workflow.getSnapshot, workflow.getSnapshot);
- const [projectId, setProjectId] = useState("");
- const [path, setPath] = useState("");
- const [title, setTitle] = useState("");
- const [selected, setSelected] = useState<string[]>([]);
- const [consent, setConsent] = useState(false);
- const [setDefault, setSetDefault] = useState(true);
- const eligible = providers.filter(isSyncableProvider);
useEffect(() => {
void workflow.start();
const unsubscribe = api.onSessionsChanged(() => void workflow.load());
@@ -53,45 +44,7 @@ export function RemoteHostSessions({ host, onClose }: { host: RemoteHostSummary;
{session.title} · {session.remoteWorkspaceLabel ?? t("workspace")}
</Button>
))}
- <form className="settings-stack" onSubmit={(event) => { event.preventDefault(); void workflow.create({ projectId, path, title }); }}>
- <Field label={t("project")}>
- <SettingsMenuSelect label={t("project")} value={projectId} disabled={view.busy || Boolean(path.trim())}
- options={[{ id: "", label: t("selectProject") }, ...view.projects.map((project) => ({ id: project.id, label: project.label }))]}
- onChange={setProjectId} fullWidth />
- </Field>
- <Field label={t("path")}>
- <Input aria-label={t("path")} value={path} placeholder={t("pathPlaceholder")} disabled={view.busy}
- onChange={(event) => setPath(event.target.value)} />
- </Field>
- <Field label={t("title")}>
- <Input aria-label={t("title")} value={title} disabled={view.busy} onChange={(event) => setTitle(event.target.value)} />
- </Field>
- <p>{t("defaultModel")}</p>
- <Button type="submit" disabled={view.busy || (!projectId && !path.trim())}>{t("create")}</Button>
- </form>
- {host.transport === "ssh" && (
- <section className="settings-stack" aria-label={t("sync")}>
- <h3 className="settings-card-heading">{t("sync")}</h3>
- <p>{t("syncWarning", { host: host.label })}</p>
- {eligible.length === 0 ? <p>{t("noProviders")}</p> : (
- <CheckboxGroup label={t("sync")} values={selected} disabled={view.busy}
- options={eligible.map((provider) => ({ value: provider.id, label: provider.name }))}
- onChange={(ids) => { setSelected(ids); setConsent(false); }} />
- )}
- <Checkbox label={t("consent")} checked={consent} disabled={view.busy || selected.length === 0}
- onChange={(event) => setConsent(event.target.checked)} />
- <Checkbox label={t("setDefault")} checked={setDefault} disabled={view.busy}
- onChange={(event) => setSetDefault(event.target.checked)} />
- <Button disabled={view.busy || !consent || selected.length === 0}
- onClick={() => { void workflow.sync(providers, selected, consent, setDefault); setConsent(false); }}>
- {t("sync")}
- </Button>
- {view.syncResult && <p role="status">{t("syncResult", {
- imported: view.syncResult.imported.length, skipped: view.syncResult.skipped.length,
- defaultSet: t(view.syncResult.defaultSet ? "yes" : "no"),
- })}</p>}
- </section>
- )}
+
</div>
</section>
);
diff --git a/apps/desktop/src/components/settings/RemoteHostsPage.tsx b/apps/desktop/src/components/settings/RemoteHostsPage.tsx
index e49341920..d29135c02 100644
--- a/apps/desktop/src/components/settings/RemoteHostsPage.tsx
+++ b/apps/desktop/src/components/settings/RemoteHostsPage.tsx
@@ -252,7 +252,6 @@ export function RemoteHostsPage() {
<Button variant="secondary" onClick={() => setSelectedHost(host)}>
{remoteT("sessions")}
</Button>
- {host.transport === "ssh" && <Button variant="ghost" onClick={() => setSelectedHost(host)}>{remoteT("sync")}</Button>}
<Button variant="ghost" disabled={reconnecting !== null} onClick={() => void reconnect(host)}>
{reconnecting === host.hostKey ? remoteT("loading") : remoteT("reconnect")}
</Button>
diff --git a/apps/desktop/src/components/workpanel/FilesTab.tsx b/apps/desktop/src/components/workpanel/FilesTab.tsx
index 5f5418231..980286306 100644
--- a/apps/desktop/src/components/workpanel/FilesTab.tsx
+++ b/apps/desktop/src/components/workpanel/FilesTab.tsx
@@ -157,7 +157,11 @@ export function FilesTab() {
const workspace = useAppStore((s) => s.workspace);
const fileRequest = useAppStore((s) => s.workPanelFileRequest);
const showToast = useAppStore((s) => s.showToast);
+ const sessionId = useAppStore((state) => state.activeSessionId);
+ const remote = workspace?.remote;
const root = workspace?.path ?? null;
+ const scopeRef = useRef({ root, sessionId });
+ scopeRef.current = { root, sessionId };
const [dirs, setDirs] = useState<Record<string, DirState>>({});
const [expanded, setExpanded] = useState<Set<string>>(new Set());
@@ -167,6 +171,7 @@ export function FilesTab() {
const [file, setFile] = useState<FsReadResult | null>(null);
const [fileError, setFileError] = useState(false);
const viewerBodyRef = useRef<HTMLDivElement>(null);
+ const fileGeneration = useRef(0);
// Workspace switches reset all browsing state. Guarded so it only fires on
// an actual root change: an unconditional [root] effect also runs on the
@@ -189,13 +194,15 @@ export function FilesTab() {
async (rel: string) => {
if (!root) return;
try {
- const res = await api.fsList(rel);
+ const res = await api.fsList(rel, sessionId);
+ if (scopeRef.current.root !== root || scopeRef.current.sessionId !== sessionId) return;
setDirs((prev) => ({ ...prev, [rel]: { entries: res.entries } }));
} catch {
+ if (scopeRef.current.root !== root || scopeRef.current.sessionId !== sessionId) return;
setDirs((prev) => ({ ...prev, [rel]: { entries: [], error: true } }));
}
},
- [root],
+ [root, sessionId],
);
useEffect(() => {
@@ -220,18 +227,22 @@ export function FilesTab() {
const openFile = useCallback(
async (rel: string, mimeType?: string, position?: { line?: number; column?: number }) => {
+ const request = ++fileGeneration.current;
setSelected(rel);
setSelectedMimeType(mimeType);
setSelectedLine(position?.line);
setFile(null);
setFileError(false);
try {
- setFile(await api.fsRead(rel, mimeType));
+ const result = await api.fsRead(rel, mimeType, sessionId);
+ if (request !== fileGeneration.current || scopeRef.current.root !== root || scopeRef.current.sessionId !== sessionId) return;
+ setFile(result);
} catch {
+ if (request !== fileGeneration.current || scopeRef.current.root !== root || scopeRef.current.sessionId !== sessionId) return;
setFileError(true);
}
},
- [],
+ [root, sessionId],
);
useEffect(() => {
@@ -246,13 +257,13 @@ export function FilesTab() {
}, [file, selectedLine]);
const openMp4 = useCallback(async () => {
- if (!selected) return;
+ if (!selected || remote) return;
try {
- await api.fsOpen(selected, selectedMimeType);
+ await api.fsOpen(selected, selectedMimeType, sessionId);
} catch {
showToast(t("panel.files.openFailed"), { variant: "error" });
}
- }, [selected, selectedMimeType, showToast, t]);
+ }, [selected, selectedMimeType, sessionId, showToast, t]);
// Chat-initiated previews: open the file and expand its ancestor folders
// so "back" lands on a tree that reveals it. Attachment blobs and absolute
@@ -368,15 +379,15 @@ export function FilesTab() {
{selected}
</span>
{file && <span className="file-viewer-size">{formatSize(file.size)}</span>}
- <TooltipButton
+ {!remote ? <TooltipButton
type="button"
className="icon-btn icon-btn-square"
tooltip={t("panel.files.reveal")}
ariaLabel={t("panel.files.reveal")}
- onClick={() => void api.fsReveal(selected)}
+ onClick={() => void api.fsReveal(selected, sessionId)}
>
<IconExternal size={14} />
- </TooltipButton>
+ </TooltipButton> : null}
</div>
<div className="file-viewer-body" ref={viewerBodyRef}>
{fileError ? (
@@ -405,7 +416,7 @@ export function FilesTab() {
: t("panel.files.binary")
}
>
- {isMp4(selected, selectedMimeType) && (
+ {!remote && isMp4(selected, selectedMimeType) && (
<Button type="button" onClick={() => void openMp4()}>
{t("chat.openFile")}
</Button>
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
index ae5eb3e8a..33e31021a 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerDraft.ts
@@ -586,7 +586,7 @@ export function useComposerDraft({
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);
+ const result = await api.fsRead(reference.path, reference.mimeType, sourceSessionId);
if (result.kind !== "text" || result.content === undefined) {
const message =
result.kind === "tooLarge"
diff --git a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts
index d7a33072b..bc6055e7c 100644
--- a/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts
+++ b/apps/desktop/src/features/chat/composer/hooks/useComposerImagePreview.ts
@@ -52,7 +52,7 @@ export function useComposerImagePreview({
};
publish();
for (const reference of images) {
- void api.fsReadImageDataUrl(reference.path, reference.mimeType).then(
+ void api.fsReadImageDataUrl(reference.path, reference.mimeType, sessionId ?? undefined).then(
(result) => {
sources.set(reference.id, result.kind === "image" && result.dataUrl
? { status: "ready", src: result.dataUrl }
diff --git a/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsx b/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsx
index 1c33af163..8d317ac90 100644
--- a/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsx
+++ b/apps/desktop/src/features/chat/transcript/GeneratedImageViewer.tsx
@@ -1,4 +1,5 @@
-import { useChatSessionCapability } from "../../../hooks/use-chat-session-capability";
+import { useSlotSessionId } from "../../../plugins/renderer-slots/use-slots";
+import { useChatNativeFilesAllowed, 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";
@@ -20,6 +21,9 @@ export function GeneratedImageViewer({ images, selectedIndex, onSelect, onClose,
focusReturnRef: RefObject<HTMLElement | null>;
}) {
const { t } = useTranslation();
+ const paneSessionId = useSlotSessionId();
+ const sessionId = useAppStore((state) => paneSessionId || state.activeSessionId);
+ const nativeFilesAllowed = useChatNativeFilesAllowed();
const localToolsAllowed = useChatSessionCapability("canUseLocalTools");
const dialogRef = useRef<HTMLDialogElement>(null);
const viewportRef = useRef<HTMLDivElement>(null);
@@ -105,9 +109,9 @@ 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 (!localToolsAllowed || !selected) return;
+ if (!localToolsAllowed || !nativeFilesAllowed || !selected) return;
try {
- await api.fsReveal(selected.path);
+ await api.fsReveal(selected.path, sessionId);
} catch {
useAppStore.getState().showToast(t("settings.imageRevealFailed"), { variant: "error" });
}
@@ -133,7 +137,7 @@ export function GeneratedImageViewer({ images, selectedIndex, onSelect, onClose,
<strong>{t("settings.generatedImage", { index: selected.index + 1 })}</strong>
<div className="generated-image-viewer-header-actions">
<TooltipButton type="button" onClick={() => { closeViewer(); void openFile(selected.path); }} tooltip={t("chat.previewFile")}><IconExternal size={18} /></TooltipButton>
- <TooltipButton type="button" onClick={() => void reveal()} tooltip={t("settings.revealGeneratedImage")}><IconFolder size={18} /></TooltipButton>
+ {nativeFilesAllowed ? <TooltipButton type="button" onClick={() => void reveal()} tooltip={t("settings.revealGeneratedImage")}><IconFolder size={18} /></TooltipButton> : null}
{src && downloadName ? <a href={src} download={downloadName} aria-label={t("settings.downloadGeneratedImage")} title={t("settings.downloadGeneratedImage")}><IconDownload size={18} /></a> : null}
</div>
</header>
diff --git a/apps/desktop/src/features/projects/ProjectArchiveIndex.tsx b/apps/desktop/src/features/projects/ProjectArchiveIndex.tsx
index c94a373cf..2f6802e05 100644
--- a/apps/desktop/src/features/projects/ProjectArchiveIndex.tsx
+++ b/apps/desktop/src/features/projects/ProjectArchiveIndex.tsx
@@ -91,7 +91,7 @@ export function ProjectArchiveIndex({
<button
type="button"
className="projects-row"
- title={project.path}
+ title={project.remote?.path ?? project.path}
aria-label={t("project.selectProject", { name: project.name })}
aria-expanded={open}
aria-current={open ? "true" : undefined}
@@ -115,7 +115,7 @@ export function ProjectArchiveIndex({
) : null}
</span>
<span className="projects-name-path">
- {shortenPath(project.path)}
+ {shortenPath(project.remote?.path ?? project.path)}
</span>
</span>
<span className="projects-row-meta">
diff --git a/apps/desktop/src/features/projects/ProjectDetailPanel.tsx b/apps/desktop/src/features/projects/ProjectDetailPanel.tsx
index 111074c7e..a58c69c9a 100644
--- a/apps/desktop/src/features/projects/ProjectDetailPanel.tsx
+++ b/apps/desktop/src/features/projects/ProjectDetailPanel.tsx
@@ -69,9 +69,9 @@ export function ProjectDetailPanel({
aria-label={t("project.foldersLabel")}
>
{project.roots.map((root) => (
- <span className="projects-detail-root" key={root.path} title={root.path}>
+ <span className="projects-detail-root" key={root.path} title={project.remote?.path ?? root.path}>
<IconFolder size={12} aria-hidden />
- <span>{shortenPath(root.path)}</span>
+ <span>{shortenPath(project.remote?.path ?? root.path)}</span>
</span>
))}
</div>
diff --git a/apps/desktop/src/hooks/use-chat-file-menu.tsx b/apps/desktop/src/hooks/use-chat-file-menu.tsx
index e41bcd5d8..0e1a167a1 100644
--- a/apps/desktop/src/hooks/use-chat-file-menu.tsx
+++ b/apps/desktop/src/hooks/use-chat-file-menu.tsx
@@ -18,6 +18,7 @@ import { useCallback, type MouseEvent as ReactMouseEvent } from "react";
import { useTranslation } from "react-i18next";
import { useContextMenu, type ContextMenuItem } from "../components/ContextMenu";
import { IconCopy, IconFolderOpen } from "../components/icons";
+import { useChatNativeFilesAllowed } from "./use-chat-session-capability";
import { useCopyChatFileRef, useRevealChatFileRef } from "./use-preview-target";
export type ChatFileMenuTarget = {
@@ -29,21 +30,22 @@ export type ChatFileMenuTarget = {
export function useChatFileMenuItems() {
const { t } = useTranslation();
+ const nativeFilesAllowed = useChatNativeFilesAllowed();
const revealFileRef = useRevealChatFileRef();
const copyFileRef = useCopyChatFileRef();
return useCallback(
({ path, baseDir }: ChatFileMenuTarget): ContextMenuItem[] => [
- {
+ ...(nativeFilesAllowed ? [{
id: "reveal-in-folder",
label: t("chat.revealFileInFolder"),
icon: <IconFolderOpen size={14} />,
onSelect: () => revealFileRef(path, baseDir),
- },
+ }] : []),
{
id: "copy-full-path",
label: t("chat.copyFullPath"),
icon: <IconCopy size={14} />,
- separatorBefore: true,
+ separatorBefore: nativeFilesAllowed,
onSelect: () => copyFileRef(path, baseDir, "absolute"),
},
{
@@ -53,7 +55,7 @@ export function useChatFileMenuItems() {
onSelect: () => copyFileRef(path, baseDir, "relative"),
},
],
- [copyFileRef, revealFileRef, t],
+ [copyFileRef, nativeFilesAllowed, revealFileRef, t],
);
}
diff --git a/apps/desktop/src/hooks/use-chat-session-capability.ts b/apps/desktop/src/hooks/use-chat-session-capability.ts
index bd71088b4..55b784800 100644
--- a/apps/desktop/src/hooks/use-chat-session-capability.ts
+++ b/apps/desktop/src/hooks/use-chat-session-capability.ts
@@ -15,3 +15,14 @@ export function useChatSessionCapability(capability: keyof SessionCapabilities):
);
});
}
+
+/** OS file-manager actions apply only to files owned by this computer. */
+export function useChatNativeFilesAllowed(): boolean {
+ const paneSessionId = useSlotSessionId();
+ return useAppStore((state) => {
+ const id = paneSessionId || state.activeSessionId;
+ const session = state.sessions.find((item) => item.id === id);
+ return sessionAllows(session ?? (id?.startsWith("remote:") ? { id } : undefined), "canUseLocalTools")
+ && !session?.remoteWorkspace && (id ? true : !state.workspace?.remote);
+ });
+}
diff --git a/apps/desktop/src/hooks/use-composer-autocomplete.ts b/apps/desktop/src/hooks/use-composer-autocomplete.ts
index 13ea7f339..00292f44b 100644
--- a/apps/desktop/src/hooks/use-composer-autocomplete.ts
+++ b/apps/desktop/src/hooks/use-composer-autocomplete.ts
@@ -165,6 +165,7 @@ export function useComposerAutocomplete({
composing: boolean;
enabled: boolean;
}) {
+ const sessionId = useAppStore((s) => s.activeSessionId);
const workspaceKey = useAppStore((s) => s.workspace?.path ?? "");
const hasWorkspace = workspaceKey !== "";
const ready = useAppStore((s) => s.ready);
@@ -232,7 +233,7 @@ export function useComposerAutocomplete({
}
let cancelled = false;
void api
- .fsIndex()
+ .fsIndex(sessionId)
.then((res) => {
filesCache = {
key: workspaceKey,
@@ -248,7 +249,7 @@ export function useComposerAutocomplete({
return () => {
cancelled = true;
};
- }, [trigger?.mode, dismissed, workspaceKey, hasWorkspace]);
+ }, [trigger?.mode, dismissed, workspaceKey, hasWorkspace, sessionId]);
// Warm the `/` source once bootstrap settles, so the first slash of a session
// does not wait for a cold host round trip (#1543). Waiting for `ready` keeps
diff --git a/apps/desktop/src/hooks/use-preview-target.ts b/apps/desktop/src/hooks/use-preview-target.ts
index 44cf92c1a..b1131e461 100644
--- a/apps/desktop/src/hooks/use-preview-target.ts
+++ b/apps/desktop/src/hooks/use-preview-target.ts
@@ -171,7 +171,7 @@ function useResolveChatFileRef() {
: null;
let result;
try {
- result = await api.fsResolveRef(anchored ?? raw, sessionId);
+ result = await api.fsResolveRef(anchored ?? raw, ownerId);
} catch {
showToast(t("chat.fileRefLookupFailed"), { variant: "error" });
return null;
@@ -223,9 +223,10 @@ function useResolveChatFileRef() {
*/
export function useOpenChatFileRef() {
const { t } = useTranslation();
+ const paneSessionId = useSlotSessionId();
const resolveRef = useResolveChatFileRef();
const workspacePath = useAppStore((s) => s.workspace?.path ?? null);
- const sessionId = useAppStore((s) => s.activeSessionId);
+ const sessionId = useAppStore((s) => paneSessionId || s.activeSessionId);
const openFile = useAppStore((s) => s.openFileInWorkPanel);
const openUrl = useAppStore((s) => s.openUrlInWorkPanel);
const openTab = useAppStore((s) => s.openWorkPanelTab);
@@ -252,6 +253,7 @@ export function useOpenChatFileRef() {
}
const hasPosition = line !== undefined || column !== undefined;
if (
+ !current.workspace?.remote &&
!hasPosition &&
resolved.inProject &&
resolved.primary &&
@@ -261,7 +263,7 @@ export function useOpenChatFileRef() {
openUrl(resolved.relativePath);
return;
}
- if (resolved.inProject && !hasPosition) {
+ if (!current.workspace?.remote && resolved.inProject && !hasPosition) {
if (await ensureFileManagerView(workspacePath)) {
const latest = useAppStore.getState();
if (
@@ -309,6 +311,8 @@ export function useOpenChatFileRef() {
export function useRevealChatFileRef() {
const { t } = useTranslation();
const resolveRef = useResolveChatFileRef();
+ const paneSessionId = useSlotSessionId();
+ const sessionId = useAppStore((s) => paneSessionId || s.activeSessionId);
const showToast = useAppStore((s) => s.showToast);
return useCallback(
@@ -317,13 +321,13 @@ export function useRevealChatFileRef() {
const resolved = await resolveRef(path, baseDir);
if (!resolved) return;
try {
- await api.fsReveal(resolved.path);
+ await api.fsReveal(resolved.path, sessionId);
} catch {
showToast(t("chat.fileRevealFailed"), { variant: "error" });
}
})();
},
- [resolveRef, showToast, t],
+ [resolveRef, sessionId, showToast, t],
);
}
diff --git a/apps/desktop/src/hooks/use-remote-projects.ts b/apps/desktop/src/hooks/use-remote-projects.ts
index f26ad27b8..663aa8670 100644
--- a/apps/desktop/src/hooks/use-remote-projects.ts
+++ b/apps/desktop/src/hooks/use-remote-projects.ts
@@ -1,14 +1,13 @@
import { useEffect, useMemo, useState } from "react";
-import type { RemoteHostSummary, RacpProjectSummary } from "@pi-desktop/shared";
+import type { RemoteHostSummary } 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. */
+/** Keep existing remote histories reachable without importing Host project catalogs. */
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(() => {
@@ -18,20 +17,14 @@ export function useRemoteProjects(enabled: boolean) {
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]);
+ const projects = useMemo(() => listRemoteProjects(hosts, [], sessions), [hosts, sessions]);
return { projects, busy, error };
}
diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.ts
index ff8c791d3..be16a3e62 100644
--- a/apps/desktop/src/lib/api.ts
+++ b/apps/desktop/src/lib/api.ts
@@ -839,6 +839,8 @@ export const api = {
invoke<{ projects: ProjectRecord[] }>(IPC.invoke.projectList),
listProjectGroups: () =>
invoke<{ groups: ProjectGroupRecord[] }>(IPC.invoke.projectGroupList),
+ createRemoteProjectGroup: (name: string, hostKey: string, path: string) =>
+ invoke<{ group: ProjectGroupRecord }>(IPC.invoke.projectGroupCreateRemote, { name, hostKey, path }),
createProjectGroup: (name: string, folders: string[]) =>
invoke<{ group: ProjectGroupRecord }>(IPC.invoke.projectGroupCreate, { name, folders }),
renameProjectGroup: (groupId: string, name: string) =>
@@ -1398,7 +1400,7 @@ export const api = {
/** Toggles the devtools console; rejects unless developer mode is on. */
toggleDevTools: (open?: boolean) =>
invoke<{ open: boolean }>(IPC.invoke.devtoolsToggle, { open }),
- workspaceDiff: () => invoke<WorkspaceDiff>(IPC.invoke.workspaceDiff),
+ workspaceDiff: (sessionId?: string) => invoke<WorkspaceDiff>(IPC.invoke.workspaceDiff, { ...(sessionId ? { sessionId } : {}) }),
workspaceReviewRollback: (input: {
sessionId: string;
snapshotId: string;
@@ -1419,22 +1421,24 @@ export const api = {
invoke(IPC.invoke.browserOpenExternal, url ? { url } : {}),
browserGetState: () =>
invoke<BrowserState | null>(IPC.invoke.browserGetState),
- fsList: (path?: string) =>
- invoke<{ entries: FsEntry[] }>(IPC.invoke.fsList, { path: path ?? "" }),
- fsRead: (path: string, mimeType?: string) =>
+ fsList: (path?: string, sessionId?: string) =>
+ invoke<{ entries: FsEntry[] }>(IPC.invoke.fsList, { path: path ?? "", ...(sessionId ? { sessionId } : {}) }),
+ fsRead: (path: string, mimeType?: string, sessionId?: string) =>
invoke<FsReadResult>(IPC.invoke.fsRead, {
path,
...(mimeType ? { mimeType } : {}),
+ ...(sessionId ? { sessionId } : {}),
}),
- fsReadImageDataUrl: (ref: string, mimeType?: string) =>
+ fsReadImageDataUrl: (ref: string, mimeType?: string, sessionId?: string) =>
invoke<FsImageDataUrlResult>(IPC.invoke.fsReadImageDataUrl, {
ref,
...(mimeType ? { mimeType } : {}),
+ ...(sessionId ? { sessionId } : {}),
}),
- fsReveal: (path: string) => invoke(IPC.invoke.fsReveal, { path }),
- fsOpen: (path: string, mimeType?: string) =>
- invoke(IPC.invoke.fsOpen, { path, mimeType }),
- fsIndex: () => invoke<FsIndexResult>(IPC.invoke.fsIndex),
+ fsReveal: (path: string, sessionId?: string) => invoke(IPC.invoke.fsReveal, { path, ...(sessionId ? { sessionId } : {}) }),
+ fsOpen: (path: string, mimeType?: string, sessionId?: string) =>
+ invoke(IPC.invoke.fsOpen, { path, mimeType, ...(sessionId ? { sessionId } : {}) }),
+ fsIndex: (sessionId?: string) => invoke<FsIndexResult>(IPC.invoke.fsIndex, { ...(sessionId ? { sessionId } : {}) }),
/**
* Complete a file reference from chat text to a real file (D320 follow-up).
* The main process owns the root order — project, session scratch,
diff --git a/apps/desktop/src/lib/project-archive.ts b/apps/desktop/src/lib/project-archive.ts
index d6b5c2132..036c0b896 100644
--- a/apps/desktop/src/lib/project-archive.ts
+++ b/apps/desktop/src/lib/project-archive.ts
@@ -1,4 +1,5 @@
import type { ProjectMeta } from "./sidebar-preferences.ts";
+import type { RemoteWorkspace } from "@pi-desktop/shared";
import { normalizeProjectPath } from "./sidebar-preferences.ts";
import { projectColor, type RecentProject } from "./recent-projects.ts";
@@ -34,6 +35,7 @@ export type ProjectIndexItem = RecentProject & {
};
export type DurableProjectGroup = {
+ remote?: RemoteWorkspace;
id: string;
name: string;
primaryPath: string;
@@ -307,6 +309,7 @@ export function buildProjectIndex(args: {
if (!key) return;
const existing = byPath.get(key);
byPath.set(key, {
+ ...(group.remote ? { remote: group.remote } : {}),
path: group.primaryPath,
name: group.name,
openedAt: Math.max(existing?.openedAt ?? 0, openedAt),
@@ -344,6 +347,7 @@ export function buildProjectIndex(args: {
color: existing?.color ?? project.color ?? projectColor(project.path),
groupId: existing?.groupId ?? `legacy:${key}`,
roots: existing?.roots ?? [{ path: project.path, name: project.name, position: 0 }],
+ ...(existing?.remote ? { remote: existing.remote } : {}),
legacy: existing?.legacy ?? true,
});
}
@@ -366,6 +370,7 @@ export function buildProjectIndex(args: {
color: existing?.color ?? projectColor(project.path),
groupId: existing?.groupId ?? `legacy:${key}`,
roots: existing?.roots ?? [{ path: project.path, name: project.name, position: 0 }],
+ ...(existing?.remote ? { remote: existing.remote } : {}),
legacy: existing?.legacy ?? true,
});
}
diff --git a/apps/desktop/src/lib/recent-projects.ts b/apps/desktop/src/lib/recent-projects.ts
index b2ddf3c33..e667438ab 100644
--- a/apps/desktop/src/lib/recent-projects.ts
+++ b/apps/desktop/src/lib/recent-projects.ts
@@ -1,4 +1,7 @@
+import type { RemoteWorkspace } from "@pi-desktop/shared";
+
export type RecentProject = {
+ remote?: RemoteWorkspace;
path: string;
name: string;
branch?: string;
@@ -38,6 +41,7 @@ export function loadRecentProjects(): RecentProject[] {
}
export function rememberProject(input: {
+ remote?: RemoteWorkspace;
path: string;
name: string;
branch?: string | null;
@@ -45,6 +49,7 @@ export function rememberProject(input: {
const list = loadRecentProjects().filter((p) => p.path !== input.path);
const prev = loadRecentProjects().find((p) => p.path === input.path);
list.unshift({
+ ...(input.remote ? { remote: input.remote } : {}),
path: input.path,
name: input.name,
branch: input.branch || undefined,
diff --git a/apps/desktop/src/lib/remote-host-workflow.ts b/apps/desktop/src/lib/remote-host-workflow.ts
index 2311746ca..0e134c4ea 100644
--- a/apps/desktop/src/lib/remote-host-workflow.ts
+++ b/apps/desktop/src/lib/remote-host-workflow.ts
@@ -1,14 +1,11 @@
-import type { ProviderPublic, RemoteHostSummary, RacpProjectSummary, SessionSummary, ProviderImportSummary } from "@pi-desktop/shared";
-import { isSyncableProvider } from "@pi-desktop/shared";
+import type { RemoteHostSummary, SessionSummary } from "@pi-desktop/shared";
import { api } from "./api";
import { safeSessionSummary } from "./remote-session-safety";
export type RemoteHostView = {
busy: boolean;
error: string | null;
- projects: RacpProjectSummary[];
sessions: SessionSummary[];
- syncResult: ProviderImportSummary | null;
};
/** One host-owned workflow. Disposal invalidates reads and never replays mutations. */
@@ -18,7 +15,7 @@ export function createRemoteHostWorkflow(
) {
let disposed = false;
let generation = 0;
- let view: RemoteHostView = { busy: false, error: null, projects: [], sessions: [], syncResult: null };
+ let view: RemoteHostView = { busy: false, error: null, sessions: [] };
const listeners = new Set<() => void>();
const publish = (patch: Partial<RemoteHostView>) => {
if (disposed) return;
@@ -38,11 +35,8 @@ export function createRemoteHostWorkflow(
}
};
const read = async (current: () => boolean) => {
- const [projects, sessions] = await Promise.all([
- api.remoteHostProjects(host.hostKey), api.remoteHostSessions(host.hostKey),
- ]);
+ const sessions = await api.remoteHostSessions(host.hostKey);
if (current()) publish({
- projects: projects.projects.filter((project) => !project.archived),
sessions: sessions.sessions.map(safeSessionSummary),
});
};
@@ -59,35 +53,5 @@ export function createRemoteHostWorkflow(
open: (session: SessionSummary) => run(async (current) => {
if (current()) await select(safeSessionSummary(session));
}),
- create: (input: { projectId: string; path: string; title: string }) => run(async (current) => {
- const path = input.path.trim();
- let projectId = input.projectId;
- if (path) {
- // Linux/macOS SSH roots only in the MVP; never resolve against Desktop cwd.
- if (!path.startsWith("/") || path.includes("\0")) throw new Error("REMOTE_ABSOLUTE_PATH_REQUIRED");
- const result = await api.registerRemoteProject(host.hostKey, path);
- if (!current()) return;
- projectId = result.project.id;
- publish({ projects: [...view.projects.filter((project) => project.id !== projectId), result.project] });
- } else if (!view.projects.some((project) => project.id === projectId)) {
- throw new Error("REMOTE_PROJECT_REQUIRED");
- }
- const result = await api.createRemoteSession({
- hostKey: host.hostKey, projectId, mode: "agent", permissionMode: "ask",
- ...(input.title.trim() ? { title: input.title.trim() } : {}),
- });
- if (!current()) return;
- const session = safeSessionSummary(result.session);
- publish({ sessions: [session, ...view.sessions.filter((item) => item.id !== session.id)] });
- await select(session);
- }),
- sync: (providers: ProviderPublic[], selected: string[], consent: boolean, setDefault: boolean) => run(async (current) => {
- const eligible = new Set(providers.filter(isSyncableProvider).map((provider) => provider.id));
- if (host.transport !== "ssh" || !consent || selected.length === 0 || selected.some((id) => !eligible.has(id))) {
- throw new Error("REMOTE_SYNC_CONSENT_REQUIRED");
- }
- const result = await api.syncRemoteProviders({ hostKey: host.hostKey, providerIds: [...new Set(selected)], setDefault });
- if (current()) publish({ syncResult: result });
- }),
};
}
diff --git a/apps/desktop/src/lib/use-referenced-image-data-url.ts b/apps/desktop/src/lib/use-referenced-image-data-url.ts
index e51c6ffe2..7f3e22f2e 100644
--- a/apps/desktop/src/lib/use-referenced-image-data-url.ts
+++ b/apps/desktop/src/lib/use-referenced-image-data-url.ts
@@ -47,6 +47,7 @@ export function useReferencedImageDataUrl(
mimeType?: string,
): string | null {
const paneSessionId = useSlotSessionId();
+ const sessionId = useAppStore((s) => paneSessionId || s.activeSessionId);
const localToolsAllowed = useAppStore((s) => {
const id = paneSessionId || s.activeSessionId;
return sessionAllows(s.sessions.find((item) => item.id === id) ?? (id?.startsWith("remote:") ? { id } : undefined), "canUseLocalTools");
@@ -54,7 +55,7 @@ export function useReferencedImageDataUrl(
const workspaceRoot = useAppStore((s) => localToolsAllowed ? s.workspace?.path ?? null : null);
const normalizedRef = typeof ref === "string" ? ref.trim() : "";
const requestedKey = localToolsAllowed && normalizedRef && !/^(?:https?|data|blob):/i.test(normalizedRef)
- ? cacheKey(workspaceRoot, normalizedRef, mimeType)
+ ? cacheKey(sessionId ? `${workspaceRoot ?? ""}:${sessionId}` : workspaceRoot, normalizedRef, mimeType)
: null;
const [resolved, setResolved] = useState<{ key: string; dataUrl: string | null }>({
key: "", dataUrl: null,
@@ -72,7 +73,7 @@ export function useReferencedImageDataUrl(
let current = true;
setResolved({ key: requestedKey, dataUrl: null });
void api
- .fsReadImageDataUrl(normalizedRef, mimeType)
+ .fsReadImageDataUrl(normalizedRef, mimeType, sessionId)
.then((result) => {
const next = result.kind === "image" && result.dataUrl ? result.dataUrl : null;
if (next) rememberDataUrl(requestedKey, next);
@@ -84,7 +85,7 @@ export function useReferencedImageDataUrl(
return () => {
current = false;
};
- }, [requestedKey, normalizedRef, mimeType]);
+ }, [requestedKey, normalizedRef, mimeType, sessionId]);
if (!requestedKey) return null;
const cached = dataUrlCache.get(requestedKey);
return cached ?? (resolved.key === requestedKey ? resolved.dataUrl : null);
diff --git a/apps/desktop/src/locales/remote.ts b/apps/desktop/src/locales/remote.ts
index 08d6cc92d..0216dbc7b 100644
--- a/apps/desktop/src/locales/remote.ts
+++ b/apps/desktop/src/locales/remote.ts
@@ -2,7 +2,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.",
+ folderPickerTitle: "Choose a folder", folderPath: "Folder path", goToFolder: "Go",
+ openFolder: "Open {{name}}", emptyFolders: "No subfolders in this directory.",
older: "Load older messages", thinking: "Thinking",
newer: "Load newer messages", latest: "Return to latest",
sessions: "Conversations / New conversation",
@@ -53,7 +54,8 @@ export const remoteZh: typeof remoteEn = {
projectHost: "主机", noConnectedHosts: "请先在设置中连接远程主机。",
projectFolder: "远程文件夹", chooseFolder: "选择文件夹或输入路径",
browseFolders: "浏览文件夹", useFolder: "使用此文件夹",
- projectNameHint: "远程项目使用文件夹名称。",
+ folderPickerTitle: "选择文件夹", folderPath: "文件夹路径", goToFolder: "前往",
+ openFolder: "打开 {{name}}", emptyFolders: "此目录下没有子文件夹。",
older: "加载更早消息", thinking: "思考",
newer: "加载较新消息", latest: "返回最新消息",
sessions: "会话 / 新建会话", reconnect: "重新连接", refresh: "刷新", close: "关闭", loading: "处理中…",
diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.ts
index 28151a9e7..c99b4e689 100644
--- a/apps/desktop/src/stores/app-state.ts
+++ b/apps/desktop/src/stores/app-state.ts
@@ -263,6 +263,11 @@ export type AppState = {
abort: () => Promise<void>;
openProject: () => Promise<void>;
closeProjectDialog: () => void;
+ createProjectFromRemote: (input: {
+ name: string;
+ hostKey: string;
+ path: string;
+ }) => Promise<void>;
createProjectFromFolders: (input: {
name: string;
folders: string[];
diff --git a/apps/desktop/src/stores/slices/project-slice.ts b/apps/desktop/src/stores/slices/project-slice.ts
index ab556ae79..37d9d4631 100644
--- a/apps/desktop/src/stores/slices/project-slice.ts
+++ b/apps/desktop/src/stores/slices/project-slice.ts
@@ -234,6 +234,7 @@ export function createProjectSlice({
| "openProject"
| "closeProjectDialog"
| "createProjectFromFolders"
+ | "createProjectFromRemote"
| "createProjectFromGit"
| "clearProject"
| "deleteProject"
@@ -307,6 +308,7 @@ export function createProjectSlice({
};
});
rememberProject({
+ ...(workspace.remote ? { remote: workspace.remote } : {}),
path: workspace.path,
name: workspace.name || workspace.path,
branch: workspace.branch,
@@ -394,6 +396,19 @@ export function createProjectSlice({
{ get, set, runtime },
{ name, folders, primaryPath },
),
+ createProjectFromRemote: async ({ name, hostKey, path }) => {
+ const normalizedName = normalizeProjectName(name);
+ if (!normalizedName) throw new Error(i18n.t("errors.projectNameLength"));
+ const intent = runtime.beginNavigationIntent();
+ const { group } = await api.createRemoteProjectGroup(normalizedName, hostKey, path);
+ if (!runtime.navigationIntentIsCurrent(intent)) return;
+ const workspace = await get().activateProject(group.primaryPath, { navigationIntent: intent });
+ if (!workspace || !runtime.navigationIntentIsCurrent(intent)) return;
+ get().renameProject(group.primaryPath, normalizedName);
+ const onboarding = await api.getOnboarding();
+ if (!runtime.navigationIntentIsCurrent(intent)) return;
+ set({ createProjectDialogOpen: false, onboarding, page: "chat" });
+ },
createProjectFromGit: async ({ name, url, parentPath }) => {
// Clone first, then create the project through the same group path, so a
// checkout and a folder pick produce identical project semantics.
diff --git a/apps/desktop/src/styles/project-create-dialog.css b/apps/desktop/src/styles/project-create-dialog.css
index 586c6d377..cc43e2ad2 100644
--- a/apps/desktop/src/styles/project-create-dialog.css
+++ b/apps/desktop/src/styles/project-create-dialog.css
@@ -492,11 +492,30 @@
}
.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 folder selection has its own navigation space and fixed actions. */
+.remote-folder-dialog-overlay { padding: 24px; }
+.remote-folder-dialog {
+ width: min(100%, 600px); height: min(560px, calc(100vh - 48px));
+ display: flex; flex-direction: column; min-width: 0; overflow: hidden;
+ padding: 0; border: 0; border-radius: var(--radius-lg-plus);
+ background: var(--ds-bg-elevated-opaque); box-shadow: var(--ds-shadow-dialog);
+}
+.remote-folder-dialog-navigation { padding: 0 18px 12px; display: grid; gap: 8px; }
+.remote-folder-dialog-path-entry { display: flex; gap: 8px; min-width: 0; }
+.remote-folder-dialog-path-entry input { min-width: 0; flex: 1; }
+.remote-folder-dialog-path-entry .btn { flex-shrink: 0; }
+.remote-folder-dialog-directory { flex: 1; min-height: 0; overflow-y: auto; padding: 0 18px 12px; overscroll-behavior: contain; }
.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-folder-dialog-entries { display: grid; gap: 4px; }
+.remote-folder-dialog-entry { width: 100%; min-height: 44px; justify-content: flex-start; gap: 10px; }
+.remote-folder-dialog-entry span { flex: 1; min-width: 0; overflow-wrap: anywhere; text-align: left; }
+.remote-folder-dialog-entry svg { flex-shrink: 0; }
+@media (max-width: 480px) {
+ .remote-folder-dialog-overlay { padding: 12px; }
+ .remote-folder-dialog { height: min(560px, calc(100vh - 24px)); }
+ .remote-project-picker .remote-folder-dialog-path-entry { flex-wrap: wrap; }
+ .remote-project-picker .remote-folder-dialog-path-entry input { flex-basis: 100%; }
+}
.remote-project-error { color: var(--ds-error); font-size: var(--text-sm); }
@media (prefers-reduced-motion: reduce) {
diff --git a/apps/desktop/test/boot-remote-hosts.test.mjs b/apps/desktop/test/boot-remote-hosts.test.mjs
index 792ca1a61..aa56d3828 100644
--- a/apps/desktop/test/boot-remote-hosts.test.mjs
+++ b/apps/desktop/test/boot-remote-hosts.test.mjs
@@ -58,8 +58,9 @@ function fakeAdapter(options = {}) {
for (const listener of listeners) listener(envelope);
},
client: {
- request: async (method, params) => {
- requests.push({ method, params });
+ request: async (method, params, timeoutMs) => {
+ requests.push({ method, params, ...(timeoutMs ? { timeoutMs } : {}) });
+ if (options.request && method.startsWith("workspace/")) return options.request(method, params);
if (method === "session/list") {
return { sessions: options.sessions ?? [] };
}
@@ -353,3 +354,39 @@ test("bootstrapHost closes its unadopted outcome when shutdown rejects its queue
assert.equal(adoptions, 0);
assert.equal(forwardCloses, 1, "a queued action rejected before entry still owns its bootstrap outcome");
});
+
+test("workspace execution keeps model configuration local and extends only the tool deadline", async () => {
+ const { dir, cleanup } = await tmpDir();
+ const adapter = fakeAdapter({ request: async () => ({ ok: true, content: "remote result" }) });
+ const boot = createRemoteHostsBoot({ dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(),
+ emit: () => {}, clientInfo: { name: "test", version: "1" }, buildAdapter: () => adapter });
+ try {
+ await boot.addHost({ hostKey: "ssh", label: "SSH", url: "wss://fixture", deviceToken: "fixture-only" });
+ const request = { hostKey: "ssh", path: "/workspace", sessionId: "local", turnId: "turn", toolCallId: "read", toolName: "Read", args: { path: "README.md" }, timeoutMs: 30_000 };
+ assert.deepEqual(await boot.executeWorkspaceTool(request), { ok: true, content: "remote result" });
+ const call = adapter.requests.find(row => row.method === "workspace/toolExecute");
+ assert.equal(call.params.hostKey, undefined);
+ assert.equal(call.timeoutMs, 45_000);
+ assert.equal(call.params.sessionId, "local");
+ assert.ok(!adapter.requests.some(row => /provider|session\/create|project\/register/.test(row.method)));
+ await assert.rejects(boot.executeWorkspaceTool({ ...request, path: "relative" }), { errorCode: "INVALID_ARGUMENT" });
+ await assert.rejects(boot.executeWorkspaceTool({ ...request, toolName: "Plugin" }), { errorCode: "INVALID_ARGUMENT" });
+ await assert.rejects(boot.executeWorkspaceTool({ ...request, timeoutMs: 0 }), { errorCode: "INVALID_ARGUMENT" });
+ } finally { await boot.closeAll(); await cleanup(); }
+});
+
+test("failed workspace execution cancels once and never replays a side effect", async () => {
+ const { dir, cleanup } = await tmpDir();
+ const adapter = fakeAdapter({ request: async (method) => {
+ if (method === "workspace/toolExecute") throw new Error("disconnected");
+ return { ok: true };
+ } });
+ const boot = createRemoteHostsBoot({ dataDir: dir, encryption: reversibleEncryption(), router: createBackendRouter(),
+ emit: () => {}, clientInfo: { name: "test", version: "1" }, buildAdapter: () => adapter });
+ try {
+ await boot.addHost({ hostKey: "ssh", label: "SSH", url: "wss://fixture", deviceToken: "fixture-only" });
+ await assert.rejects(boot.executeWorkspaceTool({ hostKey: "ssh", path: "/workspace", sessionId: "local", turnId: "turn", toolCallId: "write", toolName: "Write", args: { path: "out", content: "new" } }), /disconnected/);
+ assert.equal(adapter.requests.filter(row => row.method === "workspace/toolExecute").length, 1);
+ assert.equal(adapter.requests.filter(row => row.method === "workspace/toolAbort").length, 1);
+ } finally { await boot.closeAll(); await cleanup(); }
+});
diff --git a/apps/desktop/test/chat-file-reveal-menu.test.mjs b/apps/desktop/test/chat-file-reveal-menu.test.mjs
index c3739a6d8..1f9181e54 100644
--- a/apps/desktop/test/chat-file-reveal-menu.test.mjs
+++ b/apps/desktop/test/chat-file-reveal-menu.test.mjs
@@ -133,6 +133,12 @@ const previewTarget = loadModule("../src/hooks/use-preview-target.ts", {
"../lib/work-panel-tabs": loadModule("../src/lib/work-panel-tabs.ts", {}),
});
+const nativeCapability = loadModule("../src/hooks/use-chat-session-capability.ts", {
+ "../lib/remote-session-safety": loadModule("../src/lib/remote-session-safety.ts", {}),
+ "../plugins/renderer-slots/use-slots": { useSlotSessionId: () => "" },
+ "../stores/app-store": { useAppStore },
+});
+
const { useChatFileMenu, useChatFileMenuItems } = loadModule(
"../src/hooks/use-chat-file-menu.tsx",
{
@@ -148,6 +154,7 @@ const { useChatFileMenu, useChatFileMenuItems } = loadModule(
}),
},
"./use-preview-target": previewTarget,
+ "./use-chat-session-capability": nativeCapability,
},
);
@@ -422,3 +429,13 @@ test("the reference labels ship in the catalogs the menu reads", () => {
assert.match(zhCN, /copyFullPath: "复制完整地址"/);
assert.match(zhCN, /copyRelativePath: "复制相对地址"/);
});
+
+test("remote workspace references retain copy actions but never offer local OS reveal", () => {
+ const before = state.sessions;
+ state.sessions = [{ id: state.activeSessionId, remoteWorkspace: { hostKey: "ssh", path: "/work/app" } }];
+ let items;
+ function Harness() { items = useChatFileMenuItems()({ path: "README.md" }); return null; }
+ renderToStaticMarkup(React.createElement(Harness));
+ assert.deepEqual(items.map(item => item.id), ["copy-full-path", "copy-relative-path"]);
+ state.sessions = before;
+});
diff --git a/apps/desktop/test/chat-ref-resolve.test.mjs b/apps/desktop/test/chat-ref-resolve.test.mjs
index 533d86584..9847657ad 100644
--- a/apps/desktop/test/chat-ref-resolve.test.mjs
+++ b/apps/desktop/test/chat-ref-resolve.test.mjs
@@ -9,7 +9,7 @@ import { fileURLToPath, pathToFileURL } from "node:url";
const here = dirname(fileURLToPath(import.meta.url));
register(pathToFileURL(join(here, "helpers/ts-import-hooks.mjs")));
const { isChatRefOutsideRoots, parseChatRef, resolveChatFileRef } = await import(
- "../electron/main/chat-ref-resolve.ts"
+ "../../../packages/host-runtime/src/chat-ref-resolve.ts"
);
/**
diff --git a/apps/desktop/test/composer-file-reference-display.test.mjs b/apps/desktop/test/composer-file-reference-display.test.mjs
index 2b9033281..a17ee1af2 100644
--- a/apps/desktop/test/composer-file-reference-display.test.mjs
+++ b/apps/desktop/test/composer-file-reference-display.test.mjs
@@ -100,7 +100,7 @@ test("text file chips expand into editable draft text", () => {
);
assert.match(composer, /\? \(\) => onExpandText\(token\)/);
assert.match(composer, /event\.key !== "Enter" && event\.key !== " "/);
- assert.match(composer, /const result = await api\.fsRead\(reference\.path, reference\.mimeType\)/);
+ assert.match(composer, /const result = await api\.fsRead\(reference\.path, reference\.mimeType, sourceSessionId\)/);
assert.match(composer, /result\.kind !== "text" \|\| result\.content === undefined/);
assert.match(
composer,
diff --git a/apps/desktop/test/composer-mcp.test.mjs b/apps/desktop/test/composer-mcp.test.mjs
index 421107878..2acc45a37 100644
--- a/apps/desktop/test/composer-mcp.test.mjs
+++ b/apps/desktop/test/composer-mcp.test.mjs
@@ -49,7 +49,7 @@ test("selection uses stable encoded IDs even when labels match", async () => {
assert.equal(expandMcpInvocation("/mcp:docs template text", [{ name: "mcp:docs", kind: "template" }]), null);
});
-function promptFixture(commandService, projectPath = "/repo") {
+function promptFixture(commandService, projectPath = "/repo", remoteWorkspace) {
const handlers = new Map();
const calls = [];
const sidecarCalls = [];
@@ -57,7 +57,7 @@ function promptFixture(commandService, projectPath = "/repo") {
const host = { async call(method, params) {
calls.push({ method, params });
if (method === "settings.get") return {};
- if (method === "session.get") return { session: { id: "target", projectPath, messages: [] } };
+ if (method === "session.get") return { session: { id: "target", projectPath, remoteWorkspace, messages: [] } };
if (method === "session.beginTurn") return { turnId: "turn-1" };
if (method === "session.appendMessage") return {};
assert.fail(`unexpected RPC ${method}`);
@@ -67,7 +67,7 @@ function promptFixture(commandService, projectPath = "/repo") {
getHost: () => host,
getSidecar: () => ({ setProjectInstructionRoot() {}, async call(method, params) {
sidecarCalls.push({ method, params });
- if (method === "agent.steeringContext") return { projectPath, supportsVision: false };
+ if (method === "agent.steeringContext") return { projectPath, remoteWorkspace, supportsVision: false };
return { accepted: true, turnId: "turn-1" };
} }),
getAgentHostBridge: () => null,
@@ -265,3 +265,16 @@ test("cold composer discovery connects enabled MCP servers before the first prom
assert.deepEqual(fixture.sidecarCalls[0].params.mcpToolNames, ["mcp_docs_search"]);
} finally { runtime.disposeAll(); }
});
+
+test("remote workspace prompt and steering never resolve commands from the same local path", async () => {
+ const catalog = service([record("docs")], [ready("docs")]);
+ const selected = (await catalog.buildComposerCommands(null)).find(c => c.kind === "mcp");
+ const roots = [];
+ const fixture = promptFixture({ buildComposerCommands: async root => {
+ roots.push(root);
+ return catalog.buildComposerCommands(root);
+ } }, "/remote/workspace", { hostKey: "ssh", path: "/remote/workspace" });
+ await fixture.prompt(`/${selected.name} inspect`);
+ await fixture.steer(`/${selected.name} inspect again`);
+ assert.deepEqual(roots, [null, null]);
+});
diff --git a/apps/desktop/test/message-image-display.test.mjs b/apps/desktop/test/message-image-display.test.mjs
index dfd102010..b80e8fc2c 100644
--- a/apps/desktop/test/message-image-display.test.mjs
+++ b/apps/desktop/test/message-image-display.test.mjs
@@ -17,7 +17,7 @@ const [transcript, markdown, api, main, panel, protocol, hook] = await Promise.a
test("in-chat image display has a contained renderer-to-main bridge", () => {
assert.match(protocol, /fsReadImageDataUrl: "pi-desktop\/fs\/readImageDataUrl"/);
- assert.match(api, /fsReadImageDataUrl: \(ref: string, mimeType\?: string\)/);
+ assert.match(api, /fsReadImageDataUrl: \(ref: string, mimeType\?: string, sessionId\?: string\)/);
assert.match(main, /IPC\.invoke\.fsReadImageDataUrl/);
assert.match(main, /readOpenableImage\(/);
assert.match(panel, /export async function readOpenableImage\(/);
@@ -32,7 +32,7 @@ test("renderer hook loads referenced image data URLs with a scoped bounded cache
assert.match(hook, /dataUrlCache = new Map<string, string>\(\)/);
assert.match(hook, /DATA_URL_CACHE_ENTRIES/);
assert.match(hook, /DATA_URL_CACHE_MAX_BYTES/);
- assert.match(hook, /fsReadImageDataUrl\(normalizedRef, mimeType\)/);
+ assert.match(hook, /fsReadImageDataUrl\(normalizedRef, mimeType, sessionId\)/);
assert.match(hook, /resolved\.key === requestedKey/);
assert.match(hook, /result\.kind === "image" && result\.dataUrl/);
assert.match(hook, /https\?\|data\|blob/);
diff --git a/apps/desktop/test/remote-mvp-renderer.test.mjs b/apps/desktop/test/remote-mvp-renderer.test.mjs
index 18194e9fa..7ebe58071 100644
--- a/apps/desktop/test/remote-mvp-renderer.test.mjs
+++ b/apps/desktop/test/remote-mvp-renderer.test.mjs
@@ -76,73 +76,38 @@ test("packaged non-developer Settings exposes experimental Remote Hosts", () =>
assert.ok(nav); assert.equal(nav.experimentalBadgeKey, "settings.remoteHosts.experimental");
});
-test("host -> register absolute remote project -> create -> select real store conversation", async () => {
+test("legacy history opens through the regular store without project or model transfer", async () => {
initialize();
- const calls = bridge((channel, input) => {
- if (channel === IPC.invoke.remoteHostProjects) return { projects: [] };
- if (channel === IPC.invoke.remoteHostSessions) return { sessions: [] };
- if (channel === IPC.invoke.remoteHostRegisterProject) { assert.equal(input.path, "/srv/project"); return { project: { id: "p1", label: "Remote project", archived: false } }; }
- if (channel === IPC.invoke.remoteHostCreateSession) return { session: { ...session, projectPath: "/srv/project" } };
- return defaultRead(channel);
- });
+ const calls = bridge((channel) => channel === IPC.invoke.remoteHostSessions ? { sessions: [session] } : defaultRead(channel));
const workflow = createRemoteHostWorkflow(host, selectRemote);
await workflow.load();
- await workflow.create({ projectId: "", path: "/srv/project", title: "Remote task" });
- assert.equal(workflow.getSnapshot().error, null);
+ await workflow.open(workflow.getSnapshot().sessions[0]);
assert.equal(useAppStore.getState().activeSessionId, session.id);
assert.equal(useAppStore.getState().page, "chat");
assert.equal(useAppStore.getState().workspace.path, "/local/private");
- assert.equal(useAppStore.getState().sessions.find((item) => item.id === session.id).projectPath, undefined);
- const create = calls.find((call) => call.channel === IPC.invoke.remoteHostCreateSession);
- assert.deepEqual(create.input, { hostKey: host.hostKey, projectId: "p1", title: "Remote task", mode: "agent", permissionMode: "ask" });
- assert.ok(calls.findIndex((call) => call.channel === IPC.invoke.remoteHostRegisterProject) < calls.indexOf(create));
- assert.ok(!calls.some((call) => [IPC.invoke.projectActivate, IPC.invoke.projectClear, IPC.invoke.sessionConfigure].includes(call.channel)));
+ assert.ok(!calls.some((call) => [IPC.invoke.remoteHostProjects, IPC.invoke.remoteHostCreateSession,
+ IPC.invoke.remoteHostRegisterProject, IPC.invoke.remoteHostSyncProviders].includes(call.channel)));
workflow.dispose();
});
-test("existing project selection does not register and closing during registration never creates/selects", async () => {
+test("closing the historical conversation browser ignores a late inventory result", async () => {
initialize();
- const registration = deferred();
- const selected = [];
- const calls = bridge((channel) => {
- if (channel === IPC.invoke.remoteHostProjects) return { projects: [{ id: "p1", label: "Remote", archived: false }] };
- if (channel === IPC.invoke.remoteHostSessions) return { sessions: [session] };
- if (channel === IPC.invoke.remoteHostRegisterProject) return registration.promise;
- if (channel === IPC.invoke.remoteHostCreateSession) return { session };
- });
- const workflow = createRemoteHostWorkflow(host, async (value) => { selected.push(value); });
- await workflow.load();
- await workflow.create({ projectId: "p1", path: "", title: "" });
- assert.equal(selected.length, 1);
- assert.ok(!calls.some((call) => call.channel === IPC.invoke.remoteHostRegisterProject));
- const pending = workflow.create({ projectId: "", path: "/other", title: "" });
- workflow.dispose(); registration.resolve({ project: { id: "other", label: "Other", archived: false } });
- await pending;
- assert.equal(selected.length, 1);
- assert.equal(calls.filter((call) => call.channel === IPC.invoke.remoteHostCreateSession).length, 1);
+ const pending = deferred();
+ bridge(() => pending.promise);
+ const workflow = createRemoteHostWorkflow(host, async () => assert.fail("late selection"));
+ const load = workflow.load();
+ workflow.dispose();
+ pending.resolve({ sessions: [session] });
+ await load;
+ assert.deepEqual(workflow.getSnapshot().sessions, []);
});
-test("sync starts unselected, requires fresh consent, rejects OAuth/direct host and sends IDs only", async () => {
+test("historical conversation UI exposes no model-copy or remote-create controls", async () => {
initialize();
- const calls = bridge((channel) => channel === IPC.invoke.remoteHostSyncProviders
- ? { imported: [{ sourceId: provider.id, providerId: "remote-provider" }], skipped: [], defaultSet: true } : {});
+ const calls = bridge(() => ({}));
const html = await fixture.render("host", { host, onClose() {} });
- assert.match(html, /API credentials will be copied/);
- const checkboxes = [...html.matchAll(/<input[^>]*type="checkbox"[^>]*>/g)].map((match) => match[0]);
- assert.equal(checkboxes.length, 2);
- assert.ok(!checkboxes[0].includes('checked=""'), "consent must start unchecked");
- const workflow = createRemoteHostWorkflow(host, async () => {});
- await workflow.sync([provider], [], false, true);
- await workflow.sync([provider], [provider.id], false, true);
- await workflow.sync([{ ...provider, hasOauth: true }], [provider.id], true, true);
+ assert.doesNotMatch(html, /API credentials will be copied|type="checkbox"|Sync models|New conversation/);
assert.equal(calls.length, 0);
- await workflow.sync([provider], [provider.id], true, true);
- assert.deepEqual(calls[0].input, { hostKey: host.hostKey, providerIds: [provider.id], setDefault: true });
- assert.equal(workflow.getSnapshot().syncResult.defaultSet, true);
- const direct = createRemoteHostWorkflow({ ...host, transport: "direct" }, async () => {});
- await direct.sync([provider], [provider.id], true, true);
- assert.equal(calls.length, 1);
- workflow.dispose(); direct.dispose();
});
test("reconnect failure remains visible; retry reloads inventory without resending mutations", async () => {
diff --git a/apps/desktop/test/remote-project-dialog-user-path.test.mjs b/apps/desktop/test/remote-project-dialog-user-path.test.mjs
index d5a04fef9..b42a8be89 100644
--- a/apps/desktop/test/remote-project-dialog-user-path.test.mjs
+++ b/apps/desktop/test/remote-project-dialog-user-path.test.mjs
@@ -17,8 +17,9 @@ 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 { FilesTab } from "../../apps/desktop/src/components/workpanel/FilesTab";
+import { ProjectEditDialog } from "../../apps/desktop/src/components/ProjectEditDialog";
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";
@@ -28,33 +29,29 @@ await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,
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 } };
+let releaseOldFile;
+let savedGroup;
+const group = { id: "local-group", name: "My server app", primaryPath: "remote-project:local-group", roots: [{ id: "root", path: "remote-project:local-group", position: 0 }], remote: { hostKey: "h2", path: "/home/user/app" }, createdAt: "2026-10-11T00:00:00Z", updatedAt: "2026-10-11T00:00:00Z" };
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: {} };
+ if (input.path === "/missing") throw new Error("Directory not found");
+ return { path: input.path ?? "/home/user", parent: input.path === "/home/user/app" ? "/home/user" : "/home", entries: input.path === "/home/user/app" ? [] : [{ name: "app", path: "/home/user/app" }] };
+ case IPC.invoke.projectGroupCreateRemote: return new Promise((resolve) => { releaseCreate = () => resolve({ group: { ...group, name: input.name } }); });
+ case IPC.invoke.projectSet: return { workspace: { path: input, name: group.name, remote: group.remote, projectGroup: group } };
+ case IPC.invoke.appGetOnboarding: return { completed: true };
+ case IPC.invoke.fsList: return { entries: [{ name: "README.md", kind: "file", size: 11 }, { name: "old.txt", kind: "file", size: 9 }] };
+ case IPC.invoke.fsRead:
+ if (input.path === "old.txt") return new Promise((resolve) => { releaseOldFile = () => resolve({ kind: "text", content: "old bytes", size: 9 }); });
+ return { kind: "text", content: "remote file", size: 11 };
+ case IPC.invoke.projectGroupList: return { groups: [group] };
+ case IPC.invoke.projectGroupRename: return { group: { ...group, name: input.name } };
default: unexpectedCalls.push(channel); throw new Error("Unexpected IPC: " + channel);
} })();
return { ok: true, data };
@@ -65,91 +62,109 @@ 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);
+const button = (label, scope = document) => [...scope.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 })); }); }
+const picker = () => document.querySelector(".remote-folder-dialog");
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" });
+ useAppStore.setState({ workspace: { path: "/local/app", name: "app" }, activeProjectPath: "/local/app", openProjectPaths: ["/local/app"], openProjects: [{ path: "/local/app", name: "app" }], sessions: [], page: "chat" });
await useAppStore.getState().openProject();
- flushSync(() => view.render(React.createElement(React.Fragment, null, React.createElement(ChatSurface), React.createElement(ProjectCreateDialog))));
+ flushSync(() => view.render(React.createElement(ProjectCreateDialog)));
await until(() => button("Remote"), "remote source button missing");
+ input(document.querySelector("#project-create-name"), "My server app");
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");
+ await until(() => document.querySelector('select')?.value === "h1", "hosts did not load");
+ check(document.querySelector("#project-create-name").value === "My server app", "remote source lost editable local name");
check(!document.querySelector('option[value="offline"]'), "disconnected host offered");
+ check(document.querySelectorAll('select').length === 1, "host project catalog still required");
+ check(!calls.some((entry) => entry.channel === IPC.invoke.remoteHostProjects), "host project catalog was fetched");
+ check(!calls.some((entry) => entry.channel === IPC.invoke.remoteHostBrowseProjects), "browse loaded inside project form");
+ button("Browse folders").click();
+ await until(() => releaseOldBrowse && picker(), "folder dialog missing");
+ check(document.querySelector('.project-create-dialog').inert, "project form was interactive behind folder dialog");
+ picker().dispatchEvent(new KeyboardEvent("keydown", { key: "Escape", bubbles: true, cancelable: true }));
+ await until(() => !picker(), "Escape did not close picker"); await settle();
+ check(document.querySelector('.project-create-dialog'), "Escape closed parent project dialog");
+ check(document.activeElement === button("Browse folders"), "cancel did not restore browse focus");
choose(document.querySelector("select"), "h2");
- await until(() => document.querySelector(".remote-project-browser-path")?.textContent === "/home/user", "new host did not load");
+ button("Browse folders").click();
+ await until(() => picker()?.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");
+ const dialog = picker();
+ check(dialog.scrollWidth <= dialog.clientWidth, "folder dialog overflows narrow window");
+ const controls = [...dialog.querySelectorAll('input:not([disabled]),button:not([disabled])')];
+ controls.at(-1).focus(); controls.at(-1).dispatchEvent(new KeyboardEvent("keydown", { key: "Tab", bubbles: true, cancelable: true }));
+ check(document.activeElement === controls[0], "folder dialog focus trap failed");
+ dialog.querySelector('[aria-label="Open app"]').click();
+ await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user/app", "directory navigation failed");
+ button("Parent directory", picker()).click();
+ await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user", "parent navigation failed");
+ input(picker().querySelector("input"), "/missing");
+ picker().querySelector('form').dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ await until(() => picker()?.querySelector('[role="alert"]')?.textContent.includes("Directory not found"), "directory error missing");
+ check(button("Use this folder", picker()).disabled, "failed directory still selectable");
+ input(picker().querySelector("input"), "/home/user/app");
+ picker().querySelector('form').dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user/app", "path navigation failed");
+ button("Use this folder", picker()).click();
+ await until(() => !picker(), "choose did not close folder dialog"); await settle();
+ check(document.querySelector(".remote-project-picker input").value === "/home/user/app", "chosen path not retained");
+ check(document.querySelector("#project-create-name").value === "My server app", "folder name overrode local project name");
+ check(document.activeElement === button("Browse folders"), "choose did not restore browse focus");
+ button("Browse folders").click();
+ await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user/app", "picker did not reopen selected folder");
+ input(picker().querySelector("input"), "/home/user");
+ picker().querySelector('form').dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ await until(() => picker()?.querySelector(".remote-project-browser-path")?.textContent === "/home/user", "reopened path navigation failed");
+ check(!releaseCreate, "folder navigation submitted the parent project form");
+ button("Cancel", picker()).click(); await until(() => !picker(), "cancel button failed");
+ check(document.querySelector(".remote-project-picker input").value === "/home/user/app", "canceled navigation changed selected project folder");
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");
+ await until(() => releaseCreate, "local remote-bound project creation did not start");
+ const creations = calls.filter((entry) => entry.channel === IPC.invoke.projectGroupCreateRemote);
+ check(creations.length === 1, "duplicate project creation");
+ check(creations[0].input.name === "My server app" && creations[0].input.hostKey === "h2" && creations[0].input.path === "/home/user/app", "local name and remote path not saved together");
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 });
+ await until(() => useAppStore.getState().activeProjectPath === group.primaryPath && !document.querySelector('[role="dialog"]'), "normal project activation failed");
+ check(useAppStore.getState().workspace?.path === group.primaryPath && useAppStore.getState().page === "chat", "remote-bound group did not use normal project state");
+ check(!calls.some((entry) => [IPC.invoke.remoteHostRegisterProject, IPC.invoke.remoteHostCreateSession].includes(entry.channel)), "remote project/session catalog managed creation");
+ flushSync(() => view.render(React.createElement(ProjectEditDialog, { project: { path: group.primaryPath, name: group.name, groupId: group.id }, onClose() {}, onSaved(next) { savedGroup = next; }, onError(error) { throw error; } })));
+ await until(() => document.querySelector('#project-edit-name:not([disabled])'), "edit project did not load");
+ check(document.querySelector('.project-create-folder-path').textContent === "/home/user/app", "remote folder path not shown");
+ check(!document.querySelector('.project-create-add-folder'), "remote project offered native folder picker");
+ check(!document.querySelector('.project-edit-dialog').textContent.includes(group.primaryPath), "synthetic identity leaked in project editor");
+ input(document.querySelector('#project-edit-name'), "Renamed server app");
+ document.querySelector('form').dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
+ await until(() => savedGroup?.name === "Renamed server app", "remote-bound project rename failed");
+ check(calls.some((entry) => entry.channel === IPC.invoke.projectGroupRename && entry.input.name === "Renamed server app"), "rename did not use local project storage");
+ check(!calls.some((entry) => entry.channel === IPC.invoke.projectGroupUpdate), "rename sent synthetic folder to local fs validation");
+ useAppStore.setState({ activeSessionId: "local-persisted-session" });
+ flushSync(() => view.render(React.createElement(FilesTab)));
+ await until(() => document.querySelector('.file-tree-name')?.textContent === "README.md", "normal Files list did not load remote workspace");
+ [...document.querySelectorAll('.file-tree-name')].find((node) => node.textContent === "old.txt").closest('button').click();
+ await until(() => releaseOldFile, "slow remote file read did not begin");
+ document.querySelector('[aria-label="' + i18n.t("panel.files.back") + '"]').click();
+ await until(() => document.querySelector('.file-tree-name'), "file preview back failed");
+ document.querySelector('.file-tree-name').closest('button').click();
+ await until(() => document.querySelector('.file-viewer-body')?.textContent.includes("remote file"), "normal file preview did not show remote bytes");
+ releaseOldFile(); await settle();
+ check(!document.querySelector('.file-viewer-body').textContent.includes("old bytes"), "late remote read replaced newer selected file");
+ check(calls.filter((entry) => [IPC.invoke.fsRead, IPC.invoke.fsList].includes(entry.channel)).every((entry) => entry.input.sessionId === "local-persisted-session"), "Files view lost its owning local session");
+ check(!document.querySelector('[aria-label="' + i18n.t("panel.files.reveal") + '"]'), "remote file preview offered local Finder reveal");
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", {
+test("home project dialog chooses remote folders and creates and renames a local project", {
skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,
}, async () => {
const temp = await mkdtemp(join(root, "apps/desktop/.remote-project-ui-"));
diff --git a/apps/desktop/test/remote-workspace-files.test.mjs b/apps/desktop/test/remote-workspace-files.test.mjs
new file mode 100644
index 000000000..e437a4b7f
--- /dev/null
+++ b/apps/desktop/test/remote-workspace-files.test.mjs
@@ -0,0 +1,41 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { remoteWorkspaceForFiles } = await import("../electron/main/remote/workspace-file-scope.ts");
+const remote = { hostKey: "ssh", path: "/home/app" };
+function hostFor(sessions, selected = "/local/app", groups = [{ primaryPath: "remote-project:group", remote }]) {
+ const calls = [];
+ return { calls, async call(method, params) {
+ calls.push({ method, params });
+ if (method === "session.get") return { session: sessions[params.id] };
+ if (method === "workspace.get") return { workspace: { path: selected } };
+ if (method === "project.groups.list") return { groups };
+ assert.fail("Unexpected persistence request: " + method);
+ } };
+}
+test("a retained remote file view follows its own group while a local project is selected", async () => {
+ const host = hostFor({ remote: { projectPath: "remote-project:group" }, local: { projectPath: "/local/app" } });
+ assert.deepEqual(await remoteWorkspaceForFiles(() => host, "remote"), remote);
+ assert.equal(await remoteWorkspaceForFiles(() => host, "local"), null);
+ assert.equal(host.calls.some(call => call.method === "workspace.get"), false);
+});
+test("a home file view resolves the currently selected remote group without a remote session", async () => {
+ const host = hostFor({}, "remote-project:group");
+ assert.deepEqual(await remoteWorkspaceForFiles(() => host), remote);
+ assert.equal(host.calls.some(call => call.method.startsWith("session.")), false);
+});
+test("missing session or remote binding fails closed instead of reading current local files", async () => {
+ const host = hostFor({ remote: { projectPath: "remote-project:missing" } });
+ await assert.rejects(remoteWorkspaceForFiles(() => host, "missing"), { errorCode: "NOT_FOUND" });
+ await assert.rejects(remoteWorkspaceForFiles(() => host, "remote"), { errorCode: "NOT_FOUND" });
+});
+test("a replaced local Host cannot supply a late remote file binding", async () => {
+ let finish;
+ const owner = { call: () => new Promise(resolve => { finish = resolve; }) };
+ let active = owner;
+ const pending = remoteWorkspaceForFiles(() => active, "session");
+ active = hostFor({});
+ finish({ session: { projectPath: "remote-project:group" } });
+ await assert.rejects(pending, { errorCode: "HOST_UNAVAILABLE" });
+});
diff --git a/apps/desktop/test/remote-workspace-tools.test.mjs b/apps/desktop/test/remote-workspace-tools.test.mjs
new file mode 100644
index 000000000..8952eabad
--- /dev/null
+++ b/apps/desktop/test/remote-workspace-tools.test.mjs
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { register } from "node:module";
+register(new URL("./helpers/ts-import-hooks.mjs", import.meta.url));
+const { createRemoteWorkspaceToolRelay } = await import("../electron/main/remote/remote-workspace-tools.ts");
+const request = {
+ requestId: "request", sessionId: "session", turnId: "turn", toolCallId: "tool",
+ toolName: "Read", args: { path: "README.md" }, remoteWorkspace: { hostKey: "ssh", path: "/work/app" },
+};
+function fixture(execute) {
+ const sent = [], replies = [], aborted = [];
+ let current = true, dispatchable = true;
+ const relay = createRemoteWorkspaceToolRelay({ call: async (method, params) => replies.push({ method, params }) }, {
+ getBoot: () => ({ executeWorkspaceTool: async (input) => { sent.push(input); return execute(input); },
+ abortWorkspaceTool: async (input) => aborted.push(input) }),
+ isCurrent: () => current, isTurnDispatchable: () => dispatchable, log: () => {},
+ });
+ return { relay, sent, replies, aborted, replace: () => { current = false; }, cancelTurn: () => { dispatchable = false; } };
+}
+test("an admitted local turn sends only a workspace tool and completes locally", async () => {
+ const f = fixture(() => ({ ok: true, content: "remote README" }));
+ await f.relay.execute(request);
+ assert.deepEqual(f.sent, [{ hostKey: "ssh", path: "/work/app", sessionId: "session", turnId: "turn",
+ toolCallId: "tool", toolName: "Read", args: { path: "README.md" } }]);
+ assert.deepEqual(f.replies, [{ method: "tools.remoteComplete", params: { requestId: "request", result: { ok: true, content: "remote README" } } }]);
+});
+test("cancelled turns cannot dispatch a remote side effect", async () => {
+ const f = fixture(() => assert.fail("not admitted"));
+ f.cancelTurn();
+ await f.relay.execute(request);
+ assert.equal(f.sent.length, 0);
+ assert.equal(f.replies[0].params.result.errorCode, "TOOL_ABORTED");
+});
+test("abort is routed to the active remote call and never accepts its late success", async () => {
+ let resolve;
+ const f = fixture(() => new Promise((done) => { resolve = done; }));
+ const pending = f.relay.execute(request);
+ f.relay.cancel(request);
+ resolve({ ok: true, content: "late result" });
+ await pending;
+ assert.deepEqual(f.aborted, [{ hostKey: "ssh", sessionId: "session", toolCallId: "tool" }]);
+ assert.equal(f.replies[0].params.result.errorCode, "TOOL_ABORTED");
+});
+test("a replaced local Host does not receive a previous generation result", async () => {
+ let resolve;
+ const f = fixture(() => new Promise((done) => { resolve = done; }));
+ const pending = f.relay.execute(request);
+ f.replace(); f.relay.dispose(); resolve({ ok: true, content: "old result" });
+ await pending;
+ assert.equal(f.aborted.length, 1);
+ assert.equal(f.replies.length, 0);
+});
+test("remote failure remains an observable local tool error without fallback", async () => {
+ const f = fixture(() => { throw Object.assign(new Error("disconnected"), { errorCode: "HOST_DISCONNECTED" }); });
+ await f.relay.execute(request);
+ assert.equal(f.sent.length, 1);
+ assert.equal(f.replies[0].params.result.errorCode, "HOST_DISCONNECTED");
+ assert.equal(f.replies[0].params.result.content.error, "disconnected");
+});
+test("a duplicate dispatch does not remove the original call's cancellation owner", async () => {
+ let resolve;
+ const f = fixture(() => new Promise((done) => { resolve = done; }));
+ const pending = f.relay.execute(request);
+ await f.relay.execute({ ...request, requestId: "duplicate" });
+ f.relay.cancel(request);
+ resolve({ ok: true, content: "late result" });
+ await pending;
+ assert.equal(f.sent.length, 1);
+ assert.equal(f.aborted.length, 1);
+ assert.equal(f.replies.find(reply => reply.params.requestId === "request").params.result.errorCode, "TOOL_ABORTED");
+});
diff --git a/apps/desktop/test/rpc-lifecycle-contract.test.mjs b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
index a087b65e6..a64e5ad14 100644
--- a/apps/desktop/test/rpc-lifecycle-contract.test.mjs
+++ b/apps/desktop/test/rpc-lifecycle-contract.test.mjs
@@ -159,7 +159,12 @@ test("Bash execution remains bounded while permission transport has no deadline"
assert.match(runtimeSource, /defaults to a 60-second timeout/);
assert.match(runtimeSource, /timeoutMs,\n\s+}/);
assert.doesNotMatch(rpcTimeoutSource, /DEFAULT_BASH_RPC_TIMEOUT_MS/);
- assert.match(rpcTimeoutSource, /if \(method === "tools\.execute"\) return undefined/);
+ // A tool relay carries its own budget; the transport must not cut it with the
+ // flat default. The same holds for the remote workspace counterpart.
+ assert.match(
+ rpcTimeoutSource,
+ /if \(method === "tools\.execute" \|\| method === "tools\.workspaceExecute"\) return undefined/,
+ );
});
test("turn ownership and execution queue wake only after durable turn settlement", () => {
diff --git a/apps/desktop/test/settings-project-archive.test.mjs b/apps/desktop/test/settings-project-archive.test.mjs
index d8a34b525..cc09e2bc2 100644
--- a/apps/desktop/test/settings-project-archive.test.mjs
+++ b/apps/desktop/test/settings-project-archive.test.mjs
@@ -140,7 +140,7 @@ test("the index row carries identity and the selected row is its own card header
assert.match(projectsIndexSource, /projects-glyph/);
assert.match(projectsIndexSource, /projects-name-text/);
assert.match(projectsIndexSource, /projects-name-path/);
- assert.match(projectsIndexSource, /shortenPath\(project\.path\)/);
+ assert.match(projectsIndexSource, /shortenPath\(project\.remote\?\.path \?\? project\.path\)/);
// Detail reads right to left, capped by a disclosure indicator that turns
// down once the row owns an open card.
assert.match(projectsIndexSource, /projects-row-meta/);
diff --git a/apps/desktop/test/sidebar-navigation.test.mjs b/apps/desktop/test/sidebar-navigation.test.mjs
index c1f5af169..ac1828cba 100644
--- a/apps/desktop/test/sidebar-navigation.test.mjs
+++ b/apps/desktop/test/sidebar-navigation.test.mjs
@@ -252,12 +252,14 @@ test("project rows expose folder actions and full-path hover", () => {
assert.doesNotMatch(sidebarSource, /api\.openSessionFolder\(/);
assert.match(
sidebarSource,
- /className="sidebar-session-group-title project-toggle"[\s\S]*?tooltip=\{entry\.path\}[\s\S]*?tooltipDelayMs=\{500\}[\s\S]*?aria-describedby=\{`\$\{projectId\}-path-description`\}/,
+ /className="sidebar-session-group-title project-toggle"[\s\S]*?tooltip=\{entry\.displayPath \?\? entry\.path\}[\s\S]*?tooltipDelayMs=\{500\}[\s\S]*?aria-describedby=\{`\$\{projectId\}-path-description`\}/,
);
assert.match(sidebarSource, /<TooltipButton/);
assert.match(globalStyles, /\.ui-tooltip-path\s*\{[^}]*width:\s*max-content/);
assert.match(globalStyles, /\.ui-tooltip-path\s*\{[^}]*max-width:\s*min\(420px,\s*calc\(100vw - 16px\)\)/);
- assert.match(sidebarSource, /className="sr-only">\s*\{entry\.path\}/);
+ // The hover text and its accessible description name the path the project
+ // really lives at: the remote workspace path for a remote project.
+ assert.match(sidebarSource, /className="sr-only">\s*\{entry\.displayPath \?\? entry\.path\}/);
});
test("sidebar row menus omit project reassignment and switching actions", () => {
diff --git a/apps/desktop/test/subagent-wiring.test.mjs b/apps/desktop/test/subagent-wiring.test.mjs
index 68b7b3cc0..d3f3d6f1e 100644
--- a/apps/desktop/test/subagent-wiring.test.mjs
+++ b/apps/desktop/test/subagent-wiring.test.mjs
@@ -34,7 +34,13 @@ test("every launch resolves the subagent catalog and its pinned models", () => {
assert.match(sessionLaunchSource, /resolveSubagentProviders,/);
// The catalog is re-read per prompt, registry documents included, so an edit
// in the UI takes effect on the next turn with no restart (D202).
- assert.match(sessionLaunchSource, /await loadSubagentDefinitions\(projectPath, \{/);
+ // A remote workspace has no local instruction root: project files that merely
+ // share the remote path must never be scanned on this machine.
+ assert.match(
+ sessionLaunchSource,
+ /const localInstructionRoot = remoteWorkspace \? undefined : projectPath/,
+ );
+ assert.match(sessionLaunchSource, /await loadSubagentDefinitions\(localInstructionRoot, \{/);
assert.match(
sessionLaunchSource,
/userDocuments: await activeUserSubagentDocuments\(projectPath\),/,
diff --git a/apps/desktop/test/transcript-file-chips.test.mjs b/apps/desktop/test/transcript-file-chips.test.mjs
index c1d4552fe..223c72992 100644
--- a/apps/desktop/test/transcript-file-chips.test.mjs
+++ b/apps/desktop/test/transcript-file-chips.test.mjs
@@ -86,7 +86,10 @@ test("a file chip is routed by where the reference resolved, never optimisticall
// The OS handoff is no longer what a chat click does; the channel itself
// stays part of the public IPC surface.
assert.doesNotMatch(hook, /api\.fsOpen\(/);
- assert.match(api, /fsOpen: \(path: string, mimeType\?: string\) =>\s*invoke\(IPC\.invoke\.fsOpen, \{ path, mimeType \}\)/);
+ assert.match(
+ api,
+ /fsOpen: \(path: string, mimeType\?: string, sessionId\?: string\) =>\s*invoke\(IPC\.invoke\.fsOpen, \{ path, mimeType, \.\.\.\(sessionId \? \{ sessionId \} : \{\}\) \}\)/,
+ );
});
test("Markdown file anchors use the same project-file opener as inline references", () => {
diff --git a/apps/pi-host/README.md b/apps/pi-host/README.md
index 36940aebe..a07e846cb 100644
--- a/apps/pi-host/README.md
+++ b/apps/pi-host/README.md
@@ -12,30 +12,30 @@ Use a Desktop and Host bundle built from the same candidate.
2. Add an SSH host using your existing SSH key/configuration, or password where
supported. Bootstrap downloads the same-version platform bundle and verifies
the published checksum. The server needs Node and outbound release access.
-3. If the Host needs a model, open **Conversations / New conversation** on the
- connected host. Select eligible model configurations and explicitly consent to copying their
- API credentials to that host. Optionally set its default model. OAuth,
- CLI/plugin providers and local-only endpoints are excluded. Direct URL pairing
- does not offer credential copy.
-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 recovers
- subscriptions and pending requests without resending the turn.
-
-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.
+3. Return to Chat home and open **Create project**. Choose the connected Host,
+ open the directory-selection dialog, and choose or enter the remote directory.
+ Name the project locally, exactly as for a local project.
+4. Use the ordinary project switcher, sidebar and archive. New chats are local
+ sessions bound to the remote workspace. Select any configured local model;
+ its credentials, model requests, project metadata and transcript stay locally.
+5. Send a message, approve tools locally, and inspect Files / Review. Read, Glob,
+ Grep, Write, Edit and Bash execute on the paired Host through the owner-only
+ workspace service. A disconnected Host produces an error and never falls back
+ to local filesystem execution. Reconnect never replays a mutation.
+
+The local Agent and regular Composer are shared with local chats. Host-side model
+configuration, project registration and session creation are not prerequisites.
+Legacy remote-Agent histories still use their original backend. Trusted-extension
+model providers remain local; an extension workspace `pi.exec` needs a remote
+adapter and currently fails explicitly, while a local model helper can specify
+its local cwd. Remote terminal and legacy session features retain their existing
+capability boundaries. This is not full R2 acceptance.
**Release prerequisite:** automatic SSH install uses published release assets.
Building this branch does not update an existing release. Publish a matching
platform Host bundle before distributing the automatic-install path. For local
candidate testing, use the isolated acceptance commands below; do not point an
-old Host at a candidate Desktop and assume provider import is available.
+old Host at a candidate Desktop and assume workspace tool/file services are available.
## Build and validate a candidate
@@ -71,7 +71,17 @@ install a second dependency environment just to execute these tests.
remains the separate gate for release download, SSH/password login and recovery
on another machine. Tests require no production credentials or paid model calls.
-## Provider import operational behavior
+## Local-Agent workspace service
+
+The Host advertises additive `workspaceTools` / `workspaceFiles` capabilities.
+Only authenticated owners can use workspace/toolShell, workspace/toolExecute,
+workspace/toolAbort and workspace/files. The pure Rust runner enforces existing
+path containment and shell identity, with no Host provider, project or session
+creation. Active calls are owned by their originating connection and cancelled
+when it closes. Arguments/results are bounded to 1 MiB; operations are not
+replayed. Install a matching Host bundle before using this new workflow.
+
+## Legacy remote-Agent provider import operational behavior
The UI sends only IDs to Main. Main sends a version-1 payload over SSH stdin to
`node "$HOME/.pi-desktop/pi-host/current/pi-host.js" provider-import`. The CLI
@@ -95,12 +105,14 @@ See [remote architecture](../../docs/spec/02-architecture/05-remote-agent-contro
## Candidate notes (unreleased)
-- Experimental Remote Hosts is available without developer mode, with explicit
- model copy, project/session entry, text chat, approvals and read-only files/diffs.
+- Experimental Remote Hosts is available without developer mode. New projects use
+ a local Agent and local models with remote workspace tools and files. Legacy
+ remote-Agent sessions preserve their explicit provider-import behavior.
- Complete runtime packaging and bounded reconnect recovery avoid missing chunks,
duplicate turns, stale approval cards and remote-to-local routing fallback.
-- No local data migration or database schema change. Existing local sessions and
- provider configuration are preserved. Full R2 and publication are not implied.
+- Remote project bindings are additive local project metadata. Existing local
+ sessions and provider configuration are preserved. Full R2 and publication are
+ not implied.
- An SSH bootstrap already downloading/installing has no mid-step cancellation
interface yet. Closing prevents late registration and releases a returned forward,
but does not undo or immediately interrupt an already-started remote installation.
diff --git a/apps/pi-host/src/host-operations.ts b/apps/pi-host/src/host-operations.ts
index 9e7358cd0..6bc825201 100644
--- a/apps/pi-host/src/host-operations.ts
+++ b/apps/pi-host/src/host-operations.ts
@@ -1,3 +1,5 @@
+import { createWorkspaceFiles } from "./workspace-files.js";
+import { createWorkspaceTools } from "./workspace-tools.js";
import { readdir, realpath, stat } from "node:fs/promises";
import { homedir } from "node:os";
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
@@ -252,6 +254,8 @@ export function createHostOperations(deps: HostOperationsDeps): Omit<RacpHostOpe
sessions: createSessionCatalog(deps),
projects: createProjectCatalog(deps),
workspace: createWorkspaceAccess(deps),
+ workspaceTools: createWorkspaceTools(deps.getHost),
+ workspaceFiles: createWorkspaceFiles(),
...(deps.revokeDevice ? { revokeDevice: deps.revokeDevice } : {}),
};
}
diff --git a/apps/pi-host/src/workspace-files.test.ts b/apps/pi-host/src/workspace-files.test.ts
new file mode 100644
index 000000000..081ffb82c
--- /dev/null
+++ b/apps/pi-host/src/workspace-files.test.ts
@@ -0,0 +1,37 @@
+import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import { createWorkspaceFiles } from "./workspace-files.js";
+
+const dirs: string[] = [];
+afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); });
+const fixture = async () => {
+ const path = await mkdtemp(join(tmpdir(), "workspace-files-")); dirs.push(path);
+ await mkdir(join(path, "src")); await writeFile(join(path, "src", "main.ts"), "remote source");
+ return path;
+};
+describe("sessionless SSH file views", () => {
+ it("lists, indexes, resolves shorthand and reads the chosen root with the local file contract", async () => {
+ const path = await fixture(); const files = createWorkspaceFiles();
+ expect(await files.read({ path, operation: "list" })).toMatchObject({ entries: [{ name: "src", kind: "dir" }] });
+ expect(await files.read({ path, operation: "index" })).toMatchObject({ entries: [{ path: "src", kind: "dir" }, { path: "src/main.ts", kind: "file" }] });
+ const resolved = await files.read({ path, operation: "resolve", ref: "main.ts" });
+ expect(resolved).toMatchObject({ match: { relativePath: "src/main.ts", root: "workspace", absolutePath: join(await realpath(path), "src", "main.ts") } });
+ expect(await files.read({ path, operation: "read", ref: "src/main.ts" })).toEqual({ kind: "text", content: "remote source", size: 13 });
+ });
+ it("does not fall back to this computer or cross symlink containment", async () => {
+ const path = await fixture(); const outside = await fixture(); const files = createWorkspaceFiles();
+ await symlink(join(outside, "src", "main.ts"), join(path, "escaped.ts"));
+ await expect(files.read({ path, operation: "read", ref: join(outside, "src", "main.ts") })).rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });
+ await expect(files.read({ path, operation: "read", ref: "escaped.ts" })).rejects.toMatchObject({ code: "REMOTE_PATH_FORBIDDEN" });
+ expect(await files.read({ path, operation: "resolve", ref: join(outside, "src", "main.ts") })).toEqual({ match: null, reason: "outside-allowed-roots" });
+ });
+ it("supports canonical root aliases and refuses nonexistent/nonabsolute roots", async () => {
+ const path = await fixture(); const link = `${path}-link`; dirs.push(link); await symlink(path, link);
+ const files = createWorkspaceFiles();
+ expect(await files.read({ path: link, operation: "read", ref: "src/main.ts" })).toMatchObject({ content: "remote source" });
+ await expect(files.read({ path: "relative", operation: "list" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ await expect(files.read({ path: join(path, "missing"), operation: "list" })).rejects.toMatchObject({ code: "REMOTE_PATH_NOT_FOUND" });
+ });
+});
diff --git a/apps/pi-host/src/workspace-files.ts b/apps/pi-host/src/workspace-files.ts
new file mode 100644
index 000000000..50ea84a30
--- /dev/null
+++ b/apps/pi-host/src/workspace-files.ts
@@ -0,0 +1,34 @@
+import { realpath, stat } from "node:fs/promises";
+import { basename, isAbsolute } from "node:path";
+import { RacpError } from "@pi-desktop/agent-host";
+import { collectWorkspaceDiff, getWorkspaceFileIndex, isChatRefOutsideRoots, listDir, readOpenableFile, readOpenableImage, resolveChatFileRef } from "@pi-desktop/host-runtime";
+import type { RacpHostOperations } from "@pi-desktop/racp";
+
+/** File views are rooted in the explicit SSH workspace, without Host sessions. */
+export function createWorkspaceFiles(): NonNullable<RacpHostOperations["workspaceFiles"]> {
+ return { async read(input) {
+ if (!isAbsolute(input.path) || /[\u0000-\u001f]/.test(input.path)) throw new RacpError("INVALID_ARGUMENT", "invalid workspace root");
+ const root = await realpath(input.path).catch(() => undefined);
+ if (!root || !(await stat(root)).isDirectory()) throw new RacpError("REMOTE_PATH_NOT_FOUND", "workspace directory is unavailable");
+ const ref = input.ref ?? "";
+ try {
+ switch (input.operation) {
+ case "list": return { entries: await listDir(root, ref) };
+ case "read": return await readOpenableFile(ref, root, [], input.mimeType);
+ case "image": return await readOpenableImage(ref, root, [], input.mimeType);
+ case "index": return await getWorkspaceFileIndex(root);
+ case "diff": return await collectWorkspaceDiff(root);
+ case "resolve": {
+ const roots = { project: [{ path: root, name: basename(root), primary: true }] };
+ if (await isChatRefOutsideRoots(ref, roots)) return { match: null, reason: "outside-allowed-roots" };
+ return { match: await resolveChatFileRef(ref, roots) };
+ }
+ }
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ if (/escapes workspace root|outside allowed roots|not openable/.test(message)) throw new RacpError("REMOTE_PATH_FORBIDDEN", message);
+ if ((error as NodeJS.ErrnoException)?.code === "ENOENT") throw new RacpError("REMOTE_PATH_NOT_FOUND", message);
+ throw error;
+ }
+ } };
+}
diff --git a/apps/pi-host/src/workspace-tools.test.ts b/apps/pi-host/src/workspace-tools.test.ts
new file mode 100644
index 000000000..f7666aafc
--- /dev/null
+++ b/apps/pi-host/src/workspace-tools.test.ts
@@ -0,0 +1,59 @@
+import { mkdtemp, rm, symlink } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+import type { HostRpc } from "@pi-desktop/host-runtime";
+import { createWorkspaceTools } from "./workspace-tools.js";
+
+const dirs: string[] = [];
+afterEach(async () => { for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true }); });
+const owner = { deviceId: "paired-device", connectionId: "connection-a" };
+const input = (path: string) => ({ path, sessionId: "local-session", turnId: "local-turn", toolCallId: "call-1", toolName: "Read" as const, args: { path: "README.md" } });
+const directory = async () => { const dir = await mkdtemp(join(tmpdir(), "remote-tools-")); dirs.push(dir); return dir; };
+
+describe("owner workspace tools", () => {
+ it("canonicalizes root and dispatches only the pure runner, without project/session/provider writes", async () => {
+ const dir = await directory();
+ const link = `${dir}-link`; dirs.push(link); await symlink(dir, link);
+ const calls: Array<{ method: string; params: Record<string, unknown> }> = [];
+ const host: HostRpc = { async call<T>(method: string, params: Record<string, unknown> = {}) { calls.push({ method, params }); return { ok: true, content: "remote file" } as T; } };
+ const tools = createWorkspaceTools(() => host);
+ expect(await tools.execute(input(link), owner)).toEqual({ ok: true, content: "remote file", toolCallId: "call-1" });
+ expect(calls).toHaveLength(1); expect(calls[0]?.method).toBe("tools.workspaceExecute");
+ expect(calls[0]?.params.path).not.toBe(link);
+ expect(calls[0]?.params.sessionId).not.toBe("local-session");
+ await expect(tools.execute(input(link), owner)).rejects.toMatchObject({ code: "CONFLICT" });
+ await tools.execute(input(link), { ...owner, deviceId: "another-device" });
+ expect(calls[1]?.params.sessionId).not.toBe(calls[0]?.params.sessionId);
+ });
+ it("rejects unknown tools, relative paths, oversized args and unavailable roots without RPC", async () => {
+ let calls = 0;
+ const host: HostRpc = { async call<T>() { calls++; return {} as T; } };
+ const tools = createWorkspaceTools(() => host);
+ await expect(tools.execute(input("relative"), owner)).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ await expect(tools.execute({ ...input("/"), args: { content: "x".repeat(1024 * 1024) } }, owner)).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ await expect(tools.execute(input("/nonexistent/remote-fixture"), owner)).rejects.toMatchObject({ code: "REMOTE_PATH_NOT_FOUND" });
+ expect(calls).toBe(0);
+ });
+ it("disconnect cancels owned active calls and never accepts a late result", async () => {
+ const dir = await directory();
+ let release: (() => void) | undefined;
+ let started: (() => void) | undefined;
+ const ready = new Promise<void>(resolve => { started = resolve; });
+ const methods: string[] = [];
+ const host: HostRpc = { async call<T>(method: string) {
+ methods.push(method);
+ if (method === "tools.workspaceExecute") { started?.(); await new Promise<void>(resolve => { release = resolve; }); }
+ return { ok: true, content: "late" } as T;
+ } };
+ const tools = createWorkspaceTools(() => host);
+ const pending = tools.execute(input(dir), owner);
+ await ready;
+ await tools.abort({ sessionId: "local-session", toolCallId: "call-1" }, { ...owner, deviceId: "other" });
+ expect(methods).toEqual(["tools.workspaceExecute"]);
+ await tools.disconnect(owner.connectionId);
+ const rejection = expect(pending).rejects.toMatchObject({ code: "AGENT_UNAVAILABLE" });
+ release?.(); await rejection;
+ expect(methods).toEqual(["tools.workspaceExecute", "tools.workspaceAbort"]);
+ });
+});
diff --git a/apps/pi-host/src/workspace-tools.ts b/apps/pi-host/src/workspace-tools.ts
new file mode 100644
index 000000000..578a98eab
--- /dev/null
+++ b/apps/pi-host/src/workspace-tools.ts
@@ -0,0 +1,71 @@
+import { createHash } from "node:crypto";
+import { realpath, stat } from "node:fs/promises";
+import { isAbsolute } from "node:path";
+import { RacpError } from "@pi-desktop/agent-host";
+import { isCommandShellCatalog, type CommandShellCatalog, type WorkspaceToolExecute, type WorkspaceToolResult } from "@pi-desktop/shared";
+import type { HostRpc } from "@pi-desktop/host-runtime";
+import type { RacpHostOperations } from "@pi-desktop/racp";
+
+type Owner = { deviceId: string; connectionId: string };
+type Active = { owner: Owner; host: HostRpc; sessionId: string; toolCallId: string; cancelled: boolean };
+const TOOLS = new Set(["Read", "Glob", "Grep", "Write", "Edit", "Bash"]);
+const MAX_ACTIVE = 32;
+const MAX_SEEN = 4096;
+const MAX_BYTES = 1024 * 1024;
+
+/** Tool-only owner service. No provider, session or project persistence is needed. */
+export function createWorkspaceTools(getHost: () => HostRpc | null): NonNullable<RacpHostOperations["workspaceTools"]> {
+ const active = new Map<string, Active>();
+ const seen = new Set<string>();
+ const id = (owner: Owner, sessionId: string) => createHash("sha256").update(JSON.stringify([owner.deviceId, sessionId])).digest("hex");
+ const key = (owner: Owner, sessionId: string, toolCallId: string) => JSON.stringify([owner.deviceId, sessionId, toolCallId]);
+ const unavailable = () => new RacpError("AGENT_UNAVAILABLE", "workspace tool Host is unavailable");
+ const abortEntry = async (entry: Active) => {
+ entry.cancelled = true;
+ await entry.host.call("tools.workspaceAbort", { sessionId: entry.sessionId, toolCallId: entry.toolCallId });
+ };
+ return {
+ async execute(input: WorkspaceToolExecute, owner: Owner): Promise<WorkspaceToolResult> {
+ if (!owner.deviceId || !TOOLS.has(input.toolName) || !isAbsolute(input.path) || /[\u0000-\u001f]/.test(input.path)
+ || Buffer.byteLength(JSON.stringify(input.args)) > MAX_BYTES) throw new RacpError("INVALID_ARGUMENT", "invalid workspace tool request");
+ const requestKey = key(owner, input.sessionId, input.toolCallId);
+ if (active.has(requestKey) || seen.has(requestKey)) throw new RacpError("CONFLICT", "workspace tool execution cannot be replayed");
+ if (active.size >= MAX_ACTIVE) throw new RacpError("CONFLICT", "workspace tool execution capacity is exhausted");
+ const host = getHost();
+ if (!host) throw unavailable();
+ const entry: Active = { owner, host, sessionId: id(owner, input.sessionId), toolCallId: input.toolCallId, cancelled: false };
+ seen.add(requestKey);
+ while (seen.size > MAX_SEEN) seen.delete(seen.values().next().value!);
+ active.set(requestKey, entry);
+ try {
+ const path = await realpath(input.path).catch(() => undefined);
+ if (!path || !(await stat(path)).isDirectory()) throw new RacpError("REMOTE_PATH_NOT_FOUND", "workspace directory is unavailable");
+ if (entry.cancelled || getHost() !== host) throw unavailable();
+ const result = await host.call<WorkspaceToolResult>("tools.workspaceExecute", {
+ ...input, path, sessionId: entry.sessionId,
+ });
+ if (entry.cancelled || getHost() !== host) throw unavailable();
+ if (!result || typeof result.ok !== "boolean" || !Object.hasOwn(result, "content")
+ || Buffer.byteLength(JSON.stringify(result)) > MAX_BYTES) throw new RacpError("INTERNAL", "invalid workspace tool response");
+ return { ...result, toolCallId: input.toolCallId };
+ } finally {
+ if (active.get(requestKey) === entry) active.delete(requestKey);
+ }
+ },
+ async abort(input, owner) {
+ const entry = active.get(key(owner, input.sessionId, input.toolCallId));
+ if (entry) await abortEntry(entry);
+ },
+ async shell() {
+ const host = getHost();
+ if (!host) throw unavailable();
+ const catalog = await host.call<CommandShellCatalog>("commandShells.list", {});
+ if (getHost() !== host) throw unavailable();
+ if (!isCommandShellCatalog(catalog) || !catalog.effective?.available) throw new RacpError("CAPABILITY_UNAVAILABLE", "workspace command shell is unavailable");
+ return catalog.effective;
+ },
+ async disconnect(connectionId) {
+ await Promise.all([...active.values()].filter(entry => entry.owner.connectionId === connectionId).map(abortEntry));
+ },
+ };
+}
diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rs
index 9418b08d1..82fc5cedb 100644
--- a/crates/host-core/src/db.rs
+++ b/crates/host-core/src/db.rs
@@ -32,7 +32,10 @@ pub(crate) use migrations::{
};
pub(crate) use model::PlanWorkRow;
pub use model::{Database, ProjectMemoryEntryRecord, ProjectMemoryRecord, ProjectRecord};
-pub use project_groups::{ProjectGroupContextRecord, ProjectGroupRecord, ProjectGroupRoot};
+pub use project_groups::{
+ ProjectGroupContextRecord, ProjectGroupRecord, ProjectGroupRoot, RemoteWorkspace,
+ REMOTE_PROJECT_PREFIX,
+};
pub(crate) use repositories::{
canonical_project_path, normalize_project_path, project_display_name,
strip_obsolete_plan_approval_permission_mode, upsert_project_row, MAX_PROJECT_MEMORY_BYTES,
diff --git a/crates/host-core/src/db/project_groups.rs b/crates/host-core/src/db/project_groups.rs
index 93d923895..4d4e40017 100644
--- a/crates/host-core/src/db/project_groups.rs
+++ b/crates/host-core/src/db/project_groups.rs
@@ -14,6 +14,31 @@ const GROUP_INSTRUCTIONS_NAMESPACE: &str = "projectGroupInstructions";
pub const MAX_PROJECT_GROUP_NAME_CHARS: usize = 80;
pub const MAX_PROJECT_GROUP_INSTRUCTIONS_BYTES: usize = 32 * 1024;
+pub const REMOTE_PROJECT_PREFIX: &str = "remote-project:";
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase", deny_unknown_fields)]
+pub struct RemoteWorkspace {
+ pub host_key: String,
+ pub path: String,
+}
+
+impl RemoteWorkspace {
+ pub fn validate(&self) -> Result<()> {
+ if self.host_key.trim().is_empty()
+ || self.host_key.len() > 200
+ || self.host_key.contains(':')
+ || self.host_key.chars().any(char::is_control)
+ || !self.path.starts_with('/')
+ || self.path.len() > 4096
+ || self.path.chars().any(char::is_control)
+ {
+ return Err(anyhow!("invalid remote workspace binding"));
+ }
+ Ok(())
+ }
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProjectGroupRoot {
@@ -38,6 +63,8 @@ pub struct ProjectGroupRecord {
/// Roots removed without chats remain suppressed as legacy projections.
#[serde(default)]
pub detached_paths: Vec<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub remote: Option<RemoteWorkspace>,
}
#[derive(Debug, Clone, Serialize)]
@@ -47,6 +74,8 @@ pub struct ProjectGroupContextRecord {
pub roots: Vec<ProjectGroupRoot>,
pub instructions: String,
pub memory: ProjectMemoryRecord,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub remote: Option<RemoteWorkspace>,
}
fn group_from_value(raw: &str) -> Result<ProjectGroupRecord> {
@@ -60,6 +89,16 @@ fn group_from_value(raw: &str) -> Result<ProjectGroupRecord> {
if group.roots[0].path != group.primary_path {
return Err(anyhow!("project group primary root must be first"));
}
+ if let Some(remote) = &group.remote {
+ remote.validate()?;
+ if group.primary_path != format!("{REMOTE_PROJECT_PREFIX}{}", group.id)
+ || group.roots.len() != 1
+ {
+ return Err(anyhow!("invalid remote project identity"));
+ }
+ } else if group.primary_path.starts_with(REMOTE_PROJECT_PREFIX) {
+ return Err(anyhow!("remote project identity requires a binding"));
+ }
Ok(group)
}
@@ -79,10 +118,76 @@ fn legacy_group(project: &ProjectRecord) -> ProjectGroupRecord {
last_opened_at: project.last_opened_at,
legacy: true,
detached_paths: Vec::new(),
+ remote: None,
}
}
impl Database {
+ pub fn remote_workspace_for_path(&self, path: &str) -> Result<Option<RemoteWorkspace>> {
+ if !path.starts_with(REMOTE_PROJECT_PREFIX) {
+ return Ok(None);
+ }
+ let group = self
+ .group_by_id(&path[REMOTE_PROJECT_PREFIX.len()..])?
+ .ok_or_else(|| anyhow!("remote project not found"))?;
+ if group.primary_path != path {
+ return Err(anyhow!("invalid remote project identity"));
+ }
+ group
+ .remote
+ .map(Some)
+ .ok_or_else(|| anyhow!("remote project binding missing"))
+ }
+
+ pub fn create_remote_project_group(
+ &self,
+ name: &str,
+ remote: RemoteWorkspace,
+ ) -> Result<ProjectGroupRecord> {
+ remote.validate()?;
+ let name = name.trim();
+ if name.is_empty() || name.chars().count() > MAX_PROJECT_GROUP_NAME_CHARS {
+ return Err(anyhow!("project group name is invalid"));
+ }
+ if self
+ .stored_project_groups()?
+ .iter()
+ .any(|group| group.remote.as_ref() == Some(&remote))
+ {
+ return Err(anyhow!("folder already belongs to a project group"));
+ }
+ let id = Uuid::new_v4().to_string();
+ let primary_path = format!("{REMOTE_PROJECT_PREFIX}{id}");
+ let now = now_ms();
+ let group = ProjectGroupRecord {
+ id,
+ name: name.to_string(),
+ primary_path: primary_path.clone(),
+ roots: vec![ProjectGroupRoot {
+ path: primary_path.clone(),
+ name: name.to_string(),
+ position: 0,
+ }],
+ created_at: now,
+ updated_at: now,
+ pinned: false,
+ last_opened_at: now,
+ legacy: false,
+ detached_paths: Vec::new(),
+ remote: Some(remote),
+ };
+ let transaction = self.conn.unchecked_transaction()?;
+ // The synthetic row owns local session metadata; no remote directory is
+ // ever probed, canonicalized or created on this machine.
+ self.conn.execute(
+ "INSERT INTO projects(path,name,created_at,last_opened_at) VALUES(?1,?2,?3,?3)",
+ params![primary_path, name, now],
+ )?;
+ self.kv_set(GROUP_NAMESPACE, &group.id, &serde_json::to_value(&group)?)?;
+ transaction.commit()?;
+ Ok(group)
+ }
+
fn stored_project_groups(&self) -> Result<Vec<ProjectGroupRecord>> {
let mut stmt = self
.conn
@@ -217,6 +322,7 @@ impl Database {
last_opened_at: now,
legacy: false,
detached_paths: Vec::new(),
+ remote: None,
};
self.kv_set(GROUP_NAMESPACE, &group.id, &serde_json::to_value(&group)?)?;
Ok(group)
@@ -235,6 +341,12 @@ impl Database {
let Some(current) = self.group_by_id(id.trim())? else {
return Err(anyhow!("project group not found"));
};
+ if current.remote.is_some() {
+ if paths != [current.primary_path.clone()] {
+ return Err(anyhow!("remote project folder binding cannot be changed"));
+ }
+ return self.rename_project_group(&current.id, name);
+ }
let primary = canonical_project_path(&current.primary_path)
.ok_or_else(|| anyhow!("project group primary path is invalid"))?;
let mut selected = Vec::with_capacity(paths.len());
@@ -327,6 +439,7 @@ impl Database {
last_opened_at: current.last_opened_at,
legacy: false,
detached_paths,
+ remote: None,
};
if current.legacy {
// A legacy project may already have path-scoped memory. Merge the
@@ -439,6 +552,7 @@ impl Database {
last_opened_at: current.last_opened_at,
legacy: false,
detached_paths: current.detached_paths,
+ remote: current.remote,
};
self.kv_set(GROUP_NAMESPACE, &group.id, &serde_json::to_value(&group)?)?;
Ok(Some(group))
@@ -458,6 +572,13 @@ impl Database {
.execute(params![name, group.primary_path])?;
} else {
group.name = name.to_string();
+ if group.remote.is_some() {
+ group.roots[0].name = name.to_string();
+ self.conn.execute(
+ "UPDATE projects SET name = ?1 WHERE path = ?2",
+ params![name, group.primary_path],
+ )?;
+ }
group.updated_at = now_ms();
self.kv_set(GROUP_NAMESPACE, &group.id, &serde_json::to_value(&group)?)?;
}
@@ -583,6 +704,7 @@ impl Database {
roots: group.roots,
instructions: self.get_project_group_instructions(&group.id)?,
memory: self.get_project_group_memory(&group.id)?,
+ remote: group.remote,
}))
}
}
diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rs
index 71a425fa6..753ebf5fd 100644
--- a/crates/host-core/src/db/repositories.rs
+++ b/crates/host-core/src/db/repositories.rs
@@ -42,6 +42,9 @@ pub(crate) fn normalize_project_path(path: &str) -> Option<String> {
/// directory exists (matching `WorkspaceState::set`), then normalize
/// separators/trailing slashes.
pub(crate) fn canonical_project_path(path: &str) -> Option<String> {
+ if path.starts_with(super::REMOTE_PROJECT_PREFIX) {
+ return normalize_project_path(path);
+ }
let canonical = std::path::Path::new(path).canonicalize().ok().map(|p| {
let s = p.to_string_lossy().to_string();
// Strip Windows extended-length prefix `\\?\X:\...` → `X:\...`
@@ -323,6 +326,21 @@ impl Database {
/// exists on disk (matching `WorkspaceState::set`) so symlinked spellings
/// of the same directory share one row.
pub fn ensure_project(&self, path: &str, touch: bool) -> Result<i64> {
+ if path.starts_with(super::REMOTE_PROJECT_PREFIX) {
+ self.remote_workspace_for_path(path)?;
+ let id = self.conn.query_row(
+ "SELECT id FROM projects WHERE path = ?1",
+ params![path],
+ |row| row.get::<_, i64>(0),
+ )?;
+ if touch {
+ self.conn.execute(
+ "UPDATE projects SET last_opened_at = ?1 WHERE id = ?2",
+ params![now_ms(), id],
+ )?;
+ }
+ return Ok(id);
+ }
upsert_project_row(&self.conn, path, touch)?
.ok_or_else(|| anyhow!("project path must not be blank"))
}
diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rs
index 7b514155e..8e19185de 100644
--- a/crates/host-core/src/rpc/mod.rs
+++ b/crates/host-core/src/rpc/mod.rs
@@ -1,4 +1,5 @@
mod config_sync_rpc;
+mod remote_tools;
mod scheduled_rpc;
mod scheduled_tools;
mod todos;
@@ -514,7 +515,7 @@ fn request_budget_ms(method: &str, params: &Value) -> Option<u64> {
// requests. Keep the Host-owned workflow alive across renderer routes.
return None;
}
- if method != "tools.execute" {
+ if !matches!(method, "tools.execute" | "tools.workspaceExecute") {
return Some(RPC_REQUEST_BUDGET_MS);
}
// `ToolsExecuteParams` is `#[serde(rename_all = "camelCase")]`, so the wire
@@ -1256,7 +1257,23 @@ fn resolve_persisted_project_workspace(
session_id: &str,
) -> Result<Option<String>, JsonRpcError> {
match sessions::session_summary(&state.db, session_id) {
- Ok(Some(summary)) => Ok(summary.project_path),
+ Ok(Some(summary)) => {
+ if let Some(path) = summary.project_path.as_deref() {
+ if state
+ .db
+ .remote_workspace_for_path(path)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?
+ .is_some()
+ {
+ let scratch = scratch::session_dir(&state.data_dir, session_id)
+ .ok_or_else(|| rpc_err(1002, "invalid session id", "INVALID_PARAMS"))?;
+ std::fs::create_dir_all(&scratch)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ return Ok(Some(scratch.to_string_lossy().into_owned()));
+ }
+ }
+ Ok(summary.project_path)
+ }
// A tool request must name a persisted session: an unknown id never
// inherits the mutable global workspace.
Ok(None) => Err(rpc_err(1007, "session not found", "SESSION_NOT_FOUND")),
@@ -1301,6 +1318,14 @@ fn resolve_tool_workspace_for_call(
let Some(primary_path) = primary.as_deref() else {
return Ok(primary);
};
+ if primary_path.starts_with(crate::db::REMOTE_PROJECT_PREFIX) {
+ let remote = state
+ .db
+ .remote_workspace_for_path(primary_path)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?
+ .ok_or_else(|| rpc_err(1002, "remote workspace binding missing", "INVALID_PARAMS"))?;
+ return Ok(Some(remote.path));
+ }
let Some(raw_path) = args.get("path").and_then(Value::as_str) else {
return Ok(primary);
};
@@ -1483,9 +1508,6 @@ fn bash_cancellation_requested(receiver: &Option<tokio::sync::watch::Receiver<bo
}
async fn clear_bash_cancellation(state: &Arc<Mutex<AppState>>, p: &ToolsExecuteParams) {
- if !matches!(p.tool_name.as_str(), "Bash" | "GenerateImages") {
- return;
- }
let mut st = state.lock().await;
st.clear_bash_cancellation(&p.session_id, &p.tool_call_id);
}
@@ -1767,6 +1789,9 @@ async fn handle_request(
}
match method {
+ "tools.remoteComplete" | "tools.workspaceExecute" | "tools.workspaceAbort" => {
+ remote_tools::handle(state, method, params, tx).await
+ }
method if method.starts_with("session.collaboration.") => {
let st = state.lock().await;
crate::session_collaboration::handle(&st.db, method, &params)
@@ -1794,7 +1819,13 @@ async fn handle_request(
if let Some(pid) = pid {
if let Ok(Some(path)) = st.db.project_path(pid) {
if !path.is_empty() {
- st.workspace.set(PathBuf::from(path));
+ if path.starts_with(crate::db::REMOTE_PROJECT_PREFIX) {
+ if let Ok(Some(group)) = st.db.project_group_for_path(&path) {
+ st.workspace.set_remote(&group);
+ }
+ } else {
+ st.workspace.set(PathBuf::from(path));
+ }
}
}
}
@@ -1863,6 +1894,21 @@ async fn handle_request(
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
Ok(json!({ "groups": groups }))
}
+ "project.group.createRemote" => {
+ let name = params
+ .get("name")
+ .and_then(Value::as_str)
+ .ok_or_else(|| rpc_err(1002, "name required", "INVALID_PARAMS"))?;
+ let remote: crate::db::RemoteWorkspace =
+ serde_json::from_value(params.get("remote").cloned().unwrap_or(Value::Null))
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
+ let st = state.lock().await;
+ let group = st
+ .db
+ .create_remote_project_group(name, remote)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
+ Ok(json!({ "group": group }))
+ }
"project.group.create" => {
let name = params
.get("name")
@@ -2124,7 +2170,17 @@ async fn handle_request(
.ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
let mut st = state.lock().await;
st.hashline.drop_all();
- let ws = st.workspace.set(PathBuf::from(path));
+ let ws = if path.starts_with(crate::db::REMOTE_PROJECT_PREFIX) {
+ let group = st
+ .db
+ .project_group_for_path(path)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?
+ .filter(|group| group.remote.is_some())
+ .ok_or_else(|| rpc_err(1007, "remote project not found", "NOT_FOUND"))?;
+ st.workspace.set_remote(&group)
+ } else {
+ st.workspace.set(PathBuf::from(path))
+ };
let pid = st
.db
.ensure_project(&ws.path, true)
@@ -2153,6 +2209,13 @@ async fn handle_request(
.and_then(|value| value.as_str())
.ok_or_else(|| rpc_err(1002, "snapshotId required", "INVALID_PARAMS"))?;
let st = state.lock().await;
+ if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
+ return Err(rpc_err(
+ 1002,
+ "remote workspace rollback is unavailable",
+ "CAPABILITY_UNAVAILABLE",
+ ));
+ }
let workspace_root = resolve_tool_workspace(&st, session_id)?;
let outcome = review::rollback_change(
&st.data_dir,
@@ -2431,6 +2494,10 @@ async fn handle_request(
let st = state.lock().await;
let sessions = sessions::list_sessions(&st.db)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ let sessions = sessions
+ .into_iter()
+ .map(|summary| remote_tools::session_value(&st.db, summary))
+ .collect::<Result<Vec<_>, _>>()?;
Ok(json!({ "sessions": sessions }))
}
"session.create" => {
@@ -2474,6 +2541,11 @@ async fn handle_request(
},
)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ let session = remote_tools::decorate_session(
+ &st.db,
+ serde_json::to_value(session)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
+ )?;
Ok(json!({ "session": session }))
}
"session.fork" => {
@@ -2496,6 +2568,11 @@ async fn handle_request(
return Err(rpc_err(1008, "session is running", "CONFLICT"))
}
};
+ let session = remote_tools::decorate_session(
+ &st.db,
+ serde_json::to_value(session)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
+ )?;
Ok(json!({ "session": session }))
}
"session.moveProject" => {
@@ -2523,6 +2600,11 @@ async fn handle_request(
return Err(rpc_err(1008, "session is running", "CONFLICT"))
}
};
+ let session = remote_tools::decorate_session(
+ &st.db,
+ serde_json::to_value(session)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
+ )?;
Ok(json!({ "session": session }))
}
"session.get" => {
@@ -2574,6 +2656,11 @@ async fn handle_request(
},
)
.map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;
+ let session = remote_tools::decorate_session(
+ &st.db,
+ serde_json::to_value(session)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
+ )?;
Ok(json!({ "session": session }))
}
"todos.get" => {
@@ -2614,6 +2701,11 @@ async fn handle_request(
}
})?
.ok_or_else(|| rpc_err(1007, "session not found", "NOT_FOUND"))?;
+ let session = remote_tools::decorate_session(
+ &st.db,
+ serde_json::to_value(session)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
+ )?;
Ok(json!({ "session": session }))
}
"session.delete" => {
@@ -3633,7 +3725,11 @@ async fn handle_request(
.map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
let execution_timeout_ms = tools::effective_timeout_ms(&p.tool_name, p.timeout_ms);
- let command_shell_id = if p.tool_name == "Bash" {
+ let remote_workspace = {
+ let st = state.lock().await;
+ remote_tools::session_remote_workspace(&st, &p.session_id)?
+ };
+ let command_shell_id = if p.tool_name == "Bash" && remote_workspace.is_none() {
let catalog = {
let st = state.lock().await;
command_shell_catalog(&st)?
@@ -3695,7 +3791,8 @@ async fn handle_request(
// Register before permission evaluation so tools.abort can cancel
// an approval wait as well as an already-spawned process.
- let cancellation_receiver = if matches!(p.tool_name.as_str(), "Bash" | "GenerateImages")
+ let cancellation_receiver = if remote_workspace.is_some()
+ || matches!(p.tool_name.as_str(), "Bash" | "GenerateImages")
{
let mut st = state.lock().await;
match st.register_bash_cancellation(&p.session_id, &p.tool_call_id) {
@@ -3769,12 +3866,20 @@ async fn handle_request(
// known sessions.
let ws = resolve_tool_workspace_for_call(&st, &p.session_id, &p.args)?;
let scratch = scratch::session_dir(&st.data_dir, &p.session_id);
- let external_path_permission = requires_external_path_permission(
- ws.as_deref(),
- scratch.as_deref(),
- &p.tool_name,
- &p.args,
- );
+ let external_path_permission = if remote_workspace.is_some() {
+ remote_tools::requires_external_permission(
+ ws.as_deref(),
+ &p.tool_name,
+ &p.args,
+ )
+ } else {
+ requires_external_path_permission(
+ ws.as_deref(),
+ scratch.as_deref(),
+ &p.tool_name,
+ &p.args,
+ )
+ };
let mut auto = st
.permissions
.evaluate_auto_with_permission_mode_and_risk_and_path(
@@ -3795,7 +3900,8 @@ async fn handle_request(
// through the symlink-aware resolver, so it cannot be used
// to escape containment. A contract mode's hard deny is
// never bypassed.
- if !sessions::is_contract_mode(&durable_mode)
+ if remote_workspace.is_none()
+ && !sessions::is_contract_mode(&durable_mode)
&& auto.is_none()
&& matches!(p.tool_name.as_str(), "Write" | "Edit")
{
@@ -4034,26 +4140,30 @@ async fn handle_request(
session_id: p.session_id.as_str(),
store: &hashline_store,
};
- let pending_review = review::prepare_change(
- &data_dir,
- &p.session_id,
- &p.tool_call_id,
- ws_path.as_deref(),
- scratch_path.as_deref(),
- &p.tool_name,
- &p.args,
- )
- .unwrap_or_else(|error| {
- tracing::warn!(
- session_id = %p.session_id,
- tool_call_id = %p.tool_call_id,
- error = %error,
- "review snapshot preparation failed"
- );
+ let pending_review = if remote_workspace.is_some() {
None
- });
+ } else {
+ review::prepare_change(
+ &data_dir,
+ &p.session_id,
+ &p.tool_call_id,
+ ws_path.as_deref(),
+ scratch_path.as_deref(),
+ &p.tool_name,
+ &p.args,
+ )
+ .unwrap_or_else(|error| {
+ tracing::warn!(
+ session_id = %p.session_id,
+ tool_call_id = %p.tool_call_id,
+ error = %error,
+ "review snapshot preparation failed"
+ );
+ None
+ })
+ };
let mut bash_options = None;
- if p.tool_name == "Bash" {
+ if p.tool_name == "Bash" && remote_workspace.is_none() {
let (shell_id, cancellation) = {
let st = state.lock().await;
let catalog = command_shell_catalog(&st)?;
@@ -4125,6 +4235,15 @@ async fn handle_request(
} else if scheduled_tools::recognizes(&p.tool_name) {
let st = state.lock().await;
scheduled_tools::execute(&st, &p)
+ } else if let Some(remote) = remote_workspace.clone() {
+ remote_tools::execute_remote_tool(
+ &state,
+ &tx,
+ &p,
+ remote,
+ cancellation_receiver.clone(),
+ )
+ .await
} else {
tools::execute_tool_with_path_access(
ws_path.as_deref(),
@@ -4175,7 +4294,8 @@ async fn handle_request(
// artifacts table so the work panel file list only shows
// workspace deliverables (D114).
let result_root = result.content.get("root").and_then(|v| v.as_str());
- if result.ok
+ if remote_workspace.is_none()
+ && result.ok
&& result_root == Some("workspace")
&& matches!(p.tool_name.as_str(), "Write" | "Edit")
{
@@ -4241,6 +4361,19 @@ async fn handle_request(
let mut st = state.lock().await;
let permission_found = st.cancel_pending_permission(session_id, tool_call_id);
let (process_found, queued) = st.abort_or_queue_bash(session_id, tool_call_id);
+ let remote = match sessions::session_summary(&st.db, session_id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ {
+ Some(_) => remote_tools::session_remote_workspace(&st, session_id)?.is_some(),
+ None => false,
+ };
+ if remote {
+ send_notification(
+ &tx,
+ "tools.remoteAbort",
+ json!({ "sessionId": session_id, "toolCallId": tool_call_id }),
+ );
+ }
let found = process_found || permission_found;
Ok(json!({
"ok": true,
@@ -4299,12 +4432,21 @@ async fn handle_request(
let args = params.get("args").cloned().unwrap_or_else(|| json!({}));
let workspace_path = resolve_tool_workspace_for_call(&st, session_id, &args)?;
let scratch_path = scratch::session_dir(&st.data_dir, session_id);
- let external_path_permission = requires_external_path_permission(
- workspace_path.as_deref(),
- scratch_path.as_deref(),
- tool_name,
- &args,
- );
+ let external_path_permission =
+ if remote_tools::session_remote_workspace(&st, session_id)?.is_some() {
+ remote_tools::requires_external_permission(
+ workspace_path.as_deref(),
+ tool_name,
+ &args,
+ )
+ } else {
+ requires_external_path_permission(
+ workspace_path.as_deref(),
+ scratch_path.as_deref(),
+ tool_name,
+ &args,
+ )
+ };
let decision = st
.permissions
.evaluate_auto_with_permission_mode_and_risk_and_path(PermissionEvaluationParams {
diff --git a/crates/host-core/src/rpc/remote_tools.rs b/crates/host-core/src/rpc/remote_tools.rs
new file mode 100644
index 000000000..b82e43a21
--- /dev/null
+++ b/crates/host-core/src/rpc/remote_tools.rs
@@ -0,0 +1,343 @@
+//! Remote workspace bindings preserve local sessions, approvals and model state.
+//! Only admitted tool bodies cross to the paired host; no local runner fallback.
+use super::*;
+use crate::db::{Database, RemoteWorkspace};
+
+pub(super) fn session_remote_workspace(
+ state: &AppState,
+ session_id: &str,
+) -> Result<Option<RemoteWorkspace>, JsonRpcError> {
+ let summary = sessions::session_summary(&state.db, session_id)
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?
+ .ok_or_else(|| rpc_err(1007, "session not found", "SESSION_NOT_FOUND"))?;
+ summary
+ .project_path
+ .as_deref()
+ .map(|path| state.db.remote_workspace_for_path(path))
+ .transpose()
+ .map(Option::flatten)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))
+}
+
+pub(super) fn decorate_session(db: &Database, mut value: Value) -> Result<Value, JsonRpcError> {
+ if let Some(path) = value.get("projectPath").and_then(Value::as_str) {
+ if let Some(remote) = db
+ .remote_workspace_for_path(path)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?
+ {
+ value["remoteWorkspace"] = json!(remote);
+ }
+ }
+ Ok(value)
+}
+pub(super) fn session_value(
+ db: &Database,
+ summary: sessions::SessionSummary,
+) -> Result<Value, JsonRpcError> {
+ decorate_session(
+ db,
+ serde_json::to_value(summary).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,
+ )
+}
+
+pub(super) fn requires_external_permission(
+ root: Option<&str>,
+ tool_name: &str,
+ args: &Value,
+) -> bool {
+ matches!(tool_name, "Read" | "Glob" | "Grep" | "Write" | "Edit")
+ && args
+ .get("path")
+ .and_then(Value::as_str)
+ .is_some_and(|path| {
+ root.is_some_and(|root| {
+ let candidate = if Path::new(path).is_absolute() {
+ PathBuf::from(path)
+ } else {
+ Path::new(root).join(path)
+ };
+ !workspace::lexically_inside(Path::new(root), &candidate.to_string_lossy())
+ })
+ })
+}
+
+fn failure(
+ p: &ToolsExecuteParams,
+ code: &str,
+ message: &str,
+ started: std::time::Instant,
+) -> tools::ToolsExecuteResult {
+ tools::ToolsExecuteResult {
+ tool_call_id: p.tool_call_id.clone(),
+ ok: false,
+ is_error: Some(true),
+ content: json!({"error": message, "code": code}),
+ duration_ms: started.elapsed().as_millis() as u64,
+ denied: None,
+ error_code: Some(code.into()),
+ command_shell_id: None,
+ }
+}
+
+pub(super) async fn execute_remote_tool(
+ state: &Arc<Mutex<AppState>>,
+ tx: &mpsc::UnboundedSender<String>,
+ p: &ToolsExecuteParams,
+ remote: RemoteWorkspace,
+ mut cancellation: Option<tokio::sync::watch::Receiver<bool>>,
+) -> tools::ToolsExecuteResult {
+ let started = std::time::Instant::now();
+ if !matches!(
+ p.tool_name.as_str(),
+ "Read" | "Glob" | "Grep" | "Write" | "Edit" | "Bash"
+ ) {
+ return failure(
+ p,
+ "CAPABILITY_UNAVAILABLE",
+ "tool is unavailable for a remote workspace",
+ started,
+ );
+ }
+ if bash_cancellation_requested(&cancellation) {
+ return failure(p, "TOOL_ABORTED", "tool aborted", started);
+ }
+ let request_id = uuid::Uuid::new_v4().to_string();
+ let (sender, receiver) = oneshot::channel();
+ state
+ .lock()
+ .await
+ .remote_execs
+ .insert(request_id.clone(), sender);
+ emit_notification(
+ tx,
+ "tools.remoteExecute",
+ json!({
+ "requestId": request_id, "sessionId": p.session_id, "turnId": p.turn_id,
+ "toolCallId": p.tool_call_id, "toolName": p.tool_name, "args": p.args,
+ "remoteWorkspace": remote, "timeoutMs": p.timeout_ms,
+ "expectedCommandShellId": p.expected_command_shell_id,
+ "expectedCommandShellDialect": p.expected_command_shell_dialect,
+ }),
+ )
+ .await;
+ let timeout_ms = tools::effective_timeout_ms(&p.tool_name, p.timeout_ms).unwrap_or(120_000);
+ let outcome = tokio::select! {
+ outcome = tokio::time::timeout(Duration::from_millis(timeout_ms.saturating_add(15_000)), receiver) => match outcome {
+ Ok(Ok(value)) => Ok(value), _ => Err("TOOL_TIMEOUT"),
+ },
+ _ = wait_for_bash_cancellation(&mut cancellation) => Err("TOOL_ABORTED"),
+ };
+ state.lock().await.remote_execs.remove(&request_id);
+ match outcome {
+ Ok(value) => {
+ let Some(ok) = value.get("ok").and_then(Value::as_bool) else {
+ return failure(
+ p,
+ "INVALID_REMOTE_RESULT",
+ "remote tool result is invalid",
+ started,
+ );
+ };
+ let Some(content) = value.get("content").cloned() else {
+ return failure(
+ p,
+ "INVALID_REMOTE_RESULT",
+ "remote tool content is missing",
+ started,
+ );
+ };
+ tools::ToolsExecuteResult {
+ tool_call_id: p.tool_call_id.clone(),
+ ok,
+ is_error: if ok { None } else { Some(true) },
+ content,
+ duration_ms: started.elapsed().as_millis() as u64,
+ denied: None,
+ error_code: if ok {
+ None
+ } else {
+ Some(
+ value
+ .get("errorCode")
+ .and_then(Value::as_str)
+ .unwrap_or("TOOL_FAILED")
+ .into(),
+ )
+ },
+ command_shell_id: value
+ .get("commandShellId")
+ .and_then(Value::as_str)
+ .map(str::to_string),
+ }
+ }
+ Err(code) => {
+ send_notification(
+ tx,
+ "tools.remoteAbort",
+ json!({"sessionId":p.session_id,"toolCallId":p.tool_call_id}),
+ );
+ failure(
+ p,
+ code,
+ if code == "TOOL_ABORTED" {
+ "tool aborted"
+ } else {
+ "remote tool timed out or disconnected"
+ },
+ started,
+ )
+ }
+ }
+}
+
+pub(super) async fn handle(
+ state: Arc<Mutex<AppState>>,
+ method: &str,
+ params: Value,
+ tx: mpsc::UnboundedSender<String>,
+) -> Result<Value, JsonRpcError> {
+ if method == "tools.remoteComplete" {
+ let id = params
+ .get("requestId")
+ .and_then(Value::as_str)
+ .ok_or_else(|| rpc_err(1002, "requestId required", "INVALID_PARAMS"))?;
+ let result = params
+ .get("result")
+ .cloned()
+ .ok_or_else(|| rpc_err(1002, "result required", "INVALID_PARAMS"))?;
+ let sender = state
+ .lock()
+ .await
+ .remote_execs
+ .remove(id)
+ .ok_or_else(|| rpc_err(1007, "remote tool request not found", "NOT_FOUND"))?;
+ let _ = sender.send(result);
+ return Ok(json!({"ok":true}));
+ }
+ let session_id = params
+ .get("sessionId")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty() && s.len() <= 256)
+ .ok_or_else(|| rpc_err(1002, "sessionId required", "INVALID_PARAMS"))?;
+ let tool_call_id = params
+ .get("toolCallId")
+ .and_then(Value::as_str)
+ .filter(|s| !s.is_empty() && s.len() <= 256)
+ .ok_or_else(|| rpc_err(1002, "toolCallId required", "INVALID_PARAMS"))?;
+ if method == "tools.workspaceAbort" {
+ let (found, queued) = state
+ .lock()
+ .await
+ .abort_or_queue_bash(session_id, tool_call_id);
+ return Ok(json!({"ok":true,"found":found,"queued":queued,"aborted":found||queued}));
+ }
+ let raw_path = params
+ .get("path")
+ .and_then(Value::as_str)
+ .ok_or_else(|| rpc_err(1002, "path required", "INVALID_PARAMS"))?;
+ if !Path::new(raw_path).is_absolute()
+ || raw_path.len() > 4096
+ || raw_path.chars().any(char::is_control)
+ {
+ return Err(rpc_err(1002, "invalid workspace path", "INVALID_PARAMS"));
+ }
+ let root = workspace::simple_canonicalize(Path::new(raw_path))
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
+ if !root.is_dir() {
+ return Err(rpc_err(
+ 1002,
+ "workspace must be a directory",
+ "INVALID_PARAMS",
+ ));
+ }
+ let mut input = params.clone();
+ input["mode"] = json!("agent");
+ let p: ToolsExecuteParams = serde_json::from_value(input)
+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;
+ let started = std::time::Instant::now();
+ if !matches!(
+ p.tool_name.as_str(),
+ "Read" | "Glob" | "Grep" | "Write" | "Edit" | "Bash"
+ ) {
+ return serde_json::to_value(failure(
+ &p,
+ "CAPABILITY_UNAVAILABLE",
+ "remote runner tool unavailable",
+ started,
+ ))
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
+ }
+ tools::validate_timeout_ms(p.timeout_ms)
+ .map_err(|(code, message)| rpc_err(1002, message, &code))?;
+ let (mut cancellation, hashline, shell) = {
+ let mut st = state.lock().await;
+ let shell = if p.tool_name == "Bash" {
+ let catalog = command_shell_catalog(&st)?;
+ let shell = catalog
+ .effective
+ .ok_or_else(|| rpc_err(1002, "command shell unavailable", "SHELL_NOT_FOUND"))?;
+ if p.expected_command_shell_id.as_deref() != Some(shell.id.as_str())
+ || p.expected_command_shell_dialect.as_deref() != Some(shell.dialect.as_str())
+ {
+ return serde_json::to_value(shell_changed_result(
+ &p,
+ p.expected_command_shell_id.as_deref().unwrap_or(""),
+ p.expected_command_shell_dialect.as_deref(),
+ Some(shell.id.clone()),
+ Some(shell.dialect.as_str()),
+ started,
+ ))
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
+ }
+ shell.id
+ } else {
+ String::new()
+ };
+ let cancellation = st
+ .register_bash_cancellation(&p.session_id, &p.tool_call_id)
+ .map_err(|code| rpc_err(1008, "tool already executing", &code))?;
+ (Some(cancellation), st.hashline.clone(), shell)
+ };
+ if bash_cancellation_requested(&cancellation) {
+ state
+ .lock()
+ .await
+ .clear_bash_cancellation(&p.session_id, &p.tool_call_id);
+ return serde_json::to_value(failure(&p, "TOOL_ABORTED", "tool aborted", started))
+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"));
+ }
+ let options = tools::ToolExecutionOptions {
+ timeout_ms: tools::effective_timeout_ms(&p.tool_name, p.timeout_ms),
+ bash_options: if p.tool_name == "Bash" {
+ Some(tools::BashExecutionOptions {
+ session_id: p.session_id.clone(),
+ tool_call_id: p.tool_call_id.clone(),
+ command_shell_id: shell,
+ timeout_ms: tools::effective_timeout_ms(&p.tool_name, p.timeout_ms),
+ cancellation: cancellation.clone(),
+ output_tx: Some(tx),
+ })
+ } else {
+ None
+ },
+ allow_external_paths: false,
+ hashline: Some(tools::HashlineContext {
+ session_id: &p.session_id,
+ store: &hashline,
+ }),
+ };
+ let mut result = tokio::select! {
+ result = tools::execute_tool_with_path_access(Some(&root),None,&p.tool_name,&p.args,options) => result,
+ _ = wait_for_bash_cancellation(&mut cancellation) => failure(&p,"TOOL_ABORTED","tool aborted",started),
+ };
+ result.tool_call_id = p.tool_call_id.clone();
+ state
+ .lock()
+ .await
+ .clear_bash_cancellation(&p.session_id, &p.tool_call_id);
+ serde_json::to_value(result).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))
+}
+
+#[cfg(test)]
+#[path = "remote_tools_tests.rs"]
+mod tests;
diff --git a/crates/host-core/src/rpc/remote_tools_tests.rs b/crates/host-core/src/rpc/remote_tools_tests.rs
new file mode 100644
index 000000000..de0c5de97
--- /dev/null
+++ b/crates/host-core/src/rpc/remote_tools_tests.rs
@@ -0,0 +1,343 @@
+use super::*;
+
+fn fixture() -> (
+ tempfile::TempDir,
+ Arc<Mutex<AppState>>,
+ mpsc::UnboundedSender<String>,
+ mpsc::UnboundedReceiver<String>,
+) {
+ let dir = tempfile::tempdir().unwrap();
+ let mut state = AppState::open(dir.path()).unwrap();
+ state.handshook = true;
+ let (tx, rx) = mpsc::unbounded_channel();
+ (dir, Arc::new(Mutex::new(state)), tx, rx)
+}
+async fn create(
+ state: &Arc<Mutex<AppState>>,
+ tx: &mpsc::UnboundedSender<String>,
+) -> (String, String) {
+ let group = handle_request(
+ state.clone(),
+ "project.group.createRemote",
+ json!({"name":"My named project","remote":{"hostKey":"host-a","path":"/srv/work"}}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ let path = group["group"]["primaryPath"].as_str().unwrap().to_string();
+ let session = handle_request(
+ state.clone(),
+ "session.create",
+ json!({"projectPath":path}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ (path, session["session"]["id"].as_str().unwrap().to_string())
+}
+#[tokio::test]
+async fn remote_project_uses_local_lifecycle_without_probing_remote_directory() {
+ let (dir, state, tx, _rx) = fixture();
+ let (path, id) = create(&state, &tx).await;
+ assert!(path.starts_with("remote-project:"));
+ let set = handle_request(
+ state.clone(),
+ "workspace.set",
+ json!({"path":path}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(set["workspace"]["name"], "My named project");
+ assert_eq!(set["workspace"]["remote"]["path"], "/srv/work");
+ let listed = handle_request(state.clone(), "session.list", json!({}), tx.clone())
+ .await
+ .unwrap();
+ assert_eq!(
+ listed["sessions"][0]["remoteWorkspace"]["hostKey"],
+ "host-a"
+ );
+ let detail = handle_request(state.clone(), "session.get", json!({"id":id}), tx.clone())
+ .await
+ .unwrap();
+ assert_eq!(detail["session"]["projectPath"], path);
+ assert_eq!(detail["session"]["remoteWorkspace"]["path"], "/srv/work");
+ let group_id = path.strip_prefix("remote-project:").unwrap();
+ let renamed = handle_request(
+ state.clone(),
+ "project.group.rename",
+ json!({"groupId":group_id,"name":"Local name"}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(renamed["group"]["name"], "Local name");
+ handle_request(
+ state.clone(),
+ "project.group.instructions.set",
+ json!({"groupId":group_id,"content":"Keep local context"}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ let context = handle_request(
+ state.clone(),
+ "project.group.context",
+ json!({"path":path}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(context["context"]["instructions"], "Keep local context");
+ assert_eq!(context["context"]["remote"]["hostKey"], "host-a");
+ let guard = state.lock().await;
+ let scratch = resolve_plan_workspace(&guard, &id).unwrap();
+ assert!(scratch.starts_with(dir.path()));
+ assert!(!scratch.to_string_lossy().contains("remote-project:"));
+ drop(guard);
+ let removed = handle_request(
+ state.clone(),
+ "projects.remove",
+ json!({"path":path}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(removed["sessionsRemoved"], 1);
+ assert!(state
+ .lock()
+ .await
+ .db
+ .list_project_groups()
+ .unwrap()
+ .is_empty());
+ assert!(!dir.path().join(&path).exists());
+}
+#[tokio::test]
+async fn unregistered_remote_identity_is_rejected_before_session_or_workspace_mutation() {
+ let (_dir, state, tx, _rx) = fixture();
+ for method in ["session.create", "workspace.set"] {
+ let params = if method == "session.create" {
+ json!({"projectPath":"remote-project:unknown"})
+ } else {
+ json!({"path":"remote-project:unknown"})
+ };
+ assert!(handle_request(state.clone(), method, params, tx.clone())
+ .await
+ .is_err());
+ }
+ assert!(state.lock().await.db.list_projects().unwrap().is_empty());
+}
+#[tokio::test]
+async fn remote_read_dispatch_is_local_approval_then_relay_never_local_runner() {
+ let (_dir, state, tx, mut rx) = fixture();
+ let (_path, id) = create(&state, &tx).await;
+ let pending_state = state.clone();
+ let pending_tx = tx.clone();
+ let pending_id = id.clone();
+ let pending = tokio::spawn(async move {
+ handle_request(pending_state,"tools.execute",json!({"sessionId":pending_id,"toolCallId":"read-a","toolName":"Read","args":{"path":"README.md"},"mode":"agent"}),pending_tx).await
+ });
+ let request: Value = serde_json::from_str(
+ &tokio::time::timeout(Duration::from_secs(2), rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(request["method"], "tools.remoteExecute");
+ assert_eq!(request["params"]["remoteWorkspace"]["path"], "/srv/work");
+ handle_request(state.clone(),"tools.remoteComplete",json!({"requestId":request["params"]["requestId"],"result":{"ok":true,"content":{"text":"Remote content"}}}),tx.clone()).await.unwrap();
+ let result = pending.await.unwrap().unwrap();
+ assert_eq!(result["content"]["text"], "Remote content");
+ assert!(state.lock().await.remote_execs.is_empty());
+}
+#[tokio::test]
+async fn denied_remote_write_and_cancelled_read_never_run_locally() {
+ let (_dir, state, tx, mut rx) = fixture();
+ let (_path, id) = create(&state, &tx).await;
+ let pending_state = state.clone();
+ let pending_tx = tx.clone();
+ let pending_id = id.clone();
+ let write = tokio::spawn(async move {
+ handle_request(pending_state,"tools.execute",json!({"sessionId":pending_id,"toolCallId":"write-a","toolName":"Write","args":{"path":"a.txt","content":"value"},"mode":"agent"}),pending_tx).await
+ });
+ let request: Value = serde_json::from_str(
+ &tokio::time::timeout(Duration::from_secs(2), rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(request["method"], "permissions.request");
+ handle_request(
+ state.clone(),
+ "permissions.resolve",
+ json!({"requestId":request["params"]["requestId"],"decision":"deny"}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(write.await.unwrap().unwrap()["errorCode"], "TOOL_DENIED");
+ assert!(state.lock().await.remote_execs.is_empty());
+ let pending_state = state.clone();
+ let pending_tx = tx.clone();
+ let pending_id = id.clone();
+ let read = tokio::spawn(async move {
+ handle_request(pending_state,"tools.execute",json!({"sessionId":pending_id,"toolCallId":"read-b","toolName":"Read","args":{"path":"a.txt"},"mode":"agent"}),pending_tx).await
+ });
+ let request: Value = serde_json::from_str(
+ &tokio::time::timeout(Duration::from_secs(2), rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(request["method"], "tools.remoteExecute");
+ handle_request(
+ state.clone(),
+ "tools.abort",
+ json!({"sessionId":id,"toolCallId":"read-b"}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(read.await.unwrap().unwrap()["errorCode"], "TOOL_ABORTED");
+ assert!(state.lock().await.remote_execs.is_empty());
+}
+#[tokio::test]
+async fn workspace_runner_reads_without_creating_remote_project_session_or_provider_records() {
+ let (dir, state, tx, _rx) = fixture();
+ std::fs::write(dir.path().join("data.txt"), "remote bytes").unwrap();
+ let result=handle_request(state.clone(),"tools.workspaceExecute",json!({"path":dir.path(),"sessionId":"local-owner-session","toolCallId":"read-tool","toolName":"Read","args":{"path":"data.txt"}}),tx.clone()).await.unwrap();
+ assert_eq!(result["ok"], true);
+ assert!(result.to_string().contains("remote bytes"));
+ let guard = state.lock().await;
+ assert!(guard.db.list_project_groups().unwrap().is_empty());
+ assert!(sessions::list_sessions(&guard.db).unwrap().is_empty());
+ assert!(guard.db.list_projects().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn workspace_bash_requires_matching_shell_and_honors_abort_before_dispatch() {
+ let (dir, state, tx, _rx) = fixture();
+ let input = json!({"path":dir.path(),"sessionId":"local-owner","toolCallId":"bash-a","toolName":"Bash","args":{"command":"printf forbidden > should-not-exist"},"expectedCommandShellId":"wrong-shell","expectedCommandShellDialect":"wrong-dialect"});
+ let result = handle_request(state.clone(), "tools.workspaceExecute", input, tx.clone())
+ .await
+ .unwrap();
+ assert_eq!(result["errorCode"], "COMMAND_SHELL_CHANGED");
+ assert!(!dir.path().join("should-not-exist").exists());
+ assert!(state.lock().await.active_bash_cancellations.is_empty());
+ handle_request(
+ state.clone(),
+ "tools.workspaceAbort",
+ json!({"sessionId":"local-owner","toolCallId":"write-late"}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ let result=handle_request(state.clone(),"tools.workspaceExecute",json!({"path":dir.path(),"sessionId":"local-owner","toolCallId":"write-late","toolName":"Write","args":{"path":"should-not-exist","content":"forbidden"}}),tx.clone()).await.unwrap();
+ assert_eq!(result["errorCode"], "TOOL_ABORTED");
+ assert!(!dir.path().join("should-not-exist").exists());
+ assert!(state.lock().await.active_bash_cancellations.is_empty());
+}
+
+#[tokio::test]
+async fn remote_group_binding_names_and_memory_survive_reopen() {
+ let (dir, state, tx, _rx) = fixture();
+ let (path, _id) = create(&state, &tx).await;
+ let id = path.strip_prefix("remote-project:").unwrap();
+ handle_request(state.clone(),"project.group.memory.set",json!({"groupId":id,"entries":[{"id":"entry-1","title":"API","content":"Preserve contracts"}]}),tx.clone()).await.unwrap();
+ drop(state);
+ let mut reloaded = AppState::open(dir.path()).unwrap();
+ reloaded.handshook = true;
+ let reloaded = Arc::new(Mutex::new(reloaded));
+ let groups = handle_request(
+ reloaded.clone(),
+ "project.groups.list",
+ json!({}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(groups["groups"][0]["remote"]["path"], "/srv/work");
+ assert_eq!(groups["groups"][0]["name"], "My named project");
+ let memory = handle_request(
+ reloaded.clone(),
+ "project.group.memory.get",
+ json!({"groupId":id}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert!(memory.to_string().contains("Preserve contracts"));
+ let duplicate = handle_request(
+ reloaded.clone(),
+ "project.group.createRemote",
+ json!({"name":"Other name","remote":{"hostKey":"host-a","path":"/srv/work"}}),
+ tx.clone(),
+ )
+ .await;
+ assert!(duplicate.is_err());
+ let other_host = handle_request(
+ reloaded.clone(),
+ "project.group.createRemote",
+ json!({"name":"Other host","remote":{"hostKey":"host-b","path":"/srv/work"}}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ assert_ne!(other_host["group"]["primaryPath"], path);
+}
+
+#[tokio::test]
+async fn approved_remote_write_is_dispatched_only_after_local_permission_resolution() {
+ let (_dir, state, tx, mut rx) = fixture();
+ let (_path, id) = create(&state, &tx).await;
+ let pending_state = state.clone();
+ let pending_tx = tx.clone();
+ let pending_id = id.clone();
+ let pending = tokio::spawn(async move {
+ handle_request(pending_state,"tools.execute",json!({"sessionId":pending_id,"toolCallId":"write-approved","toolName":"Write","args":{"path":"created.txt","content":"remote value"},"mode":"agent"}),pending_tx).await
+ });
+ let approval: Value = serde_json::from_str(
+ &tokio::time::timeout(Duration::from_secs(2), rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(approval["method"], "permissions.request");
+ assert!(state.lock().await.remote_execs.is_empty());
+ handle_request(
+ state.clone(),
+ "permissions.resolve",
+ json!({"requestId":approval["params"]["requestId"],"decision":"allow-once"}),
+ tx.clone(),
+ )
+ .await
+ .unwrap();
+ let dispatch: Value = serde_json::from_str(
+ &tokio::time::timeout(Duration::from_secs(2), rx.recv())
+ .await
+ .unwrap()
+ .unwrap(),
+ )
+ .unwrap();
+ assert_eq!(dispatch["method"], "tools.remoteExecute");
+ assert_eq!(dispatch["params"]["args"]["content"], "remote value");
+ handle_request(state.clone(),"tools.remoteComplete",json!({"requestId":dispatch["params"]["requestId"],"result":{"ok":true,"content":{"path":"created.txt","root":"workspace"}}}),tx.clone()).await.unwrap();
+ assert_eq!(pending.await.unwrap().unwrap()["ok"], true);
+ let rollback = handle_request(
+ state.clone(),
+ "review.rollback",
+ json!({"sessionId":id,"snapshotId":"arbitrary"}),
+ tx.clone(),
+ )
+ .await
+ .unwrap_err();
+ assert_eq!(
+ rollback.data.unwrap()["errorCode"],
+ "CAPABILITY_UNAVAILABLE"
+ );
+}
diff --git a/crates/host-core/src/state.rs b/crates/host-core/src/state.rs
index 76de5500e..a46d35db9 100644
--- a/crates/host-core/src/state.rs
+++ b/crates/host-core/src/state.rs
@@ -52,6 +52,7 @@ pub struct AppState {
pub session_grants: HashMap<String, Vec<String>>,
/// executionId -> responder for plugin tool dispatches awaiting the
/// desktop runner (Electron main executes the plugin JS and resolves).
+ pub remote_execs: HashMap<String, tokio::sync::oneshot::Sender<serde_json::Value>>,
pub plugin_execs: HashMap<String, tokio::sync::oneshot::Sender<serde_json::Value>>,
/// Rolling plugin session API brakes. These are intentionally process-local;
/// a restart is already a natural rate-window boundary.
@@ -142,6 +143,7 @@ impl AppState {
shutting_down: false,
session_grants: HashMap::new(),
plugin_execs: HashMap::new(),
+ remote_execs: HashMap::new(),
plugin_import_rates: HashMap::new(),
plugin_batch_import_rates: HashMap::new(),
plugin_delete_rates: HashMap::new(),
@@ -304,6 +306,7 @@ impl AppState {
self.pending_bash_aborts.clear();
self.plugin_execs.clear();
+ self.remote_execs.clear();
}
pub fn uptime_ms(&self) -> u64 {
diff --git a/crates/host-core/src/workspace.rs b/crates/host-core/src/workspace.rs
index c11703a83..25930325e 100644
--- a/crates/host-core/src/workspace.rs
+++ b/crates/host-core/src/workspace.rs
@@ -28,12 +28,16 @@ pub(crate) fn simple_canonicalize(path: &Path) -> std::io::Result<PathBuf> {
pub struct WorkspaceState {
pub path: Option<String>,
pub name: Option<String>,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub remote: Option<crate::db::RemoteWorkspace>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ProjectWorkspace {
pub path: String,
pub name: String,
+ #[serde(default, skip_serializing_if = "Option::is_none")]
+ pub remote: Option<crate::db::RemoteWorkspace>,
}
impl WorkspaceState {
@@ -42,11 +46,23 @@ impl WorkspaceState {
(Some(path), Some(name)) => Some(ProjectWorkspace {
path: path.clone(),
name: name.clone(),
+ remote: self.remote.clone(),
}),
_ => None,
}
}
+ pub fn set_remote(&mut self, project: &crate::db::ProjectGroupRecord) -> ProjectWorkspace {
+ self.path = Some(project.primary_path.clone());
+ self.name = Some(project.name.clone());
+ self.remote = project.remote.clone();
+ ProjectWorkspace {
+ path: project.primary_path.clone(),
+ name: project.name.clone(),
+ remote: project.remote.clone(),
+ }
+ }
+
pub fn set(&mut self, path: impl AsRef<Path>) -> ProjectWorkspace {
let path =
simple_canonicalize(path.as_ref()).unwrap_or_else(|_| path.as_ref().to_path_buf());
@@ -56,17 +72,20 @@ impl WorkspaceState {
.unwrap_or("workspace")
.to_string();
let path_str = path.to_string_lossy().to_string();
+ self.remote = None;
self.path = Some(path_str.clone());
self.name = Some(name.clone());
ProjectWorkspace {
path: path_str,
name,
+ remote: None,
}
}
pub fn clear(&mut self) {
self.path = None;
self.name = None;
+ self.remote = None;
}
}
diff --git a/docs/adr/README.md b/docs/adr/README.md
index a4b92cdc3..fc5ae01c5 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -372,3 +372,5 @@ Each ADR includes:
| 0324 | [Make Composer Prompt Enhancement an Optional Plugin](0324-plugin-owned-composer-prompt-enhancement.md) | Accepted (D653; supersedes ADR 0121) |
| 0325 | [Smooth Windows main-window corner compositing](0325-windows-window-corner-compositing.md) | Proposed (implementation candidate; Windows E2E pending) |
| plugin-fetch-redirect-policy | [Host-enforced plugin fetch redirect policy](plugin-fetch-redirect-policy.md) | Accepted (implementation candidate for #1475) |
+
+| local-agent-remote-workspace-tools | [Local Agent and model requests for remote workspaces](local-agent-remote-workspace-tools.md) | Accepted for implementation |
diff --git a/docs/adr/local-agent-remote-workspace-tools.md b/docs/adr/local-agent-remote-workspace-tools.md
new file mode 100644
index 000000000..018bfad02
--- /dev/null
+++ b/docs/adr/local-agent-remote-workspace-tools.md
@@ -0,0 +1,72 @@
+# ADR: Local Agent and model requests for remote workspaces
+
+- Status: Accepted for implementation
+- Date: 2026-10-11
+- Supersedes the new-project execution choice in [Remote home workflow](remote-project-home-workflow.md)
+- Related: [Logical project groups](0249-chatgpt-style-logical-project-groups.md)
+
+## Context
+
+The remote MVP ran an Agent on the SSH Host and required remote providers and
+Host-owned projects. This made project names and model selection differ from
+local work. The user explicitly requires model requests and credentials to stay
+on Desktop, with the remote machine executing tools only.
+
+## Decision
+
+Keep the Agent runtime, provider resolution, credentials, model requests,
+transcripts, project names, project instructions, project memory and sessions
+on Desktop. Extend the existing Rust-owned logical project-group KV boundary
+with a remote workspace binding. An opaque project identity selects the group;
+the actual remote path is never interpreted as a local filesystem path.
+
+After the normal local permission and execution-admission gates, host-core
+relays supported workspace tools through Electron Main to the paired Host.
+RACP transports the execution identity, workspace path and tool arguments only.
+It does not carry model configuration, model credentials, or a model request.
+The Host validates its canonical browse boundary and executes the tool. Failed,
+disconnected, cancelled, timed-out or unsupported remote calls fail closed;
+they never fall back to local execution or automatically replay side effects.
+
+New projects use the ordinary project name, switcher, sidebar, archive and
+session controls. Remote directory selection is a separate accessible dialog
+with path entry, parent navigation, loading/error feedback and explicit selection.
+The Host project catalog and provider synchronization are not part of creation.
+Existing remote Agent histories remain reachable as historical data.
+
+## Alternatives
+
+- Automatically copy local providers to the remote Host: rejected because OAuth,
+ local providers and credentials would still depend on a remote model runtime.
+- Add a model gateway through reverse SSH: keeps credentials local but still
+ leaves session and Agent ownership remote, adding model transport exposure.
+- Mirror remote paths into local folders: rejected because tools would act on a
+ different filesystem and make containment and data consistency ambiguous.
+
+## Consequences
+
+The project group's `remote` binding stores `{hostKey, path}` while its primary
+root and session `projectPath` use `remote-project:<groupId>`. Unknown opaque
+identities are rejected before workspace or session mutation. The synthetic
+project row stores local metadata only; registration never probes or creates the
+remote directory on Desktop. Plan checkpoints use the local session scratch
+rather than resolving the opaque identity as a filesystem directory.
+
+The pure remote runner admits only Read, Glob, Grep, Write, Edit and Bash. It
+creates no remote project or session records, preserves workspace containment,
+and checks Bash's expected shell identity and dialect before execution. Local
+permission waits and remote dispatches both honor cancellation, including an
+abort arriving before dispatch. Missing replies fail closed and are never
+replaced with a local tool invocation.
+
+Project storage remains Rust-owned and backward compatible through additive KV
+metadata. Existing local groups and existing remote histories remain readable.
+New remote workspace sessions have the same local model and session contracts.
+The remote Host must support the additive workspace-tool endpoints; older Hosts
+report an explicit unsupported operation instead of using a remote model.
+
+Local project/workspace consumers must distinguish the opaque remote identity
+from a local directory before filesystem access. Execution has cancellation and
+cleanup owners on both sides, and permission approval stays on Desktop.
+Validation must include a local model fixture and a real remote tool boundary,
+plus project rename/restart isolation and cancelled/disconnected calls.
diff --git a/docs/adr/remote-project-home-workflow.md b/docs/adr/remote-project-home-workflow.md
index 8b221de61..86cc6b3fc 100644
--- a/docs/adr/remote-project-home-workflow.md
+++ b/docs/adr/remote-project-home-workflow.md
@@ -1,6 +1,6 @@
# ADR: Remote projects in the shared Chat home workflow
-- Status: Accepted
+- Status: Superseded for new projects by [Local Agent remote workspace tools](local-agent-remote-workspace-tools.md)
- Date: 2026-10-11
- Related: ADR 0286, ADR 0292,
[remote Agent Control](../spec/02-architecture/05-remote-agent-control.md)
diff --git a/docs/spec/02-architecture/05-remote-agent-control.md b/docs/spec/02-architecture/05-remote-agent-control.md
index 0409e216c..2f2d37085 100644
--- a/docs/spec/02-architecture/05-remote-agent-control.md
+++ b/docs/spec/02-architecture/05-remote-agent-control.md
@@ -179,28 +179,31 @@ Host uses its existing Rust RPC connection; the CLI never starts another databas
writer. 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.** 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 remote
-backends 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.
+**Desktop remote workspaces.** New projects are ordinary locally owned logical
+project groups with an additive `{hostKey, path}` remote workspace binding.
+The shared Create project dialog keeps the user-selected name locally and opens
+a separate directory-selection dialog. Host project catalogs, project
+registration, remote session creation and provider import are not part of this
+flow. The local switcher, sidebar, archive, session creation, model selection,
+project instructions and memory consume the same local project identity.
+
+The local Agent and local provider transport own model execution. API keys,
+OAuth credentials, local provider endpoints and model requests remain on Desktop.
+After local permissions and tool-admission checks, host-core emits a remote
+workspace-tool request. Main dispatches only supported workspace tools to the
+paired Host's additive `workspace/toolExecute` endpoint, and relays cancellation
+through `workspace/toolAbort`. The remote canonical workspace/browse boundary
+is independently enforced. No failed remote call falls back to the local runner,
+and no mutation is automatically retried. The opaque local project identity is
+never resolved as a directory on either machine.
+
+Existing remote Agent histories remain reachable through their previous backend.
+Their session capabilities and opaque history cursors remain enforced; this does
+not grant them local project paths or change their persisted ownership.
+`remoteHostBrowseProjects` forwards only validated Host/path input to
+`project/browse` and validates returned directory entries. See
+[Local Agent remote workspace tools](../../adr/local-agent-remote-workspace-tools.md).
+The broader R2 target below is not an acceptance claim for every transport feature.
Reconnect rebuilds SSH forwarding and RACP subscriptions, acknowledges durable
cursors, deduplicates events, and recovers snapshots on epoch/gap changes. It never
diff --git a/docs/spec/03-runtime/19-remote-agent-control-protocol.md b/docs/spec/03-runtime/19-remote-agent-control-protocol.md
index a29fcad04..0d894c9e6 100644
--- a/docs/spec/03-runtime/19-remote-agent-control-protocol.md
+++ b/docs/spec/03-runtime/19-remote-agent-control-protocol.md
@@ -600,6 +600,40 @@ session root as working directory and stream through `terminal.output`.
| `project/register` | owner | Register a Host directory as a project: the Host canonicalizes and validates the path and returns the project id (D448) |
| `project/browse` | owner | List directories under a Host path, bounded, for the remote folder picker (D448) |
+### 6.2.1 Local-Agent workspace services
+
+New Desktop remote projects keep the Agent, transcript, project metadata, model
+selection and provider transport locally. These additive, owner-only operations
+serve their remote tool workspace without creating a Host project or session.
+Legacy remote-Agent operations above remain unchanged.
+
+- `workspace/toolShell` accepts `{}` and returns `{ shell: CommandShellOption }`.
+ Desktop supplies this effective Host shell to its local Agent. Bash execution
+ verifies the same shell id and dialect, including a second check before spawn.
+- `workspace/toolExecute` accepts `{ path, sessionId, turnId, toolCallId,
+ toolName, args, timeoutMs?, expectedCommandShellId?,
+ expectedCommandShellDialect? }`. Only Read, Glob, Grep, Write, Edit and Bash are
+ accepted; extra top-level fields and provider/credential inputs are rejected.
+ `path` is the owner-selected absolute workspace root, independently
+ canonicalized by the Host. Local permissions and tool admission precede this
+ RPC. The Host reuses the existing bounded runner and containment rules with
+ external paths disabled. It returns the ordinary `{ ok, content, isError?,
+ errorCode?, toolCallId?, ...runnerMetadata }` result.
+- `workspace/toolAbort` accepts `{ sessionId, toolCallId }`, and cancels only
+ the calling device's active operation. Closing the originating connection
+ cancels its outstanding calls. Host restarts invalidate late results.
+- `workspace/files` accepts `{ path, operation, ref?, mimeType? }`, where
+ operation is list/read/index/resolve/image/diff. It reads only the canonical
+ workspace boundary using existing file helpers and no persistent Host session.
+
+`workspaceTools` and `workspaceFiles` are optional advertised capabilities; an
+older Host fails with CAPABILITY_UNAVAILABLE/METHOD_NOT_FOUND rather than
+falling back to the Desktop filesystem. Tools are not automatically replayed
+on reconnect. The Host namespaces execution by paired device and local session,
+limits concurrent tools to 32, retains a bounded 4096-key replay fence, and bounds
+arguments/results to 1 MiB. These services never carry model requests, model
+settings, provider headers, API keys or OAuth tokens.
+
### 6.3 Deferred operations
The desktop offers these locally. RACP does not expose them yet; the names
diff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.md
index 24a8517fa..3ef3082ef 100644
--- a/docs/spec/04-ux/01-ui-ia.md
+++ b/docs/spec/04-ux/01-ui-ia.md
@@ -179,14 +179,15 @@ destination, chat as the home surface, tools and permissions inline.
redundant supporting paragraph, developer starter cards, or contextual
quick-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.
+ The project name is editable for every source and remains locally managed.
+ Remote selection chooses a connected host and an absolute directory, without
+ a Host project catalog. Browse opens a separate directory dialog with path
+ entry, parent navigation, directory rows and explicit confirmation. Cancel
+ returns to the project form and restores focus; a stale host response cannot
+ replace the current selection. The same sidebar, switcher, archive and chat
+ workflow manage created projects. Model choices and requests use local settings;
+ remote machines execute admitted workspace tools only. Actual remote paths
+ are display/execution data, never local filesystem activation paths.
- With transcript: message stream + tool disclosure rows (D071), a contextual
message-scoped review card immediately after each successful workspace
Write/Edit row, docked composer, and a session-scoped permission card inline.
diff --git a/docs/spec/05-security/02-remote-control-security.md b/docs/spec/05-security/02-remote-control-security.md
index eed137707..b09c81b25 100644
--- a/docs/spec/05-security/02-remote-control-security.md
+++ b/docs/spec/05-security/02-remote-control-security.md
@@ -203,6 +203,25 @@ password for a host the user paired that way, under these rules:
- Provider state remains owned by Rust host-core and uses existing provider and
secret storage. No database schema or RACP credential surface is added.
+### 3.6 Local-Agent remote workspace tools
+
+For locally owned remote projects, all provider configuration and model requests
+remain on Desktop. Provider import is a legacy remote-Agent operation and is not
+used by this project workflow. The owner-only workspace tool service accepts no
+provider or credential fields and has no provider, project or session mutation
+endpoint. Local host-core first applies its existing permissions and admission;
+Main then sends the admitted tool request to the selected paired Host. The Host
+canonicalizes the root and reuses its pure tool runner with external paths denied.
+A disconnected or unsupported Host cannot redirect execution onto Desktop.
+
+Device/session namespace isolation prevents cross-device cancellation and tool
+identity collisions. Connection disposal aborts active calls; invalid or late
+responses remain errors. There is no automatic mutation retry or reconnect replay.
+Remote paths never reach local attachment hydration, local instruction filesystem
+resolution or mutation realpath probes. Trusted extensions still register local
+model providers. Their implicit workspace `pi.exec` is rejected for a remote root;
+local provider helpers must explicitly supply a local working directory.
+
## 4. Authorization model
### 4.1 Role matrix
@@ -251,8 +270,10 @@ The following client fields are advisory only or forbidden:
- a client cannot claim another `principal`, `agentName`, `connectionId`, or
`clientConnectionId`.
-The Host chooses the effective model/provider configuration from its own
-session and provider state. Remote control does not become a credential relay.
+For legacy remote-Agent sessions, the Host chooses the effective model/provider
+configuration from its own session and provider state. Locally owned remote
+projects instead execute their model transport on Desktop (§3.6). Neither path
+turns RACP into a credential relay.
### 4.3 Remote permission ceiling
@@ -319,7 +340,8 @@ connection fail before they reach the Agent runtime.
## 6. Workspace, file, and attachment security
-1. A remote request identifies a Session, not an arbitrary filesystem root.
+1. Legacy remote-Agent requests identify a Session. The owner-only local-Agent
+ workspace service identifies an owner-selected root and revalidates it (§3.6).
2. The Host resolves every tool path against that Session's durable project or
scratch root.
3. Remote clients send attachment bytes or opaque attachment ids, never local
diff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.md
index 94ae5d34a..4acf62da9 100644
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@ -14557,7 +14557,7 @@ browser milestones are scheduled.
- **Milestone**: Post-MVP
- **Status**: Draft; remote harness required
-#### E2E-REMOTE-MVP: Narrow remote project-to-chat workflow
+#### E2E-REMOTE-MVP: Legacy remote Agent compatibility
- **Preconditions**: Current Desktop and complete same-platform Host bundle,
isolated data/profile, and a loopback mock model. No production credentials.
@@ -14570,43 +14570,46 @@ browser milestones are scheduled.
turn execute once, in the Host project only; stale routing never falls back
locally. Snapshot recovery restores pending requests and clears peer-resolved
cards. Local workspace/model state is unchanged.
-- **Component path**: Select a provider, verify copy is disabled before consent,
- authorize and copy, enter the remote project path, create/open, type/send,
- approve, resolve from another peer, and retry a failed reconnect. Buttons,
- visible errors and listener cleanup are checked in real React/Chromium.
+- **Component path**: Open existing remote Agent history, verify model-copy and
+ remote-create controls are absent, type/send, approve, resolve from another
+ peer, and retry a failed reconnect. New projects follow E2E-REMOTE-HOME.
- **Automation**: `scripts/e2e-remote-mvp.mjs` (packaged Host, real Rust/Agent
runtime and Desktop main routing, mocked model); `scripts/e2e-remote-mvp-ui.mjs`
(real components, mocked IPC). Neither is a full SSH/Desktop acceptance result.
- **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-REMOTE-HOME: Create and continue a remote workspace as a local project
+
+- **Preconditions**: Isolated Desktop profile, connected Host directory fixtures,
+ a local provider fixture, and local/remote directories with the same basename.
+ No user profile, production host, credentials or paid model calls.
+- **Steps**: Open Create project, choose Remote, browse through a separate folder
+ dialog, cancel/reopen, navigate parent/child and confirm a directory. Enter a
+ custom name, create, rename and reopen the project. Start a normal local chat,
+ choose a local model and send a request that invokes Read and Bash remotely.
+ Approve locally, cancel a command, disconnect/reconnect and retry explicitly.
+- **Expected**: Focus and drafts survive picker cancellation. Late host responses
+ cannot replace the current host selection. Project metadata and sessions are
+ local and stable after reload, including name/memory/instructions and ordinary
+ sidebar/archive operations. Model requests and provider secrets never appear
+ in remote transport. Only locally admitted workspace tools execute on Host.
+ Equal paths on two hosts or on Desktop never collide. Failed calls never
+ execute locally or replay automatically. Existing remote histories remain readable.
+- **Specs**: `02-architecture/05-remote-agent-control.md`, `04-ux/01-ui-ia.md`,
+ ADR `local-agent-remote-workspace-tools`.
+- **Acceptance / milestone**: Local Agent remote-workspace execution; additive
+ project KV metadata and authenticated workspace-tool endpoints.
+- **Automation**: `remote-project-dialog-user-path.test.mjs`,
+ `remote-workspace-tools.test.mjs`, host-core remote project/relay tests,
+ pi-host workspace-tool tests and Agent runtime remote-workspace tests;
+ `PI_HOST_CORE_BINARY=<candidate binary> node scripts/e2e-local-agent-remote-tools.mjs`
+ runs a local model fixture through production Desktop relay, WebSocket RACP
+ and real Rust Read/Bash execution, asserting zero remote providers, projects
+ and sessions. Both local and remote Rust Hosts are real; the model service
+ and the fixture's user approval action are controlled test boundaries.
+- **Status**: Candidate implementation; real SSH release validation remains the
+ separately provisioned E2E-231 scenario.
#### E2E-231: The desktop drives a remote Host over an SSH tunnel
@@ -14712,12 +14715,12 @@ browser milestones are scheduled.
confirm both forms stay filled and their ARIA tab/panel associations remain
correct after changing language. 4) Toggle developer mode and confirm the
destination stays selected and available. 5) On a paired SSH host, open the
- inline sessions/model-copy workbench and verify copy selection and consent
- start empty; changing selection invalidates consent.
+ historical sessions browser and verify model-copy and remote-create controls
+ are absent. New workspace creation stays on Home.
- **Expected**: Experimental availability is consistent across packaged and
development builds. SSH remains the default Add tab. Existing pairing toasts
- remain. The inline workbench explains credential copying and MVP limitations;
- unsupported local workspace/model/terminal operations are not offered.
+ remain. The inline browser preserves existing remote histories; new SSH workspace
+ projects use the local model and project controls from Home.
- **Specs linked**: `04-ux/06-settings-ia.md` §1, §3,
`06-delivery/07-remote-control-rollout.md` §2 R2,
`02-architecture/05-remote-agent-control.md` §5.2
diff --git a/packages/agent-runtime/src/extensions/runner.ts b/packages/agent-runtime/src/extensions/runner.ts
index 2e0a6e293..0a04921fc 100644
--- a/packages/agent-runtime/src/extensions/runner.ts
+++ b/packages/agent-runtime/src/extensions/runner.ts
@@ -140,6 +140,8 @@ export type RegisteredTrustedExtensionAgent = {
export interface TrustedExtensionBridge {
sessionId: string;
cwd: string;
+ /** Workspace is remote; implicit workspace exec must never spawn locally. */
+ remoteWorkspace?: boolean;
getModel(): unknown;
setModel(model: unknown, signal?: AbortSignal): Promise<boolean>;
getThinkingLevel(): string;
@@ -666,6 +668,9 @@ export class TrustedExtensionRunner {
options?: ExtensionExecOptions,
): Promise<ExtensionExecResult> {
if (this.disposed) return Promise.reject(new DOMException("Extension disposed", "AbortError"));
+ if (this.bridge.remoteWorkspace && (!options?.cwd || options.cwd === this.bridge.cwd)) {
+ return Promise.reject(Object.assign(new Error("extension workspace exec is unavailable for a remote workspace"), { errorCode: "CAPABILITY_UNAVAILABLE" }));
+ }
const pending = managedExec(command, args, this.bridge.cwd, this.lifecycle.operationSignal, options);
this.processes.add(pending);
void pending.then(() => this.processes.delete(pending), (error: unknown) => {
diff --git a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
index ad7f0b079..82ac9e31a 100644
--- a/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
+++ b/packages/agent-runtime/src/extensions/runtime-lifecycle.test.ts
@@ -232,3 +232,35 @@ describe("Desktop extension lifecycle", () => {
}
});
});
+
+it("retains local extension loading but rejects implicit workspace exec for a remote root", async () => {
+ const root = mkdtempSync(join(tmpdir(), "pi-remote-extension-"));
+ const key = `__remoteExtension_${Math.random().toString(36).slice(2)}`;
+ const entry = join(root, "extension.ts");
+ writeFileSync(entry, `export default function (pi) {
+ pi.registerCommand("probe", { handler: async (_args, ctx) => {
+ let errorCode;
+ try { await pi.exec(process.execPath, ["-e", "process.stdout.write('wrong-machine')"]); }
+ catch (error) { errorCode = error.errorCode; }
+ const local = await pi.exec(process.execPath, ["-e", "process.stdout.write('local-model-helper')"], { cwd: ${JSON.stringify(root)} });
+ globalThis[${JSON.stringify(key)}] = { cwd: ctx.cwd, errorCode, helper: local.stdout };
+ } });
+ }`);
+ const runtime = new DesktopAgentRuntime({
+ host: { call: async () => ({}), onNotification: () => () => {} } as never,
+ sessionId: "remote-extension", remoteWorkspace: { hostKey: "ssh", path: "/remote/workspace" },
+ mode: "agent", thinkingLevel: "off",
+ provider: { id: "local-model", name: "Local", apiKey: "", authKind: "none", baseUrl: "http://127.0.0.1:1/v1", modelId: "fixture", supportsReasoning: false, supportedThinkingLevels: ["off"] },
+ commandShell: { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true },
+ trustedExtensions: [{ id: entry, entry, label: "Local model helper", root, source: "plugin" }],
+ onEvent: () => {},
+ });
+ try {
+ await runtime.loadTrustedExtensions();
+ expect(runtime.getTrustedExtensionReports()).toMatchObject([{ state: "loaded" }]);
+ expect(await runtime.runTrustedExtensionCommand("probe", "")).toEqual({ handled: true });
+ expect((globalThis as Record<string, unknown>)[key]).toEqual({ cwd: "/remote/workspace", errorCode: "CAPABILITY_UNAVAILABLE", helper: "local-model-helper" });
+ } finally {
+ await runtime.dispose(); delete (globalThis as Record<string, unknown>)[key]; rmSync(root, { recursive: true, force: true });
+ }
+});
diff --git a/packages/agent-runtime/src/remote-workspace.test.ts b/packages/agent-runtime/src/remote-workspace.test.ts
new file mode 100644
index 000000000..2c16c487e
--- /dev/null
+++ b/packages/agent-runtime/src/remote-workspace.test.ts
@@ -0,0 +1,13 @@
+import { describe, expect, it } from "vitest";
+import { remoteMutationIdentity } from "./remote-workspace.js";
+
+describe("remote mutation bookkeeping", () => {
+ it("uses POSIX lexical paths and host identity without consulting local canonical paths", () => {
+ expect(remoteMutationIdentity({ hostKey: "ssh-a", path: "/remote/project" }, "src/../README.md"))
+ .toBe('["ssh-a","/remote/project/README.md"]');
+ expect(remoteMutationIdentity({ hostKey: "ssh-b", path: "/remote/project" }, "README.md"))
+ .not.toBe(remoteMutationIdentity({ hostKey: "ssh-a", path: "/remote/project" }, "README.md"));
+ expect(remoteMutationIdentity({ hostKey: "ssh-a", path: "/remote/project" }, "Readme.md"))
+ .not.toBe(remoteMutationIdentity({ hostKey: "ssh-a", path: "/remote/project" }, "README.md"));
+ });
+});
diff --git a/packages/agent-runtime/src/remote-workspace.ts b/packages/agent-runtime/src/remote-workspace.ts
new file mode 100644
index 000000000..91cd95a97
--- /dev/null
+++ b/packages/agent-runtime/src/remote-workspace.ts
@@ -0,0 +1,6 @@
+import { posix } from "node:path";
+
+/** Bookkeeping only; the remote Host canonicalizes and authorizes actual paths. */
+export function remoteMutationIdentity(workspace: { hostKey: string; path: string }, path: string): string {
+ return JSON.stringify([workspace.hostKey, posix.resolve(workspace.path, path)]);
+}
diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.ts
index 492abda02..4764d1347 100644
--- a/packages/agent-runtime/src/runtime.test.ts
+++ b/packages/agent-runtime/src/runtime.test.ts
@@ -167,6 +167,7 @@ function createRuntime(
compactionSettings: ContextCompactionSettings;
compactionStrategy: CompactionStrategy;
projectPath: string;
+ remoteWorkspace: { hostKey: string; path: string };
scratchDir: string;
customSystemPrompt: import("./custom-system-prompt.js").CustomSystemPrompt;
projectInstructions: import("./project-instructions.js").ProjectInstructions;
@@ -197,6 +198,7 @@ function createRuntime(
compactionSettings: overrides.compactionSettings,
compactionStrategy: overrides.compactionStrategy,
projectPath: overrides.projectPath,
+ remoteWorkspace: overrides.remoteWorkspace,
scratchDir: overrides.scratchDir,
customSystemPrompt: overrides.customSystemPrompt,
pluginTools: overrides.pluginTools,
@@ -11734,3 +11736,22 @@ describe("inline image placement", () => {
}
});
});
+
+
+describe("local runtime with a remote tool workspace", () => {
+ it("keeps the local model and dispatches workspace tools through the Host without local instruction probes", async () => {
+ const call = vi.fn(async (method: string) => {
+ if (method === "tools.execute") return { ok: true, content: "remote contents" };
+ throw new Error(`Unexpected local workspace access: ${method}`);
+ });
+ const runtime = createRuntime({ host: { call }, remoteWorkspace: { hostKey: "ssh", path: "/remote/project" }, scratchDir: "/local/scratch" });
+ const result = await runtimeTool(runtime, "Read").execute("remote-read", { path: "README.md" }, undefined, undefined);
+ expect(result.content).toContainEqual({ type: "text", text: "remote contents" });
+ expect(call.mock.calls.map(([method]) => method)).toEqual(["tools.execute"]);
+ const internals = runtime as unknown as { projectPath: string; provider: RuntimeProviderConfig; agent: Agent };
+ expect(internals.projectPath).toBe("/remote/project");
+ expect(internals.provider.id).toBe(provider.id);
+ expect(internals.agent.state.systemPrompt).not.toContain("/local/scratch");
+ await runtime.dispose();
+ });
+});
diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.ts
index 727baab51..8d5311fa5 100644
--- a/packages/agent-runtime/src/runtime.ts
+++ b/packages/agent-runtime/src/runtime.ts
@@ -17,6 +17,7 @@ import { todoWriteDescription, todoWriteParameters } from "./todo-tool.js";
import { createJevClassifierTool } from "./jev-classifier-tool.js";
import { scheduledToolParameters, scheduledToolDescriptions } from "./scheduled-tools.js";
import { withPiFileOpToolNames } from "./pi-file-ops.js";
+import { remoteMutationIdentity } from "./remote-workspace.js";
import { randomUUID } from "node:crypto";
import { mkdirSync } from "node:fs";
import {
@@ -976,6 +977,8 @@ export type AgentRuntimeOptions = {
customSystemPrompt?: CustomSystemPrompt;
/** Session-bound workspace root used for path-scoped instruction requests. */
projectPath?: string;
+ /** Remote tool root. Model requests and runtime state remain on this machine. */
+ remoteWorkspace?: { hostKey: string; path: string };
/** Instructions resolved from the session's workspace. */
projectInstructions?: ProjectInstructions;
/** Durable project context loaded from host-owned project memory. */
@@ -1043,6 +1046,8 @@ export type RuntimeMatchConfig = {
projectInstructions?: ProjectInstructions;
projectMemory?: string;
projectPath?: string;
+ /** Remote tool root. Model requests and runtime state remain on this machine. */
+ remoteWorkspace?: { hostKey: string; path: string };
commandShell: CommandShellOption;
subagents?: SubagentDefinition[];
subagentProviders?: Record<string, RuntimeProviderConfig>;
@@ -1794,6 +1799,7 @@ export class DesktopAgentRuntime {
private activationHydrated = false;
private scratchDir?: string;
private projectPath?: string;
+ private remoteWorkspace?: { hostKey: string; path: string };
private commandShell: CommandShellOption;
private baseProjectInstructions?: ProjectInstructions;
private projectInstructions?: ProjectInstructions;
@@ -1973,8 +1979,9 @@ export class DesktopAgentRuntime {
});
}
this.commandShell = opts.commandShell;
- this.scratchDir = opts.scratchDir;
- this.projectPath = opts.projectPath?.trim() || undefined;
+ this.remoteWorkspace = opts.remoteWorkspace;
+ this.scratchDir = opts.remoteWorkspace ? undefined : opts.scratchDir;
+ this.projectPath = opts.remoteWorkspace?.path ?? (opts.projectPath?.trim() || undefined);
this.customSystemPrompt = opts.customSystemPrompt;
this.baseProjectInstructions = opts.projectInstructions;
this.projectInstructions = opts.projectInstructions;
@@ -2635,7 +2642,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
safeJson(this.customSystemPrompt ?? null) ===
safeJson(config.customSystemPrompt ?? null) &&
(this.projectMemory ?? "") === (config.projectMemory?.trim() ?? "") &&
- (this.projectPath ?? "") === (config.projectPath?.trim() ?? "") &&
+ (this.projectPath ?? "") === (config.remoteWorkspace?.path ?? config.projectPath?.trim() ?? "") &&
+ safeJson(this.remoteWorkspace ?? null) === safeJson(config.remoteWorkspace ?? null) &&
// Editing `~/.agents/subagents/*.md` must reach the next prompt. Definition
// bodies are part of the `Task` tool's behavior, so unlike skills they
// are compared in full.
@@ -2804,6 +2812,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
return {
sessionId: this.sessionId,
cwd: this.extensionCwd(),
+ remoteWorkspace: Boolean(this.remoteWorkspace),
getModel: () => runtime.model,
setModel: (model, signal) => runtime.setExtensionModel(model, signal),
modelRegistry: runtime.extensionModelRegistry(),
@@ -3316,7 +3325,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
onUpdate,
) => {
const mutationPath = PATH_MUTATING_TOOLS.has(toolName) && isRecord(params) && typeof params.path === "string"
- ? await mutationFailureKey(params.path, this.projectPath ?? this.scratchDir)
+ ? this.remoteWorkspace
+ ? remoteMutationIdentity(this.remoteWorkspace, params.path)
+ : await mutationFailureKey(params.path, this.projectPath ?? this.scratchDir)
: undefined;
await this.loadPathInstructions(toolName, params);
const isBash = toolName === "Bash";
@@ -5902,7 +5913,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
toolName: string,
params: unknown,
): Promise<void> {
- if (!PATH_SCOPED_INSTRUCTION_TOOLS.has(toolName)) {
+ if (this.remoteWorkspace || !PATH_SCOPED_INSTRUCTION_TOOLS.has(toolName)) {
return undefined;
}
const path = isRecord(params) && typeof params.path === "string"
@@ -8762,7 +8773,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
}
/** Resolve attachments against the configuration of the running turn. */
- steeringContext(expectedTurnId: string): { projectPath?: string; supportsVision: boolean } {
+ steeringContext(expectedTurnId: string): { projectPath?: string; remoteWorkspace?: { hostKey: string; path: string }; supportsVision: boolean } {
if (
this.disposed || !this.acceptingSteering || this.runCancelled ||
this.turnHadError || !this.getStatus().isRunning ||
@@ -8773,7 +8784,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the
errorCode: "TURN_NOT_FOUND",
});
}
- return { projectPath: this.projectPath, supportsVision: this.model.input.includes("image") };
+ return { projectPath: this.projectPath, ...(this.remoteWorkspace ? { remoteWorkspace: this.remoteWorkspace } : {}), supportsVision: this.model.input.includes("image") };
}
steer(input: RuntimePrompt, expectedTurnId: string, message: UiMessage): { accepted: boolean; turnId: string } {
diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.ts
index 24cefb1ca..980fdb2ed 100644
--- a/packages/agent-runtime/src/sidecar.ts
+++ b/packages/agent-runtime/src/sidecar.ts
@@ -123,6 +123,7 @@ type RuntimeParams = {
scratchDir?: string;
/** Session-bound workspace root supplied by Electron main. */
projectPath?: string;
+ remoteWorkspace?: { hostKey: string; path: string };
customSystemPrompt?: CustomSystemPrompt;
projectInstructions?: ProjectInstructions;
projectMemory?: string;
@@ -236,6 +237,7 @@ async function runtimeFor(
customSystemPrompt: params.customSystemPrompt,
projectMemory: params.projectMemory,
projectPath: params.projectPath,
+ remoteWorkspace: params.remoteWorkspace,
commandShell: params.commandShell,
})
? existing
@@ -272,7 +274,7 @@ async function runtimeFor(
const supportsVision = visionFromModelConfig(params.provider.modelConfig);
history = await hydrateAttachmentHistory(restoredMessages, {
scratchDir: params.scratchDir,
- projectPath: params.projectPath,
+ projectPath: params.remoteWorkspace ? undefined : params.projectPath,
attachmentsDir: params.attachmentsDir,
supportsVision,
});
@@ -307,6 +309,7 @@ async function runtimeFor(
subagentProviders,
subagentModelKeys,
projectPath: params.projectPath,
+ remoteWorkspace: params.remoteWorkspace,
customSystemPrompt: params.customSystemPrompt,
projectInstructions: params.projectInstructions,
projectMemory: params.projectMemory,
diff --git a/packages/host-runtime/src/chat-ref-resolve.ts b/packages/host-runtime/src/chat-ref-resolve.ts
new file mode 100644
index 000000000..eb069c7c6
--- /dev/null
+++ b/packages/host-runtime/src/chat-ref-resolve.ts
@@ -0,0 +1,480 @@
+import { lstat, readdir, realpath, stat } from "node:fs/promises";
+import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
+import type {
+ FsChatRefMatch,
+ FsChatRefMatchKind,
+ FsChatRefProjectRoot,
+ FsChatRefRoot,
+} from "@pi-desktop/shared";
+import { isAttachmentBlobRef, isIgnoredName, resolveRealPathWithinRoot } from "./workspace-files.js";
+import { getWorkspaceFileIndex } from "./fs-index.js";
+
+/**
+ * Partial-path completion for a file reference the agent printed in chat.
+ *
+ * An agent that works on `/root/dir/openimage.js` routinely names only
+ * `openimage.js` in its prose. The transcript linkified that token against the
+ * workspace root alone, so the click resolved to a path that does not exist and
+ * the work panel painted an empty state instead of the file.
+ *
+ * Resolution order is the product contract:
+ *
+ * 1. an absolute reference only names that exact file inside a known root;
+ * 2. an `attachments/<sha256>` blob names a stored file by hash rather than
+ * by path, so it resolves against the attachment store directly;
+ * 3. otherwise the roots are searched in priority order — the open project
+ * first, the session's own scratch store second, the attachment blob
+ * store last — and the first root that answers wins, so the project is
+ * searched to exhaustion before the scratch store is considered;
+ * 4. inside one root an exact path beats a shorthand, and among shorthands
+ * the longest matching tail wins, then the shallowest path, so
+ * `src/dir/a.ts` beats a second `dir/a.ts` buried deeper.
+ */
+
+export type ChatRefRoots = {
+ /**
+ * Every folder of the open project, primary first (ADR 0249). A single-folder
+ * project is a one-element list, so callers never special-case it.
+ */
+ project?: readonly FsChatRefProjectRoot[] | null;
+ scratch?: string | null;
+ /**
+ * Roots an absolute reference may name without being searched by shorthand.
+ *
+ * A generated image lives in the scratch store of the session that produced
+ * it, and the user clicks it from whatever conversation they are reading —
+ * usually a later one. Every read guard (`fsRead`, `fsOpen`, the image
+ * reader, `fsReveal`) already accepts the whole scratch store, so completing
+ * against the session's own store alone reported a restriction for a file the
+ * app can open. These entries widen the absolute-path check only: a shorthand
+ * still searches the session's own root, so it never lands in another
+ * session's files.
+ */
+ containment?: readonly ChatRefContainmentRoot[] | null;
+ attachments?: string | null;
+};
+
+/** A root an absolute reference may name, though no shorthand searches it. */
+export type ChatRefContainmentRoot = { kind: FsChatRefRoot; path: string };
+
+/** A root to search, and — for a project folder — which folder it is. */
+type ChatRefRootEntry = {
+ kind: FsChatRefRoot;
+ path: string;
+ projectRoot?: FsChatRefProjectRoot;
+};
+
+type CanonicalChatRefRoot = ChatRefRootEntry & { realPath: string | null };
+
+const MAX_REF_LENGTH = 512;
+const ATTACHMENT_HASH_PATTERN = /^[0-9a-f]{64}$/i;
+/** A tail longer than this is a user quoting a full path, not a shorthand. */
+const MAX_FUZZY_TAIL_SEGMENTS = 6;
+/** Bound for the scratch/attachment walk; those trees are small by design. */
+const MAX_ROOT_WALK_ENTRIES = 4000;
+
+/**
+ * Windows and macOS compare filenames case-insensitively; Linux does not.
+ * An exact-case match still wins on a tie, so this only widens the net.
+ */
+const CASE_INSENSITIVE_FS =
+ process.platform === "win32" || process.platform === "darwin";
+
+function toPosix(value: string): string {
+ return String(value).replaceAll("\\", "/");
+}
+
+function matchesSegment(candidate: string, wanted: string): boolean {
+ if (candidate === wanted) return true;
+ return CASE_INSENSITIVE_FS && candidate.toLowerCase() === wanted.toLowerCase();
+}
+
+/** Strip the composer sigil, optional quotes, and a `:line[:col]` reference. */
+function cleanRef(raw: string): string {
+ let value = stripRefDecorations(String(raw ?? ""));
+ if (value.includes("\0")) return "";
+ value = value.replace(/:\d+(?::\d+)?$/, "");
+ return value;
+}
+
+function stripRefDecorations(raw: string): string {
+ let value = raw.trim();
+ if (value.startsWith("@")) value = value.slice(1).trim();
+ if (value.length >= 2 && value.startsWith("\"") && value.endsWith("\"")) {
+ value = value.slice(1, -1).trim();
+ }
+ return value;
+}
+
+export type ParsedChatRef = {
+ /** Path segments with `.` dropped and `..` collapsed. */
+ segments: string[];
+ /** Whether the original token anchored at a filesystem root. */
+ absolute: boolean;
+};
+
+/**
+ * Parse a chat file token. Returns null for `~`-prefixed home paths, empty
+ * tokens, oversized tokens, and any token whose `..` walk leaves the start.
+ */
+export function parseChatRef(raw: string): ParsedChatRef | null {
+ const value = cleanRef(raw);
+ if (!value || value.length > MAX_REF_LENGTH) return null;
+ if (value.startsWith("~")) return null;
+
+ const posix = toPosix(value);
+ const absolute =
+ posix.startsWith("/") ||
+ /^[a-z]:\//i.test(posix) ||
+ posix.startsWith("//");
+
+ const segments: string[] = [];
+ for (const segment of posix.split("/")) {
+ if (!segment || segment === ".") continue;
+ if (segment === "..") {
+ if (segments.length === 0) return null;
+ segments.pop();
+ continue;
+ }
+ segments.push(segment);
+ }
+ if (segments.length === 0) return null;
+ return { segments, absolute };
+}
+
+/**
+ * Product priority: the open project first, then session scratch, then
+ * attachments. Inside the project the order is the group's own order, primary
+ * first, so the folder the agent's tools default to answers before its siblings
+ * — and the first root that answers still wins outright.
+ */
+function orderedRoots(roots: ChatRefRoots): ChatRefRootEntry[] {
+ const list: ChatRefRootEntry[] = [];
+ for (const root of roots.project ?? []) {
+ const path = String(root?.path ?? "").trim();
+ if (!path) continue;
+ list.push({ kind: "workspace", path: resolve(path), projectRoot: root });
+ }
+ for (const kind of ["scratch", "attachments"] as const) {
+ const value = roots[kind];
+ if (typeof value !== "string" || !value.trim()) continue;
+ list.push({ kind, path: resolve(value) });
+ }
+ return list;
+}
+
+/**
+ * The containment-only roots, in the same vocabulary as the searched ones.
+ *
+ * They answer absolute references and nothing else: the shorthand walk below
+ * keeps searching `orderedRoots`, so a reference is never completed from
+ * another session's store.
+ */
+function containmentEntries(roots: ChatRefRoots): ChatRefRootEntry[] {
+ const list: ChatRefRootEntry[] = [];
+ for (const root of roots.containment ?? []) {
+ const path = String(root?.path ?? "").trim();
+ if (!path) continue;
+ list.push({ kind: root.kind, path: resolve(path) });
+ }
+ return list;
+}
+
+async function isRegularFile(target: string): Promise<boolean> {
+ try {
+ return (await stat(target)).isFile();
+ } catch {
+ return false;
+ }
+}
+
+/** Root-relative POSIX path, or null when `absolute` is outside `rootPath`. */
+function relativeInside(rootPath: string, absolute: string): string | null {
+ const rel = relative(rootPath, absolute);
+ if (!rel || rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel)) {
+ return null;
+ }
+ return toPosix(rel);
+}
+
+async function canonicalRoots(roots: ChatRefRootEntry[]): Promise<CanonicalChatRefRoot[]> {
+ return Promise.all(roots.map(async (root) => {
+ try {
+ return { ...root, realPath: await realpath(root.path) };
+ } catch {
+ return { ...root, realPath: null };
+ }
+ }));
+}
+
+function couldShareVolume(target: string, roots: CanonicalChatRefRoot[]): boolean {
+ if (process.platform !== "win32") return true;
+ const volume = parse(target).root.toLowerCase();
+ return roots.some((root) => [root.path, root.realPath].some(
+ (path) => path && parse(path).root.toLowerCase() === volume,
+ ));
+}
+
+async function canonicalPathOrMissingTail(path: string): Promise<string | null> {
+ let ancestor = path;
+ const tail: string[] = [];
+ for (;;) {
+ try {
+ return resolve(await realpath(ancestor), ...tail);
+ } catch {
+ const parent = dirname(ancestor);
+ if (parent === ancestor) return null;
+ tail.unshift(basename(ancestor));
+ ancestor = parent;
+ }
+ }
+}
+
+export async function isChatRefOutsideRoots(ref: string, roots: ChatRefRoots): Promise<boolean> {
+ const parsed = parseChatRef(ref);
+ if (!parsed?.absolute) return false;
+ const cleaned = cleanRef(ref);
+ if (!isAbsolute(cleaned)) return true;
+ const absolutePath = resolve(cleaned);
+ const rootList = await canonicalRoots([...orderedRoots(roots), ...containmentEntries(roots)]);
+ if (!couldShareVolume(absolutePath, rootList)) return true;
+ const targetPath = await canonicalPathOrMissingTail(absolutePath);
+ if (!targetPath) return !rootList.some((root) => relativeInside(root.path, absolutePath) !== null);
+ return !rootList.some((root) =>
+ root.realPath && relativeInside(root.realPath, targetPath) !== null,
+ );
+}
+
+function segmentsOf(path: string): string[] {
+ return toPosix(path).split("/").filter(Boolean);
+}
+
+/** Fewer segments first, then a stable lexicographic order. */
+function compareCandidates(a: string, b: string): number {
+ const depthDelta = segmentsOf(a).length - segmentsOf(b).length;
+ if (depthDelta !== 0) return depthDelta;
+ return a.localeCompare(b);
+}
+
+function endsWithTail(fileSegments: string[], tail: string[]): boolean {
+ if (fileSegments.length < tail.length) return false;
+ const offset = fileSegments.length - tail.length;
+ for (let index = 0; index < tail.length; index += 1) {
+ if (!matchesSegment(fileSegments[offset + index], tail[index])) return false;
+ }
+ return true;
+}
+
+type FuzzyCandidate = { relativePath: string; matchedBy: FsChatRefMatchKind };
+
+/**
+ * Longest tail first, so a two-segment shorthand beats a bare leaf name.
+ * Within one tail the shallowest file wins.
+ */
+function fuzzyCandidates(
+ files: readonly string[],
+ tails: readonly string[][],
+): FuzzyCandidate[] {
+ const parsedFiles = files.map((file) => ({
+ file,
+ segments: segmentsOf(file),
+ }));
+ const candidates: FuzzyCandidate[] = [];
+ const seen = new Set<string>();
+ for (const tail of tails) {
+ const matches = parsedFiles
+ .filter((entry) => endsWithTail(entry.segments, tail))
+ .map((entry) => entry.file)
+ .sort(compareCandidates);
+ for (const file of matches) {
+ if (seen.has(file)) continue;
+ seen.add(file);
+ candidates.push({
+ relativePath: file,
+ matchedBy: tail.length === 1 ? "basename" : "path-suffix",
+ });
+ }
+ }
+ return candidates;
+}
+
+async function isContainedRegularFile(root: string, relativePath: string): Promise<boolean> {
+ const realPath = await resolveRealPathWithinRoot(root, relativePath);
+ return realPath !== null && isRegularFile(realPath);
+}
+
+async function hasInvalidLinkAncestor(root: string, segments: readonly string[]): Promise<boolean> {
+ for (let length = 1; length <= segments.length; length += 1) {
+ const prefixSegments = segments.slice(0, length);
+ try {
+ if ((await lstat(join(root, ...prefixSegments))).isSymbolicLink()
+ && !(await resolveRealPathWithinRoot(root, prefixSegments.join("/")))) return true;
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException).code;
+ // Only ordinary missing paths can fall back to an indexed suffix match.
+ if (code !== "ENOENT" && code !== "ENOTDIR") return true;
+ }
+ }
+ return false;
+}
+
+/** Bounded walk for trees with no git index (session scratch, attachments). */
+async function walkRootFiles(
+ rootPath: string,
+ budget: number,
+): Promise<string[]> {
+ const files: string[] = [];
+ const queue: string[] = [""];
+ while (queue.length > 0 && files.length < budget) {
+ const rel = queue.shift() as string;
+ let dirents;
+ try {
+ dirents = await readdir(join(rootPath, rel), { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const dirent of dirents) {
+ if (isIgnoredName(dirent.name)) continue;
+ const childRel = rel ? `${rel}/${dirent.name}` : dirent.name;
+ if (dirent.isDirectory()) {
+ queue.push(childRel);
+ } else if (dirent.isFile()) {
+ files.push(childRel);
+ if (files.length >= budget) break;
+ }
+ }
+ }
+ return files;
+}
+
+/**
+ * The project goes through the composer's cached index, which already carries
+ * gitignore semantics and the files-tab ignore set; scratch and attachments
+ * have no index and are walked directly.
+ */
+async function listRootFiles(
+ kind: FsChatRefRoot,
+ rootPath: string,
+): Promise<string[]> {
+ if (kind === "workspace") {
+ const index = await getWorkspaceFileIndex(rootPath);
+ return index.entries
+ .filter((entry) => entry.kind === "file")
+ .map((entry) => entry.path);
+ }
+ return walkRootFiles(rootPath, MAX_ROOT_WALK_ENTRIES);
+}
+
+/**
+ * Resolve one chat file reference to the best existing file, or null when
+ * nothing matches. Never throws: an unreadable root is simply not a match.
+ */
+export async function resolveChatFileRef(
+ ref: string,
+ roots: ChatRefRoots,
+): Promise<FsChatRefMatch | null> {
+ const parsed = parseChatRef(ref);
+ if (!parsed) return null;
+ const rootList = orderedRoots(roots);
+ if (rootList.length === 0 && !(roots.containment ?? []).length) return null;
+
+ const cleanedPosixRef = toPosix(cleanRef(ref));
+ const isAttachmentRef = /^attachments(?:\/|$)/i.test(cleanedPosixRef);
+
+ // Absolute references must not select an unrelated in-root file by suffix.
+ if (parsed.absolute) {
+ const cleaned = cleanRef(ref);
+ if (!isAbsolute(cleaned)) return null;
+ const absolutePath = resolve(cleaned);
+ // An absolute reference may also name a store the app reads but no shorthand
+ // searches, such as an image another session generated.
+ const canonicalRootList = await canonicalRoots([
+ ...rootList,
+ ...containmentEntries(roots),
+ ]);
+ if (!couldShareVolume(absolutePath, canonicalRootList)) return null;
+ let targetPath: string;
+ try {
+ targetPath = await realpath(absolutePath);
+ } catch {
+ return null;
+ }
+ if (!(await isRegularFile(targetPath))) return null;
+ for (const root of canonicalRootList) {
+ const relativePath = root.realPath ? relativeInside(root.realPath, targetPath) : null;
+ if (!relativePath) continue;
+ return {
+ root: root.kind,
+ relativePath,
+ absolutePath,
+ matchedBy: "exact-absolute",
+ ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
+ };
+ }
+ return null;
+ }
+
+ // 2. A content-addressed attachment blob (`attachments/<sha256>`) is not a
+ // filesystem path: it names a stored blob by hash, and the files-tab
+ // contract spells it that way. Resolve it against the attachment root
+ // directly instead of searching for a path that cannot exist.
+ if (isAttachmentRef) {
+ if (!isAttachmentBlobRef(cleanedPosixRef)) return null;
+ const attachmentsRoot = roots.attachments;
+ if (!attachmentsRoot) return null;
+ const blobHash = segmentsOf(cleanedPosixRef).at(-1);
+ if (!blobHash || !ATTACHMENT_HASH_PATTERN.test(blobHash)) return null;
+ const resolvedRoot = resolve(attachmentsRoot);
+ const absolutePath = join(resolvedRoot, blobHash.toLowerCase());
+ if (!absolutePath.startsWith(resolvedRoot + sep) && absolutePath !== resolvedRoot) {
+ return null;
+ }
+ if (!(await isContainedRegularFile(resolvedRoot, blobHash.toLowerCase()))) return null;
+ return {
+ root: "attachments",
+ relativePath: blobHash.toLowerCase(),
+ absolutePath,
+ matchedBy: "exact-relative",
+ };
+ }
+
+ // 3. Roots in product priority order, and the first root that answers wins
+ // outright: the open project is searched to exhaustion before the session
+ // scratch store is considered at all. Inside one root the reference read
+ // as a path verbatim outranks a tail match.
+ const tails: string[][] = [];
+ const longestTail = Math.min(parsed.segments.length, MAX_FUZZY_TAIL_SEGMENTS);
+ for (let length = longestTail; length >= 1; length -= 1) {
+ tails.push(parsed.segments.slice(parsed.segments.length - length));
+ }
+ for (const root of rootList) {
+ const absolutePath = join(root.path, ...parsed.segments);
+ if (await isRegularFile(absolutePath)) {
+ if (!(await isContainedRegularFile(root.path, parsed.segments.join("/")))) return null;
+ return {
+ root: root.kind,
+ relativePath: parsed.segments.join("/"),
+ absolutePath,
+ matchedBy: "exact-relative",
+ ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
+ };
+ }
+ if (await hasInvalidLinkAncestor(root.path, parsed.segments)) return null;
+ const candidates = fuzzyCandidates(
+ await listRootFiles(root.kind, root.path),
+ tails,
+ );
+ for (const candidate of candidates) {
+ if (!(await isContainedRegularFile(root.path, candidate.relativePath))) continue;
+ return {
+ root: root.kind,
+ relativePath: candidate.relativePath,
+ absolutePath: join(root.path, ...segmentsOf(candidate.relativePath)),
+ matchedBy: candidate.matchedBy,
+ ...(root.projectRoot ? { projectRoot: root.projectRoot } : {}),
+ };
+ }
+ }
+
+ return null;
+}
diff --git a/packages/host-runtime/src/fs-index.ts b/packages/host-runtime/src/fs-index.ts
new file mode 100644
index 000000000..5f4673a28
--- /dev/null
+++ b/packages/host-runtime/src/fs-index.ts
@@ -0,0 +1,173 @@
+import { spawn } from "node:child_process";
+import { readdir } from "node:fs/promises";
+import { join } from "node:path";
+import type { FsIndexEntry, FsIndexResult } from "@pi-desktop/shared";
+import { isIgnoredName } from "./workspace-files.js";
+
+/**
+ * Workspace file index for the composer "@" menu (D124, ADR 0024).
+ *
+ * Served from the main process like the files tab (ADR 0019): user-driven
+ * browsing must not round-trip agent tools or permission prompts. The index
+ * prefers `git ls-files` for exact gitignore semantics and falls back to a
+ * bounded walk over the panel's ignore set. Fuzzy filtering happens in the
+ * renderer; this only snapshots relative paths.
+ */
+
+export const FS_INDEX_MAX_ENTRIES = 8000;
+const CACHE_TTL_MS = 15_000;
+const GIT_TIMEOUT_MS = 4000;
+const MAX_GIT_BUFFER = 32 * 1024 * 1024;
+
+type CacheSlot = { at: number; result: FsIndexResult };
+const cache = new Map<string, CacheSlot>();
+
+function hasIgnoredSegment(path: string): boolean {
+ for (const segment of path.split("/")) {
+ if (isIgnoredName(segment)) return true;
+ }
+ return false;
+}
+
+/** `git ls-files -co --exclude-standard -z`, null when git is unusable. */
+function gitListFiles(root: string): Promise<string[] | null> {
+ return new Promise((resolve) => {
+ const child = spawn(
+ "git",
+ ["ls-files", "-co", "--exclude-standard", "-z"],
+ { cwd: root, env: process.env },
+ );
+ let out = "";
+ let failed = false;
+ const timer = setTimeout(() => {
+ failed = true;
+ child.kill();
+ }, GIT_TIMEOUT_MS);
+ child.stdout.on("data", (chunk) => {
+ out += String(chunk);
+ if (out.length > MAX_GIT_BUFFER) {
+ failed = true;
+ child.kill();
+ }
+ });
+ child.on("error", () => {
+ clearTimeout(timer);
+ resolve(null);
+ });
+ child.on("close", (code) => {
+ clearTimeout(timer);
+ if (failed || code !== 0) return resolve(null);
+ resolve(out.split("\0").filter((p) => p.length > 0));
+ });
+ });
+}
+
+/** Bounded recursive walk honoring the files-tab ignore set. */
+async function walkFiles(
+ root: string,
+ budget: number,
+): Promise<{ files: string[]; dirs: string[]; exhausted: boolean }> {
+ const files: string[] = [];
+ const dirs: string[] = [];
+ let exhausted = false;
+ const queue: string[] = [""];
+ while (queue.length > 0) {
+ const rel = queue.shift()!;
+ let dirents;
+ try {
+ dirents = await readdir(join(root, rel), { withFileTypes: true });
+ } catch {
+ continue;
+ }
+ for (const dirent of dirents) {
+ if (isIgnoredName(dirent.name)) continue;
+ const childRel = rel ? `${rel}/${dirent.name}` : dirent.name;
+ // Symlinks are skipped: the snapshot must never cycle or leave root.
+ if (dirent.isDirectory()) {
+ dirs.push(childRel);
+ queue.push(childRel);
+ } else if (dirent.isFile()) {
+ files.push(childRel);
+ }
+ if (files.length + dirs.length >= budget) {
+ exhausted = true;
+ queue.length = 0;
+ break;
+ }
+ }
+ }
+ return { files, dirs, exhausted };
+}
+
+function dirsFromFilePaths(files: string[]): string[] {
+ const dirs = new Set<string>();
+ for (const file of files) {
+ let at = file.indexOf("/");
+ while (at > 0) {
+ dirs.add(file.slice(0, at));
+ at = file.indexOf("/", at + 1);
+ }
+ }
+ return [...dirs];
+}
+
+function depth(path: string): number {
+ let count = 0;
+ for (const ch of path) if (ch === "/") count += 1;
+ return count;
+}
+
+/** Shallow entries first so truncation keeps the top-level tree visible. */
+function compareEntries(a: FsIndexEntry, b: FsIndexEntry): number {
+ const depthDelta = depth(a.path) - depth(b.path);
+ if (depthDelta !== 0) return depthDelta;
+ return a.path.localeCompare(b.path);
+}
+
+async function buildIndex(root: string): Promise<FsIndexResult> {
+ const viaGit = await gitListFiles(root);
+ let files: string[];
+ let dirs: string[];
+ let exhausted = false;
+ if (viaGit) {
+ // -o lists untracked-but-not-ignored files; repos without a .gitignore
+ // would still surface build output, so the panel ignore set applies too.
+ files = viaGit.filter((p) => !hasIgnoredSegment(p));
+ dirs = dirsFromFilePaths(files);
+ } else {
+ const walked = await walkFiles(root, FS_INDEX_MAX_ENTRIES + 1);
+ files = walked.files;
+ dirs = walked.dirs;
+ exhausted = walked.exhausted;
+ }
+
+ const entries: FsIndexEntry[] = [
+ ...dirs.map((path): FsIndexEntry => ({ path, kind: "dir" })),
+ ...files.map((path): FsIndexEntry => ({ path, kind: "file" })),
+ ].sort(compareEntries);
+
+ if (entries.length > FS_INDEX_MAX_ENTRIES) {
+ return { entries: entries.slice(0, FS_INDEX_MAX_ENTRIES), truncated: true };
+ }
+ return { entries, truncated: exhausted };
+}
+
+/** TTL-cached workspace index; concurrent calls share one build. */
+const pending = new Map<string, Promise<FsIndexResult>>();
+
+export async function getWorkspaceFileIndex(root: string): Promise<FsIndexResult> {
+ const cached = cache.get(root);
+ if (cached && Date.now() - cached.at < CACHE_TTL_MS) return cached.result;
+ const inFlight = pending.get(root);
+ if (inFlight) return inFlight;
+ const build = buildIndex(root)
+ .then((result) => {
+ cache.set(root, { at: Date.now(), result });
+ return result;
+ })
+ .finally(() => {
+ pending.delete(root);
+ });
+ pending.set(root, build);
+ return build;
+}
diff --git a/packages/host-runtime/src/index.ts b/packages/host-runtime/src/index.ts
index 4009c78b9..7edac2dcb 100644
--- a/packages/host-runtime/src/index.ts
+++ b/packages/host-runtime/src/index.ts
@@ -18,3 +18,5 @@ export * from "./live-work/coordinator.js";
export * from "./live-work/context.js";
export * from "./live-work/feedback-scheduler.js";
export * from "./live-work/result-summary.js";
+export * from "./fs-index.js";
+export * from "./chat-ref-resolve.js";
diff --git a/packages/racp/src/client.ts b/packages/racp/src/client.ts
index 6c1aae276..c42439cb6 100644
--- a/packages/racp/src/client.ts
+++ b/packages/racp/src/client.ts
@@ -139,22 +139,22 @@ export class RacpClient {
this.setState("disconnected");
}
- request<T = unknown>(method: string, params?: unknown): Promise<T> {
+ request<T = unknown>(method: string, params?: unknown, timeoutMs?: number): Promise<T> {
const transport = this.transport;
if (!transport || this.stateValue !== "connected") {
return Promise.reject(new RacpError("HOST_DISCONNECTED", `not connected (${this.stateValue})`, { retriable: true }));
}
- return this.send<T>(transport, method, params);
+ return this.send<T>(transport, method, params, timeoutMs);
}
- private send<T>(transport: ClientTransport, method: string, params: unknown): Promise<T> {
+ private send<T>(transport: ClientTransport, method: string, params: unknown, timeoutMs?: number): Promise<T> {
this.counter += 1;
const id = `c${this.counter}`;
return new Promise<T>((resolve, reject) => {
const timer = setTimeout(() => {
this.pending.delete(id);
reject(new RacpError("TIMEOUT", `${method} timed out`, { retriable: true }));
- }, this.options.requestTimeoutMs ?? 15_000);
+ }, timeoutMs ?? this.options.requestTimeoutMs ?? 15_000);
timer.unref?.();
this.pending.set(id, { resolve: resolve as (value: unknown) => void, reject, timer, method });
try {
diff --git a/packages/racp/src/host-operations.ts b/packages/racp/src/host-operations.ts
index 613f196f8..f0f0afac1 100644
--- a/packages/racp/src/host-operations.ts
+++ b/packages/racp/src/host-operations.ts
@@ -4,6 +4,7 @@ import type {
FsReadResult,
RacpProjectSummary,
WorkspaceDiff,
+ WorkspaceToolExecute, WorkspaceToolAbort, WorkspaceToolResult, CommandShellOption, WorkspaceFilesRequest,
} from "@pi-desktop/shared";
/**
@@ -86,6 +87,13 @@ export type RacpHostOperations = {
projects: RacpProjectCatalog;
workspace: RacpWorkspaceAccess;
terminal?: RacpTerminalAccess;
+ workspaceFiles?: { read(input: WorkspaceFilesRequest): Promise<unknown> };
+ workspaceTools?: {
+ execute(input: WorkspaceToolExecute, owner: { deviceId: string; connectionId: string }): Promise<WorkspaceToolResult>;
+ abort(input: WorkspaceToolAbort, owner: { deviceId: string; connectionId: string }): Promise<void>;
+ shell(): Promise<CommandShellOption>;
+ disconnect(connectionId: string): Promise<void>;
+ };
/** Owner-only: revoke a paired device (spec `session/revoke`). */
revokeDevice?: (deviceId: string) => Promise<boolean>;
};
diff --git a/packages/racp/src/operations.ts b/packages/racp/src/operations.ts
index d6eba1a91..72647054d 100644
--- a/packages/racp/src/operations.ts
+++ b/packages/racp/src/operations.ts
@@ -2,6 +2,7 @@ import type { AgentHost, Principal } from "@pi-desktop/agent-host";
import { RacpError } from "@pi-desktop/agent-host";
import {
RacpApprovalResponseSchema,
+ WorkspaceToolExecuteSchema, WorkspaceToolAbortSchema, WorkspaceFilesRequestSchema,
RacpCursorSchema,
RacpInputResponseSchema,
RacpRequestContextSchema,
@@ -154,6 +155,32 @@ export function createOperations(): Map<RacpOperation, OperationHandler> {
throw new RacpError("METHOD_NOT_FOUND", "host/list exists only behind a Gateway");
});
+ const requireWorkspaceTools = (context: OperationContext) => {
+ if (!context.operations.workspaceTools || !context.capabilities.workspaceTools) {
+ throw new RacpError("CAPABILITY_UNAVAILABLE", "this Host does not offer workspace tools");
+ }
+ return context.operations.workspaceTools;
+ };
+ const toolOwner = (context: OperationContext) => ({
+ deviceId: context.principal.subject, connectionId: context.connection.id,
+ });
+ handlers.set("workspace/files", async (context, params) => {
+ if (!context.operations.workspaceFiles || !context.capabilities.workspaceFiles) {
+ throw new RacpError("CAPABILITY_UNAVAILABLE", "this Host does not offer workspace files");
+ }
+ return context.operations.workspaceFiles.read(check(WorkspaceFilesRequestSchema, params));
+ });
+ handlers.set("workspace/toolExecute", async (context, params) =>
+ requireWorkspaceTools(context).execute(check(WorkspaceToolExecuteSchema, params), toolOwner(context)));
+ handlers.set("workspace/toolAbort", async (context, params) => {
+ await requireWorkspaceTools(context).abort(check(WorkspaceToolAbortSchema, params), toolOwner(context));
+ return { ok: true };
+ });
+ handlers.set("workspace/toolShell", async (context, params) => {
+ check(Type.Object({}, { additionalProperties: false }), params);
+ return { shell: await requireWorkspaceTools(context).shell() };
+ });
+
handlers.set("project/list", async (context) => ({ projects: await context.operations.projects.list() }));
handlers.set("project/register", async (context, params) => {
const input = check(Type.Object({ path: Type.String({ minLength: 1 }) }), params);
diff --git a/packages/racp/src/racp.test.ts b/packages/racp/src/racp.test.ts
index 09439ac49..af41f3ff8 100644
--- a/packages/racp/src/racp.test.ts
+++ b/packages/racp/src/racp.test.ts
@@ -375,3 +375,38 @@ describe("RACP-WS remote-host profile", () => {
/** Type-only assertion that the envelope import stays used. */
export type _Envelope = RacpEventEnvelope;
+
+describe("owner-only workspace tool boundary", () => {
+ it("routes execute/shell/abort without model or session operations, and rejects viewer/extra fields", async () => {
+ const calls: unknown[] = [];
+ const shell = { id: "bash" as const, label: "Bash", dialect: "posix" as const, available: true, isDefault: true };
+ const h = await harness({ operations: { workspaceTools: {
+ async execute(input, owner) { calls.push({ input, owner }); return { ok: true, content: "remote result" }; },
+ async abort(input, owner) { calls.push({ input, owner }); },
+ async shell() { return shell; },
+ async disconnect(connectionId) { calls.push({ disconnected: connectionId }); },
+ } } });
+ const { client } = await h.connect(OWNER_TOKEN);
+ expect(client.initialized?.capabilities.workspaceTools).toBe(true);
+ const input = { path: "/workspace", sessionId: "local-session", turnId: "local-turn", toolCallId: "call-1", toolName: "Read", args: { path: "a.txt" } };
+ expect(await client.request("workspace/toolExecute", input)).toEqual({ ok: true, content: "remote result" });
+ expect(await client.request("workspace/toolShell", {})).toEqual({ shell });
+ await client.request("workspace/toolAbort", { sessionId: "local-session", toolCallId: "call-1" });
+ expect(calls).toHaveLength(2);
+ await expect(client.request("workspace/toolExecute", { ...input, providerApiKey: "fixture-only" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ await expect(client.request("workspace/toolExecute", { ...input, toolName: "provider.getSecret" })).rejects.toMatchObject({ code: "INVALID_ARGUMENT" });
+ const viewer = await h.connect(VIEWER_TOKEN);
+ await expect(viewer.client.request("workspace/toolExecute", input)).rejects.toMatchObject({ code: "FORBIDDEN" });
+ await expect(viewer.client.request("workspace/toolShell", {})).rejects.toMatchObject({ code: "FORBIDDEN" });
+ expect(h.runtime.prompts).toHaveLength(0);
+ await client.close();
+ await flush();
+ expect(calls).toHaveLength(3);
+ await viewer.client.close();
+ });
+ it("fails closed when the paired Host lacks the tool service", async () => {
+ const h = await harness(); const { client } = await h.connect(OWNER_TOKEN);
+ await expect(client.request("workspace/toolShell", {})).rejects.toMatchObject({ code: "CAPABILITY_UNAVAILABLE" });
+ await client.close();
+ });
+});
diff --git a/packages/racp/src/server.ts b/packages/racp/src/server.ts
index 08edea5d9..f9599f19d 100644
--- a/packages/racp/src/server.ts
+++ b/packages/racp/src/server.ts
@@ -178,6 +178,8 @@ export class RacpServer {
remoteHostProfile: true,
toolRelay: false,
terminal: Boolean(options.operations.terminal),
+ workspaceTools: Boolean(options.operations.workspaceTools),
+ workspaceFiles: Boolean(options.operations.workspaceFiles),
notifications: false,
bindings: ["RACP-WS"],
};
@@ -262,6 +264,9 @@ export class RacpServer {
this.options.operations.terminal?.detach(terminalId);
}
connection.terminals.clear();
+ void this.options.operations.workspaceTools?.disconnect(connection.id).catch(() => {
+ this.options.log("warn", "workspace tool disconnect cleanup failed", { connectionId: connection.id });
+ });
connection.close(1000, "closed");
this.options.log("info", "racp connection released", { connectionId: connection.id });
}
diff --git a/packages/shared/fixtures/racp.schema.json b/packages/shared/fixtures/racp.schema.json
index 1dd5b75de..e2bc3c58d 100644
--- a/packages/shared/fixtures/racp.schema.json
+++ b/packages/shared/fixtures/racp.schema.json
@@ -2044,6 +2044,12 @@
"terminal": {
"type": "boolean"
},
+ "workspaceTools": {
+ "type": "boolean"
+ },
+ "workspaceFiles": {
+ "type": "boolean"
+ },
"notifications": {
"type": "boolean"
},
diff --git a/packages/shared/src/changelog-de.ts b/packages/shared/src/changelog-de.ts
index 165f208de..14a32ed63 100644
--- a/packages/shared/src/changelog-de.ts
+++ b/packages/shared/src/changelog-de.ts
@@ -5,6 +5,7 @@ export const deEntries: ChangelogEntry[] = [
"version": "0.18.0",
"date": "2026-10-09",
"highlights": [
+ "SSH-Arbeitsbereichsprojekte auf der Startseite benennen und Ordner in einem eigenen Dialog wählen; Modellanfragen und Zugangsdaten bleiben auf Ihrem Computer.",
"Richten Sie den Jev-Klassifizierer von TypeSafe über „Dienst hinzufügen“ ein; der API-Schlüssel wird vor dem Speichern geprüft.",
"Cloud-Synchronisierung ist in den Einstellungen der installierten Version verfügbar und als experimentell gekennzeichnet. Projektlisten bleiben auf dem jeweiligen Gerät.",
"Fügen Sie über „Dienst hinzufügen“ Plugin-eigene API-Schlüssel-Dienste hinzu, mit lokalisierten Beschreibungen und Modellerkennung nach der Einrichtung.",
diff --git a/packages/shared/src/changelog-en.ts b/packages/shared/src/changelog-en.ts
index fe87663f3..ae882ff57 100644
--- a/packages/shared/src/changelog-en.ts
+++ b/packages/shared/src/changelog-en.ts
@@ -5,6 +5,7 @@ export const enEntries: ChangelogEntry[] = [
version: "0.18.0",
date: "2026-10-09",
highlights: [
+ "Create named SSH workspace projects from Home, browse folders in a separate dialog, and keep model requests and credentials on your computer.",
"Set up TypeSafe's Jev classifier from Add Service and verify its API key before saving.",
"Find Cloud sync in packaged Settings with its Experimental badge. Project lists stay on each device.",
"Add plugin-owned API-key services from Add Service, with localized descriptions and model discovery after setup.",
diff --git a/packages/shared/src/changelog-es.ts b/packages/shared/src/changelog-es.ts
index d1ab47e0c..75f4fb845 100644
--- a/packages/shared/src/changelog-es.ts
+++ b/packages/shared/src/changelog-es.ts
@@ -5,6 +5,7 @@ export const esEntries: ChangelogEntry[] = [
"version": "0.18.0",
"date": "2026-10-09",
"highlights": [
+ "Crea y nombra proyectos SSH desde Inicio, elige carpetas en un diálogo separado y conserva las solicitudes y credenciales del modelo en tu equipo.",
"Configura el clasificador Jev de TypeSafe desde Añadir servicio y verifica la clave API antes de guardarla.",
"La sincronización en la nube ya está disponible en los ajustes de la versión empaquetada y se marca como experimental. Las listas de proyectos permanecen en cada dispositivo.",
"Añade desde Añadir servicio proveedores de plugins con clave API, descripciones localizadas y detección de modelos tras configurarlos.",
diff --git a/packages/shared/src/changelog-fr.ts b/packages/shared/src/changelog-fr.ts
index 7e8fbb5bf..2081ffabf 100644
--- a/packages/shared/src/changelog-fr.ts
+++ b/packages/shared/src/changelog-fr.ts
@@ -5,6 +5,7 @@ export const frEntries: ChangelogEntry[] = [
"version": "0.18.0",
"date": "2026-10-09",
"highlights": [
+ "Créez et nommez des projets SSH depuis l’accueil, choisissez les dossiers dans une boîte de dialogue dédiée et gardez les requêtes et identifiants du modèle sur votre ordinateur.",
"Configurez le classificateur Jev de TypeSafe depuis Ajouter un service et vérifiez la clé API avant de l'enregistrer.",
"La synchronisation cloud est disponible dans les paramètres de la version empaquetée et porte la mention « expérimental ». Les listes de projets restent sur chaque appareil.",
"Ajoutez depuis Ajouter un service des fournisseurs de plugins avec clé API, descriptions localisées et découverte des modèles après configuration.",
diff --git a/packages/shared/src/changelog-ko.ts b/packages/shared/src/changelog-ko.ts
index dac8aafb4..64559bf0e 100644
--- a/packages/shared/src/changelog-ko.ts
+++ b/packages/shared/src/changelog-ko.ts
@@ -5,6 +5,7 @@ export const koEntries: ChangelogEntry[] = [
"version": "0.18.0",
"date": "2026-10-09",
"highlights": [
+ "홈에서 SSH 작업 공간 프로젝트를 만들고 이름을 지정하세요. 별도 대화상자에서 폴더를 선택하며 모델 요청과 자격 증명은 내 컴퓨터에 유지됩니다.",
"서비스 추가에서 TypeSafe Jev 분류기를 설정하고 저장 전에 API 키를 확인하세요.",
"패키지 빌드의 설정에서 클라우드 동기화를 사용할 수 있으며 실험적 기능으로 표시됩니다. 프로젝트 목록은 각 기기에만 유지됩니다.",
"서비스 추가에서 플러그인이 제공하는 API 키 서비스를 추가하고, 현지화된 설명을 확인한 뒤 키 설정 후 모델을 검색하세요.",
diff --git a/packages/shared/src/changelog-pt-BR.ts b/packages/shared/src/changelog-pt-BR.ts
index 2a6dda817..4a59ca0f4 100644
--- a/packages/shared/src/changelog-pt-BR.ts
+++ b/packages/shared/src/changelog-pt-BR.ts
@@ -5,6 +5,7 @@ export const ptBREntries: ChangelogEntry[] = [
"version": "0.18.0",
"date": "2026-10-09",
"highlights": [
+ "Crie e nomeie projetos SSH na página inicial, escolha pastas em um diálogo separado e mantenha solicitações e credenciais do modelo no seu computador.",
"Configure o classificador Jev da TypeSafe em Adicionar serviço e valide a chave de API antes de salvá-la.",
"A sincronização na nuvem está disponível nas configurações da versão empacotada e é identificada como experimental. As listas de projetos permanecem em cada dispositivo.",
"Adicione em Adicionar serviço provedores de plugins com chave de API, descrições localizadas e descoberta de modelos após a configuração.",
diff --git a/packages/shared/src/changelog-tr.ts b/packages/shared/src/changelog-tr.ts
index 396126762..267f69c22 100644
--- a/packages/shared/src/changelog-tr.ts
+++ b/packages/shared/src/changelog-tr.ts
@@ -5,6 +5,7 @@ export const trEntries: ChangelogEntry[] = [
"version": "0.18.0",
"date": "2026-10-09",
"highlights": [
+ "Ana sayfadan SSH çalışma alanı projeleri oluşturup adlandırın; klasörleri ayrı bir iletişim kutusunda seçin, model istekleri ve kimlik bilgileri bilgisayarınızda kalsın.",
"TypeSafe Jev sınıflandırıcısını Hizmet Ekle'den kurun ve kaydetmeden önce API anahtarını doğrulayın.",
"Bulut eşitlemesi paketlenmiş sürümün ayarlarında kullanılabilir ve deneysel olarak işaretlenir. Proje listeleri her cihazda yerel olarak kalır.",
"Yerelleştirilmiş açıklamalar ve anahtar kurulumundan sonra model keşfiyle eklenti kaynaklı API anahtarlı hizmetleri ekleyin.",
diff --git a/packages/shared/src/changelog-zh-CN.ts b/packages/shared/src/changelog-zh-CN.ts
index d773430ad..45eaea186 100644
--- a/packages/shared/src/changelog-zh-CN.ts
+++ b/packages/shared/src/changelog-zh-CN.ts
@@ -5,6 +5,7 @@ export const zhCNEntries: ChangelogEntry[] = [
version: "0.18.0",
date: "2026-10-09",
highlights: [
+ "从首页创建并命名 SSH 工作区项目,在独立弹窗中选择目录;模型请求和密钥始终留在本机。",
"可从「添加服务」接入 TypeSafe 的 Jev 分类器;保存前会先验证 API 密钥。",
"打包版设置现已开放云同步,并标注为实验性功能。项目列表仅保留本机。",
"可从「添加服务」添加插件提供的 API 密钥服务;提供本地化说明,并在配置密钥后发现模型。",
diff --git a/packages/shared/src/changelog-zh-TW.ts b/packages/shared/src/changelog-zh-TW.ts
index d74204971..3427a4feb 100644
--- a/packages/shared/src/changelog-zh-TW.ts
+++ b/packages/shared/src/changelog-zh-TW.ts
@@ -5,6 +5,7 @@ export const zhTWEntries: ChangelogEntry[] = [
version: "0.18.0",
date: "2026-10-09",
highlights: [
+ "從首頁建立並命名 SSH 工作區專案,在獨立對話框中選擇目錄;模型請求和金鑰始終留在本機。",
"可從「新增服務」設定 TypeSafe 的 Jev 分類器,並在儲存前驗證 API 金鑰。",
"打包版設定現已開放雲端同步,並標示為實驗性功能。專案清單僅保留於本機。",
"可從「新增服務」加入外掛提供的 API 金鑰服務,查看在地化說明,並在設定金鑰後探索模型。",
diff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.ts
index a557c92ca..acefa91a5 100644
--- a/packages/shared/src/protocol.ts
+++ b/packages/shared/src/protocol.ts
@@ -176,6 +176,7 @@ export const IPC = {
projectMemoryGet: "pi-desktop/project/memory/get",
projectMemorySave: "pi-desktop/project/memory/save",
projectGroupList: "pi-desktop/project-group/list",
+ projectGroupCreateRemote: "pi-desktop/project-group/createRemote",
projectGroupCreate: "pi-desktop/project-group/create",
projectGroupRename: "pi-desktop/project-group/rename",
projectGroupUpdate: "pi-desktop/project-group/update",
diff --git a/packages/shared/src/racp.ts b/packages/shared/src/racp.ts
index 8bd8e7386..10e91a701 100644
--- a/packages/shared/src/racp.ts
+++ b/packages/shared/src/racp.ts
@@ -103,6 +103,34 @@ export const RacpRequestContextSchema = Type.Object({
});
export type RacpRequestContext = Static<typeof RacpRequestContextSchema>;
+export const WorkspaceFilesRequestSchema = Type.Object({
+ path: Type.String({ minLength: 1, maxLength: 4096 }),
+ operation: Type.Union([Type.Literal("list"), Type.Literal("read"), Type.Literal("index"), Type.Literal("resolve"), Type.Literal("image"), Type.Literal("diff")]),
+ ref: Type.Optional(Type.String({ maxLength: 4096 })),
+ mimeType: Type.Optional(Type.String({ maxLength: 256 })),
+}, { additionalProperties: false });
+export type WorkspaceFilesRequest = Static<typeof WorkspaceFilesRequestSchema>;
+
+/** Narrow owner-only tool service; model configuration and credentials never cross it. */
+export const WorkspaceToolExecuteSchema = Type.Object({
+ path: Type.String({ minLength: 1, maxLength: 4096 }),
+ sessionId: Type.String({ minLength: 1, maxLength: 256 }),
+ turnId: Type.String({ minLength: 1, maxLength: 256 }),
+ toolCallId: Type.String({ minLength: 1, maxLength: 256 }),
+ toolName: Type.Union([Type.Literal("Read"), Type.Literal("Glob"), Type.Literal("Grep"), Type.Literal("Write"), Type.Literal("Edit"), Type.Literal("Bash")]),
+ args: Type.Record(Type.String(), Type.Unknown()),
+ timeoutMs: Type.Optional(Type.Integer({ minimum: 1, maximum: 21_600_000 })),
+ expectedCommandShellId: Type.Optional(Type.String({ minLength: 1, maxLength: 256 })),
+ expectedCommandShellDialect: Type.Optional(Type.Union([Type.Literal("posix"), Type.Literal("powershell"), Type.Literal("cmd")])),
+}, { additionalProperties: false });
+export type WorkspaceToolExecute = Static<typeof WorkspaceToolExecuteSchema>;
+export const WorkspaceToolAbortSchema = Type.Object({
+ sessionId: Type.String({ minLength: 1, maxLength: 256 }),
+ toolCallId: Type.String({ minLength: 1, maxLength: 256 }),
+}, { additionalProperties: false });
+export type WorkspaceToolAbort = Static<typeof WorkspaceToolAbortSchema>;
+export type WorkspaceToolResult = { ok: boolean; content: unknown; isError?: boolean; errorCode?: string; toolCallId?: string };
+
// ---------------------------------------------------------------------------
// Canonical resources (spec §5)
// ---------------------------------------------------------------------------
@@ -422,6 +450,8 @@ export const RacpServerCapabilitiesSchema = Type.Object({
remoteHostProfile: Type.Boolean(),
toolRelay: Type.Boolean(),
terminal: Type.Boolean(),
+ workspaceTools: Type.Optional(Type.Boolean()),
+ workspaceFiles: Type.Optional(Type.Boolean()),
notifications: Type.Boolean(),
bindings: Type.Array(Type.Union([Type.Literal("RACP-WS"), Type.Literal("RACP-HTTP"), Type.Literal("RACP-GRPC")])),
});
@@ -559,6 +589,10 @@ export const RACP_OPERATIONS = {
"workspace/list": { role: "viewer", profile: "remote-host", mutation: false },
"workspace/read": { role: "viewer", profile: "remote-host", mutation: false },
"workspace/diff": { role: "viewer", profile: "remote-host", mutation: false },
+ "workspace/toolExecute": { role: "owner", profile: "remote-host", mutation: true },
+ "workspace/toolAbort": { role: "owner", profile: "remote-host", mutation: true },
+ "workspace/toolShell": { role: "owner", profile: "remote-host", mutation: false },
+ "workspace/files": { role: "owner", profile: "remote-host", mutation: false },
"terminal/open": { role: "controller", profile: "remote-host", mutation: true },
"terminal/input": { role: "controller", profile: "remote-host", mutation: true },
"terminal/resize": { role: "controller", profile: "remote-host", mutation: true },
diff --git a/packages/shared/src/rpc-timeouts.ts b/packages/shared/src/rpc-timeouts.ts
index 65a7c8523..0df025f53 100644
--- a/packages/shared/src/rpc-timeouts.ts
+++ b/packages/shared/src/rpc-timeouts.ts
@@ -86,6 +86,6 @@ export function rpcTimeoutMs(
): number | undefined {
if (method === "agent.compact") return AGENT_COMPACT_RPC_TIMEOUT_MS;
if (method === "configSync.syncNow") return undefined;
- if (method === "tools.execute") return undefined;
+ if (method === "tools.execute" || method === "tools.workspaceExecute") return undefined;
return DEFAULT_RPC_TIMEOUT_MS;
}
diff --git a/packages/shared/src/types/sessions.ts b/packages/shared/src/types/sessions.ts
index d6542acef..34dc4b6c8 100644
--- a/packages/shared/src/types/sessions.ts
+++ b/packages/shared/src/types/sessions.ts
@@ -1,4 +1,5 @@
/** Shared public types grouped by the owning application domain. */
+import type { RemoteWorkspace } from "./workspace.js";
import type { Mode } from "./common.js";
import type { SessionThinkingLevel, ThinkingLevel } from "./models.js";
import type { PermissionMode } from "./permissions.js";
@@ -32,6 +33,7 @@ export type SessionCapabilities = {
};
export type SessionSummary = {
+ remoteWorkspace?: RemoteWorkspace;
id: string;
/** Transcript authority. Omitted by older hosts and normalized to `desktop`. */
source?: SessionSource;
diff --git a/packages/shared/src/types/workspace.ts b/packages/shared/src/types/workspace.ts
index fed9f342d..59827198e 100644
--- a/packages/shared/src/types/workspace.ts
+++ b/packages/shared/src/types/workspace.ts
@@ -19,7 +19,10 @@ export type NotificationListResult = {
unreadCount: number;
};
+export type RemoteWorkspace = { hostKey: string; path: string };
+
export type ProjectWorkspace = {
+ remote?: RemoteWorkspace;
path: string;
name: string;
/** Best-effort git branch from .git/HEAD when available. */
@@ -42,6 +45,7 @@ export type ProjectGroupRoot = {
};
export type ProjectGroupRecord = {
+ remote?: RemoteWorkspace;
id: string;
name: string;
primaryPath: string;
@@ -57,6 +61,7 @@ export type ProjectGroupRecord = {
};
export type ProjectGroupContext = {
+ remote?: RemoteWorkspace;
groupId: string;
roots: ProjectGroupRoot[];
instructions: string;
diff --git a/scripts/e2e-local-agent-remote-tools.mjs b/scripts/e2e-local-agent-remote-tools.mjs
new file mode 100644
index 000000000..ee51eb96a
--- /dev/null
+++ b/scripts/e2e-local-agent-remote-tools.mjs
@@ -0,0 +1,129 @@
+#!/usr/bin/env node
+/** Isolated local model -> real Main relay -> loopback RACP -> real Rust tools.
+ * The Host has no providers. No SSH, credentials, paid APIs or user app is used. */
+import assert from "node:assert/strict";
+import { createServer } from "node:http";
+import { once } from "node:events";
+import { mkdtemp, mkdir, writeFile, readFile, rm } from "node:fs/promises";
+import { tmpdir } from "node:os";
+import { join, resolve } from "node:path";
+import { register } from "node:module";
+register(new URL("../apps/desktop/test/helpers/ts-import-hooks.mjs", import.meta.url));
+const { DesktopAgentRuntime } = await import("../packages/agent-runtime/dist/index.js");
+const { HostProcess, createHostSessionPort } = await import("../packages/host-runtime/dist/index.js");
+const { AgentHost } = await import("../packages/agent-host/dist/index.js");
+const { bindRacpWebSocket, RacpServer, MemoryCredentialStore, DeviceTokenAuthenticator, hashToken, newDeviceToken } = await import("../packages/racp/dist/index.js");
+const { createWorkspaceTools } = await import("../apps/pi-host/dist/workspace-tools.js");
+const { createHostOperations } = await import("../apps/pi-host/dist/host-operations.js");
+const OWNER_TOKEN = newDeviceToken();
+const { createRemoteHostsBoot } = await import("../apps/desktop/electron/main/bootstrap/remote-hosts.ts");
+const { createRemoteWorkspaceToolRelay } = await import("../apps/desktop/electron/main/remote/remote-workspace-tools.ts");
+const { createBackendRouter } = await import("../apps/desktop/electron/main/remote/backend-router.ts");
+
+assert.ok(process.env.PI_HOST_CORE_BINARY, "PI_HOST_CORE_BINARY must name the current candidate Rust binary");
+const root = await mkdtemp(join(process.env.PI_SCRATCH_DIR ?? tmpdir(), "local-agent-remote-tools-"));
+const remoteRoot = join(root, "remote-workspace");
+await mkdir(remoteRoot); await mkdir(join(root, "desktop"));
+await writeFile(join(remoteRoot, "README.md"), "REMOTE_READ_FIXTURE\n");
+const KEY = "local-model-fixture-key-never-forwarded";
+let modelCalls = 0;
+let modelError;
+let host;
+let localHost;
+let relay;
+let localPermissions = 0;
+let binding;
+let boot;
+let runtime;
+let h;
+const wireCalls = [];
+const model = createServer(async (req, res) => {
+ try {
+ assert.equal(req.headers.authorization, `Bearer ${KEY}`);
+ let body = ""; for await (const chunk of req) body += chunk;
+ const input = JSON.parse(body);
+ assert.equal(input.model, "local-fixture");
+ modelCalls++;
+ res.writeHead(200, { "content-type": "text/event-stream" });
+ const frame = (delta, finish_reason = null) => res.write(`data: ${JSON.stringify({ id: `local-${modelCalls}`, object: "chat.completion.chunk", created: 1, model: input.model, choices: [{ index: 0, delta, finish_reason }] })}\n\n`);
+ if (modelCalls <= 2) {
+ if (modelCalls === 2) assert.ok(JSON.stringify(input.messages).includes("REMOTE_READ_FIXTURE"), "actual remote Read enters local model context");
+ const name = modelCalls === 1 ? "Read" : "Bash";
+ const args = name === "Read" ? { path: "README.md" } : { command: "printf 'REMOTE_BASH_FIXTURE\\n' > marker.txt" };
+ frame({ role: "assistant", tool_calls: [{ index: 0, id: `local-tool-${modelCalls}`, type: "function", function: { name, arguments: JSON.stringify(args) } }] });
+ frame({}, "tool_calls");
+ } else {
+ assert.equal(modelCalls, 3, "model/tool execution is not replayed");
+ assert.ok(input.messages.some(message => message.role === "tool"));
+ frame({ role: "assistant", content: "LOCAL_MODEL_REMOTE_TOOLS_OK" }); frame({}, "stop");
+ }
+ res.end("data: [DONE]\n\n");
+ } catch (error) { modelError = error; if (!res.headersSent) res.writeHead(500); res.end(); }
+});
+model.listen(0, "127.0.0.1"); await once(model, "listening");
+const deadline = setTimeout(() => { console.error("local-Agent remote-tool acceptance exceeded 60s"); process.exit(1); }, 60_000);
+try {
+ host = new HostProcess({ binaryPath: resolve(process.env.PI_HOST_CORE_BINARY), dataDir: join(root, "host"), onStderr: () => {} });
+ await host.handshake();
+ const tools = createWorkspaceTools(() => host);
+ let remotePrompts = 0;
+ const agentHost = new AgentHost({ sessions: createHostSessionPort(() => host),
+ runtime: { async prompt() { remotePrompts++; throw new Error("remote models must not run"); }, async stop() { return { requested: false }; }, async abort() {}, async respondInput() {} },
+ approvals: { async resolveTool() { throw new Error("no remote approval"); }, async resolveContract() { throw new Error("no remote contract"); }, async listPendingTools() { return []; } },
+ });
+ const credentials = new MemoryCredentialStore();
+ await credentials.saveDevice({ deviceId: "fixture-owner", label: "Fixture", roles: ["owner"], tokenHash: hashToken(OWNER_TOKEN), createdAt: new Date().toISOString() });
+ const authenticator = new DeviceTokenAuthenticator(credentials);
+ const operations = createHostOperations({ getHost: () => host, runtime: { isBusy: () => false, async compact() { throw new Error("no remote model"); } } });
+ operations.workspaceTools = { ...tools, async execute(input, owner) { wireCalls.push(structuredClone(input)); return tools.execute(input, owner); } };
+ h = { server: new RacpServer({ agentHost, operations, authenticator, hostId: "tool-host", serverVersion: "fixture", log: () => {} }), remotePrompts: () => remotePrompts };
+ binding = await bindRacpWebSocket({ server: h.server, authenticator, host: "127.0.0.1", port: 0, log: () => {} });
+ boot = createRemoteHostsBoot({ dataDir: join(root, "desktop"), router: createBackendRouter(), clientInfo: { name: "local-agent-fixture", version: "fixture" }, emit: () => {}, encryption: { isAvailable: () => true, encryptString: value => Buffer.from(value), decryptString: value => value.toString() } });
+ assert.equal((await boot.addHost({ hostKey: "fixture", label: "Fixture", url: `ws://127.0.0.1:${binding.address.port}/v1/racp/ws`, deviceToken: OWNER_TOKEN })).connected, true);
+ const shell = await boot.workspaceCommandShell("fixture");
+ localHost = new HostProcess({ binaryPath: resolve(process.env.PI_HOST_CORE_BINARY), dataDir: join(root, "local-host"), onStderr: () => {} });
+ await localHost.handshake();
+ const created = await localHost.call("project.group.createRemote", { name: "Locally named remote project", remote: { hostKey: "fixture", path: remoteRoot } });
+ const localSession = await localHost.call("session.create", { projectPath: created.group.primaryPath, mode: "agent" });
+ relay = createRemoteWorkspaceToolRelay(localHost, { getBoot: () => boot, isCurrent: () => true, isTurnDispatchable: (sessionId, turnId) => sessionId === localSession.session.id && turnId === "local-turn", log: () => {} });
+ localHost.onNotification((method, params) => {
+ if (method === "tools.remoteExecute") void relay.execute(params);
+ if (method === "tools.remoteAbort") relay.cancel(params);
+ if (method === "permissions.request") {
+ localPermissions++;
+ void localHost.call("permissions.resolve", { requestId: params.requestId, decision: "allow-once" });
+ }
+ });
+ let ended;
+ const done = new Promise((resolveDone, rejectDone) => { ended = envelope => { if (envelope.event.type === "error") rejectDone(new Error(JSON.stringify(envelope.event))); if (envelope.event.type === "agent_end") resolveDone(); }; });
+ runtime = new DesktopAgentRuntime({
+ sessionId: localSession.session.id, mode: "agent", thinkingLevel: "off", commandShell: shell,
+ remoteWorkspace: { hostKey: "fixture", path: remoteRoot },
+ provider: { id: "local-provider", name: "Local fixture", modelId: "local-fixture", baseUrl: `http://127.0.0.1:${model.address().port}/v1`, apiStyle: "chat_completions", apiKey: KEY, authKind: "api_key", supportsReasoning: false, supportedThinkingLevels: ["off"] },
+ host: { call: (method, params) => localHost.call(method, params), onNotification: handler => localHost.onNotification(handler) },
+ onEvent: envelope => ended(envelope),
+ });
+ await Promise.all([runtime.prompt("Read README.md and write marker.txt using Bash.", "user-1", "local-turn"), done]);
+ assert.equal(modelError, undefined);
+ assert.equal(modelCalls, 3);
+ assert.equal(localPermissions, 1, "Bash is approved by local permissions before remote dispatch");
+ assert.equal(await readFile(join(remoteRoot, "marker.txt"), "utf8"), "REMOTE_BASH_FIXTURE\n");
+ assert.deepEqual(wireCalls.map(call => call.toolName), ["Read", "Bash"]);
+ assert.ok(!JSON.stringify(wireCalls).includes(KEY), "local provider key never crosses the workspace boundary");
+ assert.ok(wireCalls.every(call => !Object.keys(call).some(key => /provider|model|secret|auth/i.test(key))));
+ const providers = await host.call("providers.list", {});
+ assert.equal(providers.providers.length, 0, "Host needs no provider configuration");
+ const sessions = await host.call("session.list", {});
+ assert.equal(sessions.sessions.length, 0, "tool service creates no persistent remote session");
+ const projects = await host.call("projects.list", {});
+ assert.equal(projects.projects.length, 0, "tool service creates no persistent remote project");
+ assert.equal(h.remotePrompts(), 0, "no remote Agent/model invocation");
+ await assert.rejects(boot.executeWorkspaceTool({ ...wireCalls[0], hostKey: "fixture" }), "duplicate tool id cannot replay");
+ await boot.removeHost("fixture");
+ await assert.rejects(boot.executeWorkspaceTool({ ...wireCalls[0], toolCallId: "after-disconnect", hostKey: "fixture" }), { errorCode: "AGENT_UNAVAILABLE" });
+ console.log("PASS local model/key + local Rust project/permission relay + real RACP/Rust Read/Bash, no remote providers/projects/sessions, no replay/fallback");
+} finally {
+ clearTimeout(deadline);
+ await runtime?.dispose(); relay?.dispose(); await localHost?.dispose(); await boot?.closeAll(); h?.server.close(); await binding?.close(); await host?.dispose();
+ model.closeAllConnections(); await new Promise(resolveClose => model.close(resolveClose)); await rm(root, { recursive: true, force: true });
+}
diff --git a/scripts/e2e/remote-mvp-ui.jsx b/scripts/e2e/remote-mvp-ui.jsx
index 741b9ad03..91d8386e0 100644
--- a/scripts/e2e/remote-mvp-ui.jsx
+++ b/scripts/e2e/remote-mvp-ui.jsx
@@ -29,7 +29,7 @@ window.piDesktop = {
calls.push({ channel, input });
let data = {};
if (channel === IPC.invoke.remoteHostProjects) data = { projects: [] };
- else if (channel === IPC.invoke.remoteHostSessions) data = { sessions: [] };
+ else if (channel === IPC.invoke.remoteHostSessions) data = { sessions: [session] };
else if (channel === IPC.invoke.remoteHostSyncProviders) data = { imported: [{ sourceId: provider.id, providerId: "remote-provider" }], skipped: [], defaultSet: true };
else if (channel === IPC.invoke.remoteHostRegisterProject) data = { project: { id: "project", label: "Project" } };
else if (channel === IPC.invoke.remoteHostCreateSession) data = { session };
@@ -79,22 +79,11 @@ globalThis.remoteMvpProbe = async () => {
const unsubscribe = subscribeRemoteInteractions();
const root = createRoot(document.getElementById("root"));
root.render(<Fixture />);
- await until(() => button(remoteEn.sync) && !document.querySelector('[aria-busy="true"]'), "host inventory never loaded");
- assert(button(remoteEn.sync).disabled, "sync must require selection and consent");
- button(provider.name).click();
- await until(() => !checkbox(remoteEn.consent).disabled, "consent never enabled");
- assert(button(remoteEn.sync).disabled, "selection alone must not copy credentials");
- checkbox(remoteEn.consent).click();
- await until(() => !button(remoteEn.sync).disabled, "explicit consent did not enable sync");
- button(remoteEn.sync).click();
- await until(() => calls.some(call => call.channel === IPC.invoke.remoteHostSyncProviders) && !document.querySelector('[aria-busy="true"]'), "sync did not complete");
- const sync = calls.find(call => call.channel === IPC.invoke.remoteHostSyncProviders).input;
- assert(JSON.stringify(sync) === JSON.stringify({ hostKey: host.hostKey, providerIds: [provider.id], setDefault: true }), "only selected provider IDs cross renderer IPC");
- assert(!checkbox(remoteEn.consent).checked, "consent must be cleared after sync");
- 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(".chat-surface"), "created session did not open");
+ await until(() => button(`${session.title} · ${session.remoteWorkspaceLabel}`) && !document.querySelector('[aria-busy="true"]'), "history never loaded");
+ assert(!button(remoteEn.sync) && !button(remoteEn.create), "legacy history exposes remote model or project creation");
+ assert(!calls.some(call => call.channel === IPC.invoke.remoteHostProjects || call.channel === IPC.invoke.remoteHostSyncProviders), "history fetched project or model state");
+ button(`${session.title} · ${session.remoteWorkspaceLabel}`).click();
+ await until(() => document.querySelector(".chat-surface"), "existing session did not open");
assert(useAppStore.getState().workspace.path === "/local/private", "remote selection changed local workspace");
const editor = document.querySelector(".composer-input");
editor.textContent = "Inspect remote project";
@@ -123,5 +112,5 @@ globalThis.remoteMvpProbe = async () => {
assert(!calls.some(call => [IPC.invoke.projectActivate, IPC.invoke.sessionConfigure].includes(call.channel)), "remote UI called a local workspace/model operation");
root.unmount(); unsubscribe();
assert(listeners.size === 0, "component listeners leaked");
- return { ok: true, scenarios: ["consent", "create/open", "send", "approve", "peer resolution", "reconnect without replay", "local isolation", "cleanup"] };
+ return { ok: true, scenarios: ["history without model transfer", "open", "send", "approve", "peer resolution", "reconnect without replay", "local isolation", "cleanup"] };
};