Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat: isolate parallel sessions of one project in git worktrees
renwanga128246dd7de1
diff --git a/apps/desktop/electron/main/ipc/agent-ipc.ts b/apps/desktop/electron/main/ipc/agent-ipc.tsindex face8cce2..43be507c8 100644--- a/apps/desktop/electron/main/ipc/agent-ipc.ts+++ b/apps/desktop/electron/main/ipc/agent-ipc.ts@@ -322,7 +322,7 @@ export function registerAgentIpc({session,settings,);- sidecar.setProjectInstructionRoot(req.sessionId, launch.projectPath);+ sidecar.setProjectInstructionRoot(req.sessionId, launch.workspaceRoot ?? launch.projectPath);// Open a durable turn row, then persist the user message under it.const turn = await host.call<{ turnId?: string }>("session.beginTurn", {@@ -593,7 +593,7 @@ export function registerAgentIpc({detail.session,settings,);- sidecar.setProjectInstructionRoot(req.sessionId, launch.projectPath);+ sidecar.setProjectInstructionRoot(req.sessionId, launch.workspaceRoot ?? launch.projectPath);// A lost reply is not the sidecar's verdict: the sidecar keeps summarizing// and persists the checkpoint through host-core, so the durable record// decides whether this manual compaction succeeded (issue #795).diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex b406531c8..eff042db9 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -1,5 +1,5 @@import { join } from "node:path";-import { dialog, type BrowserWindow, type IpcMain, type IpcMainInvokeEvent } from "electron";+import { dialog, shell, type BrowserWindow, type IpcMain, type IpcMainInvokeEvent } from "electron";import { err, ErrorCodes, IPC, ok, type Result } from "@pi-desktop/shared";import type { AgentHostBridge } from "../agent-host-bridge";import type { AgentSidecar } from "../agent-sidecar";@@ -29,6 +29,7 @@ import { registerAgentImportIpc } from "./agent-import-ipc";import { registerRemoteHostIpc } from "./remote-host-ipc";import { fetchSkillMarketDocument, searchSkillMarket } from "../skill-market-catalog";import { registerWindowIpc } from "./window-ipc";+import { registerWorktreeIpc } from "./worktree-ipc";import { createComposerTemplateLoader, registerWorkspaceIpc } from "./workspace-ipc";import { registerComposerIpc } from "./composer-ipc";import { registerSpeechIpc } from "./speech-ipc";@@ -302,6 +303,13 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {onProviderInvalidated: (providerId) => liveCallService?.invalidateProvider(providerId),});registerJevIpc({ registrar, logger });+ registerWorktreeIpc({+ registrar,+ getHost,+ logger,+ openPath: (path) => shell.openPath(path),+ stripWinLongPrefix,+ });const loadComposerTemplatesCached = createComposerTemplateLoader(logger);const composerCommandService = registerComposerIpc({registrar,diff --git a/apps/desktop/electron/main/ipc/worktree-ipc.ts b/apps/desktop/electron/main/ipc/worktree-ipc.tsnew file mode 100644index 000000000..ed289415a--- /dev/null+++ b/apps/desktop/electron/main/ipc/worktree-ipc.ts@@ -0,0 +1,127 @@+/**+ * Isolated-session worktree channels (ADR 0328).+ *+ * A thin pass-through to host-core's `worktree.*` methods: host-core owns every+ * git command and every worktree path. The renderer names a session or a+ * project and never receives a worktree path; "Reveal" resolves the path here+ * and hands it straight to the OS file manager.+ */+import { ErrorCodes, IPC } from "@pi-desktop/shared";+import type { HostProcess } from "../host-process";+import type { Logger } from "../logger";+import type { IpcRegistrar } from "./types";++export type WorktreeIpcDependencies = {+ registrar: IpcRegistrar;+ getHost: () => HostProcess | null;+ logger: Pick<Logger, "app">;+ openPath: (path: string) => Promise<string>;+ stripWinLongPrefix: (path: string) => string;+};++function requiredText(input: unknown, field: string): string {+ const value =+ input && typeof input === "object" ? (input as Record<string, unknown>)[field] : undefined;+ const text = typeof value === "string" ? value.trim() : "";+ if (!text) {+ throw Object.assign(new Error(`${field} required`), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }+ return text;+}++export function registerWorktreeIpc({+ registrar,+ getHost,+ logger,+ openPath,+ stripWinLongPrefix,+}: WorktreeIpcDependencies): void {+ const host = (): HostProcess => {+ const current = getHost();+ if (!current) throw new Error("host unavailable");+ return current;+ };++ registrar.handle(IPC.invoke.worktreeProbe, async (input: unknown) =>+ host().call("worktree.probe", { projectPath: requiredText(input, "projectPath") }),+ );++ registrar.handle(IPC.invoke.worktreePreview, async (input: unknown) => {+ const result = await host().call<{ preview: unknown }>("worktree.preview", {+ sessionId: requiredText(input, "sessionId"),+ });+ return result.preview;+ });++ registrar.handle(IPC.invoke.worktreeMerge, async (input: unknown) => {+ const sessionId = requiredText(input, "sessionId");+ const result = await host().call<{ outcome: unknown }>("worktree.merge", {+ sessionId,+ previewToken: requiredText(input, "previewToken"),+ });+ logger.app("session", "info", "isolated session merged into project", { sessionId });+ return result.outcome;+ });++ registrar.handle(IPC.invoke.worktreeBehind, async (input: unknown) => {+ const result = await host().call<{ commits: number }>("worktree.behind", {+ sessionId: requiredText(input, "sessionId"),+ });+ return result.commits;+ });++ registrar.handle(IPC.invoke.worktreeBehindAll, async () =>+ host().call("worktree.behindAll", {}),+ );++ registrar.handle(IPC.invoke.worktreeSync, async (input: unknown) => {+ const sessionId = requiredText(input, "sessionId");+ const result = await host().call<{ outcome: unknown }>("worktree.sync", { sessionId });+ logger.app("session", "info", "isolated session synced from project", { sessionId });+ return result.outcome;+ });++ registrar.handle(IPC.invoke.worktreePendingWork, async (input: unknown) => {+ const result = await host().call<{ pending: unknown }>("worktree.pendingWork", {+ sessionId: requiredText(input, "sessionId"),+ });+ return result.pending;+ });++ registrar.handle(IPC.invoke.worktreeSetupLog, async (input: unknown) =>+ host().call("worktree.setupLog", { sessionId: requiredText(input, "sessionId") }),+ );++ registrar.handle(IPC.invoke.worktreeReveal, async (input: unknown) => {+ const result = await host().call<{ path: string }>("worktree.location", {+ sessionId: requiredText(input, "sessionId"),+ });+ const openError = await openPath(stripWinLongPrefix(result.path));+ if (openError) throw new Error(openError);+ return { ok: true };+ });++ registrar.handle(IPC.invoke.worktreeSetupCommandGet, async (input: unknown) =>+ host().call("worktree.setupCommand.get", {+ projectPath: requiredText(input, "projectPath"),+ }),+ );++ registrar.handle(IPC.invoke.worktreeSetupCommandSet, async (input: unknown) => {+ const command =+ input && typeof input === "object"+ ? (input as Record<string, unknown>).command+ : undefined;+ if (command !== undefined && command !== null && typeof command !== "string") {+ throw Object.assign(new Error("command must be a string"), {+ errorCode: ErrorCodes.INVALID_ARGUMENT,+ });+ }+ return host().call("worktree.setupCommand.set", {+ projectPath: requiredText(input, "projectPath"),+ command: typeof command === "string" ? command : null,+ });+ });+}diff --git a/apps/desktop/electron/main/runtime/session-launch.ts b/apps/desktop/electron/main/runtime/session-launch.tsindex 70a5c0471..a44f86cdb 100644--- a/apps/desktop/electron/main/runtime/session-launch.ts+++ b/apps/desktop/electron/main/runtime/session-launch.ts@@ -273,6 +273,25 @@ export function createSessionLaunchRuntime({return catalog;}+ /**+ * The worktree root of an isolated session, resolved by host-core from its+ * own registry; `undefined` for every other session. A missing worktree+ * fails the launch instead of silently falling back to the main checkout.+ */+ async function isolatedWorkspaceRoot(+ sessionId: string,+ session: { worktree?: unknown } | null | undefined,+ ): Promise<string | undefined> {+ if (!session?.worktree) return undefined;+ if (!runtimeState.host) throw new Error("host unavailable");+ const result = await runtimeState.host.call<{ path?: string }>("worktree.location", {+ sessionId,+ });+ const root = typeof result.path === "string" ? result.path.trim() : "";+ if (!root) throw new Error("isolated worktree location unavailable");+ return root;+ }+async function resolveAgentRuntimeLaunch(sessionId: string,session: any,@@ -402,7 +421,16 @@ export function createSessionLaunchRuntime({? session.projectPath.trim(): undefined;const localInstructionRoot = remoteWorkspace ? undefined : projectPath;- let projectInstructions = await loadInstructionChain(localInstructionRoot);+ // ADR 0328: an isolated session reads and writes files in its worktree.+ // `projectPath` stays the project identity (memory, skills, plugins, MCP,+ // subagents, group context); only files follow `workspaceRoot`. Remote+ // workspaces are never isolated.+ const workspaceRoot = remoteWorkspace+ ? undefined+ : await isolatedWorkspaceRoot(sessionId, session);+ let projectInstructions = await loadInstructionChain(+ remoteWorkspace ? undefined : (workspaceRoot ?? projectPath),+ );if (remoteWorkspace) {projectInstructions = await loadRemoteWorkspaceInstructions(remoteBoot!.workspaceFiles, remoteWorkspace, projectInstructions,@@ -422,7 +450,9 @@ export function createSessionLaunchRuntime({} | null;}>("project.group.context", { path: projectPath });const groupRoots = result.context?.roots ?? [];- const groupRootGuide = groupRoots.length > 1+ // An isolated session's root is its worktree; the group's other roots+ // are outside it and are not advertised (ADR 0328).+ const groupRootGuide = !workspaceRoot && groupRoots.length > 1? [`Primary root: ${groupRoots[0]?.path ?? projectPath}`,...groupRoots.slice(1).map((root) => `Additional root: ${root.path}`),@@ -669,6 +699,7 @@ export function createSessionLaunchRuntime({providerId: provider.id,modelId,projectPath,+ workspaceRoot,sidecarParams: {sessionId,mode,@@ -681,6 +712,7 @@ export function createSessionLaunchRuntime({attachmentsDir: join(dataDir, "attachments"),projectPath,...(remoteWorkspace ? { remoteWorkspace } : {}),+ ...(workspaceRoot ? { workspaceRoot } : {}),customSystemPrompt,projectInstructions,projectMemory,diff --git a/apps/desktop/electron/main/runtime/sidecar.ts b/apps/desktop/electron/main/runtime/sidecar.tsindex 9edc060ae..15d026c63 100644--- a/apps/desktop/electron/main/runtime/sidecar.ts+++ b/apps/desktop/electron/main/runtime/sidecar.ts@@ -364,21 +364,40 @@ export function createSidecarRuntime({const s = new AgentSidecar((text) => logger.child("agent", text));wireSidecar(s);- s.setProjectInstructionResolver(async ({ projectPath, path }) => {+ // The directory a session's file tools work in: its isolated worktree+ // (ADR 0328), resolved by host-core from its own registry, or its project.+ const sessionFileRoot = async (sessionId: string): Promise<string | null> => {+ const host = runtimeState.host;+ if (!host) return null;+ const res = await host.call<{+ session: { projectPath?: string; worktree?: unknown } | null;+ }>("session.get", { id: sessionId });+ if (res?.session?.worktree) {+ const location = await host.call<{ path?: string }>("worktree.location", { sessionId });+ return location.path?.trim() || null;+ }+ return res?.session?.projectPath?.trim() || null;+ };+ s.setProjectInstructionResolver(async ({ sessionId, 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 = projectPath?.startsWith("remote-project:")? await loadInstructionChain(undefined) : await loadInstructionChain(projectPath, path);if (!projectPath || !runtimeState.host) return instructions;+ // An isolated session registers its worktree as the root (ADR 0328); the+ // group context stays keyed by the session's project, and the group's+ // other roots are not advertised inside the worktree.+ const project = sessionProjects.get(sessionId) ?? projectPath;+ const isolated = project !== projectPath;try {const result = await runtimeState.host.call<{context?: {roots?: Array<{ path?: string }>;instructions?: string;} | null;- }>("project.group.context", { path: projectPath });+ }>("project.group.context", { path: project });const roots = result.context?.roots ?? [];- const rootGuide = roots.length > 1+ const rootGuide = !isolated && roots.length > 1? [`Primary root: ${roots[0]?.path ?? projectPath}`,...roots.slice(1).map((root) => `Additional root: ${root.path ?? ""}`),@@ -562,10 +581,7 @@ export function createSidecarRuntime({}let root: string | null = null;try {- const res = (await runtimeState.host?.call("session.get", { id: sessionId })) as- | { session: { projectPath?: string } | null }- | undefined;- root = res?.session?.projectPath?.trim() || null;+ root = await sessionFileRoot(sessionId);} catch {root = null;}@@ -649,10 +665,7 @@ export function createSidecarRuntime({registerPluginDevTools(s, {resolveWorkspace: async (sessionId) => {try {- const res = (await runtimeState.host?.call("session.get", { id: sessionId })) as- | { session: { projectPath?: string } | null }- | undefined;- return res?.session?.projectPath?.trim() || null;+ return await sessionFileRoot(sessionId);} catch {return null;}diff --git a/apps/desktop/src/components/Sidebar.tsx b/apps/desktop/src/components/Sidebar.tsxindex 412dc2d1d..94f263981 100644--- a/apps/desktop/src/components/Sidebar.tsx+++ b/apps/desktop/src/components/Sidebar.tsx@@ -72,6 +72,14 @@ import {import { BrandLogo } from "./BrandLogo";import { NotificationCenter } from "./NotificationCenter";import { ProjectEditDialog } from "./ProjectEditDialog";+import {+ WorktreeBadge,+ WorktreeDeleteLossNote,+ WorktreeDialogs,+ WorktreeProjectMenuItems,+ WorktreeSessionMenuItems,+} from "../features/worktree/WorktreeSidebarParts";+import { WorktreeBehindWatcher } from "../features/worktree/WorktreeBehind";import { useArmedDelete } from "../hooks/use-armed-delete";import { ProjectDeleteDialog } from "./ProjectDeleteDialog";import { SessionRenameDialog } from "./SessionRenameDialog";@@ -1770,6 +1778,7 @@ export function Sidebar({<span className="thread-item-source" title="Native Pi session">Pi</span>) : null}{isRemoteSession(session) && <span className="thread-item-source" title={session.remoteHostLabel}>{t("remote:remote")}</span>}+ <WorktreeBadge worktree={session.worktree} sessionId={session.id} /><span className="thread-item-title">{taskTitle(session.title)}</span>{options?.global ? (<span className="thread-item-project">@@ -2179,6 +2188,13 @@ export function Sidebar({{t("nav.createBranch")}</button>) : null}+ <WorktreeSessionMenuItems+ sessionId={session.id}+ title={taskTitle(session.title)}+ worktree={session.worktree}+ running={Boolean(runningSessions[session.id])}+ onDone={() => closeMenus(false)}+ /><buttontype="button"role="menuitem"@@ -2220,9 +2236,10 @@ export function Sidebar({onClick={() => requestDeleteSession(session)}><IconX size={14} />- {armedDelete === session.id- ? t("nav.deleteTaskConfirm", { defaultValue: "Delete?" })- : t("nav.deleteTask", { defaultValue: "Delete" })}+ {armedDelete === session.id ? t("nav.deleteTaskConfirm", { defaultValue: "Delete?" }) : t("nav.deleteTask", { defaultValue: "Delete" })}+ {armedDelete === session.id && session.worktree ? (+ <WorktreeDeleteLossNote sessionId={session.id} />+ ) : null}</button>) : null}</>@@ -2252,6 +2269,11 @@ export function Sidebar({<IconPencil size={14} />{t("project.edit", { defaultValue: "Edit project" })}</button>+ <WorktreeProjectMenuItems+ projectPath={entry.path}+ projectName={entry.name}+ onDone={() => closeMenus(false)}+ /><buttontype="button"role="menuitem"@@ -2567,6 +2589,8 @@ export function Sidebar({scheduleHide={scheduleSessionHoverCardHide}/>) : null}+ <WorktreeDialogs />+ <WorktreeBehindWatcher />{renameFor ? (<SessionRenameDialogsession={renameFor}diff --git a/apps/desktop/src/features/worktree/WorktreeBehind.tsx b/apps/desktop/src/features/worktree/WorktreeBehind.tsxnew file mode 100644index 000000000..904aaa870--- /dev/null+++ b/apps/desktop/src/features/worktree/WorktreeBehind.tsx@@ -0,0 +1,85 @@+import { useEffect } from "react";+import { useTranslation } from "react-i18next";+import type { SessionSummary } from "@pi-desktop/shared";+import { Badge } from "../../components/ui";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { useWorktreeUi } from "./worktree-ui-store";++/** A refocused window re-reads the counts at most this often. */+export const BEHIND_FOCUS_REFRESH_MS = 15_000;++/**+ * Changes whenever an isolated session appears, goes away, changes status, or+ * finishes a turn: the moments its "behind" count can change from inside the+ * app. Commits made outside the app are picked up on window focus.+ */+export function isolatedSessionsKey(sessions: readonly SessionSummary[]): string {+ return sessions+ .filter((session) => session.worktree && session.worktree.status !== "missing")+ .map((session) => `${session.id}:${session.worktree?.status}:${session.updatedAt}`)+ .sort()+ .join("|");+}++/**+ * Keeps the per-session "behind" counts current (ADR 0328). The sidebar list+ * never waits for git: the counts are read in the background and the marker+ * appears when they arrive. Renders nothing.+ */+export function WorktreeBehindWatcher() {+ const key = useAppStore((s) => isolatedSessionsKey(s.sessions));+ const revision = useWorktreeUi((s) => s.behindRevision);+ const refreshBehind = useWorktreeUi((s) => s.refreshBehind);++ useEffect(() => {+ const { setBehind } = useWorktreeUi.getState();+ if (!key) {+ setBehind({});+ return;+ }+ // A slower, older answer never overwrites a newer one.+ let current = true;+ api+ .getWorktreeBehindAll()+ .then((result) => {+ if (!current) return;+ setBehind(result.counts);+ // A conflict resolved outside the app cleared its badge on the host.+ if (result.statusesChanged) void useAppStore.getState().refreshSessions();+ })+ .catch(() => undefined);+ return () => {+ current = false;+ };+ }, [key, revision]);++ useEffect(() => {+ let last = Date.now();+ const onFocus = () => {+ if (Date.now() - last < BEHIND_FOCUS_REFRESH_MS) return;+ last = Date.now();+ refreshBehind();+ };+ window.addEventListener("focus", onFocus);+ return () => window.removeEventListener("focus", onFocus);+ }, [refreshBehind]);++ return null;+}++/** "↓2" next to the badge of a session that lacks project commits. */+export function WorktreeBehindMarker({ sessionId }: { sessionId: string }) {+ const { t } = useTranslation();+ const count = useWorktreeUi((s) => s.behind[sessionId] ?? 0);+ if (count <= 0) return null;+ return (+ <span+ className="thread-item-worktree"+ title={t("worktree.badge.behindTitle", { count })}+ data-worktree-behind={count}+ >+ <Badge tone="neutral">{t("worktree.badge.behind", { count })}</Badge>+ </span>+ );+}diff --git a/apps/desktop/src/features/worktree/WorktreeDialogFrame.tsx b/apps/desktop/src/features/worktree/WorktreeDialogFrame.tsxnew file mode 100644index 000000000..3e28e26d2--- /dev/null+++ b/apps/desktop/src/features/worktree/WorktreeDialogFrame.tsx@@ -0,0 +1,111 @@+import { useEffect, useRef, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { IconClose } from "../../components/icons";+import { TooltipButton } from "../../components/ui";+import { useBlockingOverlay } from "../../lib/blocking-overlay";+import { portalToBody } from "../../lib/portal-visibility";++/**+ * Modal frame shared by the worktree dialogs: blocking overlay, Esc to close,+ * Tab kept inside, focus restored on close. Same markup and classes as the+ * project dialogs so it inherits their styling.+ */+export function WorktreeDialogFrame({+ id,+ title,+ subtitle,+ busy = false,+ onClose,+ children,+ actions,+}: {+ id: string;+ title: string;+ subtitle?: string;+ busy?: boolean;+ onClose: () => void;+ children: ReactNode;+ actions: ReactNode;+}) {+ useBlockingOverlay();+ const { t } = useTranslation();+ const dialogRef = useRef<HTMLDivElement | null>(null);+ const busyRef = useRef(busy);+ busyRef.current = busy;++ useEffect(() => {+ const previouslyFocused = document.activeElement as HTMLElement | null;+ requestAnimationFrame(() => dialogRef.current?.focus());+ const onKeyDown = (event: KeyboardEvent) => {+ if (event.key === "Escape") {+ event.preventDefault();+ if (!busyRef.current) onClose();+ return;+ }+ if (event.key !== "Tab") return;+ const focusable = dialogRef.current?.querySelectorAll<HTMLElement>(+ "button:not([disabled]), textarea:not([disabled])",+ );+ if (!focusable?.length) return;+ const first = focusable[0];+ const last = focusable[focusable.length - 1];+ if (event.shiftKey && document.activeElement === first) {+ event.preventDefault();+ last.focus();+ } else if (!event.shiftKey && document.activeElement === last) {+ event.preventDefault();+ first.focus();+ }+ };+ window.addEventListener("keydown", onKeyDown);+ return () => {+ window.removeEventListener("keydown", onKeyDown);+ if (previouslyFocused?.isConnected) previouslyFocused.focus();+ };+ }, [onClose]);++ const dialog = (+ <div+ className="overlay project-instructions-dialog-overlay"+ role="presentation"+ onClick={(event) => {+ if (event.target === event.currentTarget && !busyRef.current) onClose();+ }}+ >+ <div+ ref={dialogRef}+ className="dialog project-instructions-dialog worktree-dialog"+ role="dialog"+ aria-modal="true"+ aria-labelledby={`${id}-title`}+ tabIndex={-1}+ data-worktree-dialog={id}+ onClick={(event) => event.stopPropagation()}+ >+ <div className="project-instructions-dialog-head">+ <div>+ <h2 id={`${id}-title`} className="project-instructions-dialog-title">+ {title}+ </h2>+ {subtitle ? (+ <div className="project-instructions-dialog-project">{subtitle}</div>+ ) : null}+ </div>+ <TooltipButton+ type="button"+ className="project-instructions-dialog-close"+ tooltip={t("common.close")}+ ariaLabel={t("common.close")}+ disabled={busy}+ onClick={onClose}+ >+ <IconClose size={16} />+ </TooltipButton>+ </div>+ <div className="worktree-dialog-body">{children}</div>+ <div className="project-instructions-dialog-actions">{actions}</div>+ </div>+ </div>+ );+ return typeof document === "undefined" ? dialog : portalToBody(dialog);+}diff --git a/apps/desktop/src/features/worktree/WorktreeMergeDialog.tsx b/apps/desktop/src/features/worktree/WorktreeMergeDialog.tsxnew file mode 100644index 000000000..0a7285a0b--- /dev/null+++ b/apps/desktop/src/features/worktree/WorktreeMergeDialog.tsx@@ -0,0 +1,179 @@+import { useCallback, useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type { WorktreeMergePreview } from "@pi-desktop/shared";+import { Button } from "../../components/ui";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { WorktreeDialogFrame } from "./WorktreeDialogFrame";+import { useWorktreeUi } from "./worktree-ui-store";+import { mergeFailureState, worktreeErrorMessage } from "./worktree-actions";++type State =+ | { phase: "loading" }+ | { phase: "ready"; preview: WorktreePreviewState }+ | { phase: "conflict"; files: string[] }+ | { phase: "failed"; message: string };++type WorktreePreviewState = WorktreeMergePreview & { notice?: string };++/**+ * "Merge into project" (PRD R4, Q10 = A): show the commits and changed files,+ * land them only after confirmation, and keep conflicts inside the session.+ */+export function WorktreeMergeDialog({+ sessionId,+ title,+ onClose,+}: {+ sessionId: string;+ title: string;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const showToast = useAppStore((s) => s.showToast);+ const refreshSessions = useAppStore((s) => s.refreshSessions);+ const [state, setState] = useState<State>({ phase: "loading" });+ const [busy, setBusy] = useState(false);+ const alive = useRef(true);+ useEffect(() => {+ // Reset on (re)mount: StrictMode runs this cleanup once before the real mount.+ alive.current = true;+ return () => {+ alive.current = false;+ };+ }, []);++ const load = useCallback(+ async (notice?: string) => {+ setState({ phase: "loading" });+ try {+ const preview = await api.previewWorktreeMerge(sessionId);+ if (alive.current) setState({ phase: "ready", preview: { ...preview, notice } });+ } catch (error) {+ if (alive.current) setState({ phase: "failed", message: worktreeErrorMessage(error, t) });+ }+ },+ [sessionId, t],+ );+ useEffect(() => void load(), [load]);++ const merge = async (preview: WorktreeMergePreview) => {+ setBusy(true);+ try {+ const outcome = await api.mergeWorktree(sessionId, preview.previewToken);+ if (!alive.current) return;+ showToast(+ outcome.result === "merged"+ ? t("worktree.merge.success", { branch: preview.ownerBranch })+ : t("worktree.merge.nothing"),+ { variant: outcome.result === "merged" ? "success" : "info" },+ );+ void refreshSessions();+ // Other sessions of the project are now behind it.+ useWorktreeUi.getState().refreshBehind();+ onClose();+ } catch (error) {+ if (!alive.current) return;+ const failure = mergeFailureState(error, t);+ if (failure.phase === "reload") {+ await load(failure.notice);+ } else {+ setState(failure);+ // A conflict changes the session's badge.+ if (failure.phase === "conflict") void refreshSessions();+ }+ } finally {+ if (alive.current) setBusy(false);+ }+ };++ const ready = state.phase === "ready" ? state.preview : null;+ const empty = ready ? ready.commits.length === 0 && ready.files.length === 0 && !ready.conflict : false;+ const uncommitted = ready ? ready.files.some((file) => file.uncommitted) : false;++ return (+ <WorktreeDialogFrame+ id="worktree-merge"+ title={t("worktree.merge.title")}+ subtitle={title}+ busy={busy}+ onClose={onClose}+ actions={+ <>+ <Button type="button" variant="ghost" disabled={busy} onClick={onClose}>+ {t("common.cancel")}+ </Button>+ {ready && !empty ? (+ <Button+ type="button"+ variant="primary"+ disabled={busy}+ data-action="worktree-merge-confirm"+ onClick={() => void merge(ready)}+ >+ {busy ? t("worktree.merge.merging") : t("worktree.merge.confirm")}+ </Button>+ ) : null}+ </>+ }+ >+ {state.phase === "loading" ? <p>{t("common.loading")}</p> : null}+ {state.phase === "failed" ? (+ <p className="project-delete-dialog-warning" role="alert">+ {state.message}+ </p>+ ) : null}+ {state.phase === "conflict" ? (+ <div role="alert">+ <p className="project-delete-dialog-warning">{t("worktree.merge.conflict")}</p>+ <ul className="worktree-file-list">+ {state.files.map((file) => (+ <li key={file}>+ <code>{file}</code>+ </li>+ ))}+ </ul>+ </div>+ ) : null}+ {ready ? (+ empty ? (+ <p>{t("worktree.merge.nothing")}</p>+ ) : (+ <>+ {ready.notice ? (+ <p className="project-delete-dialog-warning" role="status">+ {ready.notice}+ </p>+ ) : null}+ <p className="project-memory-dialog-description">+ {t("worktree.merge.description", {+ branch: ready.branch,+ ownerBranch: ready.ownerBranch,+ })}+ </p>+ <p data-worktree-commit-count={ready.commits.length}>+ {t("worktree.merge.commits", { count: ready.commits.length })}+ </p>+ <p data-worktree-file-count={ready.files.length}>+ {t("worktree.merge.files", { count: ready.files.length })}+ </p>+ <ul className="worktree-file-list">+ {ready.files.map((file) => (+ <li key={file.path} data-worktree-file={file.path}>+ <code>{file.status}</code> <code>{file.path}</code>+ {file.uncommitted ? ` · ${t("worktree.merge.uncommittedFile")}` : ""}+ </li>+ ))}+ </ul>+ {uncommitted ? (+ <p className="project-memory-dialog-hint">{t("worktree.merge.uncommittedNote")}</p>+ ) : null}+ {ready.conflict ? (+ <p className="project-memory-dialog-hint">{t("worktree.merge.resolving")}</p>+ ) : null}+ </>+ )+ ) : null}+ </WorktreeDialogFrame>+ );+}diff --git a/apps/desktop/src/features/worktree/WorktreeSetupDialogs.tsx b/apps/desktop/src/features/worktree/WorktreeSetupDialogs.tsxnew file mode 100644index 000000000..8ebdbf290--- /dev/null+++ b/apps/desktop/src/features/worktree/WorktreeSetupDialogs.tsx@@ -0,0 +1,150 @@+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import type { WorktreeSetupLog } from "@pi-desktop/shared";+import { Button, Field, Textarea } from "../../components/ui";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { WorktreeDialogFrame } from "./WorktreeDialogFrame";++/** Per-project command run in every new isolated worktree (PRD R2a). */+export function WorktreeSetupCommandDialog({+ projectPath,+ projectName,+ onClose,+}: {+ projectPath: string;+ projectName: string;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const showToast = useAppStore((s) => s.showToast);+ const [command, setCommand] = useState<string | null>(null);+ const [busy, setBusy] = useState(false);+ const alive = useRef(true);+ useEffect(() => {+ // Reset on (re)mount: StrictMode runs this cleanup once before the real mount.+ alive.current = true;+ return () => {+ alive.current = false;+ };+ }, []);++ useEffect(() => {+ api+ .getWorktreeSetupCommand(projectPath)+ .then((result) => alive.current && setCommand(result.command ?? ""))+ .catch((error: unknown) => {+ if (!alive.current) return;+ setCommand("");+ showToast(error instanceof Error ? error.message : String(error), { variant: "error" });+ });+ }, [projectPath, showToast]);++ const save = async () => {+ setBusy(true);+ try {+ await api.setWorktreeSetupCommand(projectPath, command?.trim() ? command : null);+ showToast(t("worktree.setupCommand.saved"), { variant: "success" });+ onClose();+ } catch (error) {+ showToast(error instanceof Error ? error.message : String(error), { variant: "error" });+ } finally {+ if (alive.current) setBusy(false);+ }+ };++ return (+ <WorktreeDialogFrame+ id="worktree-setup-command"+ title={t("worktree.setupCommand.title")}+ subtitle={projectName}+ busy={busy}+ onClose={onClose}+ actions={+ <>+ <Button type="button" variant="ghost" disabled={busy} onClick={onClose}>+ {t("common.cancel")}+ </Button>+ <Button+ type="button"+ variant="primary"+ disabled={busy || command === null}+ data-action="worktree-setup-command-save"+ onClick={() => void save()}+ >+ {busy ? t("common.saving") : t("common.save")}+ </Button>+ </>+ }+ >+ <p className="project-memory-dialog-description">{t("worktree.setupCommand.description")}</p>+ <Field label={t("worktree.setupCommand.label")} hint={t("worktree.setupCommand.hint")}>+ <Textarea+ rows={4}+ value={command ?? ""}+ disabled={command === null || busy}+ placeholder={t("worktree.setupCommand.placeholder")}+ onChange={(event) => setCommand(event.target.value)}+ />+ </Field>+ </WorktreeDialogFrame>+ );+}++/** Output of the setup command for an isolated session (AC3). */+export function WorktreeSetupLogDialog({+ sessionId,+ title,+ onClose,+}: {+ sessionId: string;+ title: string;+ onClose: () => void;+}) {+ const { t } = useTranslation();+ const [log, setLog] = useState<WorktreeSetupLog | null>(null);+ const [failure, setFailure] = useState<string | null>(null);++ useEffect(() => {+ let alive = true;+ api+ .getWorktreeSetupLog(sessionId)+ .then((result) => alive && setLog(result))+ .catch((error: unknown) => alive && setFailure(error instanceof Error ? error.message : String(error)));+ return () => {+ alive = false;+ };+ }, [sessionId]);++ const status = log?.setupStatus;+ return (+ <WorktreeDialogFrame+ id="worktree-setup-log"+ title={t("worktree.setupLog.title")}+ subtitle={title}+ onClose={onClose}+ actions={+ <Button type="button" variant="ghost" onClick={onClose}>+ {t("common.close")}+ </Button>+ }+ >+ {failure ? <p role="alert">{failure}</p> : null}+ {!log && !failure ? <p>{t("common.loading")}</p> : null}+ {log ? (+ <>+ <p data-worktree-setup-status={status ?? "none"}>+ {status === "running"+ ? t("worktree.setupLog.running")+ : status === "ok"+ ? t("worktree.setupLog.ok")+ : status === "failed"+ ? t("worktree.setupLog.failed")+ : t("worktree.setupLog.none")}+ </p>+ {log.log ? <pre className="worktree-setup-log">{log.log}</pre> : null}+ </>+ ) : null}+ </WorktreeDialogFrame>+ );+}diff --git a/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx b/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsxnew file mode 100644index 000000000..75c2fc3d9--- /dev/null+++ b/apps/desktop/src/features/worktree/WorktreeSidebarParts.tsx@@ -0,0 +1,286 @@+import { useEffect, useId, useState } from "react";+import { useTranslation } from "react-i18next";+import type { SessionWorktreeSummary, WorktreePendingWork } from "@pi-desktop/shared";+import {+ IconBranch,+ IconFileText,+ IconFolderOpen,+ IconPullRequest,+ IconRefresh,+ IconWrench,+} from "../../components/icons";+import { Badge } from "../../components/ui";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { WorktreeMergeDialog } from "./WorktreeMergeDialog";+import { WorktreeSetupCommandDialog, WorktreeSetupLogDialog } from "./WorktreeSetupDialogs";+import {+ createIsolatedSession,+ isolationAvailability,+ type IsolationProbeState,+ syncIsolatedSession,+ worktreeErrorMessage,+} from "./worktree-actions";+import { WorktreeBehindMarker } from "./WorktreeBehind";+import { useWorktreeUi } from "./worktree-ui-store";++/** Session-row badge for an isolated session (PRD R3). */+export function WorktreeBadge({+ worktree,+ sessionId,+}: {+ worktree?: SessionWorktreeSummary;+ /** Shows the "behind the project" marker when given. */+ sessionId?: string;+}) {+ const { t } = useTranslation();+ if (!worktree) return null;+ const [tone, label] =+ worktree.status === "conflict"+ ? (["warning", t("worktree.badge.conflict")] as const)+ : worktree.status === "missing"+ ? (["error", t("worktree.badge.missing")] as const)+ : worktree.setupStatus === "failed"+ ? (["warning", t("worktree.badge.setupFailed")] as const)+ : (["neutral", t("worktree.badge.isolated")] as const);+ return (+ <>+ <span+ className="thread-item-worktree"+ title={t("worktree.badge.title", { branch: worktree.branch })}+ data-worktree-status={worktree.status}+ >+ <Badge tone={tone}>{label}</Badge>+ </span>+ {/* A conflicted session cannot sync until it resolves the conflict. */}+ {sessionId && worktree.status !== "missing" && worktree.status !== "conflict" ? (+ <WorktreeBehindMarker sessionId={sessionId} />+ ) : null}+ </>+ );+}++/** Project-menu items: create an isolated session, edit the setup command. */+export function WorktreeProjectMenuItems({+ projectPath,+ projectName,+ onDone,+}: {+ projectPath: string;+ projectName: string;+ onDone: () => void;+}) {+ const { t } = useTranslation();+ const open = useWorktreeUi((s) => s.open);+ const reasonId = useId();+ const [probe, setProbe] = useState<IsolationProbeState>("checking");+ // Probed each time the menu opens, so the item reflects the current+ // repository state; a stale answer for another project is dropped.+ useEffect(() => {+ let current = true;+ setProbe("checking");+ api+ .probeWorktree(projectPath)+ .then((result) => current && setProbe(result))+ .catch(() => current && setProbe("unknown"));+ return () => {+ current = false;+ };+ }, [projectPath]);+ const { disabled, reason } = isolationAvailability(probe, t);+ return (+ <>+ <button+ type="button"+ role="menuitem"+ data-action="new-isolated-session"+ disabled={disabled}+ aria-busy={probe === "checking" || undefined}+ aria-describedby={reason ? reasonId : undefined}+ title={reason}+ onClick={() => {+ onDone();+ void createIsolatedSession(projectPath, t);+ }}+ >+ <IconBranch size={14} />+ {t("worktree.newIsolatedSession")}+ </button>+ {reason ? (+ <p id={reasonId} className="worktree-menu-reason" data-worktree-unavailable="">+ {reason}+ </p>+ ) : null}+ <button+ type="button"+ role="menuitem"+ data-action="worktree-setup-command"+ onClick={() => {+ onDone();+ open({ kind: "setupCommand", projectPath, projectName });+ }}+ >+ <IconWrench size={14} />+ {t("worktree.setupCommand.menu")}+ </button>+ </>+ );+}++/** Session-menu items of an isolated session; nothing for other sessions. */+export function WorktreeSessionMenuItems({+ sessionId,+ title,+ worktree,+ running,+ onDone,+}: {+ sessionId: string;+ title: string;+ worktree?: SessionWorktreeSummary;+ running: boolean;+ onDone: () => void;+}) {+ const { t } = useTranslation();+ const open = useWorktreeUi((s) => s.open);+ // A conflicted session resolves first; syncing again would only report+ // the same conflict.+ const conflicted = worktree?.status === "conflict";+ const syncable = Boolean(worktree) && worktree?.status !== "missing" && !conflicted;+ // Project commits the session lacks, counted when the menu opens; `-1`+ // when the count failed (syncing still reports the reason).+ const [behind, setBehind] = useState<number | null>(null);+ useEffect(() => {+ if (!syncable) return;+ let current = true;+ setBehind(null);+ api+ .getWorktreeBehind(sessionId)+ .then((count) => {+ if (!current) return;+ setBehind(count);+ useWorktreeUi.getState().setBehindFor(sessionId, count);+ })+ .catch(() => current && setBehind(-1));+ return () => {+ current = false;+ };+ }, [sessionId, syncable]);+ if (!worktree) return null;+ const missing = worktree.status === "missing";+ return (+ <>+ <button+ type="button"+ role="menuitem"+ data-action="worktree-merge"+ disabled={running || missing}+ onClick={() => {+ onDone();+ open({ kind: "merge", sessionId, title });+ }}+ >+ <IconPullRequest size={14} />+ {t("worktree.merge.menu")}+ </button>+ <button+ type="button"+ role="menuitem"+ data-action="worktree-sync"+ disabled={running || !syncable || behind === null || behind === 0}+ aria-busy={behind === null && syncable ? true : undefined}+ title={+ conflicted+ ? t("worktree.sync.resolveFirst")+ : behind === 0+ ? t("worktree.sync.upToDate")+ : undefined+ }+ onClick={() => {+ onDone();+ void syncIsolatedSession(sessionId, t);+ }}+ >+ <IconRefresh size={14} />+ {syncable && behind !== null && behind > 0+ ? t("worktree.sync.menuBehind", { count: behind })+ : t("worktree.sync.menu")}+ </button>+ <button+ type="button"+ role="menuitem"+ data-action="worktree-reveal"+ disabled={missing}+ onClick={() => {+ onDone();+ api.revealWorktree(sessionId).catch((error: unknown) =>+ useAppStore.getState().showToast(worktreeErrorMessage(error, t), { variant: "error" }),+ );+ }}+ >+ <IconFolderOpen size={14} />+ {t("worktree.reveal")}+ </button>+ {worktree.setupStatus && worktree.setupStatus !== "none" ? (+ <button+ type="button"+ role="menuitem"+ data-action="worktree-setup-log"+ onClick={() => {+ onDone();+ open({ kind: "setupLog", sessionId, title });+ }}+ >+ <IconFileText size={14} />+ {t("worktree.setupLog.menu")}+ </button>+ ) : null}+ </>+ );+}++/**+ * Note after the armed "Delete?" label of an isolated session: deleting removes+ * its worktree and branch, so unmerged work is named before the second click+ * (PRD R5). Renders nothing when nothing would be lost.+ */+export function WorktreeDeleteLossNote({ sessionId }: { sessionId: string }) {+ const { t } = useTranslation();+ const [pending, setPending] = useState<WorktreePendingWork | null>(null);+ useEffect(() => {+ let alive = true;+ api+ .getWorktreePendingWork(sessionId)+ .then((result) => alive && setPending(result))+ .catch(() => undefined);+ return () => {+ alive = false;+ };+ }, [sessionId]);+ if (!pending || (pending.unmergedCommits === 0 && !pending.uncommittedChanges)) return null;+ return (+ <span className="worktree-delete-loss" data-worktree-loss="true">+ {t("worktree.deleteLoss")}+ </span>+ );+}++/** Renders the open worktree dialog. Mounted once by the sidebar. */+export function WorktreeDialogs() {+ const dialog = useWorktreeUi((s) => s.dialog);+ const close = useWorktreeUi((s) => s.close);+ if (!dialog) return null;+ if (dialog.kind === "merge") {+ return <WorktreeMergeDialog sessionId={dialog.sessionId} title={dialog.title} onClose={close} />;+ }+ if (dialog.kind === "setupLog") {+ return <WorktreeSetupLogDialog sessionId={dialog.sessionId} title={dialog.title} onClose={close} />;+ }+ return (+ <WorktreeSetupCommandDialog+ projectPath={dialog.projectPath}+ projectName={dialog.projectName}+ onClose={close}+ />+ );+}diff --git a/apps/desktop/src/features/worktree/worktree-actions.ts b/apps/desktop/src/features/worktree/worktree-actions.tsnew file mode 100644index 000000000..101652235--- /dev/null+++ b/apps/desktop/src/features/worktree/worktree-actions.ts@@ -0,0 +1,148 @@+import { WorktreeErrorCodes, type WorktreeProbeResult } from "@pi-desktop/shared";+import type { TFunction } from "i18next";+import { api } from "../../lib/api";+import { useAppStore } from "../../stores/app-store";+import { useWorktreeUi } from "./worktree-ui-store";++/** Catalog keys for the `WORKTREE_*` codes a user can act on. */+const ERROR_KEYS: Record<string, string> = {+ [WorktreeErrorCodes.NOT_GIT]: "worktree.errors.notGit",+ [WorktreeErrorCodes.NO_COMMITS]: "worktree.errors.noCommits",+ [WorktreeErrorCodes.DETACHED_HEAD]: "worktree.errors.detachedHead",+ [WorktreeErrorCodes.GIT_MISSING]: "worktree.errors.gitMissing",+ [WorktreeErrorCodes.GIT_TOO_OLD]: "worktree.errors.gitTooOld",+ [WorktreeErrorCodes.BRANCH_NAMESPACE_TAKEN]: "worktree.errors.branchNamespaceTaken",+ [WorktreeErrorCodes.BUSY]: "worktree.errors.busy",+ [WorktreeErrorCodes.CHANGED_SINCE_PREVIEW]: "worktree.errors.changedSincePreview",+ [WorktreeErrorCodes.OWNER_BRANCH_CHANGED]: "worktree.errors.ownerBranchChanged",+ [WorktreeErrorCodes.PROJECT_DIRTY]: "worktree.errors.projectDirty",+ [WorktreeErrorCodes.MISSING]: "worktree.errors.missing",+ [WorktreeErrorCodes.COMMIT_FAILED]: "worktree.errors.commitFailed",+ [WorktreeErrorCodes.MOVE_UNSUPPORTED]: "worktree.errors.moveUnsupported",+ [WorktreeErrorCodes.MERGE_FAILED]: "worktree.errors.mergeFailed",+ [WorktreeErrorCodes.PATH_EXISTS]: "worktree.errors.pathExists",+ [WorktreeErrorCodes.NOT_READY]: "worktree.errors.notReady",+ [WorktreeErrorCodes.NOT_ISOLATED]: "worktree.errors.notIsolated",+ [WorktreeErrorCodes.GIT_FAILED]: "worktree.errors.gitFailed",+ [WorktreeErrorCodes.GIT_TIMEOUT]: "worktree.errors.gitTimeout",+ [WorktreeErrorCodes.REMOTE_UNSUPPORTED]: "worktree.errors.remoteUnsupported",+};++/** The `WORKTREE_*` code of an API error; `invoke` stores it as `code`. */+export function worktreeErrorCode(error: unknown): string | undefined {+ if (!error || typeof error !== "object") return undefined;+ const value = error as { code?: unknown; errorCode?: unknown };+ const code = typeof value.code === "string" ? value.code : value.errorCode;+ return typeof code === "string" ? code : undefined;+}++/** Conflicting files reported with `WORKTREE_CONFLICT`. */+export function worktreeConflictFiles(error: unknown): string[] {+ const details = (error as { details?: { files?: unknown } } | null)?.details;+ return Array.isArray(details?.files)+ ? details.files.filter((file): file is string => typeof file === "string")+ : [];+}++/** A localized sentence for a worktree error, or the host's own message. */+export function worktreeErrorMessage(error: unknown, t: TFunction): string {+ const key = ERROR_KEYS[worktreeErrorCode(error) ?? ""];+ if (key) return t(key);+ if (error instanceof Error) return error.message;+ const message = (error as { message?: unknown } | null)?.message;+ return typeof message === "string" ? message : String(error);+}++/** Result of the project-menu probe: still running, answered, or failed. */+export type IsolationProbeState = "checking" | "unknown" | WorktreeProbeResult;++/**+ * Whether "New isolated session" is offered (PRD R6, AC9). Disabled while the+ * probe runs and, with the reason, when the project cannot host a worktree.+ * A failed probe leaves it enabled; creating re-probes and reports the error.+ */+export function isolationAvailability(+ state: IsolationProbeState,+ t: TFunction,+): { disabled: boolean; reason?: string } {+ if (state === "checking") return { disabled: true };+ if (state === "unknown" || state.available) return { disabled: false };+ return {+ disabled: true,+ reason: worktreeErrorMessage({ code: state.errorCode, message: state.message }, t),+ };+}++/** What the merge dialog shows after a failed merge. */+export type MergeFailureState =+ | { phase: "conflict"; files: string[] }+ | { phase: "reload"; notice: string }+ | { phase: "failed"; message: string };++/**+ * Conflicts list their files and stay in the session; a session that changed+ * after the preview is previewed again; anything else is a plain error.+ */+export function mergeFailureState(error: unknown, t: TFunction): MergeFailureState {+ const code = worktreeErrorCode(error);+ if (code === WorktreeErrorCodes.CONFLICT) {+ return { phase: "conflict", files: worktreeConflictFiles(error) };+ }+ if (code === WorktreeErrorCodes.CHANGED_SINCE_PREVIEW) {+ return { phase: "reload", notice: t("worktree.errors.changedSincePreview") };+ }+ return { phase: "failed", message: worktreeErrorMessage(error, t) };+}++/**+ * "Sync from project": bring the project's new commits into the session's+ * worktree. A conflict stays in the session and is listed; the sidebar is+ * refreshed either way so the badge follows.+ */+export async function syncIsolatedSession(sessionId: string, t: TFunction): Promise<void> {+ const { showToast, refreshSessions } = useAppStore.getState();+ try {+ const outcome = await api.syncWorktree(sessionId);+ if (outcome.result === "synced") {+ showToast(t("worktree.sync.success", { count: outcome.commits }), { variant: "success" });+ } else {+ showToast(t("worktree.sync.upToDate"), { variant: "info" });+ }+ } catch (error) {+ const files =+ worktreeErrorCode(error) === WorktreeErrorCodes.CONFLICT ? worktreeConflictFiles(error) : [];+ showToast(+ files.length > 0+ ? t("worktree.sync.conflict", { files: files.join(", ") })+ : worktreeErrorMessage(error, t),+ { variant: "error" },+ );+ } finally {+ void refreshSessions();+ useWorktreeUi.getState().refreshBehind();+ }+}++/**+ * "New isolated session": check that the project can host a worktree, say so+ * when uncommitted project changes stay behind (PRD R2b), then create the+ * session. Failures are reported as toasts in the user's language.+ */+export async function createIsolatedSession(projectPath: string, t: TFunction): Promise<void> {+ const { newSession, showToast } = useAppStore.getState();+ try {+ const probe = await api.probeWorktree(projectPath);+ if (!probe.available) {+ showToast(worktreeErrorMessage({ code: probe.errorCode, message: probe.message }, t), {+ variant: "error",+ });+ return;+ }+ if (probe.uncommittedChanges) {+ showToast(t("worktree.uncommittedNotIncluded"), { variant: "info" });+ }+ await newSession({ projectPath, isolated: true });+ } catch (error) {+ showToast(worktreeErrorMessage(error, t), { variant: "error" });+ }+}diff --git a/apps/desktop/src/features/worktree/worktree-ui-store.ts b/apps/desktop/src/features/worktree/worktree-ui-store.tsnew file mode 100644index 000000000..7eed2d3f1--- /dev/null+++ b/apps/desktop/src/features/worktree/worktree-ui-store.ts@@ -0,0 +1,36 @@+import { create } from "zustand";++/** The one worktree dialog that is open, if any (ADR 0328). */+export type WorktreeDialog =+ | { kind: "merge"; sessionId: string; title: string }+ | { kind: "setupLog"; sessionId: string; title: string }+ | { kind: "setupCommand"; projectPath: string; projectName: string };++type WorktreeUiState = {+ dialog: WorktreeDialog | null;+ open: (dialog: WorktreeDialog) => void;+ close: () => void;+ /** Project commits each isolated session lacks, for the sidebar marker. */+ behind: Record<string, number>;+ setBehind: (counts: Record<string, number>) => void;+ setBehindFor: (sessionId: string, count: number) => void;+ /** Bumped after a merge or sync so the counts are read again. */+ behindRevision: number;+ refreshBehind: () => void;+};++/**+ * Dialog and "behind" state shared by the sidebar parts of isolated sessions.+ * Kept out of the central app store on purpose.+ */+export const useWorktreeUi = create<WorktreeUiState>((set) => ({+ dialog: null,+ open: (dialog) => set({ dialog }),+ close: () => set({ dialog: null }),+ behind: {},+ setBehind: (counts) => set({ behind: counts }),+ setBehindFor: (sessionId, count) =>+ set((state) => (state.behind[sessionId] === count ? state : { behind: { ...state.behind, [sessionId]: count } })),+ behindRevision: 0,+ refreshBehind: () => set((state) => ({ behindRevision: state.behindRevision + 1 })),+}));diff --git a/apps/desktop/src/lib/api.ts b/apps/desktop/src/lib/api.tsindex b6fa7423c..d80dbc48b 100644--- a/apps/desktop/src/lib/api.ts+++ b/apps/desktop/src/lib/api.ts@@ -88,6 +88,14 @@ import type {SessionSearchContext,SessionSearchContextRequest,SessionSummary,+ CreatedSessionWorktree,+ WorktreeMergeOutcome,+ WorktreeMergePreview,+ WorktreePendingWork,+ WorktreeSyncOutcome,+ WorktreeBehindCounts,+ WorktreeProbeResult,+ WorktreeSetupLog,SessionCollaborationSummary,TraySessionPreferences,ToolPermissionResolution,@@ -343,6 +351,12 @@ async function invoke<T>(channel: string, ...args: unknown[]): Promise<T> {return result.data;}+/** `session.create` input: summary fields plus the isolation switch. */+export type CreateSessionInput = Partial<SessionSummary> & {+ /** Run the session in its own git worktree (ADR 0328). */+ isolated?: boolean;+};+function normalizeSession(session: SessionSummary): SessionSummary {return {...safeSessionSummary(session),@@ -603,10 +617,34 @@ export const api = {...result,sessions: result.sessions.map(normalizeSession),})),- createSession: (input?: Partial<SessionSummary>) =>- invoke<{ session: SessionSummary }>(IPC.invoke.sessionCreate, input ?? {}).then(- (result) => ({ ...result, session: normalizeSession(result.session) }),- ),+ createSession: (input?: CreateSessionInput) =>+ invoke<{ session: SessionSummary; worktree?: CreatedSessionWorktree }>(+ IPC.invoke.sessionCreate,+ input ?? {},+ ).then((result) => ({ ...result, session: normalizeSession(result.session) })),+ /** Isolated sessions in git worktrees (ADR 0328). No call returns a path. */+ probeWorktree: (projectPath: string) =>+ invoke<WorktreeProbeResult>(IPC.invoke.worktreeProbe, { projectPath }),+ previewWorktreeMerge: (sessionId: string) =>+ invoke<WorktreeMergePreview>(IPC.invoke.worktreePreview, { sessionId }),+ mergeWorktree: (sessionId: string, previewToken: string) =>+ invoke<WorktreeMergeOutcome>(IPC.invoke.worktreeMerge, { sessionId, previewToken }),+ getWorktreeBehind: (sessionId: string) =>+ invoke<number>(IPC.invoke.worktreeBehind, { sessionId }),+ /** Project commits each isolated session lacks, keyed by session id. */+ getWorktreeBehindAll: () => invoke<WorktreeBehindCounts>(IPC.invoke.worktreeBehindAll),+ syncWorktree: (sessionId: string) =>+ invoke<WorktreeSyncOutcome>(IPC.invoke.worktreeSync, { sessionId }),+ getWorktreePendingWork: (sessionId: string) =>+ invoke<WorktreePendingWork>(IPC.invoke.worktreePendingWork, { sessionId }),+ getWorktreeSetupLog: (sessionId: string) =>+ invoke<WorktreeSetupLog>(IPC.invoke.worktreeSetupLog, { sessionId }),+ revealWorktree: (sessionId: string) =>+ invoke<{ ok: boolean }>(IPC.invoke.worktreeReveal, { sessionId }),+ getWorktreeSetupCommand: (projectPath: string) =>+ invoke<{ command: string | null }>(IPC.invoke.worktreeSetupCommandGet, { projectPath }),+ setWorktreeSetupCommand: (projectPath: string, command: string | null) =>+ invoke<{ ok: boolean }>(IPC.invoke.worktreeSetupCommandSet, { projectPath, command }),forkSession: (sessionId: string, title?: string, throughMessageId?: string) =>invoke<{ session: SessionDetail }>(IPC.invoke.sessionFork, {sessionId,diff --git a/apps/desktop/src/lib/session-create.ts b/apps/desktop/src/lib/session-create.tsindex bfc4687fc..3f0b442bb 100644--- a/apps/desktop/src/lib/session-create.ts+++ b/apps/desktop/src/lib/session-create.ts@@ -14,13 +14,18 @@ export const EMPTY_SESSION_WINDOW = {} as const;export function sessionIsReusableEmpty(- session: { messageCount: number },+ session: { messageCount: number; worktree?: unknown },options: {running?: boolean;liveMessageCount?: number;submitted?: boolean;+ /** The request asks for an isolated session (ADR 0328). */+ isolated?: boolean;} = {},): boolean {+ // An isolated request always gets its own worktree, and an empty isolated+ // session is never handed out for an ordinary request (ADR 0328).+ if (options.isolated === true || session.worktree) return false;if (session.messageCount > 0) return false;if (options.running === true) return false;if ((options.liveMessageCount ?? 0) > 0) return false;diff --git a/apps/desktop/src/stores/app-state.ts b/apps/desktop/src/stores/app-state.tsindex 9ad9dea03..df1bcb998 100644--- a/apps/desktop/src/stores/app-state.ts+++ b/apps/desktop/src/stores/app-state.ts@@ -208,7 +208,12 @@ export type AppState = {id: string,opts?: { record?: boolean } & NavigationOptions,) => Promise<void>;- newSession: (options?: { projectPath?: string | null; remoteProject?: RemoteProjectTarget }) => Promise<void>;+ newSession: (options?: {+ projectPath?: string | null;+ remoteProject?: RemoteProjectTarget;+ /** Create an isolated session in its own git worktree (ADR 0328). */+ isolated?: boolean;+ }) => Promise<void>;forkSession: (id: string) => Promise<void>;forkAssistantMessage: (messageId: string) => Promise<void>;configureActiveSession: (config: {diff --git a/apps/desktop/src/stores/runtime/session-coordination.ts b/apps/desktop/src/stores/runtime/session-coordination.tsindex e71947a39..195a7e0e8 100644--- a/apps/desktop/src/stores/runtime/session-coordination.ts+++ b/apps/desktop/src/stores/runtime/session-coordination.ts@@ -37,6 +37,8 @@ export type PersistSessionOptions = {intent?: number;projectPath?: string | null;draftConfiguration?: DraftSessionConfiguration | null;+ /** Run the new session in its own git worktree (ADR 0328). */+ isolated?: boolean;};export type SessionCoordination = {@@ -320,6 +322,7 @@ export function createSessionCoordination({providerId: inherited.providerId,modelId: inherited.modelId,projectPath: projectPath ?? undefined,+ ...(options.isolated ? { isolated: true } : {}),});} catch (error) {if (previousSessionId && runtime.navigationIntentIsCurrent(active)) {diff --git a/apps/desktop/src/stores/slices/session-slice.ts b/apps/desktop/src/stores/slices/session-slice.tsindex 5a3a328c5..e1c41d699 100644--- a/apps/desktop/src/stores/slices/session-slice.ts+++ b/apps/desktop/src/stores/slices/session-slice.ts@@ -647,7 +647,8 @@ export function createSessionSlice({options && "projectPath" in options? options.projectPath ?? null: get().workspace?.path ?? null;- const scopeKey = runtime.newSessionScopeKey(requestedProjectPath);+ const isolated = options?.isolated === true;+ const scopeKey = `${runtime.newSessionScopeKey(requestedProjectPath)}${isolated ? "\u0000isolated" : ""}`;const pending = runtime.pendingNewSessionRequests.get(scopeKey);if (pending) {await pending;@@ -682,6 +683,7 @@ export function createSessionSlice({if (latest &&sessionIsReusableEmpty(latest, {+ isolated,running: get().runningSessions[latest.id] === true,liveMessageCount: runtime.liveMessageCountForSession(latest.id, get()),submitted: runtime.submittedComposerDrafts.has(latest.id),@@ -696,6 +698,7 @@ export function createSessionSlice({intent,projectPath: requestedProjectPath,draftConfiguration: null,+ ...(isolated ? { isolated: true } : {}),});})();runtime.pendingNewSessionRequests.set(scopeKey, request);diff --git a/apps/desktop/src/styles/globals.css b/apps/desktop/src/styles/globals.cssindex 19e24e98f..b37ad23b5 100644--- a/apps/desktop/src/styles/globals.css+++ b/apps/desktop/src/styles/globals.css@@ -27,6 +27,7 @@@import "./projects.css";@import "./project-create-dialog.css";@import "./sessions.css";+@import "./worktree.css";@import "./work-panel.css";@import "./providers.css";@import "./model-config.css";diff --git a/apps/desktop/src/styles/worktree.css b/apps/desktop/src/styles/worktree.cssnew file mode 100644index 000000000..358d15105--- /dev/null+++ b/apps/desktop/src/styles/worktree.css@@ -0,0 +1,58 @@+/* Isolated sessions in git worktrees (ADR 0328). */++.thread-item-worktree {+ display: inline-flex;+ flex-shrink: 0;+ margin-inline-end: 4px;+}++.worktree-dialog-body {+ display: flex;+ flex-direction: column;+ gap: 8px;+ overflow-wrap: anywhere;+}++.worktree-dialog-body p {+ margin: 0;+}++.worktree-file-list {+ max-height: 220px;+ margin: 0;+ padding: 8px 12px;+ overflow: auto;+ list-style: none;+ border: 1px solid var(--ds-border-default);+ border-radius: var(--radius-xs);+ background: var(--ds-bg-inset);+ font-size: var(--text-sm);+}++.worktree-setup-log {+ max-height: 320px;+ margin: 0;+ padding: 8px 12px;+ overflow: auto;+ white-space: pre-wrap;+ border: 1px solid var(--ds-border-default);+ border-radius: var(--radius-xs);+ background: var(--ds-bg-inset);+ font-size: var(--text-sm);+}++/* Why "New isolated session" is unavailable, under the disabled item. */+.worktree-menu-reason {+ max-width: 260px;+ margin: -2px 0 4px;+ padding: 0 8px 0 30px;+ color: var(--ds-text-muted);+ font-size: var(--text-sm);+ white-space: normal;+ overflow-wrap: anywhere;+}++.worktree-delete-loss {+ margin-inline-start: 6px;+ color: var(--ds-error);+}diff --git a/apps/desktop/test/browser-preview-tool.test.mjs b/apps/desktop/test/browser-preview-tool.test.mjsindex 18584b58f..9c7a68f62 100644--- a/apps/desktop/test/browser-preview-tool.test.mjs+++ b/apps/desktop/test/browser-preview-tool.test.mjs@@ -53,9 +53,18 @@ test("main serves BrowserPreview from its originating session workspace", () =>mainSource.indexOf("sidecar = s;"),);assert.match(handler, /async \(\{ args, sessionId \}\)/);- assert.match(handler, /host\?\.call\("session\.get", \{ id: sessionId \}\)/);- assert.match(handler, /res\?\.session\?\.projectPath/);+ assert.match(handler, /root = await sessionFileRoot\(sessionId\)/);assert.doesNotMatch(handler, /workspace\.get/);+ // The root comes from the durable session: its project, or the worktree of an+ // isolated session resolved by host-core (ADR 0328).+ const resolver = mainSource.slice(+ mainSource.indexOf("const sessionFileRoot = async"),+ mainSource.indexOf('s.setLocalTool("BrowserPreview"'),+ );+ assert.match(resolver, /"session\.get", \{ id: sessionId \}/);+ assert.match(resolver, /res\?\.session\?\.projectPath/);+ assert.match(resolver, /"worktree\.location", \{ sessionId \}/);+ assert.doesNotMatch(resolver, /workspace\.get/);assert.match(handler, /browserHost\.previewWorkspaceFile\(sessionId, raw, root\)/);assert.ok(handler.indexOf("resolveLocalFile(raw, root)") <diff --git a/apps/desktop/test/isolated-session-launch.test.mjs b/apps/desktop/test/isolated-session-launch.test.mjsnew file mode 100644index 000000000..b113acc7f--- /dev/null+++ b/apps/desktop/test/isolated-session-launch.test.mjs@@ -0,0 +1,136 @@+import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import test from "node:test";+import { pathToFileURL } from "node:url";+import { repositoryRoot } from "../../../scripts/e2e/boot.mjs";++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");++// ADR 0328: an isolated session reads files (AGENTS.md) from its worktree while+// project-keyed configuration (group instructions, memory) stays on the project.+test("an isolated session launches in its worktree with its project's configuration", async () => {+ const temp = await mkdtemp(join(root, "apps/desktop/.isolated-launch-test-"));+ const priorHome = process.env.HOME;+ process.env.HOME = temp;+ try {+ const project = join(temp, "project");+ const worktree = join(temp, "worktrees", "project-1", "s1");+ await mkdir(project, { recursive: true });+ await mkdir(worktree, { recursive: true });+ await writeFile(join(project, "AGENTS.md"), "MAIN CHECKOUT RULES\n");+ await writeFile(join(worktree, "AGENTS.md"), "SESSION BRANCH RULES\n");++ const bundle = join(temp, "session-launch.mjs");+ await build({+ entryPoints: [join(root, "apps/desktop/electron/main/runtime/session-launch.ts")],+ outfile: bundle,+ bundle: true,+ platform: "node",+ format: "esm",+ packages: "external",+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ const { createSessionLaunchRuntime } = await import(pathToFileURL(bundle).href);++ const provider = {+ id: "fixture-provider",+ name: "Fixture provider",+ authKind: "none",+ apiStyle: "openai-completions",+ baseUrl: "http://127.0.0.1:11434/v1",+ enabled: true,+ defaultModelId: "fixture-model",+ models: [],+ };+ const groupContextPaths = [];+ let locationAvailable = true;+ const host = {+ isAvailable: () => true,+ async call(method, input) {+ if (method === "commandShells.list") {+ const shell = { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true };+ return { configuredId: "bash", effective: shell, fallback: false, choices: [shell] };+ }+ if (method === "providers.list") return { providers: [provider] };+ if (method === "providers.getSecret") return { value: "" };+ if (method === "skills.disabledBuiltins") return { disabled: [] };+ if (method === "skills.active") return { skills: [] };+ if (method === "mcp.active") return { servers: [] };+ if (method === "agents.active") return { subagents: [] };+ if (method === "agents.disabledBuiltins") return { disabled: [] };+ if (method === "worktree.location") {+ assert.deepEqual(input, { sessionId: "session-fixture" });+ if (!locationAvailable) throw new Error("the isolated worktree folder no longer exists");+ return { path: worktree };+ }+ if (method === "project.group.context") {+ groupContextPaths.push(input.path);+ return {+ context: {+ roots: [{ path: project }, { path: join(temp, "other-root") }],+ instructions: "GROUP NOTES",+ memory: { content: "PROJECT MEMORY" },+ },+ };+ }+ throw new Error("Unexpected fixture Host method: " + method);+ },+ };+ const launchRuntime = createSessionLaunchRuntime({+ runtimeState: { host, sidecar: { setVendorAuthBindings() {} }, agentHostBridge: null },+ logger: { app() {} },+ userMcp: { setRecords() {}, async toolsForProject() { return []; } },+ plugins: { getTools: () => [], getSkills: () => [], listLoaded: () => [], getAgentExtensions: () => [] },+ sessionProjects: new Map(),+ dataDir: temp,+ vendorOAuth: { async bindingFor() { return undefined; } },+ modelsDevCatalog: { async ensureLoaded() {}, configureAccount() {}, findModel() { return undefined; } },+ getWorkspacePath: () => null,+ pluginActiveInProject: () => true,+ bindingForModel: () => undefined,+ effectiveSubagentModelConfig: () => ({ modelConfig: undefined, capabilities: {} }),+ normalizeThinkingLevel: () => "off",+ });+ const settings = { defaultProviderId: provider.id, defaultModelId: provider.defaultModelId };+ const launch = (session) =>+ launchRuntime.resolveAgentRuntimeLaunch(+ "session-fixture",+ { providerId: provider.id, modelId: provider.defaultModelId, projectPath: project, ...session },+ settings,+ );+ const text = (instructions) => JSON.stringify(instructions?.entries ?? []);++ const isolated = await launch({ worktree: { branch: "pi-desktop/s1", status: "active" } });+ assert.equal(isolated.projectPath, project);+ assert.equal(isolated.workspaceRoot, worktree);+ assert.equal(isolated.sidecarParams.projectPath, project);+ assert.equal(isolated.sidecarParams.workspaceRoot, worktree);+ const isolatedText = text(isolated.sidecarParams.projectInstructions);+ assert.match(isolatedText, /SESSION BRANCH RULES/);+ assert.doesNotMatch(isolatedText, /MAIN CHECKOUT RULES/);+ assert.match(isolatedText, /GROUP NOTES/);+ assert.doesNotMatch(isolatedText, /Additional root/);+ assert.equal(isolated.sidecarParams.projectMemory, "PROJECT MEMORY");+ assert.deepEqual(groupContextPaths, [project]);++ const ordinary = await launch({});+ assert.equal(ordinary.workspaceRoot, undefined);+ assert.equal("workspaceRoot" in ordinary.sidecarParams, false);+ const ordinaryText = text(ordinary.sidecarParams.projectInstructions);+ assert.match(ordinaryText, /MAIN CHECKOUT RULES/);+ assert.match(ordinaryText, /Additional root/);++ locationAvailable = false;+ await assert.rejects(+ launch({ worktree: { branch: "pi-desktop/s1", status: "missing" } }),+ /no longer exists/,+ );+ } finally {+ if (priorHome === undefined) delete process.env.HOME;+ else process.env.HOME = priorHome;+ await rm(temp, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/test/session-create.test.mjs b/apps/desktop/test/session-create.test.mjsindex a3a737c02..4dcc4b70f 100644--- a/apps/desktop/test/session-create.test.mjs+++ b/apps/desktop/test/session-create.test.mjs@@ -28,6 +28,15 @@ test("an empty latest session is reusable only when the renderer agrees", () =>);});+test("isolated sessions are never reused for a new task (ADR 0328)", () => {+ const empty = { messageCount: 0 };+ const emptyIsolated = { messageCount: 0, worktree: { branch: "pi-desktop/a", status: "active" } };+ assert.equal(sessionIsReusableEmpty(emptyIsolated), false, "ordinary + must not pick an isolated session");+ assert.equal(sessionIsReusableEmpty(emptyIsolated, { isolated: true }), false);+ assert.equal(sessionIsReusableEmpty(empty, { isolated: true }), false, "isolation always creates a worktree");+ assert.equal(sessionIsReusableEmpty(empty, { isolated: false }), true);+});+test("empty sessions have a whole, already-known transcript window", () => {assert.deepEqual(EMPTY_SESSION_WINDOW, {messageStart: 0,diff --git a/apps/desktop/test/worktree-ipc.test.mjs b/apps/desktop/test/worktree-ipc.test.mjsnew file mode 100644index 000000000..d20778067--- /dev/null+++ b/apps/desktop/test/worktree-ipc.test.mjs@@ -0,0 +1,119 @@+import assert from "node:assert/strict";+import test from "node:test";+import { IPC } from "@pi-desktop/shared";+import { registerWorktreeIpc } from "../electron/main/ipc/worktree-ipc.ts";++function setup(responses = {}) {+ const handlers = new Map();+ const calls = [];+ const opened = [];+ const host = {+ async call(method, params) {+ calls.push({ method, params });+ const response = responses[method];+ if (response instanceof Error) throw response;+ return typeof response === "function" ? response(params) : response ?? {};+ },+ };+ registerWorktreeIpc({+ registrar: {+ handle: (channel, handler) => handlers.set(channel, handler),+ },+ getHost: () => host,+ logger: { app: () => {} },+ openPath: async (path) => {+ opened.push(path);+ return "";+ },+ stripWinLongPrefix: (path) => path,+ });+ const invoke = (channel, input) => handlers.get(channel)(input);+ return { invoke, calls, opened };+}++test("reveal opens the host-resolved folder and never returns its path", async () => {+ const { invoke, calls, opened } = setup({+ "worktree.location": { path: "/home/u/.pi-desktop/worktrees/app-1/s1" },+ });+ const result = await invoke(IPC.invoke.worktreeReveal, { sessionId: "s1" });+ assert.deepEqual(result, { ok: true });+ assert.deepEqual(opened, ["/home/u/.pi-desktop/worktrees/app-1/s1"]);+ assert.deepEqual(calls, [{ method: "worktree.location", params: { sessionId: "s1" } }]);+});++test("preview, merge, and pending work pass the session through and unwrap results", async () => {+ const preview = { previewToken: "t1", commits: [], files: [], conflict: false };+ const { invoke, calls } = setup({+ "worktree.preview": { preview },+ "worktree.merge": { outcome: { result: "merged", commits: 1, files: 2 } },+ "worktree.pendingWork": { pending: { unmergedCommits: 3, uncommittedChanges: true } },+ });+ assert.deepEqual(await invoke(IPC.invoke.worktreePreview, { sessionId: " s1 " }), preview);+ assert.deepEqual(+ await invoke(IPC.invoke.worktreeMerge, { sessionId: "s1", previewToken: "t1" }),+ { result: "merged", commits: 1, files: 2 },+ );+ assert.deepEqual(await invoke(IPC.invoke.worktreePendingWork, { sessionId: "s1" }), {+ unmergedCommits: 3,+ uncommittedChanges: true,+ });+ assert.deepEqual(calls.map((call) => call.params), [+ { sessionId: "s1" },+ { sessionId: "s1", previewToken: "t1" },+ { sessionId: "s1" },+ ]);+});++test("host errors such as a merge conflict reach the caller unchanged", async () => {+ const conflict = Object.assign(new Error("merge conflict in 1 file(s)"), {+ data: { errorCode: "WORKTREE_CONFLICT", files: ["f.txt"] },+ });+ const { invoke } = setup({ "worktree.merge": conflict });+ await assert.rejects(+ invoke(IPC.invoke.worktreeMerge, { sessionId: "s1", previewToken: "t1" }),+ (error) => error.data?.errorCode === "WORKTREE_CONFLICT" && error.data.files[0] === "f.txt",+ );+});++test("missing identifiers and non-string setup commands are rejected before the host", async () => {+ const { invoke, calls } = setup();+ await assert.rejects(invoke(IPC.invoke.worktreePreview, {}), { errorCode: "INVALID_ARGUMENT" });+ await assert.rejects(invoke(IPC.invoke.worktreeMerge, { sessionId: "s1" }), {+ errorCode: "INVALID_ARGUMENT",+ });+ await assert.rejects(+ invoke(IPC.invoke.worktreeSetupCommandSet, { projectPath: "/p", command: 42 }),+ { errorCode: "INVALID_ARGUMENT" },+ );+ assert.equal(calls.length, 0);++ await invoke(IPC.invoke.worktreeSetupCommandSet, { projectPath: "/p", command: "pnpm i" });+ await invoke(IPC.invoke.worktreeSetupCommandSet, { projectPath: "/p" });+ assert.deepEqual(calls.map((call) => call.params), [+ { projectPath: "/p", command: "pnpm i" },+ { projectPath: "/p", command: null },+ ]);+});++test("sync from project forwards the session and unwraps the count and outcome", async () => {+ const { invoke, calls } = setup({+ "worktree.behind": { commits: 2 },+ "worktree.sync": { outcome: { result: "synced", commits: 2 } },+ });+ assert.equal(await invoke(IPC.invoke.worktreeBehind, { sessionId: "s1" }), 2);+ assert.deepEqual(await invoke(IPC.invoke.worktreeSync, { sessionId: " s1 " }), {+ result: "synced",+ commits: 2,+ });+ assert.deepEqual(calls, [+ { method: "worktree.behind", params: { sessionId: "s1" } },+ { method: "worktree.sync", params: { sessionId: "s1" } },+ ]);+});++test("behind counts for the sidebar pass through unchanged", async () => {+ const behind = { counts: { s1: 2, s2: 0 }, statusesChanged: false };+ const { invoke, calls } = setup({ "worktree.behindAll": behind });+ assert.deepEqual(await invoke(IPC.invoke.worktreeBehindAll), behind);+ assert.deepEqual(calls, [{ method: "worktree.behindAll", params: {} }]);+});diff --git a/apps/desktop/test/worktree-menu-user-path.test.mjs b/apps/desktop/test/worktree-menu-user-path.test.mjsnew file mode 100644index 000000000..d60c97ac4--- /dev/null+++ b/apps/desktop/test/worktree-menu-user-path.test.mjs@@ -0,0 +1,217 @@+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import test from "node:test";+import { repositoryRoot, resolveElectronBinary } from "../../../scripts/e2e/boot.mjs";++// PRD R6 / AC9: the project menu greys out "New isolated session" with the+// reason for a project that cannot host a worktree, and creates the session+// for one that can. Rendered in a real DOM so the probe effect runs.++const root = repositoryRoot();+const { build } = createRequire(join(root, "packages/agent-runtime/package.json"))("esbuild");+const fixture = String.raw`+import React from "react";+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import i18n from "i18next";+import { initReactI18next } from "react-i18next";+import { catalogs, flattenCatalog } from "@pi-desktop/i18n";+import { IPC } from "@pi-desktop/shared";+import { WorktreeBadge, WorktreeProjectMenuItems, WorktreeSessionMenuItems } from "../../apps/desktop/src/features/worktree/WorktreeSidebarParts";+import { WorktreeBehindWatcher } from "../../apps/desktop/src/features/worktree/WorktreeBehind";+import { WorktreeMergeDialog } from "../../apps/desktop/src/features/worktree/WorktreeMergeDialog";+import { useAppStore } from "../../apps/desktop/src/stores/app-store";++await i18n.use(initReactI18next).init({ lng: "en", keySeparator: false,+ resources: { en: { translation: flattenCatalog(catalogs.en) } },+ interpolation: { escapeValue: false } });+const probes = {+ "/plain": { available: false, errorCode: "WORKTREE_NOT_GIT", message: "raw" },+ "/odd": { available: false, errorCode: "WORKTREE_INTERNAL", message: "git exploded" },+ "/repo": { available: true, uncommittedChanges: false },+};+const pending = [];+const behind = { stale: 2, current: 0 };+const synced = [];+let behindAllCalls = 0;+window.piDesktop = { platform: "linux", on() { return () => {}; },+ invoke(channel, payload) {+ if (channel === IPC.invoke.worktreeBehind) return Promise.resolve({ ok: true, data: behind[payload.sessionId] });+ if (channel === IPC.invoke.worktreeBehindAll) {+ behindAllCalls += 1;+ return Promise.resolve({ ok: true, data: { counts: { ...behind }, statusesChanged: false } });+ }+ if (channel === IPC.invoke.worktreeSync) {+ synced.push(payload.sessionId);+ const commits = behind[payload.sessionId];+ behind[payload.sessionId] = 0;+ return Promise.resolve({ ok: true, data: { result: "synced", commits } });+ }+ if (channel === IPC.invoke.worktreePreview) {+ return Promise.resolve({ ok: true, data: { branch: "pi-desktop/s1", ownerBranch: "main",+ commits: [{ sha: "abc", subject: "edit f" }], files: [{ status: "M", path: "f.txt", uncommitted: false }],+ conflict: false, previewToken: "t" } });+ }+ if (channel !== IPC.invoke.worktreeProbe) throw new Error("Unexpected IPC " + channel);+ return new Promise((resolve) => pending.push(() => resolve({ ok: true, data: probes[payload.projectPath] })));+ } };+const created = [];+const toasts = [];+useAppStore.setState({+ newSession: async (options) => { created.push(options); },+ showToast: (message) => { toasts.push(message); },+ refreshSessions: async () => {},+});+const frame = () => new Promise(requestAnimationFrame);+async function settle() { await frame(); await frame(); }+function check(condition, message) { if (!condition) throw new Error(message); }+const item = () => document.querySelector('[data-action="new-isolated-session"]');+const reason = () => document.querySelector("[data-worktree-unavailable]");+const rootNode = createRoot(document.getElementById("root"));+function show(projectPath) {+ flushSync(() => rootNode.render(React.createElement(WorktreeProjectMenuItems,+ { projectPath, projectName: "P", onDone() {} })));+}+async function answer() { while (pending.length) pending.shift()(); await settle(); }+window.menuProbe = async () => {+ show("/plain");+ check(item().disabled, "item must be disabled while the probe runs");+ check(!reason(), "no reason before the probe answers");+ await answer();+ check(item().disabled, "a non-git project must keep the item disabled");+ check(reason()?.textContent === i18n.t("worktree.errors.notGit"), "missing localized reason");+ check(item().getAttribute("aria-describedby") === reason().id, "reason not linked to the item");+ item().click();+ check(created.length === 0, "a disabled item created a session");++ show("/odd");+ await answer();+ check(reason()?.textContent === "git exploded", "unknown codes must show the host message");++ show("/repo");+ check(item().disabled, "switching project re-probes");+ await answer();+ check(!item().disabled && !reason(), "a git project must enable the item");+ item().click();+ await answer();+ await settle();+ check(JSON.stringify(created) === JSON.stringify([{ projectPath: "/repo", isolated: true }]), "session not created: " + JSON.stringify(created));+ check(toasts.length === 0, "unexpected toast " + JSON.stringify(toasts));+ flushSync(() => rootNode.unmount());++ // The app renders under StrictMode, which mounts every effect twice; the+ // merge preview must still leave the loading state.+ const dialogRoot = createRoot(document.getElementById("root"));+ flushSync(() => dialogRoot.render(React.createElement(React.StrictMode, null,+ React.createElement(WorktreeMergeDialog, { sessionId: "s1", title: "Task", onClose() {} }))));+ await settle();+ const confirm = document.querySelector('[data-action="worktree-merge-confirm"]');+ check(confirm && !confirm.disabled, "merge preview stuck loading under StrictMode");+ check(document.body.textContent.includes("f.txt"), "preview files not shown");+ flushSync(() => dialogRoot.unmount());++ // The sidebar marker: the watcher reads every session's count in the+ // background, the badge shows it, and a sync clears it.+ const at = "2020-01-01T00:00:00Z";+ const worktreeOf = (id) => ({ branch: "pi-desktop/" + id, status: "active", setupStatus: "none" });+ useAppStore.setState({ sessions: [+ { id: "stale", title: "Stale", createdAt: at, updatedAt: at, worktree: worktreeOf("stale") },+ { id: "current", title: "Current", createdAt: at, updatedAt: at, worktree: worktreeOf("current") },+ ] });+ const sidebarRoot = document.createElement("div");+ document.body.appendChild(sidebarRoot);+ const rows = createRoot(sidebarRoot);+ flushSync(() => rows.render(React.createElement(React.StrictMode, null,+ React.createElement(WorktreeBehindWatcher),+ React.createElement("div", { "data-row": "stale" }, React.createElement(WorktreeBadge, { sessionId: "stale", worktree: worktreeOf("stale") })),+ React.createElement("div", { "data-row": "current" }, React.createElement(WorktreeBadge, { sessionId: "current", worktree: worktreeOf("current") })))));+ await settle();+ const marker = (id) => sidebarRoot.querySelector('[data-row="' + id + '"] [data-worktree-behind]');+ check(marker("stale")?.textContent === i18n.t("worktree.badge.behind", { count: 2 }), "stale session has no behind marker");+ check(!marker("current"), "an up-to-date session must have no marker");++ // "Sync from project" shows how far behind the session is and syncs it.+ const menuRoot = createRoot(document.getElementById("root"));+ const sessionMenu = (sessionId) => flushSync(() => menuRoot.render(React.createElement(React.StrictMode, null,+ React.createElement(WorktreeSessionMenuItems, { sessionId, title: "Task", running: false, onDone() {},+ worktree: { branch: "pi-desktop/" + sessionId, status: "active", setupStatus: "none" } }))));+ const syncItem = () => document.querySelector('[data-action="worktree-sync"]');+ sessionMenu("current");+ await settle();+ check(syncItem().disabled, "an up-to-date session must not offer a sync");+ sessionMenu("stale");+ await settle();+ check(!syncItem().disabled, "a session behind the project must offer a sync");+ check(syncItem().textContent.includes(i18n.t("worktree.sync.menuBehind", { count: 2 })), "missing behind count");+ toasts.length = 0;+ syncItem().click();+ await settle();+ check(JSON.stringify(synced) === JSON.stringify(["stale"]), "sync not requested: " + JSON.stringify(synced));+ check(toasts[0] === i18n.t("worktree.sync.success", { count: 2 }), "missing sync toast: " + JSON.stringify(toasts));+ await settle();+ check(behindAllCalls >= 2, "a sync must re-read the counts");+ check(!marker("stale"), "the marker must clear after the sync");+ flushSync(() => menuRoot.unmount());+ flushSync(() => rows.unmount());+ return { passed: true };+};+`;++test("isolated-session sidebar: unavailable reason, merge preview, behind marker, and sync from project", {+ skip: process.platform === "linux" && !process.env.DISPLAY ? "Electron requires a display" : false,+}, async () => {+ const temp = await mkdtemp(join(root, "apps/desktop/.worktree-menu-ui-"));+ try {+ await build({+ stdin: { contents: fixture, resolveDir: join(root, "scripts/e2e"), loader: "tsx" },+ outfile: join(temp, "renderer.js"), bundle: true, platform: "browser", format: "esm", jsx: "automatic",+ // Development React, like `pnpm dev`: StrictMode double-mounts effects.+ define: { "process.env.NODE_ENV": '"development"' },+ alias: {+ "@pi-desktop/i18n": join(root, "packages/i18n/src"),+ "@pi-desktop/shared": join(root, "packages/shared/src"),+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ i18next: join(root, "apps/desktop/node_modules/i18next"),+ "react-i18next": join(root, "apps/desktop/node_modules/react-i18next"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await writeFile(join(temp, "index.html"), '<!doctype html><meta charset="utf-8"><meta http-equiv="Content-Security-Policy" content="default-src \'self\'; style-src \'self\' \'unsafe-inline\'"><div id="root"></div><script type="module" src="renderer.js"></script>');+ await writeFile(join(temp, "main.cjs"), `+const { app, BrowserWindow } = require("electron");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+app.whenReady().then(async () => {+ const win = new BrowserWindow({ show: false, width: 800, height: 600,+ webPreferences: { sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false } });+ try {+ await win.loadFile(path.join(__dirname, "index.html"));+ console.log("MENU_PROBE " + JSON.stringify(await win.webContents.executeJavaScript("window.menuProbe()")));+ app.exit(0);+ } catch (error) { console.error(error?.stack ?? error); app.exit(1); }+});`);+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(resolveElectronBinary(root).electronBinary, [join(temp, "main.cjs")], { env, stdio: ["ignore", "pipe", "pipe"] });+ let output = "";+ for (const stream of [child.stdout, child.stderr]) {+ stream.setEncoding("utf8");+ stream.on("data", (chunk) => { output += chunk; });+ }+ const timer = setTimeout(() => child.kill("SIGKILL"), 45_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => { child.once("error", reject); child.once("close", resolve); });+ } finally { clearTimeout(timer); }+ assert.equal(code, 0, output.slice(-6000));+ const line = output.split(/\r?\n/).find((entry) => entry.startsWith("MENU_PROBE "));+ assert.ok(line, output.slice(-6000));+ assert.deepEqual(JSON.parse(line.slice("MENU_PROBE ".length)), { passed: true });+ } finally {+ await rm(temp, { recursive: true, force: true });+ }+});diff --git a/apps/desktop/test/worktree-ui.test.mjs b/apps/desktop/test/worktree-ui.test.mjsnew file mode 100644index 000000000..5a329dbb8--- /dev/null+++ b/apps/desktop/test/worktree-ui.test.mjs@@ -0,0 +1,377 @@+import assert from "node:assert/strict";+import test, { after, before } from "node:test";+import { fileURLToPath } from "node:url";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import i18n from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { IPC } from "@pi-desktop/shared";+import { createServer } from "vite";++// ADR 0328 renderer surface: badge, menus, create flow, merge failures, and+// the rule that an ordinary "+" never reuses an empty isolated session.++let server;+let modules;+const en = catalogs.en.worktree;+const previousDocument = globalThis.document;+const previousWindow = globalThis.window;++before(async () => {+ server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ esbuild: { jsx: "automatic" },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ modules = {+ sidebar: await server.ssrLoadModule("/src/components/Sidebar.tsx"),+ parts: await server.ssrLoadModule("/src/features/worktree/WorktreeSidebarParts.tsx"),+ actions: await server.ssrLoadModule("/src/features/worktree/worktree-actions.ts"),+ store: await server.ssrLoadModule("/src/stores/app-store.ts"),+ behind: await server.ssrLoadModule("/src/features/worktree/WorktreeBehind.tsx"),+ worktreeUi: await server.ssrLoadModule("/src/features/worktree/worktree-ui-store.ts"),+ shared: await import("@pi-desktop/shared"),+ };+ // Same interpolation setting as the app (main.tsx): React escapes output.+ await i18n.init({+ lng: "en",+ resources: { en: { translation: catalogs.en } },+ interpolation: { escapeValue: false },+ });+});++after(async () => {+ globalThis.document = previousDocument;+ globalThis.window = previousWindow;+ await server?.close();+});++const wrap = (element) => renderToStaticMarkup(createElement(I18nextProvider, { i18n }, element));++/** Route renderer `invoke` calls to `handlers[channel]`. */+function stubBridge(handlers) {+ const calls = [];+ globalThis.window = {+ piDesktop: {+ async invoke(channel, payload) {+ calls.push({ channel, payload });+ const handler = handlers[channel];+ if (!handler) return { ok: false, error: { code: "INTERNAL", message: `no stub for ${channel}` } };+ try {+ return { ok: true, data: await handler(payload) };+ } catch (error) {+ return { ok: false, error: { code: error.code, message: error.message, details: error.details } };+ }+ },+ },+ };+ return calls;+}++test("the sidebar badges isolated sessions and leaves ordinary ones unchanged", () => {+ const { Sidebar } = modules.sidebar;+ const { useAppStore } = modules.store;+ const at = "2020-01-01T00:00:00Z";+ const session = (id, worktree) => ({ id, title: id, projectPath: "/open", createdAt: at, updatedAt: at, worktree });+ Object.assign(useAppStore.getInitialState(), {+ sessions: [+ session("plain"),+ session("isolated", { branch: "pi-desktop/a", status: "active", setupStatus: "none" }),+ session("conflicted", { branch: "pi-desktop/b", status: "conflict" }),+ session("vanished", { branch: "pi-desktop/c", status: "missing" }),+ session("broken-setup", { branch: "pi-desktop/d", status: "active", setupStatus: "failed" }),+ ],+ sessionMeta: {},+ projectMeta: {},+ openProjectPaths: ["/open"],+ openProjects: [],+ workspace: null,+ activeProjectPath: null,+ activeSessionId: null,+ selectingSessionId: null,+ page: "chat",+ projectCollapsed: {},+ sessionView: { sort: "recent", archived: false },+ });+ globalThis.document = { documentElement: { dataset: { theme: "light" } } };+ const html = wrap(+ createElement(Sidebar, {+ collapsed: false,+ onToggle() {},+ sidebarWidth: 275,+ onWidthChange() {},+ onWidthCommit() {},+ }),+ );+ const row = (id) => {+ const start = html.indexOf(`data-sidebar-session-row="${id}"`);+ const next = html.indexOf("data-sidebar-session-row=", start + 1);+ return html.slice(start, next === -1 ? undefined : next);+ };+ assert.doesNotMatch(row("plain"), /thread-item-worktree/);+ assert.match(row("isolated"), /data-worktree-status="active"/);+ assert.ok(row("isolated").includes(en.badge.isolated));+ assert.ok(row("isolated").includes("pi-desktop/a"), "the branch is named in the badge title");+ assert.match(row("conflicted"), /badge-warning[^>]*>Conflict</);+ assert.match(row("vanished"), /badge-error[^>]*>Folder missing</);+ assert.ok(row("broken-setup").includes(en.badge.setupFailed));+});++test("only isolated sessions get worktree menu items, disabled while running or missing", () => {+ const { WorktreeSessionMenuItems, WorktreeProjectMenuItems } = modules.parts;+ const props = { sessionId: "s1", title: "Task", running: false, onDone() {} };+ assert.equal(wrap(createElement(WorktreeSessionMenuItems, props)), "");++ const idle = wrap(+ createElement(WorktreeSessionMenuItems, {+ ...props,+ worktree: { branch: "pi-desktop/s1", status: "active", setupStatus: "failed" },+ }),+ );+ assert.match(idle, /data-action="worktree-merge"/);+ assert.doesNotMatch(idle, /data-action="worktree-merge"[^>]*disabled/);+ assert.match(idle, /data-action="worktree-reveal"/);+ assert.match(idle, /data-action="worktree-setup-log"/);+ // "Sync from project" waits for the behind count before it can be used.+ assert.match(idle, /data-action="worktree-sync"[^>]*disabled/);+ assert.ok(idle.includes(en.sync.menu));++ const running = wrap(+ createElement(WorktreeSessionMenuItems, {+ ...props,+ running: true,+ worktree: { branch: "pi-desktop/s1", status: "active", setupStatus: "none" },+ }),+ );+ assert.match(running, /data-action="worktree-merge"[^>]*disabled/);+ assert.doesNotMatch(running, /worktree-setup-log/);++ const missing = wrap(+ createElement(WorktreeSessionMenuItems, {+ ...props,+ worktree: { branch: "pi-desktop/s1", status: "missing" },+ }),+ );+ assert.match(missing, /data-action="worktree-merge"[^>]*disabled/);+ assert.match(missing, /data-action="worktree-reveal"[^>]*disabled/);++ const project = wrap(+ createElement(WorktreeProjectMenuItems, { projectPath: "/p", projectName: "P", onDone() {} }),+ );+ assert.ok(project.includes(en.newIsolatedSession));+ assert.ok(project.includes(en.setupCommand.menu));+ // Before the probe answers the item cannot be clicked.+ assert.match(project, /data-action="new-isolated-session"[^>]*disabled/);+});++test("the isolated-session menu item explains why a project cannot host one", () => {+ const { isolationAvailability } = modules.actions;+ const t = i18n.t.bind(i18n);+ assert.deepEqual(isolationAvailability("checking", t), { disabled: true });+ assert.deepEqual(isolationAvailability("unknown", t), { disabled: false });+ assert.deepEqual(isolationAvailability({ available: true, uncommittedChanges: true }, t), { disabled: false });+ assert.deepEqual(+ isolationAvailability({ available: false, errorCode: "WORKTREE_DETACHED_HEAD", message: "raw" }, t),+ { disabled: true, reason: en.errors.detachedHead },+ );+ assert.deepEqual(+ isolationAvailability({ available: false, errorCode: "WORKTREE_INTERNAL", message: "git exploded" }, t),+ { disabled: true, reason: "git exploded" },+ );+});++test("creating an isolated session probes first and explains every refusal", async () => {+ const { createIsolatedSession } = modules.actions;+ const { useAppStore } = modules.store;+ const t = i18n.t.bind(i18n);+ const created = [];+ const toasts = [];+ useAppStore.setState({+ newSession: async (options) => {+ created.push(options);+ },+ showToast: (message, options) => toasts.push({ message, variant: options?.variant }),+ });++ stubBridge({+ [IPC.invoke.worktreeProbe]: () => ({ available: false, errorCode: "WORKTREE_NOT_GIT", message: "raw" }),+ });+ await createIsolatedSession("/plain", t);+ assert.deepEqual(created, []);+ assert.deepEqual(toasts, [{ message: en.errors.notGit, variant: "error" }]);++ toasts.length = 0;+ const calls = stubBridge({+ [IPC.invoke.worktreeProbe]: () => ({ available: true, uncommittedChanges: true }),+ });+ await createIsolatedSession("/repo", t);+ assert.deepEqual(calls[0].payload, { projectPath: "/repo" });+ assert.deepEqual(created, [{ projectPath: "/repo", isolated: true }]);+ assert.deepEqual(toasts, [{ message: en.uncommittedNotIncluded, variant: "info" }]);++ toasts.length = 0;+ useAppStore.setState({+ newSession: async () => {+ throw Object.assign(new Error("git 2.20 is older than the required 2.29"), {+ code: "WORKTREE_GIT_TOO_OLD",+ });+ },+ });+ stubBridge({+ [IPC.invoke.worktreeProbe]: () => ({ available: true, uncommittedChanges: false }),+ });+ await createIsolatedSession("/repo", t);+ assert.deepEqual(toasts, [{ message: en.errors.gitTooOld, variant: "error" }]);+});++test("merge failures keep conflicts in the session and re-preview a changed session", () => {+ const { mergeFailureState } = modules.actions;+ const t = i18n.t.bind(i18n);+ const conflict = Object.assign(new Error("merge conflict"), {+ code: "WORKTREE_CONFLICT",+ details: { errorCode: "WORKTREE_CONFLICT", files: ["src/a.ts", "README.md"] },+ });+ assert.deepEqual(mergeFailureState(conflict, t), {+ phase: "conflict",+ files: ["src/a.ts", "README.md"],+ });+ assert.deepEqual(mergeFailureState({ code: "WORKTREE_CHANGED_SINCE_PREVIEW" }, t), {+ phase: "reload",+ notice: en.errors.changedSincePreview,+ });+ assert.deepEqual(mergeFailureState({ code: "WORKTREE_PROJECT_DIRTY" }, t), {+ phase: "failed",+ message: en.errors.projectDirty,+ });+ assert.deepEqual(mergeFailureState(new Error("unexpected host failure"), t), {+ phase: "failed",+ message: "unexpected host failure",+ });+});++test("the delete loss note stays empty until unmerged work is known", () => {+ const { WorktreeDeleteLossNote } = modules.parts;+ // Before the pending-work answer arrives only the ordinary armed label shows.+ assert.equal(wrap(createElement(WorktreeDeleteLossNote, { sessionId: "s1" })), "");+ assert.ok(en.deleteLoss.length > 0);+});++test("syncing from the project reports new commits, an up-to-date session, and conflicts", async () => {+ const { syncIsolatedSession } = modules.actions;+ const { useAppStore } = modules.store;+ const t = i18n.t.bind(i18n);+ const toasts = [];+ let refreshed = 0;+ useAppStore.setState({+ showToast: (message, options) => toasts.push({ message, variant: options?.variant }),+ refreshSessions: async () => {+ refreshed += 1;+ },+ });++ stubBridge({ [IPC.invoke.worktreeSync]: () => ({ result: "synced", commits: 3 }) });+ await syncIsolatedSession("s1", t);+ stubBridge({ [IPC.invoke.worktreeSync]: () => ({ result: "upToDate" }) });+ await syncIsolatedSession("s1", t);+ stubBridge({+ [IPC.invoke.worktreeSync]: () => {+ throw Object.assign(new Error("merge conflict"), {+ code: "WORKTREE_CONFLICT",+ details: { errorCode: "WORKTREE_CONFLICT", files: ["f.txt", "g.txt"] },+ });+ },+ });+ await syncIsolatedSession("s1", t);++ assert.deepEqual(toasts, [+ { message: i18n.t("worktree.sync.success", { count: 3 }), variant: "success" },+ { message: en.sync.upToDate, variant: "info" },+ { message: i18n.t("worktree.sync.conflict", { files: "f.txt, g.txt" }), variant: "error" },+ ]);+ // The badge follows: the list is refreshed after every attempt.+ assert.equal(refreshed, 3);+});++test("the behind marker shows only for sessions that lack project commits", () => {+ const { WorktreeBadge } = modules.parts;+ const { isolatedSessionsKey } = modules.behind;+ const { useWorktreeUi } = modules.worktreeUi;+ const active = { branch: "pi-desktop/a", status: "active", setupStatus: "none" };+ // Server rendering reads the store's initial state (as the sidebar test does).+ Object.assign(useWorktreeUi.getInitialState(), { behind: { s1: 3, s2: 0 } });++ const behind = wrap(createElement(WorktreeBadge, { worktree: active, sessionId: "s1" }));+ assert.match(behind, /data-worktree-behind="3"/);+ assert.ok(behind.includes(i18n.t("worktree.badge.behind", { count: 3 })));+ assert.ok(behind.includes(i18n.t("worktree.badge.behindTitle", { count: 3 }).replaceAll('"', """)));+ assert.doesNotMatch(wrap(createElement(WorktreeBadge, { worktree: active, sessionId: "s2" })), /data-worktree-behind/);+ assert.doesNotMatch(wrap(createElement(WorktreeBadge, { worktree: active })), /data-worktree-behind/);+ assert.doesNotMatch(+ wrap(createElement(WorktreeBadge, { worktree: { ...active, status: "missing" }, sessionId: "s1" })),+ /data-worktree-behind/,+ );++ // The counts are re-read when an isolated session appears, changes status,+ // or finishes a turn; ordinary sessions never trigger it.+ const at = "2020-01-01T00:00:00Z";+ const plain = { id: "p", updatedAt: at };+ const isolated = { id: "s1", updatedAt: at, worktree: active };+ const base = isolatedSessionsKey([plain, isolated]);+ assert.equal(isolatedSessionsKey([isolated]), base);+ assert.equal(isolatedSessionsKey([plain]), "");+ assert.notEqual(isolatedSessionsKey([{ ...isolated, updatedAt: "2020-01-02T00:00:00Z" }]), base);+ assert.notEqual(isolatedSessionsKey([{ ...isolated, worktree: { ...active, status: "merged" } }]), base);+ assert.equal(isolatedSessionsKey([{ ...isolated, worktree: { ...active, status: "missing" } }]), "");+});++test("a conflicted session hides the behind marker and cannot sync until it resolves", () => {+ const { WorktreeBadge, WorktreeSessionMenuItems } = modules.parts;+ const { useWorktreeUi } = modules.worktreeUi;+ Object.assign(useWorktreeUi.getInitialState(), { behind: { s1: 3 } });+ const conflicted = { branch: "pi-desktop/s1", status: "conflict", setupStatus: "none" };++ const badge = wrap(createElement(WorktreeBadge, { worktree: conflicted, sessionId: "s1" }));+ assert.match(badge, /data-worktree-status="conflict"/);+ assert.doesNotMatch(badge, /data-worktree-behind/);++ const menu = wrap(+ createElement(WorktreeSessionMenuItems, {+ sessionId: "s1",+ title: "Task",+ running: false,+ onDone() {},+ worktree: conflicted,+ }),+ );+ const sync = menu.slice(menu.indexOf('data-action="worktree-sync"') - 200, menu.indexOf("</button>", menu.indexOf('data-action="worktree-sync"')));+ assert.match(sync, /disabled=""/);+ assert.ok(sync.includes(en.sync.resolveFirst), sync);+ assert.doesNotMatch(sync, /aria-busy/);+ // Merging stays available: it concludes the resolution.+ assert.doesNotMatch(menu, /data-action="worktree-merge"[^>]*disabled/);+});++test("every actionable worktree error has a localized message in every locale", () => {+ const { worktreeErrorMessage } = modules.actions;+ const { WorktreeErrorCodes } = modules.shared;+ const t = i18n.t.bind(i18n);+ // Conflicts list their files and a changed session is previewed again.+ const handledElsewhere = new Set(["WORKTREE_CONFLICT"]);+ for (const code of Object.values(WorktreeErrorCodes)) {+ if (handledElsewhere.has(code)) continue;+ const message = worktreeErrorMessage(Object.assign(new Error("raw git output"), { code }), t);+ assert.notEqual(message, "raw git output", `${code} shows the raw host message`);+ }+ for (const [locale, catalog] of Object.entries(catalogs)) {+ assert.deepEqual(+ Object.keys(catalog.worktree.errors).sort(),+ Object.keys(en.errors).sort(),+ `${locale} worktree errors`,+ );+ assert.match(catalog.worktree.sync.conflict, /\{\{files\}\}/, `${locale} sync conflict`);+ }+});diff --git a/crates/host-core/src/data_relocation.rs b/crates/host-core/src/data_relocation.rsindex b450924da..1db88b23d 100644--- a/crates/host-core/src/data_relocation.rs+++ b/crates/host-core/src/data_relocation.rs@@ -336,6 +336,9 @@ fn relocate_database(roots: &Roots) -> Result<()> {("artifacts", "path", false),("turn_queue", "attachments_json", true),("scheduled_tasks", "config_json", true),+ // Isolated-session worktrees live under the data directory (ADR 0328);+ // host-core repairs git's back-links on the next start.+ ("worktrees", "path", false),] {if !column_exists(&transaction, table, column)? {continue;diff --git a/crates/host-core/src/db.rs b/crates/host-core/src/db.rsindex 82fc5cedb..518e0005a 100644--- a/crates/host-core/src/db.rs+++ b/crates/host-core/src/db.rs@@ -7,7 +7,7 @@ pub(crate) use serde_json::Value;pub(crate) use std::path::{Path, PathBuf};/// Current SQLite schema version.-pub const SCHEMA_VERSION: i64 = 23;+pub const SCHEMA_VERSION: i64 = 24;/// Absolute approval deadline for a newly submitted Plan or Goal proposal.pub const PLAN_APPROVAL_TIMEOUT_MS: i64 = 30 * 60 * 1000;@@ -23,6 +23,7 @@ mod repositories;mod schema;mod session_collaboration_migration;mod session_title_source_migration;+mod worktree_migration;pub(crate) use migrations::{archive_legacy_db, create_migration_backup, migrate_and_validate_top_level_mode,migrate_app_settings, migrate_v10_to_v15, migrate_v11_to_v15, migrate_v12_to_v15,@@ -43,6 +44,7 @@ pub(crate) use repositories::{};pub(crate) use schema::{PLAN_APPROVALS_SCHEMA, SCHEMA_LATEST, SESSION_TODO_DDL};pub(crate) use session_title_source_migration::migrate_v22_to_v23;+pub(crate) use worktree_migration::{migrate_v23_to_v24, WORKTREE_DDL};pub fn now_ms() -> i64 {chrono::Utc::now().timestamp_millis()diff --git a/crates/host-core/src/db/repositories.rs b/crates/host-core/src/db/repositories.rsindex 753ebf5fd..30bc39d30 100644--- a/crates/host-core/src/db/repositories.rs+++ b/crates/host-core/src/db/repositories.rs@@ -146,6 +146,7 @@ impl Database {tx.execute_batch(SCHEMA_LATEST)?;tx.execute_batch(PLAN_APPROVALS_SCHEMA)?;tx.execute_batch(crate::session_collaboration::SCHEMA)?;+ tx.execute_batch(WORKTREE_DDL)?;tx.pragma_update(None, "user_version", SCHEMA_VERSION)?;tx.commit()?;}@@ -203,6 +204,9 @@ impl Database {22 => {migrate_v22_to_v23(&conn, path)?;}+ 23 => {+ migrate_v23_to_v24(&conn, path)?;+ }legacy @ 1..=6 => {let _ = conn.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);");drop(conn);@@ -249,6 +253,10 @@ impl Database {}if migrated_version == 22 {migrate_v22_to_v23(&conn, path)?;+ migrated_version = conn.query_row("PRAGMA user_version", [], |row| row.get(0))?;+ }+ if migrated_version == 23 {+ migrate_v23_to_v24(&conn, path)?;}let db = Self { conn, data_dir };db.boot_maintenance()?;diff --git a/crates/host-core/src/db/schema.rs b/crates/host-core/src/db/schema.rsindex dc2b2a4af..c23bf809d 100644--- a/crates/host-core/src/db/schema.rs+++ b/crates/host-core/src/db/schema.rs@@ -42,7 +42,9 @@ CREATE TABLE projects (name TEXT NOT NULL,pinned INTEGER NOT NULL DEFAULT 0,created_at INTEGER NOT NULL,- last_opened_at INTEGER NOT NULL+ last_opened_at INTEGER NOT NULL,+ -- Optional command run in every new isolated worktree (schema v24, ADR 0328).+ worktree_setup_command TEXT);CREATE TABLE providers (diff --git a/crates/host-core/src/db/tests.rs b/crates/host-core/src/db/tests.rsindex 765e42b10..8f524583b 100644--- a/crates/host-core/src/db/tests.rs+++ b/crates/host-core/src/db/tests.rs@@ -178,6 +178,118 @@ fn v22_database_migrates_session_title_sources_without_losing_titles() {);}+/// v24 adds the isolated-session worktree registry (ADR 0328). A v23 database+/// keeps its projects and sessions, gains the nullable setup-command column+/// and the `worktrees` table, and leaves a pre-migration backup.+#[test]+fn v23_database_gains_worktree_registry_without_losing_projects() {+ let dir = tempfile::tempdir().unwrap();+ let path = dir.path().join("pi.sqlite");+ let session_id = {+ let db = Database::open(&path).unwrap();+ db.conn()+ .execute(+ "INSERT INTO projects (path, name, pinned, created_at, last_opened_at)+ VALUES ('/work/app', 'app', 1, 1, 2)",+ [],+ )+ .unwrap();+ let session =+ crate::sessions::create_session(&db, Some("Kept".into()), None, None, None, None)+ .unwrap();+ db.conn()+ .execute_batch(+ "DROP TABLE worktrees;+ ALTER TABLE projects DROP COLUMN worktree_setup_command;",+ )+ .unwrap();+ db.conn().pragma_update(None, "user_version", 23).unwrap();+ session.id+ };++ let db = Database::open(&path).unwrap();+ assert_eq!(schema_version(db.conn()), SCHEMA_VERSION);+ assert!(migration_backup_path(&path, 23).exists());+ let (name, pinned, command): (String, i64, Option<String>) = db+ .conn()+ .query_row(+ "SELECT name, pinned, worktree_setup_command FROM projects WHERE path = '/work/app'",+ [],+ |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)),+ )+ .unwrap();+ assert_eq!((name.as_str(), pinned, command), ("app", 1, None));+ assert!(crate::sessions::get_session(&db, &session_id)+ .unwrap()+ .is_some());+ let worktrees: i64 = db+ .conn()+ .query_row("SELECT COUNT(*) FROM worktrees", [], |row| row.get(0))+ .unwrap();+ assert_eq!(worktrees, 0);+}++/// Deleting a session through any path must keep the worktree row, with its+/// session cleared, so the orphan cleanup can still remove the directory and+/// branch that exist on disk.+#[test]+fn deleting_a_session_orphans_its_worktree_rows_instead_of_dropping_them() {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ db.conn()+ .execute(+ "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, branch,+ owner_branch, status, created_at, updated_at)+ VALUES ('w1', ?1, NULL, '/data/worktrees/p/s1', '/repo/.git', 'pi-desktop/s1',+ 'main', 'active', 1, 1)",+ params![session.id],+ )+ .unwrap();+ assert!(crate::sessions::delete_session(&db, &session.id).unwrap());+ let session_id: Option<String> = db+ .conn()+ .query_row(+ "SELECT session_id FROM worktrees WHERE id = 'w1'",+ [],+ |row| row.get(0),+ )+ .unwrap();+ assert_eq!(session_id, None);+}++/// A session owns at most one worktree of its own plus one per delegation,+/// and two active worktrees never share a port block.+#[test]+fn worktree_registry_enforces_one_row_per_owner_and_unique_ports() {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ let insert = |id: &str, delegation: Option<&str>, port: Option<i64>| {+ db.conn().execute(+ "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, branch,+ owner_branch, status, port_base, created_at, updated_at)+ VALUES (?1, ?2, ?3, '/w/' || ?1, '/repo/.git', 'pi-desktop/' || ?1, 'main',+ 'active', ?4, 1, 1)",+ params![id, session.id, delegation, port],+ )+ };+ insert("a", None, Some(41000)).unwrap();+ assert!(+ insert("b", None, Some(41010)).is_err(),+ "second own worktree"+ );+ insert("c", Some("d1"), Some(41010)).unwrap();+ assert!(+ insert("e", Some("d1"), None).is_err(),+ "second worktree for one delegation"+ );+ assert!(+ insert("f", Some("d2"), Some(41000)).is_err(),+ "shared port block"+ );+}+/// v21 owns the session checklist. A real v20 database has neither the/// `sessions` stamps nor the `session_todo` table, so the upgrade must add/// both, keep the v20 rows, leave a readable pre-migration backup, and staydiff --git a/crates/host-core/src/db/worktree_migration.rs b/crates/host-core/src/db/worktree_migration.rsnew file mode 100644index 000000000..325ce5f99--- /dev/null+++ b/crates/host-core/src/db/worktree_migration.rs@@ -0,0 +1,72 @@+use super::{create_migration_backup, Connection, Context, Path, Result};+use rusqlite::Transaction;++/// Registry of git worktrees that host-core created for isolated sessions and+/// their Write/Edit delegates (ADR 0328).+///+/// `session_id` uses `ON DELETE SET NULL`, not `CASCADE`: a session removed by+/// any path leaves an orphan row that the cleanup pass turns into a link-safe+/// removal of the directory and branch. A cascade would drop the only record+/// of a worktree that still exists on disk.+///+/// Shared verbatim by the fresh schema and the v23 -> v24 migration;+/// `IF NOT EXISTS` keeps a second run harmless.+pub(crate) const WORKTREE_DDL: &str = r#"+CREATE TABLE IF NOT EXISTS worktrees (+ id TEXT PRIMARY KEY,+ session_id TEXT REFERENCES sessions(id) ON DELETE SET NULL,+ delegation_id TEXT,+ path TEXT NOT NULL UNIQUE,+ -- Canonical common git directory: serialization key, and where branches are+ -- deleted after the worktree directory is gone.+ common_dir TEXT NOT NULL,+ -- Project directory relative to the repository top level ('' at the top).+ prefix TEXT NOT NULL DEFAULT '',+ branch TEXT NOT NULL,+ owner_branch TEXT NOT NULL,+ status TEXT NOT NULL+ CHECK (status IN ('creating', 'active', 'conflict', 'merged', 'missing')),+ setup_status TEXT+ CHECK (setup_status IS NULL+ OR setup_status IN ('none', 'running', 'ok', 'failed')),+ setup_log TEXT,+ port_base INTEGER,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL+);+CREATE UNIQUE INDEX IF NOT EXISTS idx_worktrees_session_delegation+ ON worktrees(session_id, IFNULL(delegation_id, ''))+ WHERE session_id IS NOT NULL;+CREATE UNIQUE INDEX IF NOT EXISTS idx_worktrees_port_base+ ON worktrees(port_base) WHERE port_base IS NOT NULL;+CREATE INDEX IF NOT EXISTS idx_worktrees_orphans+ ON worktrees(updated_at) WHERE session_id IS NULL;+"#;++fn migrate_v23_to_v24_tx(tx: &Transaction<'_>) -> Result<()> {+ let has_setup_command: bool = tx.query_row(+ "SELECT EXISTS(SELECT 1 FROM pragma_table_info('projects')+ WHERE name = 'worktree_setup_command')",+ [],+ |row| row.get(0),+ )?;+ if !has_setup_command {+ tx.execute_batch("ALTER TABLE projects ADD COLUMN worktree_setup_command TEXT;")?;+ }+ tx.execute_batch(WORKTREE_DDL)?;+ tx.pragma_update(None, "user_version", 24i64)?;+ Ok(())+}++pub(crate) fn migrate_v23_to_v24(conn: &Connection, path: &Path) -> Result<()> {+ let backup = create_migration_backup(conn, path, 23)?;+ let tx = conn.unchecked_transaction()?;+ migrate_v23_to_v24_tx(&tx)?;+ tx.commit().with_context(|| {+ format!(+ "commit schema v23 to v24 migration; backup {} remains",+ backup.display()+ )+ })?;+ Ok(())+}diff --git a/crates/host-core/src/main.rs b/crates/host-core/src/main.rsindex bcc75a0ba..8c9d71e30 100644--- a/crates/host-core/src/main.rs+++ b/crates/host-core/src/main.rs@@ -23,6 +23,7 @@ mod scratch;mod secrets;mod session_collaboration;mod session_search;+mod session_worktrees;mod sessions;mod state;mod todos;@@ -97,5 +98,11 @@ async fn main() -> anyhow::Result<()> {review::sweep(&data_dir, &live);}}+ // Drop half-created worktrees, mark vanished ones, repair links after a+ // moved data directory, and remove orphans (ADR 0328).+ tokio::spawn(session_worktrees::lifecycle::reconcile(+ state.clone(),+ session_worktrees::git::GitRunner::default(),+ ));rpc::serve(state).await}diff --git a/crates/host-core/src/plugins/providers/tests.rs b/crates/host-core/src/plugins/providers/tests.rsindex f028989c2..bab05ca21 100644--- a/crates/host-core/src/plugins/providers/tests.rs+++ b/crates/host-core/src/plugins/providers/tests.rs@@ -99,9 +99,10 @@ fn a_new_database_carries_the_owner_column_at_the_current_schema_version() {let (_dir, db, _secrets) = test_context();// v17 added the owner column, v18 the turn-queue priority column,// v19 session omit, v21 the session Todo checklist, and v22 the- // session-list index. A fresh database is stamped with the newest version,- // so the column set is the current one.- assert_eq!(SCHEMA_VERSION, 23);+ // session-list index, v23 the session title source, and v24 the worktree+ // registry. A fresh database is stamped with the newest version, so the+ // column set is the current one.+ assert_eq!(SCHEMA_VERSION, 24);let version: i64 = db.conn().query_row("PRAGMA user_version", [], |row| row.get(0))diff --git a/crates/host-core/src/rpc/mod.rs b/crates/host-core/src/rpc/mod.rsindex 76cf50788..8bd0d8aaf 100644--- a/crates/host-core/src/rpc/mod.rs+++ b/crates/host-core/src/rpc/mod.rs@@ -4,6 +4,7 @@ mod scheduled_rpc;mod scheduled_tools;mod todos;mod window_corner_rpc;+mod worktree_rpc;use std::io::{self, BufRead, BufReader as StdBufReader, Read, Write};use std::path::{Path, PathBuf};@@ -1287,6 +1288,13 @@ fn resolve_tool_workspace() -> Result<Option<String>, JsonRpcError> {match sessions::session_summary(&state.db, session_id) {Ok(Some(summary)) => {+ // An isolated session's root is its worktree and never falls back+ // to the main checkout (ADR 0328).+ match crate::session_worktrees::lifecycle::tool_root(&state.db, session_id) {+ Ok(Some(root)) => return Ok(Some(root.to_string_lossy().into_owned())),+ Ok(None) => {}+ Err(error) => return Err(worktree_rpc::to_rpc(error)),+ }if let Some(project_path) = summary.project_path {return Ok(Some(project_path));}@@ -2504,7 +2512,32 @@ async fn handle_request("session.create" => {let thinking_level = thinking_level_param(¶ms)?;let permission_parent = permission_parent_param(¶ms)?;+ // ADR 0328: an isolated session gets its own git worktree.+ let isolated = params+ .get("isolated")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let isolated_project = if isolated {+ Some(+ params+ .get("projectPath")+ .and_then(|v| v.as_str())+ .map(str::to_string)+ .ok_or_else(|| {+ rpc_err(+ 1002,+ "an isolated session needs a projectPath",+ "INVALID_PARAMS",+ )+ })?,+ )+ } else {+ None+ };let st = state.lock().await;+ if let Some(project) = isolated_project.as_deref() {+ worktree_rpc::ensure_local_project(&st.db, project)?;+ }let permission_mode = if let Some(parent_id) = permission_parent {Some(sessions::session_permission_mode(&st.db, &parent_id)@@ -2542,12 +2575,22 @@ 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 }))+ let Some(project) = isolated_project else {+ let session = remote_tools::decorate_session(+ &st.db,+ serde_json::to_value(session)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?,+ )?;+ return Ok(json!({ "session": session }));+ };+ drop(st);+ let created = worktree_rpc::isolate_new_session(&state, &session.id, &project).await?;+ let st = state.lock().await;+ let session = sessions::session_summary(&st.db, &session.id)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?+ .ok_or_else(|| rpc_err(1007, "session not found", "NOT_FOUND"))?;+ let session = remote_tools::session_value(&st.db, session)?;+ Ok(json!({ "session": session, "worktree": created }))}"session.fork" => {let session_id = params@@ -2590,6 +2633,18 @@ async fn handle_request(.filter(|value| !value.is_empty()).ok_or_else(|| rpc_err(1002, "projectPath required", "INVALID_PARAMS"))?;let st = state.lock().await;+ // An isolated session's worktree belongs to its project's repository.+ let isolated = crate::session_worktrees::registry::for_owner(&st.db, session_id, None)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?+ .is_some();+ if isolated {+ return Err(worktree_rpc::to_rpc(+ crate::session_worktrees::WorktreeError::new(+ "WORKTREE_MOVE_UNSUPPORTED",+ "an isolated session cannot move to another project",+ ),+ ));+ }let session = match sessions::move_session_project(&st.db, session_id, project_path).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?{@@ -2714,12 +2769,17 @@ async fn handle_request(.get("id").and_then(|v| v.as_str()).ok_or_else(|| rpc_err(1002, "id required", "INVALID_PARAMS"))?;+ // Delete = discard for isolated sessions (ADR 0328); a git failure+ // keeps the session.+ worktree_rpc::remove_before_delete(&state, id).await?;let st = state.lock().await;let ok = sessions::delete_session(&st.db, id).map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;if ok {drop_session_side_data(&st, id);}+ drop(st);+ worktree_rpc::spawn_orphan_cleanup(&state);Ok(json!({ "ok": ok }))}"session.rename" => {@@ -3713,6 +3773,10 @@ async fn handle_request(scheduled_rpc::handle(&st, method, params)}+ method if method.starts_with("worktree.") => {+ worktree_rpc::handle(&state, method, params).await+ }+"tools.list" => {let mut definitions = tools::builtin_tool_defs();if let Some(items) = definitions.as_array_mut() {@@ -3867,7 +3931,16 @@ async fn handle_request(// isolated when the renderer switches between project tabs.// The session's project remains the containment root for all// known sessions.- let ws = resolve_tool_workspace_for_call(&st, &p.session_id, &p.args)?;+ let ws = match crate::session_worktrees::delegate::tool_root(+ &st.db,+ &p.session_id,+ p.delegation_id.as_deref(),+ )+ .map_err(worktree_rpc::to_rpc)?+ {+ Some(root) => Some(root.to_string_lossy().into_owned()),+ None => 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 = if remote_workspace.is_some() {remote_tools::requires_external_permission(@@ -4102,11 +4175,28 @@ async fn handle_request(// Admission follows permission so approval waits do not occupy// execution capacity. Keep this permit through review, the// runner, and bookkeeping so every accepted call is bounded.- let tool_budget = {+ // A subagent working in its own worktree (ADR 0328) is not+ // stopped while its session's worktree is held for a merge.+ let (tool_budget, own_worktree) = {let st = state.lock().await;- st.tool_budget.clone()+ let own = matches!(+ crate::session_worktrees::delegate::tool_root(+ &st.db,+ &p.session_id,+ p.delegation_id.as_deref(),+ ),+ Ok(Some(_))+ );+ (st.tool_budget.clone(), own)+ };+ let admitted = if own_worktree {+ tool_budget+ .acquire_in_own_worktree(&p.session_id, &p.tool_name)+ .await+ } else {+ tool_budget.acquire(&p.session_id, &p.tool_name).await};- let _tool_permit = match tool_budget.acquire(&p.session_id, &p.tool_name).await {+ let _tool_permit = match admitted {Ok(permit) => permit,Err(error) => {tracing::warn!(@@ -4135,9 +4225,17 @@ async fn handle_request(};let ws_path = workspace_path.map(PathBuf::from);- let (data_dir, hashline_store) = {+ let (data_dir, hashline_store, worktree_env) = {let st = state.lock().await;- (st.data_dir.clone(), st.hashline.clone())+ (+ st.data_dir.clone(),+ st.hashline.clone(),+ crate::session_worktrees::delegate::tool_env(+ &st.db,+ &p.session_id,+ p.delegation_id.as_deref(),+ ),+ )};let hashline_ctx = tools::HashlineContext {session_id: p.session_id.as_str(),@@ -4216,6 +4314,7 @@ async fn handle_request(timeout_ms: execution_timeout_ms,cancellation,output_tx: Some(tx.clone()),+ extra_env: worktree_env.clone(),});}@@ -4292,6 +4391,20 @@ async fn handle_request(}}+ // ADR 0328: a session that resolved its merge conflict (or+ // aborted the merge) drops its conflict badge before the turn+ // ends and the sidebar refreshes.+ if p.delegation_id.is_none()+ && matches!(p.tool_name.as_str(), "Write" | "Edit" | "Bash")+ {+ crate::session_worktrees::lifecycle::refresh_conflict_status(+ &state,+ &crate::session_worktrees::git::GitRunner::default(),+ &p.session_id,+ )+ .await;+ }+let st = state.lock().await;// Scratch files are temp by definition: keep them out of the// artifacts table so the work panel file list only showsdiff --git a/crates/host-core/src/rpc/remote_tools.rs b/crates/host-core/src/rpc/remote_tools.rsindex 235ca70ff..d1fe3d8ae 100644--- a/crates/host-core/src/rpc/remote_tools.rs+++ b/crates/host-core/src/rpc/remote_tools.rs@@ -340,6 +340,8 @@ pub(super) async fn handle(timeout_ms: tools::effective_timeout_ms(&p.tool_name, p.timeout_ms),cancellation: cancellation.clone(),output_tx: Some(tx),+ // Remote workspaces are never isolated (ADR 0328).+ extra_env: Vec::new(),})} else {Nonediff --git a/crates/host-core/src/rpc/remote_tools_tests.rs b/crates/host-core/src/rpc/remote_tools_tests.rsindex de0c5de97..937f4d539 100644--- a/crates/host-core/src/rpc/remote_tools_tests.rs+++ b/crates/host-core/src/rpc/remote_tools_tests.rs@@ -341,3 +341,46 @@ async fn approved_remote_write_is_dispatched_only_after_local_permission_resolut"CAPABILITY_UNAVAILABLE");}++/// ADR 0328: a remote-host project cannot host an isolated session; the+/// probe says why and creation is refused before a session exists.+#[tokio::test]+async fn remote_projects_cannot_create_isolated_sessions() {+ let (_dir, state, tx, _rx) = fixture();+ let (path, _id) = create(&state, &tx).await;+ let probe = handle_request(+ state.clone(),+ "worktree.probe",+ json!({"projectPath": path}),+ tx.clone(),+ )+ .await+ .unwrap();+ assert_eq!(probe["available"], false);+ assert_eq!(probe["errorCode"], "WORKTREE_REMOTE_UNSUPPORTED");+ let before = handle_request(state.clone(), "session.list", json!({}), tx.clone())+ .await+ .unwrap()["sessions"]+ .as_array()+ .unwrap()+ .len();+ let refused = handle_request(+ state.clone(),+ "session.create",+ json!({"projectPath": path, "isolated": true}),+ tx.clone(),+ )+ .await+ .unwrap_err();+ assert_eq!(+ refused.data.unwrap()["errorCode"],+ "WORKTREE_REMOTE_UNSUPPORTED"+ );+ let after = handle_request(state.clone(), "session.list", json!({}), tx.clone())+ .await+ .unwrap()["sessions"]+ .as_array()+ .unwrap()+ .len();+ assert_eq!(before, after);+}diff --git a/crates/host-core/src/rpc/worktree_rpc.rs b/crates/host-core/src/rpc/worktree_rpc.rsnew file mode 100644index 000000000..bc0406d18--- /dev/null+++ b/crates/host-core/src/rpc/worktree_rpc.rs@@ -0,0 +1,265 @@+//! `worktree.*` methods and the isolated-session hooks of `session.create` and+//! `session.delete` (ADR 0328). Callers name a session or a project; no+//! method accepts a worktree path.++use std::path::Path;+use std::sync::Arc;++use serde_json::{json, Value};+use tokio::sync::Mutex;++use super::{rpc_err, JsonRpcError};+use crate::session_worktrees::git::GitRunner;+use crate::session_worktrees::{delegate, lifecycle, merge, probe, registry, WorktreeError};+use crate::sessions;+use crate::state::AppState;++/// Numeric JSON-RPC code shared by every `WORKTREE_*` error; `errorCode`+/// carries the specific reason.+const WORKTREE_RPC_CODE: i64 = 1025;++pub(super) fn to_rpc(error: WorktreeError) -> JsonRpcError {+ let mut data = json!({ "errorCode": error.code });+ if !error.files.is_empty() {+ data["files"] = json!(error.files);+ }+ JsonRpcError {+ code: WORKTREE_RPC_CODE,+ message: error.message,+ data: Some(data),+ }+}++/// Code of a refusal to isolate a remote-host project: its path names a+/// workspace on another machine, not a local git checkout.+const REMOTE_UNSUPPORTED: &str = "WORKTREE_REMOTE_UNSUPPORTED";++/// Isolated sessions need a local checkout; remote-host projects run their+/// tools on the remote machine and are refused before anything is created.+pub(super) fn ensure_local_project(+ db: &crate::db::Database,+ project_path: &str,+) -> Result<(), JsonRpcError> {+ let remote = db+ .remote_workspace_for_path(project_path)+ .map_err(|e| rpc_err(1002, e.to_string(), "INVALID_PARAMS"))?;+ match remote {+ Some(_) => Err(to_rpc(WorktreeError::new(+ REMOTE_UNSUPPORTED,+ "isolated sessions are not available for remote projects",+ ))),+ None => Ok(()),+ }+}++fn str_param<'a>(params: &'a Value, name: &str) -> Result<&'a str, JsonRpcError> {+ params+ .get(name)+ .and_then(Value::as_str)+ .map(str::trim)+ .filter(|value| !value.is_empty())+ .ok_or_else(|| rpc_err(1002, format!("{name} required"), "INVALID_PARAMS"))+}++pub(super) async fn handle(+ state: &Arc<Mutex<AppState>>,+ method: &str,+ params: Value,+) -> Result<Value, JsonRpcError> {+ let git = GitRunner::default();+ match method {+ // Whether a project can host isolated sessions, for the create switch+ // (PRD R6) and the "uncommitted changes are not included" notice (R2b).+ "worktree.probe" => {+ let project = str_param(¶ms, "projectPath")?;+ if let Err(error) = ensure_local_project(&state.lock().await.db, project) {+ let data = error.data.unwrap_or_default();+ return Ok(json!({+ "available": false,+ "errorCode": data["errorCode"],+ "message": error.message,+ }));+ }+ match probe::probe(&git, Path::new(project)).await {+ Ok(_) => {+ let dirty = !merge::worktree_status(&git, Path::new(project))+ .await+ .map_err(to_rpc)?+ .is_empty();+ Ok(json!({ "available": true, "uncommittedChanges": dirty }))+ }+ Err(error) => Ok(json!({+ "available": false,+ "errorCode": error.code(),+ "message": error.to_string(),+ })),+ }+ }+ "worktree.preview" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let preview = lifecycle::preview_session(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "preview": preview }))+ }+ "worktree.merge" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let token = str_param(¶ms, "previewToken")?;+ let outcome = lifecycle::merge_session(state, &git, session_id, token)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "outcome": outcome }))+ }+ // "Sync from project": `behind` sizes the menu item, `sync` merges+ // the project's branch into the session worktree.+ "worktree.behind" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let commits = lifecycle::behind_session(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "commits": commits }))+ }+ "worktree.behindAll" => {+ let behind = lifecycle::behind_all(state, &git).await.map_err(to_rpc)?;+ Ok(json!(behind))+ }+ "worktree.sync" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let outcome = lifecycle::sync_session(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "outcome": outcome }))+ }+ "worktree.pendingWork" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let pending = lifecycle::pending_work(state, &git, session_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "pending": pending }))+ }+ "worktree.setupLog" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let st = state.lock().await;+ let row = registry::for_owner(&st.db, session_id, None)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ Ok(json!({+ "setupStatus": row.as_ref().and_then(|row| row.setup_status),+ "log": row.and_then(|row| row.setup_log),+ }))+ }+ // For Electron Main's "Reveal in folder" only; never forwarded to+ // the renderer.+ "worktree.location" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let st = state.lock().await;+ let root = lifecycle::tool_root(&st.db, session_id)+ .map_err(to_rpc)?+ .ok_or_else(|| {+ to_rpc(WorktreeError::new(+ "WORKTREE_NOT_ISOLATED",+ "the session has no isolated worktree",+ ))+ })?;+ Ok(json!({ "path": root }))+ }+ // Called by the agent runtime for Write/Edit subagents of an+ // isolated session; `delegationId` is the subagent's chain id.+ "worktree.delegate.create" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let delegation_id = str_param(¶ms, "delegationId")?;+ let worktree =+ delegate::create_delegate_worktree(state, &git, session_id, delegation_id)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "worktree": worktree }))+ }+ "worktree.delegate.settle" => {+ let session_id = str_param(¶ms, "sessionId")?;+ let delegation_id = str_param(¶ms, "delegationId")?;+ let merge = params+ .get("merge")+ .and_then(Value::as_bool)+ .unwrap_or(false);+ let settlement =+ delegate::settle_delegate_worktree(state, &git, session_id, delegation_id, merge)+ .await+ .map_err(to_rpc)?;+ Ok(json!({ "settlement": settlement }))+ }+ "worktree.setupCommand.get" => {+ let project = str_param(¶ms, "projectPath")?;+ let st = state.lock().await;+ let command = lifecycle::setup_command(&st.db, project)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ Ok(json!({ "command": command }))+ }+ "worktree.setupCommand.set" => {+ let project = str_param(¶ms, "projectPath")?;+ let command = params.get("command").and_then(Value::as_str);+ let st = state.lock().await;+ let updated = lifecycle::set_setup_command(&st.db, project, command)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?;+ if !updated {+ return Err(rpc_err(1007, "project not found", "NOT_FOUND"));+ }+ Ok(json!({ "ok": true }))+ }+ _ => Err(rpc_err(+ -32601,+ format!("method not found: {method}"),+ "NOT_FOUND",+ )),+ }+}++/// Give a just-created session its worktree. On failure the session is+/// deleted again, so no half-created isolated session remains (design §5.1).+pub(super) async fn isolate_new_session(+ state: &Arc<Mutex<AppState>>,+ session_id: &str,+ project_path: &str,+) -> Result<lifecycle::CreatedWorktree, JsonRpcError> {+ match lifecycle::create_session_worktree(state, &GitRunner::default(), session_id, project_path)+ .await+ {+ Ok(created) => Ok(created),+ Err(error) => {+ let st = state.lock().await;+ if let Err(cleanup) = sessions::delete_session(&st.db, session_id) {+ tracing::warn!(%cleanup, "could not delete a session whose worktree failed");+ }+ Err(to_rpc(error))+ }+ }+}++/// Remove an isolated session's worktrees and branches before the session row+/// is deleted. A failure keeps the session (nothing is half-removed silently).+pub(super) async fn remove_before_delete(+ state: &Arc<Mutex<AppState>>,+ session_id: &str,+) -> Result<(), JsonRpcError> {+ let has_worktrees = {+ let st = state.lock().await;+ !registry::for_session(&st.db, session_id)+ .map_err(|e| rpc_err(1000, e.to_string(), "INTERNAL"))?+ .is_empty()+ };+ if !has_worktrees {+ return Ok(());+ }+ lifecycle::remove_session_worktrees(state, &GitRunner::default(), session_id)+ .await+ .map_err(to_rpc)+}++/// After any deletion, remove worktrees orphaned by other deletion paths.+pub(super) fn spawn_orphan_cleanup(state: &Arc<Mutex<AppState>>) {+ let state = state.clone();+ tokio::spawn(async move {+ lifecycle::cleanup_orphans(&state, &GitRunner::default()).await;+ });+}++#[cfg(test)]+mod tests;diff --git a/crates/host-core/src/rpc/worktree_rpc/tests.rs b/crates/host-core/src/rpc/worktree_rpc/tests.rsnew file mode 100644index 000000000..17892807c--- /dev/null+++ b/crates/host-core/src/rpc/worktree_rpc/tests.rs@@ -0,0 +1,389 @@+//! Representative user path through the real RPC entry point (ADR 0328):+//! probe -> create isolated session -> agent writes and runs Bash in the+//! worktree -> preview -> merge -> delete.++use std::collections::HashMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use serde_json::{json, Value};+use tokio::sync::{mpsc, Mutex};++use super::super::{handle_request, requires_external_path_permission, resolve_tool_workspace};+use crate::session_worktrees::lifecycle;+use crate::session_worktrees::test_support::{git_cmd, init_repo};+use crate::state::AppState;++async fn call(state: &Arc<Mutex<AppState>>, method: &str, params: Value) -> Result<Value, Value> {+ handle_request(state.clone(), method, params, mpsc::unbounded_channel().0)+ .await+ .map_err(|error| {+ json!({+ "code": error.code,+ "errorCode": error.data.as_ref().and_then(|data| data.get("errorCode")).cloned(),+ })+ })+}++fn tool_options(+ bash: Option<crate::tools::BashExecutionOptions>,+) -> crate::tools::ToolExecutionOptions<'static> {+ crate::tools::ToolExecutionOptions {+ timeout_ms: None,+ bash_options: bash,+ allow_external_paths: false,+ hashline: None,+ }+}++fn canonical(path: &Path) -> PathBuf {+ crate::workspace::simple_canonicalize(path).unwrap()+}++#[tokio::test]+async fn isolated_session_user_path_from_create_to_delete() {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "base\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let project_text = project.to_string_lossy().into_owned();++ let probe = call(+ &state,+ "worktree.probe",+ json!({ "projectPath": project_text }),+ )+ .await+ .unwrap();+ assert_eq!(probe["available"], true);+ assert_eq!(probe["uncommittedChanges"], false);++ let created = call(+ &state,+ "session.create",+ json!({ "projectPath": project_text, "isolated": true, "title": "Feature" }),+ )+ .await+ .unwrap();+ let session_id = created["session"]["id"].as_str().unwrap().to_string();+ let branch = created["session"]["worktree"]["branch"]+ .as_str()+ .unwrap()+ .to_string();+ assert_eq!(created["worktree"]["worktree"]["status"], "active");+ let listed = call(&state, "session.list", json!({})).await.unwrap();+ let row = listed["sessions"]+ .as_array()+ .unwrap()+ .iter()+ .find(|session| session["id"] == session_id.as_str())+ .unwrap();+ assert_eq!(row["worktree"]["branch"], branch.as_str());++ // Every tool of the session resolves to the worktree, not the project.+ let (root, env) = {+ let st = state.lock().await;+ (+ PathBuf::from(resolve_tool_workspace(&st, &session_id).unwrap().unwrap()),+ lifecycle::tool_env(&st.db, &session_id),+ )+ };+ assert!(!canonical(&root).starts_with(canonical(&project)));++ let written = crate::tools::execute_tool_with_path_access(+ Some(&root),+ None,+ "Write",+ &json!({ "path": "f.txt", "content": "isolated\n" }),+ tool_options(None),+ )+ .await;+ assert!(written.ok, "{:?}", written.content);+ assert_eq!(fs::read_to_string(project.join("f.txt")).unwrap(), "base\n");++ // The main checkout is outside the root, so it needs the existing+ // external-path permission; isolation does not weaken containment.+ assert!(requires_external_path_permission(+ Some(&root.to_string_lossy()),+ None,+ "Write",+ &json!({ "path": project.join("f.txt").to_string_lossy() }),+ ));++ let env_map: HashMap<_, _> = env.iter().cloned().collect();+ // Bash runs in the default command shell: PowerShell on Windows.+ let shell_id = crate::tools::shell::default_shell_id();+ let probe = if crate::tools::shell::dialect_for_id(shell_id) == Some("powershell") {+ "(Get-Location).Path; Write-Output $env:PI_PORT"+ } else {+ "pwd; printf %s \"$PI_PORT\""+ };+ let bash = crate::tools::execute_tool_with_path_access(+ Some(&root),+ None,+ "Bash",+ &json!({ "command": probe }),+ tool_options(Some(crate::tools::BashExecutionOptions {+ session_id: session_id.clone(),+ tool_call_id: "t1".into(),+ command_shell_id: shell_id.into(),+ timeout_ms: None,+ cancellation: None,+ output_tx: None,+ extra_env: env,+ })),+ )+ .await;+ assert!(bash.ok, "{:?}", bash.content);+ let stdout = bash.content["stdout"].as_str().unwrap();+ assert!(stdout.contains(&env_map["PI_PORT"]), "{stdout}");+ assert_eq!(+ canonical(Path::new(stdout.lines().next().unwrap().trim())),+ canonical(&root)+ );++ let preview = call(+ &state,+ "worktree.preview",+ json!({ "sessionId": session_id }),+ )+ .await+ .unwrap();+ let files = preview["preview"]["files"].as_array().unwrap();+ assert!(files.iter().any(|file| file["path"] == "f.txt"));+ let token = preview["preview"]["previewToken"]+ .as_str()+ .unwrap()+ .to_string();++ let stale = call(+ &state,+ "worktree.merge",+ json!({ "sessionId": session_id, "previewToken": "stale" }),+ )+ .await+ .unwrap_err();+ assert_eq!(stale["code"], 1025);+ assert_eq!(stale["errorCode"], "WORKTREE_CHANGED_SINCE_PREVIEW");++ let merged = call(+ &state,+ "worktree.merge",+ json!({ "sessionId": session_id, "previewToken": token }),+ )+ .await+ .unwrap();+ assert_eq!(merged["outcome"]["result"], "merged");+ assert_eq!(+ fs::read_to_string(project.join("f.txt")).unwrap(),+ "isolated\n"+ );+ assert!(git_cmd(&project, &["log", "--format=%s", "-1"]).contains("pi: Feature"));++ let moved = call(+ &state,+ "session.moveProject",+ json!({ "sessionId": session_id, "projectPath": dir.path().to_string_lossy() }),+ )+ .await+ .unwrap_err();+ assert_eq!(moved["errorCode"], "WORKTREE_MOVE_UNSUPPORTED");++ let pending = call(+ &state,+ "worktree.pendingWork",+ json!({ "sessionId": session_id }),+ )+ .await+ .unwrap();+ assert_eq!(pending["pending"]["unmergedCommits"], 0);+ assert_eq!(pending["pending"]["uncommittedChanges"], false);++ let deleted = call(&state, "session.delete", json!({ "id": session_id }))+ .await+ .unwrap();+ assert_eq!(deleted["ok"], true);+ assert!(!root.exists());+ assert!(!git_cmd(&project, &["branch", "--list"]).contains(&branch));+}++#[tokio::test]+async fn an_isolated_session_is_not_created_for_a_project_without_git() {+ let dir = tempfile::tempdir().unwrap();+ let plain = dir.path().join("plain");+ fs::create_dir_all(&plain).unwrap();+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));++ let probe = call(&state, "worktree.probe", json!({ "projectPath": plain }))+ .await+ .unwrap();+ assert_eq!(probe["available"], false);+ assert_eq!(probe["errorCode"], "WORKTREE_NOT_GIT");++ let error = call(+ &state,+ "session.create",+ json!({ "projectPath": plain, "isolated": true }),+ )+ .await+ .unwrap_err();+ assert_eq!(error["errorCode"], "WORKTREE_NOT_GIT");+ let listed = call(&state, "session.list", json!({})).await.unwrap();+ assert!(listed["sessions"].as_array().unwrap().is_empty());++ // Without `isolated`, the same project creates an ordinary session.+ let ordinary = call(&state, "session.create", json!({ "projectPath": plain }))+ .await+ .unwrap();+ assert!(ordinary["session"].get("worktree").is_none());+}++/// Through `tools.execute`: an agent Write that resolves the last conflict+/// clears the session's conflict badge in `session.list`.+#[tokio::test]+async fn resolving_a_conflict_through_a_tool_call_clears_the_badge() {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "base\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let project_text = project.to_string_lossy().into_owned();+ call(+ &state,+ "settings.set",+ json!({ "defaultPermissionMode": "auto" }),+ )+ .await+ .unwrap();+ let created = call(+ &state,+ "session.create",+ json!({ "projectPath": project_text, "isolated": true, "mode": "agent" }),+ )+ .await+ .unwrap();+ let session_id = created["session"]["id"].as_str().unwrap().to_string();+ let root = {+ let st = state.lock().await;+ PathBuf::from(resolve_tool_workspace(&st, &session_id).unwrap().unwrap())+ };+ fs::write(root.join("f.txt"), "session\n").unwrap();+ fs::write(project.join("f.txt"), "project\n").unwrap();+ git_cmd(&project, &["commit", "-q", "-am", "project"]);+ let preview = call(+ &state,+ "worktree.preview",+ json!({ "sessionId": session_id }),+ )+ .await+ .unwrap();+ let token = preview["preview"]["previewToken"].clone();+ let refused = call(+ &state,+ "worktree.merge",+ json!({ "sessionId": session_id, "previewToken": token }),+ )+ .await+ .unwrap_err();+ assert_eq!(refused["errorCode"], "WORKTREE_CONFLICT");+ let badge = |listed: &Value| {+ listed["sessions"]+ .as_array()+ .unwrap()+ .iter()+ .find(|session| session["id"] == session_id.as_str())+ .unwrap()["worktree"]["status"]+ .clone()+ };+ assert_eq!(+ badge(&call(&state, "session.list", json!({})).await.unwrap()),+ "conflict"+ );++ let written = call(+ &state,+ "tools.execute",+ json!({+ "sessionId": session_id,+ "toolCallId": "resolve-1",+ "mode": "agent",+ "toolName": "Write",+ "args": { "path": "f.txt", "content": "both\n" },+ }),+ )+ .await+ .unwrap();+ assert_eq!(written["ok"], true, "{written}");+ assert_eq!(+ badge(&call(&state, "session.list", json!({})).await.unwrap()),+ "active"+ );+}++/// `worktree.behind` and `worktree.sync` through the RPC entry point.+#[tokio::test]+async fn sync_from_project_through_rpc() {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "base\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let mut app = AppState::open(&data).unwrap();+ app.handshook = true;+ let state = Arc::new(Mutex::new(app));+ let created = call(+ &state,+ "session.create",+ json!({ "projectPath": project.to_string_lossy(), "isolated": true }),+ )+ .await+ .unwrap();+ let session_id = created["session"]["id"].as_str().unwrap().to_string();+ assert_eq!(behind(&state, &session_id).await, 0);+ fs::write(project.join("g.txt"), "new\n").unwrap();+ git_cmd(&project, &["add", "g.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "g"]);+ assert_eq!(behind(&state, &session_id).await, 1);++ let synced = call(&state, "worktree.sync", json!({ "sessionId": session_id }))+ .await+ .unwrap();+ assert_eq!(+ synced["outcome"],+ json!({ "result": "synced", "commits": 1 })+ );+ let root = {+ let st = state.lock().await;+ PathBuf::from(resolve_tool_workspace(&st, &session_id).unwrap().unwrap())+ };+ assert_eq!(fs::read_to_string(root.join("g.txt")).unwrap(), "new\n");+ let again = call(&state, "worktree.sync", json!({ "sessionId": session_id }))+ .await+ .unwrap();+ assert_eq!(again["outcome"], json!({ "result": "upToDate" }));+}++async fn behind(state: &Arc<Mutex<AppState>>, session_id: &str) -> Value {+ call(state, "worktree.behind", json!({ "sessionId": session_id }))+ .await+ .unwrap()["commits"]+ .clone()+}diff --git a/crates/host-core/src/session_worktrees/delegate.rs b/crates/host-core/src/session_worktrees/delegate.rsnew file mode 100644index 000000000..e36dd53bd--- /dev/null+++ b/crates/host-core/src/session_worktrees/delegate.rs@@ -0,0 +1,447 @@+//! Worktrees for the Write/Edit subagents of an isolated session (ADR 0328,+//! PRD R7/R7a).+//!+//! A delegate worktree branches from the session branch; the session worktree+//! is its owner. When the subagent ends its work is merged back with the same+//! algorithm as "Merge into project" (`merge::land`): conflicts stay in the+//! delegate worktree and the session worktree is only fast-forwarded. The+//! session is held while its worktree changes (`SessionHold`), so the parent's+//! tools do not interleave with the merge; anything git+//! still refuses keeps the subagent branch for a later retry, never forced.+//!+//! The runtime names a delegate by its chain id, so a resumed subagent keeps+//! its worktree (and any conflict it has to resolve).++use std::path::{Path, PathBuf};+use std::time::Duration;++use serde::Serialize;++use super::git::GitRunner;+use super::include::copy_included;+use super::lifecycle::{+ discard_failed_creation, ensure_branch_free, env_for, missing_error, port_is_free, run_setup,+ setup_command, short_id, unmerged_commits, SharedState, WorktreeSummary,+};+use super::merge::{self, commit_all, commits_ahead, land, merge_in_progress};+use super::probe::BRANCH_NAMESPACE;+use super::registry::{self, NewWorktree, SetupStatus, WorktreeRow, WorktreeStatus};+use super::remove::{drop_admin_entry, remove_worktree};+use super::{repo_lock, WorktreeError};+use crate::db::Database;+use crate::sessions;+use crate::tool_budget::{SessionExclusivePermit, ToolPermit};++/// What happened to a subagent's worktree when it ended; reported to the+/// parent agent in the delegate report.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase", tag = "result")]+pub enum DelegateSettlement {+ /// The subagent had no worktree (read-only, or not an isolated session).+ None,+ /// Nothing changed; the worktree and branch were removed.+ NoChanges,+ /// Its commits are now on the session branch; worktree and branch removed.+ Merged { commits: u64 },+ /// A conflict with the session branch stays in the subagent's worktree.+ Conflict { files: Vec<String> },+ /// git refused the fast-forward (or the session was busy); kept for retry.+ NotMerged { reason: String },+ /// The run did not complete; its changes are kept for a resume.+ Kept,+}++/// Tool root of a delegate that has its own worktree; `None` for every other+/// call (no delegation id, or a delegate without a worktree).+pub fn tool_root(+ db: &Database,+ session_id: &str,+ delegation_id: Option<&str>,+) -> Result<Option<PathBuf>, WorktreeError> {+ let Some(delegation_id) = delegation_id else {+ return Ok(None);+ };+ let Some(row) = registry::for_owner(db, session_id, Some(delegation_id))? else {+ return Ok(None);+ };+ let root = row.workspace_root();+ if row.status == WorktreeStatus::Missing || !root.is_dir() {+ return Err(missing_error());+ }+ Ok(Some(root))+}++/// Shell environment of a delegate's own worktree, else the session's.+pub fn tool_env(+ db: &Database,+ session_id: &str,+ delegation_id: Option<&str>,+) -> Vec<(String, String)> {+ let row =+ delegation_id.and_then(|id| registry::for_owner(db, session_id, Some(id)).ok().flatten());+ match row {+ Some(row) => {+ let project = sessions::session_summary(db, session_id)+ .ok()+ .flatten()+ .and_then(|summary| summary.project_path);+ env_for(&row, project.as_deref())+ }+ None => super::lifecycle::tool_env(db, session_id),+ }+}++async fn session_row(state: &SharedState, session_id: &str) -> Result<WorktreeRow, WorktreeError> {+ let st = state.lock().await;+ let row = registry::for_owner(&st.db, session_id, None)?.ok_or_else(|| {+ WorktreeError::new(+ "WORKTREE_NOT_ISOLATED",+ "the session has no isolated worktree",+ )+ })?;+ if row.status == WorktreeStatus::Missing || !Path::new(&row.path).is_dir() {+ return Err(missing_error());+ }+ Ok(row)+}++/// How long a subagent's create/merge waits for the session's in-flight tools+/// before it falls back to holding only the write permit.+const SESSION_QUIET_WAIT: Duration = Duration::from_secs(5);++/// Keeps the session's own tools away from its worktree while held.+enum SessionHold {+ /// No tool of the session runs; new ones wait.+ Exclusive { _permit: SessionExclusivePermit },+ /// A long tool (for example a test run in Bash) kept running: only the+ /// parent's Write/Edit are held back. git refuses what still collides,+ /// which keeps the subagent branch instead of forcing it.+ Writes { _permit: ToolPermit },+}++/// Commit the session worktree's uncommitted work while holding the session+/// (see `SessionHold`), so no tool of the parent lands mid-commit.+async fn checkpoint_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ session: &WorktreeRow,+ message: &str,+) -> Result<SessionHold, WorktreeError> {+ let budget = state.lock().await.tool_budget.clone();+ let hold = match budget+ .acquire_session_exclusive(session_id, SESSION_QUIET_WAIT)+ .await+ {+ Some(permit) => SessionHold::Exclusive { _permit: permit },+ None => {+ let permit = budget.acquire(session_id, "Write").await.map_err(|_| {+ WorktreeError::new(+ "WORKTREE_BUSY",+ "the session is busy writing files; try again",+ )+ })?;+ SessionHold::Writes { _permit: permit }+ }+ };+ let root = Path::new(&session.path);+ if merge_in_progress(git, root).await? {+ return Err(WorktreeError::new(+ "WORKTREE_BUSY",+ "the session has an unfinished merge conflict; resolve it first",+ ));+ }+ commit_all(git, root, message).await?;+ Ok(hold)+}++/// Re-create a vanished delegate worktree on its existing branch so the+/// subagent's committed work survives a resume; `None` when the branch is+/// gone too. The caller holds the repo lock.+async fn reattach(+ state: &SharedState,+ git: &GitRunner,+ session: &WorktreeRow,+ row: WorktreeRow,+) -> Result<Option<WorktreeRow>, WorktreeError> {+ let common_dir = Path::new(&row.common_dir);+ let branch_exists = git+ .run_git_dir(+ common_dir,+ &[+ "show-ref",+ "--verify",+ "--quiet",+ &merge::head_ref(&row.branch),+ ],+ )+ .await+ .is_ok();+ if !branch_exists {+ return Ok(None);+ }+ drop_admin_entry(common_dir, Path::new(&row.path))?;+ git.run(+ Path::new(&session.path),+ &["worktree", "add", "-q", &row.path, &row.branch],+ )+ .await?;+ git.run(+ Path::new(&row.path),+ &[+ "worktree",+ "lock",+ "--reason",+ "PI-Desktop subagent",+ &row.path,+ ],+ )+ .await?;+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ Ok(Some(registry::get(&st.db, &row.id)?.unwrap_or(row)))+}+/// Create (or, for a resumed subagent, reuse) a delegate worktree branched from+/// the session's current state.+pub async fn create_delegate_worktree(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ delegation_id: &str,+) -> Result<WorktreeSummary, WorktreeError> {+ let session = session_row(state, session_id).await?;+ let existing = registry::for_owner(&state.lock().await.db, session_id, Some(delegation_id))?;+ if let Some(row) = existing {+ let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;+ if row.status != WorktreeStatus::Creating {+ if Path::new(&row.path).is_dir() {+ // A re-attach that failed after `worktree add` left the+ // folder back but the row `missing`; the folder decides.+ if row.status == WorktreeStatus::Missing {+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ return Ok(summary(®istry::get(&st.db, &row.id)?.unwrap_or(row)));+ }+ return Ok(summary(&row));+ }+ if let Some(row) = reattach(state, git, &session, row.clone()).await? {+ return Ok(summary(&row));+ }+ }+ remove_worktree(git, &row).await?;+ registry::remove(&state.lock().await.db, &row.id)?;+ }++ let _guard = repo_lock::lock(Path::new(&session.common_dir)).await;+ {+ // The subagent starts from what the parent has written so far.+ let _permit = checkpoint_session(+ state,+ git,+ session_id,+ &session,+ "pi: checkpoint before subagent",+ )+ .await?;+ }++ let name = format!("{}-{}", short_id(session_id), short_id(delegation_id));+ let parent = Path::new(&session.path)+ .parent()+ .ok_or_else(|| WorktreeError::new("WORKTREE_INTERNAL", "session worktree has no parent"))?;+ let root = parent.join(&name);+ if root.exists() {+ return Err(WorktreeError::new(+ "WORKTREE_PATH_EXISTS",+ format!("{} already exists", root.display()),+ ));+ }+ let branch = format!("{BRANCH_NAMESPACE}/{name}");+ ensure_branch_free(git, Path::new(&session.path), &branch).await?;+ let root_text = root.to_string_lossy().into_owned();+ let project_path = sessions::session_summary(&state.lock().await.db, session_id)?+ .and_then(|summary| summary.project_path);++ let row = {+ let st = state.lock().await;+ let port = registry::next_port_base(&st.db, port_is_free)?;+ registry::insert(+ &st.db,+ &NewWorktree {+ session_id,+ delegation_id: Some(delegation_id),+ path: &root_text,+ common_dir: &session.common_dir,+ prefix: &session.prefix,+ branch: &branch,+ owner_branch: &session.branch,+ port_base: port,+ },+ )?+ };++ let session_root = Path::new(&session.path);+ let created: Result<(), WorktreeError> = async {+ git.run(+ session_root,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ &branch,+ &root_text,+ &merge::head_ref(&session.branch),+ ],+ )+ .await?;+ git.run(+ &root,+ &[+ "worktree",+ "lock",+ "--reason",+ &format!("PI-Desktop subagent {delegation_id}"),+ &root_text,+ ],+ )+ .await?;+ if let Some(project) = project_path.as_deref() {+ let toplevel = git+ .run(Path::new(project), &["rev-parse", "--show-toplevel"])+ .await?;+ copy_included(git, Path::new(toplevel.trim()), &root).await?;+ }+ Ok(())+ }+ .await;+ if let Err(error) = created {+ discard_failed_creation(state, git, &row).await;+ return Err(error);+ }++ let (row, command) = {+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ let command = match project_path.as_deref() {+ Some(project) => setup_command(&st.db, project)?,+ None => None,+ };+ let status = if command.is_some() {+ SetupStatus::Running+ } else {+ SetupStatus::None+ };+ registry::set_setup_status(&st.db, &row.id, status, None)?;+ (registry::get(&st.db, &row.id)?.unwrap_or(row), command)+ };+ if let (Some(command), Some(project)) = (command, project_path) {+ tokio::spawn(run_setup(state.clone(), row.clone(), project, command));+ }+ Ok(summary(&row))+}++/// Settle a subagent's worktree when it ends. `merge` is true for a completed+/// run; a failed or stopped run keeps changes for a resume.+pub async fn settle_delegate_worktree(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ delegation_id: &str,+ merge: bool,+) -> Result<DelegateSettlement, WorktreeError> {+ let Some(row) = registry::for_owner(&state.lock().await.db, session_id, Some(delegation_id))?+ else {+ return Ok(DelegateSettlement::None);+ };+ let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;+ let worktree = Path::new(&row.path);+ if !worktree.is_dir() {+ // The folder vanished; its branch may still hold committed work,+ // which a resume re-attaches instead of deleting.+ if unmerged_commits(git, &row).await? > 0 {+ registry::set_status(&state.lock().await.db, &row.id, WorktreeStatus::Missing)?;+ return Ok(DelegateSettlement::Kept);+ }+ drop_row(state, git, &row).await?;+ return Ok(DelegateSettlement::NoChanges);+ }++ let resolving = merge_in_progress(git, worktree).await?;+ if !merge {+ let changed = resolving+ || commits_ahead(git, &row).await? > 0+ || !merge::worktree_status(git, worktree).await?.is_empty();+ if changed {+ return Ok(DelegateSettlement::Kept);+ }+ drop_row(state, git, &row).await?;+ return Ok(DelegateSettlement::NoChanges);+ }++ // An unfinished merge is concluded by `land` once its markers are gone;+ // committing it here could seal unresolved conflict markers.+ if !resolving {+ commit_all(git, worktree, "pi: subagent changes").await?;+ }+ let commits = commits_ahead(git, &row).await?;+ if commits == 0 && !resolving {+ drop_row(state, git, &row).await?;+ return Ok(DelegateSettlement::NoChanges);+ }++ let session = session_row(state, session_id).await?;+ let permit = match checkpoint_session(+ state,+ git,+ session_id,+ &session,+ "pi: checkpoint before merging subagent",+ )+ .await+ {+ Ok(permit) => permit,+ Err(error) => {+ return Ok(DelegateSettlement::NotMerged {+ reason: error.message,+ })+ }+ };+ let landed = land(git, &row, Path::new(&session.path), "pi: subagent changes").await;+ drop(permit);+ match landed {+ Ok(()) => {+ drop_row(state, git, &row).await?;+ Ok(DelegateSettlement::Merged { commits })+ }+ Err(error) if error.code == "WORKTREE_CONFLICT" => {+ registry::set_status(&state.lock().await.db, &row.id, WorktreeStatus::Conflict)?;+ Ok(DelegateSettlement::Conflict { files: error.files })+ }+ Err(error) => Ok(DelegateSettlement::NotMerged {+ reason: error.message,+ }),+ }+}++/// Remove a delegate worktree, branch, and row; the caller holds the repo lock.+async fn drop_row(+ state: &SharedState,+ git: &GitRunner,+ row: &WorktreeRow,+) -> Result<(), WorktreeError> {+ remove_worktree(git, row).await?;+ registry::remove(&state.lock().await.db, &row.id)?;+ Ok(())+}++fn summary(row: &WorktreeRow) -> WorktreeSummary {+ WorktreeSummary {+ branch: row.branch.clone(),+ status: row.status,+ setup_status: row.setup_status,+ }+}++#[cfg(test)]+mod tests;diff --git a/crates/host-core/src/session_worktrees/delegate/tests.rs b/crates/host-core/src/session_worktrees/delegate/tests.rsnew file mode 100644index 000000000..7ed6894b2--- /dev/null+++ b/crates/host-core/src/session_worktrees/delegate/tests.rs@@ -0,0 +1,345 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use tokio::sync::Mutex;++use super::*;+use crate::session_worktrees::lifecycle::{self, create_session_worktree};+use crate::session_worktrees::test_support::{git_cmd, init_repo};+use crate::state::AppState;++struct Env {+ _dir: tempfile::TempDir,+ state: SharedState,+ git: GitRunner,+ project: PathBuf,+ session: String,+ session_root: PathBuf,+}++async fn env() -> Env {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "one\ntwo\nthree\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let state: SharedState = Arc::new(Mutex::new(AppState::open(&data).unwrap()));+ let git = GitRunner::default();+ let session = {+ let st = state.lock().await;+ crate::sessions::create_session_with_options(+ &st.db,+ crate::sessions::SessionCreateOptions {+ title: Some("Isolated".into()),+ mode: None,+ provider_id: None,+ model_id: None,+ project_path: Some(project.to_string_lossy().into_owned()),+ thinking_level: None,+ permission_mode: None,+ },+ )+ .unwrap()+ .id+ };+ create_session_worktree(&state, &git, &session, &project.to_string_lossy())+ .await+ .unwrap();+ let session_root = lifecycle::tool_root(&state.lock().await.db, &session)+ .unwrap()+ .unwrap();+ Env {+ _dir: dir,+ state,+ git,+ project,+ session,+ session_root,+ }+}++impl Env {+ async fn create(&self, delegation: &str) -> PathBuf {+ create_delegate_worktree(&self.state, &self.git, &self.session, delegation)+ .await+ .unwrap();+ tool_root(&self.state.lock().await.db, &self.session, Some(delegation))+ .unwrap()+ .unwrap()+ }++ async fn settle(&self, delegation: &str, merge: bool) -> DelegateSettlement {+ settle_delegate_worktree(&self.state, &self.git, &self.session, delegation, merge)+ .await+ .unwrap()+ }++ async fn row(&self, delegation: &str) -> Option<WorktreeRow> {+ registry::for_owner(&self.state.lock().await.db, &self.session, Some(delegation)).unwrap()+ }++ fn branches(&self) -> String {+ git_cmd(&self.project, &["branch", "--list"])+ }+}++fn read(path: &Path) -> String {+ fs::read_to_string(path).unwrap()+}++/// R7: the subagent starts from the parent's current, uncommitted state, and+/// only calls that name its chain id resolve to its worktree.+#[tokio::test]+async fn a_writing_subagent_starts_from_the_parents_current_files() {+ let env = env().await;+ fs::write(env.session_root.join("parent.txt"), "draft").unwrap();+ let root = env.create("chain-a").await;++ assert_ne!(root, env.session_root);+ assert_eq!(read(&root.join("parent.txt")), "draft");+ assert_eq!(git_cmd(&env.session_root, &["status", "--porcelain"]), "");+ assert!(git_cmd(&env.session_root, &["log", "--format=%s", "-1"])+ .contains("checkpoint before subagent"));++ let st = env.state.lock().await;+ assert_eq!(tool_root(&st.db, &env.session, None).unwrap(), None);+ assert_eq!(+ tool_root(&st.db, &env.session, Some("unknown")).unwrap(),+ None+ );+ let own: std::collections::HashMap<_, _> = tool_env(&st.db, &env.session, Some("chain-a"))+ .into_iter()+ .collect();+ let parent: std::collections::HashMap<_, _> =+ tool_env(&st.db, &env.session, None).into_iter().collect();+ assert_ne!(own["PI_PORT"], parent["PI_PORT"]);+ assert_eq!(PathBuf::from(&own["PI_WORKTREE_ROOT"]), root);+}++/// AC10 + AC11: two writing subagents edit one file in parallel without+/// interfering, and both land on the session branch.+#[tokio::test]+async fn parallel_subagents_merge_back_into_the_session() {+ let env = env().await;+ let a = env.create("chain-a").await;+ let b = env.create("chain-b").await;+ fs::write(a.join("f.txt"), "ONE\ntwo\nthree\n").unwrap();+ fs::write(b.join("f.txt"), "one\ntwo\nTHREE\n").unwrap();+ assert_eq!(read(&a.join("f.txt")), "ONE\ntwo\nthree\n");+ assert_eq!(read(&b.join("f.txt")), "one\ntwo\nTHREE\n");++ assert_eq!(+ env.settle("chain-a", true).await,+ DelegateSettlement::Merged { commits: 1 }+ );+ assert_eq!(+ env.settle("chain-b", true).await,+ DelegateSettlement::Merged { commits: 1 }+ );+ assert_eq!(read(&env.session_root.join("f.txt")), "ONE\ntwo\nTHREE\n");+ assert!(!a.exists() && !b.exists());+ assert!(env.row("chain-a").await.is_none());+ assert!(!env.branches().contains("-chain"), "{}", env.branches());+ assert_eq!(read(&env.project.join("f.txt")), "one\ntwo\nthree\n");+}++/// AC11: a subagent without changes leaves no worktree or branch.+#[tokio::test]+async fn a_subagent_without_changes_leaves_nothing_behind() {+ let env = env().await;+ let root = env.create("chain-a").await;+ let before = env.branches();+ assert_eq!(+ env.settle("chain-a", true).await,+ DelegateSettlement::NoChanges+ );+ assert!(!root.exists());+ assert!(env.row("chain-a").await.is_none());+ assert!(env.branches().lines().count() < before.lines().count());+}++/// AC11: a conflict stays in the subagent worktree; after it is resolved+/// (as a resumed subagent would), the merge is retried and lands.+#[tokio::test]+async fn a_conflict_is_kept_for_the_subagent_and_merges_after_resolution() {+ let env = env().await;+ let a = env.create("chain-a").await;+ let b = env.create("chain-b").await;+ fs::write(a.join("f.txt"), "FROM A\ntwo\nthree\n").unwrap();+ fs::write(b.join("f.txt"), "FROM B\ntwo\nthree\n").unwrap();+ assert_eq!(+ env.settle("chain-a", true).await,+ DelegateSettlement::Merged { commits: 1 }+ );++ assert_eq!(+ env.settle("chain-b", true).await,+ DelegateSettlement::Conflict {+ files: vec!["f.txt".into()]+ }+ );+ assert_eq!(+ env.row("chain-b").await.unwrap().status,+ WorktreeStatus::Conflict+ );+ assert_eq!(+ read(&env.session_root.join("f.txt")),+ "FROM A\ntwo\nthree\n"+ );+ assert!(!env.session_root.join(".git").is_dir());+ assert_eq!(git_cmd(&env.session_root, &["status", "--porcelain"]), "");++ // A resume reuses the same worktree, conflict included.+ assert_eq!(env.create("chain-b").await, b);+ fs::write(b.join("f.txt"), "FROM A AND B\ntwo\nthree\n").unwrap();+ assert!(matches!(+ env.settle("chain-b", true).await,+ DelegateSettlement::Merged { .. }+ ));+ assert_eq!(+ read(&env.session_root.join("f.txt")),+ "FROM A AND B\ntwo\nthree\n"+ );+ assert!(!b.exists());+}++/// A failed or stopped run keeps its work for a resume and is not merged.+#[tokio::test]+async fn an_unfinished_run_keeps_its_changes_unmerged() {+ let env = env().await;+ let a = env.create("chain-a").await;+ fs::write(a.join("new.txt"), "partial").unwrap();+ assert_eq!(env.settle("chain-a", false).await, DelegateSettlement::Kept);+ assert!(a.join("new.txt").exists());+ assert!(!env.session_root.join("new.txt").exists());++ let b = env.create("chain-b").await;+ assert_eq!(+ env.settle("chain-b", false).await,+ DelegateSettlement::NoChanges+ );+ assert!(!b.exists());+ assert_eq!(+ env.settle("never-created", true).await,+ DelegateSettlement::None+ );+}++/// Anything git refuses keeps the subagent branch; nothing is forced.+#[tokio::test]+async fn an_unfinished_session_merge_blocks_without_forcing() {+ let env = env().await;+ let a = env.create("chain-a").await;+ fs::write(a.join("g.txt"), "subagent").unwrap();+ // The session worktree is in the middle of its own conflict resolution.+ git_cmd(&env.project, &["checkout", "-q", "-b", "side"]);+ fs::write(env.project.join("f.txt"), "SIDE\ntwo\nthree\n").unwrap();+ git_cmd(&env.project, &["commit", "-q", "-am", "side"]);+ git_cmd(&env.project, &["checkout", "-q", "main"]);+ fs::write(env.session_root.join("f.txt"), "SESSION\ntwo\nthree\n").unwrap();+ git_cmd(&env.session_root, &["commit", "-q", "-am", "session"]);+ let merged = std::process::Command::new("git")+ .arg("-C")+ .arg(&env.session_root)+ .args(["merge", "side"])+ .output()+ .unwrap();+ assert!(!merged.status.success());++ match env.settle("chain-a", true).await {+ DelegateSettlement::NotMerged { reason } => assert!(reason.contains("merge"), "{reason}"),+ other => panic!("expected NotMerged, got {other:?}"),+ }+ assert!(a.join("g.txt").exists());+ assert!(env.row("chain-a").await.is_some());+ assert!(!env.session_root.join("g.txt").exists());+}++/// A vanished subagent folder keeps its committed branch, and a resume+/// re-attaches it instead of deleting the work.+#[tokio::test]+async fn a_vanished_subagent_folder_keeps_and_reattaches_its_branch() {+ let env = env().await;+ let a = env.create("chain-a").await;+ fs::write(a.join("g.txt"), "committed").unwrap();+ git_cmd(&a, &["add", "g.txt"]);+ git_cmd(&a, &["commit", "-q", "-m", "subagent work"]);+ let branch = env.row("chain-a").await.unwrap().branch;+ crate::session_worktrees::remove::clear_contents(&a).unwrap();+ fs::remove_dir_all(&a).unwrap();++ assert_eq!(env.settle("chain-a", true).await, DelegateSettlement::Kept);+ assert!(env.branches().contains(&branch));++ let resumed = env.create("chain-a").await;+ assert_eq!(read(&resumed.join("g.txt")), "committed");+ assert!(matches!(+ env.settle("chain-a", true).await,+ DelegateSettlement::Merged { .. }+ ));+ assert_eq!(read(&env.session_root.join("g.txt")), "committed");+}++/// A long parent tool (for example a test run in Bash) never blocks the+/// subagent: after a bounded wait it merges holding only the write permit.+#[tokio::test]+async fn a_long_parent_tool_does_not_block_the_merge_back() {+ let env = env().await;+ let a = env.create("chain-a").await;+ fs::write(a.join("g.txt"), "subagent").unwrap();+ let budget = env.state.lock().await.tool_budget.clone();+ let _long_bash = budget.acquire(&env.session, "Bash").await.unwrap();++ assert!(matches!(+ env.settle("chain-a", true).await,+ DelegateSettlement::Merged { .. }+ ));+ assert_eq!(read(&env.session_root.join("g.txt")), "subagent");+}++/// Review follow-ups: a vanished subagent folder still counts toward the+/// delete warning, and a row left `missing` next to an existing folder is+/// usable again.+#[tokio::test]+async fn vanished_subagent_work_is_reported_and_a_restored_folder_is_usable() {+ let env = env().await;+ let a = env.create("chain-a").await;+ fs::write(a.join("g.txt"), "committed").unwrap();+ git_cmd(&a, &["add", "g.txt"]);+ git_cmd(&a, &["commit", "-q", "-m", "subagent work"]);+ crate::session_worktrees::remove::clear_contents(&a).unwrap();+ fs::remove_dir_all(&a).unwrap();+ let pending = lifecycle::pending_work(&env.state, &env.git, &env.session)+ .await+ .unwrap();+ assert!(pending.unmerged_commits >= 1, "{pending:?}");++ // A re-attach that failed after `worktree add` leaves the folder back+ // but the row `missing`.+ let b = env.create("chain-b").await;+ let row = env.row("chain-b").await.unwrap();+ registry::set_status(&env.state.lock().await.db, &row.id, WorktreeStatus::Missing).unwrap();+ assert_eq!(env.create("chain-b").await, b);+ assert_eq!(+ env.row("chain-b").await.unwrap().status,+ WorktreeStatus::Active+ );+}++/// With the owner branch gone, commits a subagent branch shares with the+/// session still count: the subagent branch is deleted with the session.+#[tokio::test]+async fn subagent_branches_do_not_hide_session_work_when_the_owner_is_gone() {+ let env = env().await;+ fs::write(env.session_root.join("f.txt"), "session\n").unwrap();+ git_cmd(&env.session_root, &["commit", "-q", "-am", "session work"]);+ env.create("chain-a").await;+ git_cmd(&env.project, &["branch", "-m", "main", "renamed"]);+ let pending = lifecycle::pending_work(&env.state, &env.git, &env.session)+ .await+ .unwrap();+ assert!(pending.unmerged_commits >= 1, "{pending:?}");+}diff --git a/crates/host-core/src/session_worktrees/git.rs b/crates/host-core/src/session_worktrees/git.rsnew file mode 100644index 000000000..5ac386114--- /dev/null+++ b/crates/host-core/src/session_worktrees/git.rs@@ -0,0 +1,364 @@+//! The only way host-core runs git for isolated worktrees (ADR 0328).+//!+//! Every invocation is non-interactive and hardened, because host-core runs+//! these commands on the user's behalf without a permission card:+//!+//! - hooks are disabled. A relative `core.hooksPath` (husky style) resolves+//! inside the worktree, so a hook file written with Write/Edit alone would+//! otherwise run here and bypass the Bash permission;+//! - `core.fsmonitor` is disabled, since it is a config-defined command;+//! - `safe.bareRepository=explicit` refuses implicitly discovered bare+//! repositories;+//! - variables that redirect git to another repository or index are removed.++use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::time::Duration;++use tokio::process::Command;++#[cfg(windows)]+const NULL_HOOKS_PATH: &str = "NUL";+#[cfg(not(windows))]+const NULL_HOOKS_PATH: &str = "/dev/null";++pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(120);++/// Environment that would point git at another repository, index, or config.+const REDIRECT_ENV: &[&str] = &[+ "GIT_DIR",+ "GIT_WORK_TREE",+ "GIT_INDEX_FILE",+ "GIT_COMMON_DIR",+ "GIT_OBJECT_DIRECTORY",+ "GIT_ALTERNATE_OBJECT_DIRECTORIES",+ "GIT_NAMESPACE",+ "GIT_CEILING_DIRECTORIES",+ "GIT_CONFIG_PARAMETERS",+ "GIT_CONFIG_COUNT",+];++#[derive(Debug, thiserror::Error)]+pub enum GitError {+ #[error("git executable was not found")]+ Missing,+ #[error("git could not be started: {0}")]+ Spawn(std::io::Error),+ #[error("git {args} timed out after {secs}s")]+ Timeout { args: String, secs: u64 },+ #[error("git {args} failed with exit code {status}: {stderr}")]+ Failed {+ args: String,+ status: i32,+ stdout: String,+ stderr: String,+ },+}++impl GitError {+ pub fn code(&self) -> &'static str {+ match self {+ GitError::Missing => "WORKTREE_GIT_MISSING",+ GitError::Spawn(_) | GitError::Failed { .. } => "WORKTREE_GIT_FAILED",+ GitError::Timeout { .. } => "WORKTREE_GIT_TIMEOUT",+ }+ }+}++/// Raw result of a git command that is allowed to exit non-zero.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct GitOutput {+ pub status: i32,+ pub stdout: String,+ pub stderr: String,+}++impl GitOutput {+ pub fn success(&self) -> bool {+ self.status == 0+ }+}++#[derive(Debug, Clone)]+pub struct GitRunner {+ program: PathBuf,+ path_env: Option<String>,+ timeout: Duration,+}++impl Default for GitRunner {+ fn default() -> Self {+ Self {+ program: PathBuf::from("git"),+ // GUI launches lack the terminal PATH; use the login PATH the Bash+ // tool already uses (D181) so the same git is found.+ path_env: crate::tools::shell::user_login_path().map(str::to_string),+ timeout: DEFAULT_TIMEOUT,+ }+ }+}++impl GitRunner {+ #[cfg(test)]+ pub fn with_program(program: impl Into<PathBuf>) -> Self {+ Self {+ program: program.into(),+ ..Self::default()+ }+ }++ /// Run git in `dir` and return stdout; a non-zero exit is an error.+ pub async fn run(&self, dir: &Path, args: &[&str]) -> Result<String, GitError> {+ Self::checked(args, self.output(dir, args).await?)+ }++ /// Run git against an explicit git directory (`--git-dir`), for work that+ /// must not depend on a working tree that may already be gone.+ pub async fn run_git_dir(&self, git_dir: &Path, args: &[&str]) -> Result<String, GitError> {+ Self::checked(+ args,+ self.spawn(self.command(Location::GitDir(git_dir), args), args, None)+ .await?,+ )+ }++ fn checked(args: &[&str], output: GitOutput) -> Result<String, GitError> {+ if output.success() {+ Ok(output.stdout)+ } else {+ Err(GitError::Failed {+ args: args.join(" "),+ status: output.status,+ stdout: output.stdout,+ stderr: output.stderr.trim().to_string(),+ })+ }+ }++ /// Run git in `dir` and return its exit status and output.+ pub async fn output(&self, dir: &Path, args: &[&str]) -> Result<GitOutput, GitError> {+ self.spawn(self.command(Location::WorkTree(dir), args), args, None)+ .await+ }++ /// Like `output`, with `input` written to git's stdin (for `--stdin`).+ pub async fn output_with_input(+ &self,+ dir: &Path,+ args: &[&str],+ input: Vec<u8>,+ ) -> Result<GitOutput, GitError> {+ let mut command = self.command(Location::WorkTree(dir), args);+ command.stdin(Stdio::piped());+ self.spawn(command, args, Some(input)).await+ }++ async fn spawn(+ &self,+ mut command: Command,+ args: &[&str],+ input: Option<Vec<u8>>,+ ) -> Result<GitOutput, GitError> {+ let mut child = command.spawn().map_err(|error| {+ if error.kind() == std::io::ErrorKind::NotFound {+ GitError::Missing+ } else {+ GitError::Spawn(error)+ }+ })?;+ if let (Some(input), Some(mut stdin)) = (input, child.stdin.take()) {+ // Written concurrently with reading output so a large input cannot+ // deadlock against a full output pipe.+ tokio::spawn(async move {+ use tokio::io::AsyncWriteExt;+ let _ = stdin.write_all(&input).await;+ });+ }+ let output = tokio::time::timeout(self.timeout, child.wait_with_output())+ .await+ .map_err(|_| GitError::Timeout {+ args: args.join(" "),+ secs: self.timeout.as_secs(),+ })?+ .map_err(GitError::Spawn)?;+ Ok(GitOutput {+ // A signal-terminated git has no code; report it as a failure.+ status: output.status.code().unwrap_or(-1),+ stdout: String::from_utf8_lossy(&output.stdout).into_owned(),+ stderr: String::from_utf8_lossy(&output.stderr).into_owned(),+ })+ }++ fn command(&self, location: Location<'_>, args: &[&str]) -> Command {+ let mut command = Command::new(&self.program);+ match location {+ Location::WorkTree(dir) => {+ command.arg("-C").arg(dir);+ }+ Location::GitDir(git_dir) => {+ let mut flag = std::ffi::OsString::from("--git-dir=");+ flag.push(git_dir);+ command.arg(flag);+ }+ }+ command.args([+ "-c",+ &format!("core.hooksPath={NULL_HOOKS_PATH}"),+ "-c",+ "core.fsmonitor=false",+ "-c",+ "safe.bareRepository=explicit",+ ]);+ #[cfg(windows)]+ command.args(["-c", "core.longpaths=true"]);+ command.args(args);+ for name in REDIRECT_ENV {+ command.env_remove(name);+ }+ command+ .env("GIT_TERMINAL_PROMPT", "0")+ // Background reads must not take the index lock (git-status(1),+ // "BACKGROUND REFRESH"); required locks are unaffected.+ .env("GIT_OPTIONAL_LOCKS", "0")+ // Stable, parseable messages regardless of the user's locale.+ .env("LC_ALL", "C");+ if let Some(path) = self.path_env.as_deref() {+ command.env("PATH", path);+ }+ command+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ #[cfg(windows)]+ command.creation_flags(0x0800_0000);+ command+ }+}++#[derive(Clone, Copy)]+enum Location<'a> {+ WorkTree(&'a Path),+ GitDir(&'a Path),+}++/// Parse `git version 2.51.0`, `git version 2.39.3 (Apple Git-146)`, or+/// `git version 2.45.1.windows.1` into `(major, minor)`.+pub fn parse_version(text: &str) -> Option<(u32, u32)> {+ let version = text.trim().strip_prefix("git version ")?;+ let mut parts = version.split(|c: char| c == '.' || c.is_whitespace());+ let major = parts.next()?.parse().ok()?;+ let minor = parts.next()?.parse().ok()?;+ Some((major, minor))+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::test_support::init_repo;++ #[test]+ fn parses_release_vendor_and_windows_versions() {+ assert_eq!(parse_version("git version 2.51.0\n"), Some((2, 51)));+ assert_eq!(+ parse_version("git version 2.39.3 (Apple Git-146)"),+ Some((2, 39))+ );+ assert_eq!(parse_version("git version 2.45.1.windows.1"), Some((2, 45)));+ assert_eq!(parse_version("not git"), None);+ }++ #[tokio::test]+ async fn a_missing_executable_is_reported_as_missing() {+ let dir = tempfile::tempdir().unwrap();+ let git = GitRunner::with_program(dir.path().join("no-such-git"));+ let error = git.run(dir.path(), &["--version"]).await.unwrap_err();+ assert_eq!(error.code(), "WORKTREE_GIT_MISSING");+ }++ /// AC13: a hook file the agent could write with Write/Edit alone (a+ /// relative, husky-style `core.hooksPath` inside the worktree) must not run+ /// when host-core commits, checks out, or merges. Git for Windows runs+ /// such a hook through its bundled `sh` without an executable bit.+ #[tokio::test]+ async fn host_initiated_commit_and_merge_never_run_repository_hooks() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(dir.path());+ let git = GitRunner::default();+ git.run(&repo, &["config", "core.hooksPath", ".husky/_"])+ .await+ .unwrap();+ let marker = dir.path().join("hook-ran");+ // `sh` on Windows takes forward slashes.+ let marker_for_sh = marker.display().to_string().replace('\\', "/");+ let hooks = repo.join(".husky/_");+ std::fs::create_dir_all(&hooks).unwrap();+ for hook in [+ "pre-commit",+ "prepare-commit-msg",+ "commit-msg",+ "post-commit",+ "pre-merge-commit",+ "post-merge",+ "post-checkout",+ ] {+ let script = hooks.join(hook);+ std::fs::write(+ &script,+ format!("#!/bin/sh\necho {hook} >> '{marker_for_sh}'\nexit 1\n"),+ )+ .unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ }+ std::fs::write(repo.join("a.txt"), "a").unwrap();+ commit_all_with(&git, &repo, "a").await;+ git.run(&repo, &["checkout", "-q", "-b", "side", "HEAD~1"])+ .await+ .unwrap();+ std::fs::write(repo.join("b.txt"), "b").unwrap();+ commit_all_with(&git, &repo, "b").await;+ git.run(&repo, &["merge", "-q", "--no-edit", "main"])+ .await+ .unwrap();+ assert!(+ !marker.exists(),+ "a repository hook ran during a host git command: {:?}",+ std::fs::read_to_string(&marker).ok()+ );+ }++ async fn commit_all_with(git: &GitRunner, repo: &Path, message: &str) {+ git.run(repo, &["add", "-A", "--", ".", ":!.husky"])+ .await+ .unwrap();+ git.run(repo, &["commit", "-q", "-m", message])+ .await+ .unwrap();+ }++ #[test]+ fn every_command_removes_repository_redirect_variables() {+ let runner = GitRunner::default();+ let command = runner.command(Location::WorkTree(Path::new(".")), &["status"]);+ let envs: Vec<_> = command.as_std().get_envs().collect();+ for name in REDIRECT_ENV {+ assert!(+ envs.iter()+ .any(|(key, value)| *key == std::ffi::OsStr::new(name) && value.is_none()),+ "{name} is not removed"+ );+ }+ let args: Vec<_> = command+ .as_std()+ .get_args()+ .map(|arg| arg.to_string_lossy().into_owned())+ .collect();+ assert!(args.contains(&format!("core.hooksPath={NULL_HOOKS_PATH}")));+ assert!(args.contains(&"core.fsmonitor=false".to_string()));+ assert!(args.contains(&"safe.bareRepository=explicit".to_string()));+ }+}diff --git a/crates/host-core/src/session_worktrees/include.rs b/crates/host-core/src/session_worktrees/include.rsnew file mode 100644index 000000000..3c5d43b76--- /dev/null+++ b/crates/host-core/src/session_worktrees/include.rs@@ -0,0 +1,285 @@+//! Copy ignored local files listed in `.worktreeinclude` into a new worktree+//! (PRD R2c). The format is the one Claude Code and Conductor read: gitignore+//! syntax, and only files that git already ignores are copied, so tracked+//! files are never duplicated and nothing becomes tracked.++use std::collections::BTreeSet;+use std::fs;+use std::path::Path;++use serde::Serialize;++use super::git::GitRunner;+use super::WorktreeError;++pub const INCLUDE_FILE: &str = ".worktreeinclude";++#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct IncludeReport {+ pub copied: Vec<String>,+ /// Matching entries that are symbolic links; never followed or copied.+ pub skipped_links: Vec<String>,+}++/// `toplevel` is the repository top level of the main checkout and+/// `worktree` the new worktree root; relative paths are preserved.+pub async fn copy_included(+ git: &GitRunner,+ toplevel: &Path,+ worktree: &Path,+) -> Result<IncludeReport, WorktreeError> {+ if !toplevel.join(INCLUDE_FILE).is_file() {+ return Ok(IncludeReport::default());+ }+ let listed = git+ .run(+ toplevel,+ &[+ "ls-files",+ "-z",+ "--others",+ "--ignored",+ &format!("--exclude-from={INCLUDE_FILE}"),+ ],+ )+ .await?;+ let candidates: Vec<&str> = listed.split('\0').filter(|path| !path.is_empty()).collect();+ if candidates.is_empty() {+ return Ok(IncludeReport::default());+ }+ let ignored = ignored_by_git(git, toplevel, &candidates).await?;++ let mut report = IncludeReport::default();+ for relative in candidates {+ if !ignored.contains(relative) {+ continue;+ }+ let source = toplevel.join(relative);+ let metadata = match fs::symlink_metadata(&source) {+ Ok(metadata) => metadata,+ Err(_) => continue,+ };+ // Git for Windows lists files inside a junction as ordinary paths, so+ // every component is checked, not only the entry itself.+ if has_link_component(toplevel, relative) {+ report.skipped_links.push(relative.to_string());+ continue;+ }+ if !metadata.is_file() {+ continue;+ }+ let target = worktree.join(relative);+ // The checked-out branch may contain links at these paths; never+ // write through one to a location outside the worktree.+ if has_link_component(worktree, relative) {+ report.skipped_links.push(relative.to_string());+ continue;+ }+ if let Some(parent) = target.parent() {+ fs::create_dir_all(parent)?;+ }+ fs::copy(&source, &target)?;+ report.copied.push(relative.to_string());+ }+ Ok(report)+}++/// Whether `relative` or any of its parent directories inside `root` is a+/// symbolic link (or, on Windows, a junction or other reparse point).+fn has_link_component(root: &Path, relative: &str) -> bool {+ let mut current = root.to_path_buf();+ for component in Path::new(relative).components() {+ current.push(component);+ match fs::symlink_metadata(¤t) {+ Ok(metadata) if is_link(&metadata) => return true,+ Ok(_) => {}+ Err(_) => return false,+ }+ }+ false+}++#[cfg(windows)]+fn is_link(metadata: &fs::Metadata) -> bool {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;+ metadata.file_type().is_symlink()+ || metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0+}++#[cfg(not(windows))]+fn is_link(metadata: &fs::Metadata) -> bool {+ metadata.file_type().is_symlink()+}++/// The subset of `paths` that the repository's standard ignore rules ignore.+async fn ignored_by_git(+ git: &GitRunner,+ toplevel: &Path,+ paths: &[&str],+) -> Result<BTreeSet<String>, WorktreeError> {+ let mut input = Vec::new();+ for path in paths {+ input.extend_from_slice(path.as_bytes());+ input.push(0);+ }+ let output = git+ .output_with_input(toplevel, &["check-ignore", "-z", "--stdin"], input)+ .await?;+ // Exit 1 means "none of these is ignored"; anything else is an error.+ if output.status != 0 && output.status != 1 {+ return Err(WorktreeError::new(+ "WORKTREE_GIT_FAILED",+ format!("git check-ignore failed: {}", output.stderr.trim()),+ ));+ }+ Ok(output+ .stdout+ .split('\0')+ .filter(|path| !path.is_empty())+ .map(str::to_string)+ .collect())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::test_support::{git_cmd, init_repo, link_dir, try_link_file};++ /// AC18: only ignored files that match `.worktreeinclude` are copied.+ #[tokio::test]+ async fn copies_only_ignored_files_that_match_the_include_file() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ fs::write(+ repo.join(".gitignore"),+ ".env\n.env.local\nnode_modules/\ncerts/\n",+ )+ .unwrap();+ fs::write(+ repo.join(INCLUDE_FILE),+ ".env\n.env.local\ncerts/local/**\nconfig.json\nnotes.txt\n",+ )+ .unwrap();+ fs::write(repo.join("config.json"), "{}").unwrap();+ git_cmd(&repo, &["add", ".gitignore", INCLUDE_FILE, "config.json"]);+ git_cmd(&repo, &["commit", "-q", "-m", "rules"]);+ fs::write(repo.join(".env"), "A").unwrap();+ fs::write(repo.join(".env.local"), "B").unwrap();+ fs::create_dir_all(repo.join("certs/local")).unwrap();+ fs::write(repo.join("certs/local/a.pem"), "C").unwrap();+ fs::create_dir_all(repo.join("node_modules/x")).unwrap();+ fs::write(repo.join("node_modules/x/i.js"), "D").unwrap();+ // Untracked but not ignored: listed in the include file, never copied.+ fs::write(repo.join("notes.txt"), "E").unwrap();+ let worktree = dir.path().join("wt");+ fs::create_dir_all(&worktree).unwrap();++ let report = copy_included(&GitRunner::default(), &repo, &worktree)+ .await+ .unwrap();++ let mut copied = report.copied.clone();+ copied.sort();+ assert_eq!(copied, vec![".env", ".env.local", "certs/local/a.pem"]);+ assert_eq!(+ fs::read_to_string(worktree.join("certs/local/a.pem")).unwrap(),+ "C"+ );+ assert!(!worktree.join("config.json").exists());+ assert!(!worktree.join("notes.txt").exists());+ assert!(!worktree.join("node_modules").exists());+ }++ #[tokio::test]+ async fn without_an_include_file_nothing_is_copied() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ fs::write(repo.join(".gitignore"), ".env\n").unwrap();+ fs::write(repo.join(".env"), "A").unwrap();+ let worktree = dir.path().join("wt");+ fs::create_dir_all(&worktree).unwrap();+ let report = copy_included(&GitRunner::default(), &repo, &worktree)+ .await+ .unwrap();+ assert_eq!(report, IncludeReport::default());+ assert!(!worktree.join(".env").exists());+ }++ #[tokio::test]+ async fn symbolic_links_are_reported_and_not_followed() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ fs::write(repo.join(".gitignore"), ".env\n").unwrap();+ fs::write(repo.join(INCLUDE_FILE), ".env\n").unwrap();+ fs::write(dir.path().join("secret"), "S").unwrap();+ if !try_link_file(&dir.path().join("secret"), &repo.join(".env")) {+ return;+ }+ let worktree = dir.path().join("wt");+ fs::create_dir_all(&worktree).unwrap();+ let report = copy_included(&GitRunner::default(), &repo, &worktree)+ .await+ .unwrap();+ assert!(report.copied.is_empty());+ assert_eq!(report.skipped_links, vec![".env"]);+ assert!(!worktree.join(".env").exists());+ }++ /// A linked directory in the project (a junction on Windows) is not+ /// walked, so files outside the project are never copied in. Git for+ /// Windows lists the files inside a junction; git on Unix lists a+ /// symlinked directory as one entry, so this guards the Windows path.+ #[tokio::test]+ async fn a_linked_project_directory_is_not_followed() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ fs::write(repo.join(".gitignore"), "certs\n").unwrap();+ fs::write(repo.join(INCLUDE_FILE), "certs/**\n").unwrap();+ let outside = dir.path().join("outside");+ fs::create_dir_all(&outside).unwrap();+ fs::write(outside.join("a.pem"), "OUTSIDE").unwrap();+ link_dir(&outside, &repo.join("certs"));+ let worktree = dir.path().join("wt");+ fs::create_dir_all(&worktree).unwrap();+ let report = copy_included(&GitRunner::default(), &repo, &worktree)+ .await+ .unwrap();+ assert!(report.copied.is_empty(), "{report:?}");+ assert!(!worktree.join("certs").exists());+ }++ /// A link already in the worktree (for example committed on the branch)+ /// is never written through, even at an included path. On Windows the+ /// directory link is a junction, which only the reparse-point check sees.+ #[tokio::test]+ async fn links_in_the_worktree_are_never_written_through() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ fs::write(repo.join(".gitignore"), ".env\ncerts/\n").unwrap();+ fs::write(repo.join(INCLUDE_FILE), ".env\ncerts/**\n").unwrap();+ fs::write(repo.join(".env"), "SECRET").unwrap();+ fs::create_dir_all(repo.join("certs")).unwrap();+ fs::write(repo.join("certs/a.pem"), "PEM").unwrap();+ let outside = dir.path().join("outside");+ fs::create_dir_all(&outside).unwrap();+ fs::write(outside.join("victim"), "keep").unwrap();+ let worktree = dir.path().join("wt");+ fs::create_dir_all(&worktree).unwrap();+ let file_link = try_link_file(&outside.join("victim"), &worktree.join(".env"));+ link_dir(&outside, &worktree.join("certs"));++ let report = copy_included(&GitRunner::default(), &repo, &worktree)+ .await+ .unwrap();+ let expected: Vec<String> = if file_link {+ Vec::new()+ } else {+ vec![".env".to_string()]+ };+ assert_eq!(report.copied, expected, "{report:?}");+ assert_eq!(fs::read_to_string(outside.join("victim")).unwrap(), "keep");+ assert!(!outside.join("a.pem").exists());+ }+}diff --git a/crates/host-core/src/session_worktrees/lifecycle.rs b/crates/host-core/src/session_worktrees/lifecycle.rsnew file mode 100644index 000000000..eea714e6f--- /dev/null+++ b/crates/host-core/src/session_worktrees/lifecycle.rs@@ -0,0 +1,885 @@+//! Isolated-session worktree lifecycle (ADR 0328): create, resolve, merge,+//! remove, orphan cleanup, and startup reconciliation.+//!+//! The global `AppState` lock is held only for short registry reads and+//! writes, never across a git command or the setup command.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::Arc;++use anyhow::Result;+use rusqlite::params;+use serde::Serialize;+use serde_json::json;+use tokio::sync::Mutex;++use super::git::GitRunner;+use super::include::{copy_included, IncludeReport};+use super::merge::{self, MergeOutcome, MergePreview, SyncOutcome};+use super::probe::{probe, BRANCH_NAMESPACE};+use super::registry::{self, NewWorktree, SetupStatus, WorktreeRow, WorktreeStatus};+use super::remove::remove_worktree;+use super::{fnv1a64, repo_lock, WorktreeError};+use crate::db::Database;+use crate::sessions;+use crate::state::AppState;++pub type SharedState = Arc<Mutex<AppState>>;++/// Bound for the per-project setup command (dependency installs can be slow).+pub const SETUP_TIMEOUT_MS: u64 = 30 * 60 * 1000;+const SETUP_LOG_LIMIT: usize = 16 * 1024;++/// What the renderer needs to badge a session row; no filesystem paths.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct WorktreeSummary {+ pub branch: String,+ pub status: WorktreeStatus,+ pub setup_status: Option<SetupStatus>,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct CreatedWorktree {+ pub worktree: WorktreeSummary,+ pub included: IncludeReport,+ /// The main checkout had uncommitted changes that were not carried over.+ pub project_had_uncommitted_changes: bool,+}++/// Unmerged work that deleting the session would lose (delete confirmation).+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PendingWork {+ pub unmerged_commits: u64,+ pub uncommitted_changes: bool,+}++pub fn worktrees_dir(data_dir: &Path) -> PathBuf {+ data_dir.join("worktrees")+}++/// `<sanitized repository name>-<hash of its canonical path>`: readable, and+/// distinct for two repositories with the same folder name.+fn project_key(toplevel: &Path) -> String {+ let name: String = toplevel+ .file_name()+ .map(|name| name.to_string_lossy().into_owned())+ .unwrap_or_default()+ .chars()+ .map(|c| {+ if c.is_ascii_alphanumeric() || c == '-' || c == '_' {+ c+ } else {+ '-'+ }+ })+ .take(24)+ .collect();+ let hash = fnv1a64(toplevel.to_string_lossy().as_bytes());+ format!(+ "{}-{:08x}",+ if name.is_empty() { "repo" } else { &name },+ hash as u32+ )+}++pub(super) fn short_id(id: &str) -> String {+ id.chars()+ .filter(char::is_ascii_alphanumeric)+ .take(12)+ .collect()+}++pub(super) fn port_is_free(port: u16) -> bool {+ std::net::TcpListener::bind(("127.0.0.1", port)).is_ok()+}++// ---- project setting --------------------------------------------------------++pub fn setup_command(db: &Database, project_path: &str) -> Result<Option<String>> {+ let path =+ crate::db::canonical_project_path(project_path).unwrap_or_else(|| project_path.to_string());+ Ok(db+ .conn()+ .query_row(+ "SELECT worktree_setup_command FROM projects WHERE path = ?1",+ params![path],+ |row| row.get::<_, Option<String>>(0),+ )+ .ok()+ .flatten()+ .filter(|command| !command.trim().is_empty()))+}++/// Returns false when the project is not registered.+pub fn set_setup_command(db: &Database, project_path: &str, command: Option<&str>) -> Result<bool> {+ let path =+ crate::db::canonical_project_path(project_path).unwrap_or_else(|| project_path.to_string());+ let command = command.map(str::trim).filter(|command| !command.is_empty());+ Ok(db.conn().execute(+ "UPDATE projects SET worktree_setup_command = ?2 WHERE path = ?1",+ params![path, command],+ )? > 0)+}++// ---- resolution (sync, called under the AppState lock) ----------------------++fn own_row(db: &Database, session_id: &str) -> Result<Option<WorktreeRow>, WorktreeError> {+ Ok(registry::for_owner(db, session_id, None)?)+}++/// The tool root of an isolated session, or `None` for every other session.+/// An isolated session never falls back to the main checkout.+pub fn tool_root(db: &Database, session_id: &str) -> Result<Option<PathBuf>, WorktreeError> {+ let Some(row) = own_row(db, session_id)? else {+ return Ok(None);+ };+ match row.status {+ WorktreeStatus::Creating => Err(WorktreeError::new(+ "WORKTREE_NOT_READY",+ "the isolated worktree is still being created",+ )),+ WorktreeStatus::Missing => Err(missing_error()),+ _ => {+ let root = row.workspace_root();+ if root.is_dir() {+ Ok(Some(root))+ } else {+ Err(missing_error())+ }+ }+ }+}++pub(super) fn missing_error() -> WorktreeError {+ WorktreeError::new(+ "WORKTREE_MISSING",+ "the isolated worktree folder no longer exists; delete this session",+ )+}++/// `PI_PORT`, `PI_PROJECT_ROOT`, and `PI_WORKTREE_ROOT` for an isolated+/// session's shell commands (PRD R2d); empty for every other session.+pub fn tool_env(db: &Database, session_id: &str) -> Vec<(String, String)> {+ let Ok(Some(row)) = own_row(db, session_id) else {+ return Vec::new();+ };+ let project = sessions::session_summary(db, session_id)+ .ok()+ .flatten()+ .and_then(|summary| summary.project_path);+ env_for(&row, project.as_deref())+}++pub(super) fn env_for(row: &WorktreeRow, project: Option<&str>) -> Vec<(String, String)> {+ let mut env = vec![(+ "PI_WORKTREE_ROOT".to_string(),+ row.workspace_root().to_string_lossy().into_owned(),+ )];+ if let Some(project) = project {+ env.push(("PI_PROJECT_ROOT".to_string(), project.to_string()));+ }+ if let Some(port) = row.port_base {+ env.push(("PI_PORT".to_string(), port.to_string()));+ }+ env+}++/// Badges for the given sessions' own worktrees, keyed by session id.+pub fn summaries(db: &Database) -> Result<HashMap<String, WorktreeSummary>> {+ let mut statement = db.conn().prepare_cached(+ "SELECT session_id, branch, status, setup_status FROM worktrees+ WHERE session_id IS NOT NULL AND delegation_id IS NULL",+ )?;+ let rows = statement+ .query_map([], |row| {+ Ok((+ row.get::<_, String>(0)?,+ row.get::<_, String>(1)?,+ row.get::<_, String>(2)?,+ row.get::<_, Option<String>>(3)?,+ ))+ })?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ let mut out = HashMap::new();+ for (session_id, branch, status, setup) in rows {+ let Some(status) = parse_status(&status) else {+ continue;+ };+ out.insert(+ session_id,+ WorktreeSummary {+ branch,+ status,+ setup_status: setup.as_deref().and_then(parse_setup),+ },+ );+ }+ Ok(out)+}++fn parse_status(value: &str) -> Option<WorktreeStatus> {+ WorktreeStatus::parse(value).ok()+}++fn parse_setup(value: &str) -> Option<SetupStatus> {+ SetupStatus::parse(value).ok()+}++fn summary_of(row: &WorktreeRow) -> WorktreeSummary {+ WorktreeSummary {+ branch: row.branch.clone(),+ status: row.status,+ setup_status: row.setup_status,+ }+}++// ---- create -----------------------------------------------------------------++/// Refuse a branch name that already exists, so cleanup after a failed+/// creation never deletes a branch this call did not create.+pub(super) async fn ensure_branch_free(+ git: &GitRunner,+ repo_dir: &Path,+ branch: &str,+) -> Result<(), WorktreeError> {+ let taken = git+ .output(+ repo_dir,+ &["show-ref", "--verify", "--quiet", &merge::head_ref(branch)],+ )+ .await?+ .success();+ if taken {+ return Err(WorktreeError::new(+ "WORKTREE_PATH_EXISTS",+ format!("branch `{branch}` already exists"),+ ));+ }+ Ok(())+}++/// Undo a failed creation. The row (still `creating`) stays when cleanup+/// fails, so the startup or orphan pass retries it instead of leaving an+/// unrecorded directory and branch behind.+pub(super) async fn discard_failed_creation(+ state: &SharedState,+ git: &GitRunner,+ row: &WorktreeRow,+) {+ match remove_worktree(git, row).await {+ Ok(()) => {+ let st = state.lock().await;+ if let Err(error) = registry::remove(&st.db, &row.id) {+ tracing::warn!(%error, "could not unregister a failed worktree creation");+ }+ }+ Err(error) => {+ tracing::warn!(%error, path = %row.path, "could not clean up a failed worktree creation")+ }+ }+}++/// Create the session's own worktree from the project's current branch tip,+/// copy `.worktreeinclude` files, and start the optional setup command in the+/// background. On failure nothing is left behind.+pub async fn create_session_worktree(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ project_path: &str,+) -> Result<CreatedWorktree, WorktreeError> {+ let project = Path::new(project_path);+ let repo = probe(git, project).await?;+ let project_had_uncommitted_changes = !merge::worktree_status(git, project).await?.is_empty();+ let _guard = repo_lock::lock(&repo.common_dir).await;++ let data_dir = state.lock().await.data_dir.clone();+ let parent = worktrees_dir(&data_dir).join(project_key(&repo.toplevel));+ std::fs::create_dir_all(&parent)?;+ let parent = crate::workspace::simple_canonicalize(&parent)?;+ let name = short_id(session_id);+ let root = parent.join(&name);+ if root.exists() {+ return Err(WorktreeError::new(+ "WORKTREE_PATH_EXISTS",+ format!("{} already exists", root.display()),+ ));+ }+ let branch = format!("{BRANCH_NAMESPACE}/{name}");+ ensure_branch_free(git, project, &branch).await?;+ let root_text = root.to_string_lossy().into_owned();+ let common_dir = repo.common_dir.to_string_lossy().into_owned();++ let row = {+ let st = state.lock().await;+ let port = registry::next_port_base(&st.db, port_is_free)?;+ registry::insert(+ &st.db,+ &NewWorktree {+ session_id,+ delegation_id: None,+ path: &root_text,+ common_dir: &common_dir,+ prefix: &repo.prefix,+ branch: &branch,+ owner_branch: &repo.branch,+ port_base: port,+ },+ )?+ };++ let created: Result<IncludeReport, WorktreeError> = async {+ git.run(+ project,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ &branch,+ &root_text,+ &merge::head_ref(&repo.branch),+ ],+ )+ .await?;+ git.run(+ &root,+ &[+ "worktree",+ "lock",+ "--reason",+ &format!("PI-Desktop session {session_id}"),+ &root_text,+ ],+ )+ .await?;+ copy_included(git, &repo.toplevel, &root).await+ }+ .await;++ let included = match created {+ Ok(included) => included,+ Err(error) => {+ discard_failed_creation(state, git, &row).await;+ return Err(error);+ }+ };++ let (row, command) = {+ let st = state.lock().await;+ registry::set_status(&st.db, &row.id, WorktreeStatus::Active)?;+ let command = setup_command(&st.db, project_path)?;+ let status = if command.is_some() {+ SetupStatus::Running+ } else {+ SetupStatus::None+ };+ registry::set_setup_status(&st.db, &row.id, status, None)?;+ let row = registry::get(&st.db, &row.id)?.unwrap_or(row);+ (row, command)+ };+ if let Some(command) = command {+ tokio::spawn(run_setup(+ state.clone(),+ row.clone(),+ project_path.to_string(),+ command,+ ));+ }+ Ok(CreatedWorktree {+ worktree: summary_of(&row),+ included,+ project_had_uncommitted_changes,+ })+}++pub(super) async fn run_setup(+ state: SharedState,+ row: WorktreeRow,+ project_path: String,+ command: String,+) {+ let shell_id = {+ let st = state.lock().await;+ let configured = st+ .db+ .get_setting("app")+ .ok()+ .flatten()+ .and_then(|settings| {+ settings+ .get("defaultCommandShell")+ .and_then(|value| value.as_str())+ .map(str::to_string)+ });+ crate::tools::shell::catalog(configured.as_deref())+ .effective+ .map(|option| option.id)+ .unwrap_or_else(|| crate::tools::shell::default_shell_id().to_string())+ };+ let root = row.workspace_root();+ let result = crate::tools::execute_tool_with_path_access(+ Some(&root),+ None,+ "Bash",+ &json!({ "command": command }),+ crate::tools::ToolExecutionOptions {+ timeout_ms: Some(SETUP_TIMEOUT_MS),+ bash_options: Some(crate::tools::BashExecutionOptions {+ session_id: row.session_id.clone().unwrap_or_default(),+ tool_call_id: format!("worktree-setup-{}", row.id),+ command_shell_id: shell_id,+ timeout_ms: Some(SETUP_TIMEOUT_MS),+ cancellation: None,+ output_tx: None,+ extra_env: env_for(&row, Some(&project_path)),+ }),+ allow_external_paths: false,+ hashline: None,+ },+ )+ .await;+ let log = setup_log(&result.content);+ let status = if result.ok {+ SetupStatus::Ok+ } else {+ SetupStatus::Failed+ };+ let st = state.lock().await;+ if let Err(error) = registry::set_setup_status(&st.db, &row.id, status, Some(&log)) {+ tracing::warn!(%error, "could not record the worktree setup result");+ }+}++fn setup_log(content: &serde_json::Value) -> String {+ let text = match content {+ serde_json::Value::String(text) => text.clone(),+ value => {+ let stdout = value.get("stdout").and_then(|v| v.as_str()).unwrap_or("");+ let stderr = value.get("stderr").and_then(|v| v.as_str()).unwrap_or("");+ let exit = value+ .get("exitCode")+ .map(|code| code.to_string())+ .unwrap_or_default();+ format!(+ "{stdout}{}{stderr}\n[exit {exit}]",+ if stderr.is_empty() { "" } else { "\n" }+ )+ }+ };+ if text.len() <= SETUP_LOG_LIMIT {+ return text;+ }+ let mut start = text.len() - SETUP_LOG_LIMIT;+ while !text.is_char_boundary(start) {+ start += 1;+ }+ format!("[earlier output omitted]\n{}", &text[start..])+}++// ---- merge ------------------------------------------------------------------++struct MergeTarget {+ row: WorktreeRow,+ project_path: String,+ title: String,+}++async fn merge_target(state: &SharedState, session_id: &str) -> Result<MergeTarget, WorktreeError> {+ let st = state.lock().await;+ let row = own_row(&st.db, session_id)?.ok_or_else(|| {+ WorktreeError::new(+ "WORKTREE_NOT_ISOLATED",+ "the session has no isolated worktree",+ )+ })?;+ if row.status == WorktreeStatus::Missing || !Path::new(&row.path).is_dir() {+ return Err(missing_error());+ }+ let summary = sessions::session_summary(&st.db, session_id)?+ .ok_or_else(|| WorktreeError::new("WORKTREE_NOT_ISOLATED", "session not found"))?;+ let project_path = summary+ .project_path+ .ok_or_else(|| WorktreeError::new("WORKTREE_NOT_ISOLATED", "the session has no project"))?;+ Ok(MergeTarget {+ row,+ project_path,+ title: summary.title,+ })+}++fn ensure_idle(db: &Database, session_id: &str) -> Result<(), WorktreeError> {+ if sessions::session_has_running_turn(db, session_id)? {+ return Err(WorktreeError::new(+ "WORKTREE_BUSY",+ "the session is running; wait for it to finish",+ ));+ }+ Ok(())+}++pub async fn preview_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<MergePreview, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ merge::preview(git, &target.row).await+}++pub async fn merge_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+ preview_token: &str,+) -> Result<MergeOutcome, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ ensure_idle(&state.lock().await.db, session_id)?;+ let _guard = repo_lock::lock(Path::new(&target.row.common_dir)).await;+ let result = merge::merge(+ git,+ &target.row,+ Path::new(&target.project_path),+ &target.title,+ preview_token,+ )+ .await;+ let status = match &result {+ Ok(MergeOutcome::Merged { .. }) => Some(WorktreeStatus::Merged),+ Err(error) if error.code == "WORKTREE_CONFLICT" => Some(WorktreeStatus::Conflict),+ _ => None,+ };+ match status {+ Some(status) => {+ let st = state.lock().await;+ registry::set_status(&st.db, &target.row.id, status)?;+ }+ // A failure after the resolution was concluded (for example a dirty+ // project) must not leave a stale conflict badge.+ None if result.is_err() => {+ refresh_conflict_status(state, git, session_id).await;+ }+ None => {}+ }+ result+}++/// How many project commits "Sync from project" would bring in; for the+/// session menu.+pub async fn behind_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<u64, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ // Opening the menu also picks up a conflict resolved outside the app.+ refresh_conflict_status(state, git, session_id).await;+ merge::commits_behind(git, &target.row).await+}++/// How many sessions `behind_all` checks at once.+const BEHIND_CONCURRENCY: usize = 8;++/// Result of `behind_all`.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct BehindCounts {+ pub counts: HashMap<String, u64>,+ /// A conflict badge was cleared (resolved outside the app), so the+ /// renderer should refresh its session list.+ pub statuses_changed: bool,+}++/// Project commits each isolated session lacks, keyed by session id, for the+/// sidebar's "behind" marker. Sessions whose count cannot be read (missing+/// folder, owner branch gone) are left out. Conflicted sessions are checked+/// for a resolution first. Runs git outside the state lock, a few sessions at+/// a time; the renderer calls it in the background, never while rendering.+pub async fn behind_all(+ state: &SharedState,+ git: &GitRunner,+) -> Result<BehindCounts, WorktreeError> {+ let rows = registry::all(&state.lock().await.db)?;+ let limit = Arc::new(tokio::sync::Semaphore::new(BEHIND_CONCURRENCY));+ let mut tasks = tokio::task::JoinSet::new();+ for row in rows {+ let Some(session_id) = row.session_id.clone() else {+ continue;+ };+ if row.delegation_id.is_some()+ || matches!(+ row.status,+ WorktreeStatus::Missing | WorktreeStatus::Creating+ )+ || !Path::new(&row.path).is_dir()+ {+ continue;+ }+ let (state, git, limit) = (state.clone(), git.clone(), limit.clone());+ tasks.spawn(async move {+ let _slot = limit.acquire_owned().await.ok();+ let cleared = row.status == WorktreeStatus::Conflict+ && refresh_conflict_status(&state, &git, &session_id).await;+ let count = merge::commits_behind(&git, &row).await.ok();+ (session_id, count, cleared)+ });+ }+ let mut result = BehindCounts::default();+ while let Some(joined) = tasks.join_next().await {+ let Ok((session_id, count, cleared)) = joined else {+ continue;+ };+ result.statuses_changed |= cleared;+ if let Some(count) = count {+ result.counts.insert(session_id, count);+ }+ }+ Ok(result)+}++/// "Sync from project" (ADR 0328): merge the project's branch into the+/// session's worktree so the session continues on current code. The project+/// checkout is never touched; a conflict stays in the worktree and marks the+/// session, exactly like a merge into the project.+pub async fn sync_session(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<SyncOutcome, WorktreeError> {+ let target = merge_target(state, session_id).await?;+ ensure_idle(&state.lock().await.db, session_id)?;+ let _guard = repo_lock::lock(Path::new(&target.row.common_dir)).await;+ let result =+ merge::sync_from_owner(git, &target.row, &merge::commit_message(&target.title)).await;+ let status = match &result {+ Ok(_) => WorktreeStatus::Active,+ Err(error) if error.code == "WORKTREE_CONFLICT" => WorktreeStatus::Conflict,+ Err(_) => {+ refresh_conflict_status(state, git, session_id).await;+ return result;+ }+ };+ let st = state.lock().await;+ registry::set_status(&st.db, &target.row.id, status)?;+ result+}++/// After the session's own Write/Edit/Bash call: clear a `conflict` badge+/// once the agent resolved every conflict (the merge itself still concludes+/// on "Merge into project") or abandoned the merge. Cheap for every other+/// session: one registry read, no git. Failures only log; the badge then+/// stays until the next merge attempt.+///+/// Returns whether the status was cleared.+pub async fn refresh_conflict_status(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> bool {+ let row = match registry::for_owner(&state.lock().await.db, session_id, None) {+ Ok(Some(row)) if row.status == WorktreeStatus::Conflict => row,+ Ok(_) => return false,+ Err(error) => {+ tracing::warn!(%error, "could not read the worktree registry");+ return false;+ }+ };+ let root = Path::new(&row.path);+ let settled = async {+ Ok::<bool, WorktreeError>(+ !merge::merge_in_progress(git, root).await?+ || merge::conflicts_resolved(git, root).await?,+ )+ }+ .await;+ match settled {+ Ok(true) => {+ let st = state.lock().await;+ match registry::set_status(&st.db, &row.id, WorktreeStatus::Active) {+ Ok(_) => true,+ Err(error) => {+ tracing::warn!(%error, "could not clear the worktree conflict status");+ false+ }+ }+ }+ Ok(false) => false,+ Err(error) => {+ tracing::warn!(%error, path = %row.path, "could not check worktree conflicts");+ false+ }+ }+}++// ---- remove -----------------------------------------------------------------++/// Commits on `row`'s branch that its owner branch lacks. When the owner+/// branch is gone, counts commits no other local branch has, so the delete+/// confirmation never reports lost work as zero. Runs in the repository, so+/// it also works when the worktree folder vanished.+pub(super) async fn unmerged_commits(+ git: &GitRunner,+ row: &WorktreeRow,+) -> Result<u64, WorktreeError> {+ let common_dir = Path::new(&row.common_dir);+ let branch = merge::head_ref(&row.branch);+ let branch_exists = git+ .run_git_dir(common_dir, &["show-ref", "--verify", "--quiet", &branch])+ .await+ .is_ok();+ if !branch_exists {+ return Ok(0);+ }+ let range = format!("{}..{}", merge::head_ref(&row.owner_branch), branch);+ let count = match git+ .run_git_dir(common_dir, &["rev-list", "--count", &range])+ .await+ {+ Ok(count) => count,+ Err(_) => {+ // Every branch of this session (its own and its subagents') goes+ // away with it, so none of them may count as keeping the work.+ let mut args = vec![+ "rev-list".to_string(),+ "--count".to_string(),+ branch.clone(),+ "--not".to_string(),+ ];+ args.push(format!("--exclude={}", row.branch));+ if let Some(session_id) = row.session_id.as_deref() {+ let session_branch = format!("{BRANCH_NAMESPACE}/{}", short_id(session_id));+ args.push(format!("--exclude={session_branch}"));+ args.push(format!("--exclude={session_branch}-*"));+ }+ args.push("--branches".to_string());+ let args: Vec<&str> = args.iter().map(String::as_str).collect();+ git.run_git_dir(common_dir, &args).await?+ }+ };+ count.trim().parse().map_err(|_| {+ WorktreeError::new(+ "WORKTREE_GIT_FAILED",+ format!("unexpected rev-list output: {}", count.trim()),+ )+ })+}++/// Unmerged commits and uncommitted changes across every worktree of the+/// session, for the delete confirmation.+pub async fn pending_work(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<PendingWork, WorktreeError> {+ let rows = registry::for_session(&state.lock().await.db, session_id)?;+ let mut pending = PendingWork::default();+ for row in rows {+ // Counted from the repository, so a vanished folder whose branch+ // still holds commits is still reported before it is deleted.+ pending.unmerged_commits += unmerged_commits(git, &row).await?;+ let root = Path::new(&row.path);+ if root.is_dir() && !merge::worktree_status(git, root).await?.is_empty() {+ pending.uncommitted_changes = true;+ }+ }+ Ok(pending)+}++/// Remove every worktree and branch of a session (delete = discard, PRD R5).+/// Stops at the first failure so the session and the remaining rows stay.+pub async fn remove_session_worktrees(+ state: &SharedState,+ git: &GitRunner,+ session_id: &str,+) -> Result<(), WorktreeError> {+ let rows = {+ let st = state.lock().await;+ ensure_idle(&st.db, session_id)?;+ registry::for_session(&st.db, session_id)?+ };+ for row in rows.iter().rev() {+ remove_row(state, git, row).await?;+ }+ Ok(())+}++async fn remove_row(+ state: &SharedState,+ git: &GitRunner,+ row: &WorktreeRow,+) -> Result<(), WorktreeError> {+ let _guard = repo_lock::lock(Path::new(&row.common_dir)).await;+ remove_worktree(git, row).await?;+ let st = state.lock().await;+ registry::remove(&st.db, &row.id)?;+ Ok(())+}++/// Remove worktrees whose session was deleted by any path (ON DELETE SET+/// NULL). Returns how many were removed; failures stay for the next pass.+pub async fn cleanup_orphans(state: &SharedState, git: &GitRunner) -> usize {+ let orphans = match registry::orphans(&state.lock().await.db) {+ Ok(rows) => rows,+ Err(error) => {+ tracing::warn!(%error, "could not list orphaned worktrees");+ return 0;+ }+ };+ let mut removed = 0;+ for row in orphans {+ match remove_row(state, git, &row).await {+ Ok(()) => removed += 1,+ Err(error) => {+ tracing::warn!(%error, path = %row.path, "could not remove an orphaned worktree")+ }+ }+ }+ removed+}++/// Startup pass: drop half-created worktrees, mark vanished ones missing,+/// repair git's links after a moved data directory, and clean orphans.+pub async fn reconcile(state: SharedState, git: GitRunner) {+ let rows = match registry::all(&state.lock().await.db) {+ Ok(rows) => rows,+ Err(error) => {+ tracing::warn!(%error, "could not read the worktree registry");+ return;+ }+ };+ for row in rows {+ if row.session_id.is_none() {+ continue;+ }+ if row.status == WorktreeStatus::Creating {+ if let Err(error) = remove_row(&state, &git, &row).await {+ tracing::warn!(%error, path = %row.path, "could not drop a half-created worktree");+ }+ continue;+ }+ let root = Path::new(&row.path);+ if !root.is_dir() {+ let st = state.lock().await;+ let _ = registry::set_status(&st.db, &row.id, WorktreeStatus::Missing);+ continue;+ }+ let common_dir = Path::new(&row.common_dir);+ if common_dir.is_dir() {+ let _guard = repo_lock::lock(common_dir).await;+ if let Err(error) = git+ .run_git_dir(common_dir, &["worktree", "repair", &row.path])+ .await+ {+ tracing::warn!(%error, path = %row.path, "git worktree repair failed");+ }+ }+ }+ cleanup_orphans(&state, &git).await;+}++#[cfg(test)]+mod tests;diff --git a/crates/host-core/src/session_worktrees/lifecycle/tests.rs b/crates/host-core/src/session_worktrees/lifecycle/tests.rsnew file mode 100644index 000000000..7a31a2c1a--- /dev/null+++ b/crates/host-core/src/session_worktrees/lifecycle/tests.rs@@ -0,0 +1,685 @@+use std::fs;+use std::path::{Path, PathBuf};+use std::time::Duration;++use super::*;+use crate::session_worktrees::test_support::{git_cmd, init_repo};++struct Env {+ _dir: tempfile::TempDir,+ state: SharedState,+ git: GitRunner,+ project: PathBuf,+}++fn env() -> Env {+ let dir = tempfile::tempdir().unwrap();+ let project = init_repo(&dir.path().join("project"));+ fs::write(project.join("f.txt"), "base\n").unwrap();+ git_cmd(&project, &["add", "f.txt"]);+ git_cmd(&project, &["commit", "-q", "-m", "f"]);+ let data = dir.path().join("data");+ fs::create_dir_all(&data).unwrap();+ let state = Arc::new(Mutex::new(AppState::open(&data).unwrap()));+ Env {+ _dir: dir,+ state,+ git: GitRunner::default(),+ project,+ }+}++async fn new_session(env: &Env, project: &Path) -> String {+ let st = env.state.lock().await;+ sessions::create_session_with_options(+ &st.db,+ sessions::SessionCreateOptions {+ title: Some("Isolated".into()),+ mode: None,+ provider_id: None,+ model_id: None,+ project_path: Some(project.to_string_lossy().into_owned()),+ thinking_level: None,+ permission_mode: None,+ },+ )+ .unwrap()+ .id+}++async fn isolated(env: &Env) -> (String, CreatedWorktree, PathBuf) {+ isolated_in(env, &env.project.clone()).await+}++async fn isolated_in(env: &Env, project: &Path) -> (String, CreatedWorktree, PathBuf) {+ let session = new_session(env, project).await;+ let created =+ create_session_worktree(&env.state, &env.git, &session, &project.to_string_lossy())+ .await+ .unwrap();+ let root = tool_root(&env.state.lock().await.db, &session)+ .unwrap()+ .unwrap();+ (session, created, root)+}++async fn wait_for_setup(env: &Env, session: &str) -> WorktreeRow {+ for _ in 0..600 {+ let row = registry::for_owner(&env.state.lock().await.db, session, None)+ .unwrap()+ .unwrap();+ if row.setup_status != Some(SetupStatus::Running) {+ return row;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ panic!("setup did not finish");+}++fn canonical(path: &Path) -> PathBuf {+ crate::workspace::simple_canonicalize(path).unwrap()+}++/// AC2: the root lies outside the project, nothing is created inside the+/// project, and the project stays clean.+#[tokio::test]+async fn an_isolated_session_works_outside_an_untouched_project() {+ let env = env();+ let before: Vec<_> = fs::read_dir(&env.project)+ .unwrap()+ .map(|e| e.unwrap().file_name())+ .collect();+ let (session, created, root) = isolated(&env).await;++ assert!(!canonical(&root).starts_with(canonical(&env.project)));+ assert!(root.join("f.txt").is_file());+ assert_eq!(created.worktree.status, WorktreeStatus::Active);+ assert!(created.worktree.branch.starts_with("pi-desktop/"));+ let after: Vec<_> = fs::read_dir(&env.project)+ .unwrap()+ .map(|e| e.unwrap().file_name())+ .collect();+ assert_eq!(before, after);+ assert_eq!(git_cmd(&env.project, &["status", "--porcelain"]), "");+ assert!(git_cmd(&env.project, &["branch", "--list"]).contains(&created.worktree.branch));++ let summary = sessions::session_summary(&env.state.lock().await.db, &session)+ .unwrap()+ .unwrap();+ assert_eq!(summary.worktree.unwrap().branch, created.worktree.branch);+}++/// AC1: two isolated sessions edit the same file without seeing each other.+#[tokio::test]+async fn two_isolated_sessions_edit_the_same_file_independently() {+ let env = env();+ let (_a, _, root_a) = isolated(&env).await;+ let (_b, _, root_b) = isolated(&env).await;+ assert_ne!(root_a, root_b);+ fs::write(root_a.join("f.txt"), "from a\n").unwrap();+ fs::write(root_b.join("f.txt"), "from b\n").unwrap();+ assert_eq!(+ fs::read_to_string(root_a.join("f.txt")).unwrap(),+ "from a\n"+ );+ assert_eq!(+ fs::read_to_string(root_b.join("f.txt")).unwrap(),+ "from b\n"+ );+ assert_eq!(+ fs::read_to_string(env.project.join("f.txt")).unwrap(),+ "base\n"+ );+}++/// AC12: sessions without a worktree resolve exactly as before.+#[tokio::test]+async fn a_regular_session_has_no_worktree_root_or_environment() {+ let env = env();+ let session = new_session(&env, &env.project).await;+ let st = env.state.lock().await;+ assert_eq!(tool_root(&st.db, &session).unwrap(), None);+ assert!(tool_env(&st.db, &session).is_empty());+ assert!(sessions::session_summary(&st.db, &session)+ .unwrap()+ .unwrap()+ .worktree+ .is_none());+}++/// AC4: uncommitted project changes are reported and not carried over.+#[tokio::test]+async fn uncommitted_project_changes_are_not_carried_over() {+ let env = env();+ fs::write(env.project.join("f.txt"), "local edit\n").unwrap();+ fs::write(env.project.join("draft.txt"), "draft").unwrap();+ let (_session, created, root) = isolated(&env).await;+ assert!(created.project_had_uncommitted_changes);+ assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), "base\n");+ assert!(!root.join("draft.txt").exists());+}++/// AC19: distinct port blocks; the variables reach only isolated sessions.+#[tokio::test]+async fn each_worktree_gets_its_own_port_block_and_environment() {+ let env = env();+ let (a, _, root_a) = isolated(&env).await;+ let (b, _, _) = isolated(&env).await;+ let st = env.state.lock().await;+ let env_a: HashMap<_, _> = tool_env(&st.db, &a).into_iter().collect();+ let env_b: HashMap<_, _> = tool_env(&st.db, &b).into_iter().collect();+ let port_a: i64 = env_a["PI_PORT"].parse().unwrap();+ let port_b: i64 = env_b["PI_PORT"].parse().unwrap();+ assert!((port_a - port_b).abs() >= registry::PORT_BLOCK);+ assert_eq!(PathBuf::from(&env_a["PI_WORKTREE_ROOT"]), root_a);+ assert_eq!(+ canonical(Path::new(&env_a["PI_PROJECT_ROOT"])),+ canonical(&env.project)+ );+}++/// The setup command runs in the default command shell, which is PowerShell+/// on Windows and bash elsewhere, so each command is written per dialect.+fn default_shell_is_powershell() -> bool {+ crate::tools::shell::dialect_for_id(crate::tools::shell::default_shell_id())+ == Some("powershell")+}++/// AC3 + AC15: the setup command runs in the new worktree with the project+/// root available; a failure is recorded and the session stays usable.+#[tokio::test]+async fn the_setup_command_runs_once_and_its_failure_does_not_block() {+ let env = env();+ fs::write(env.project.join(".gitignore"), ".env\n").unwrap();+ git_cmd(&env.project, &["add", ".gitignore"]);+ git_cmd(&env.project, &["commit", "-q", "-m", "ignore"]);+ fs::write(env.project.join(".env"), "SECRET=1\n").unwrap();+ {+ let st = env.state.lock().await;+ let session = new_session_blocking(&st.db, &env.project);+ drop(session);+ let command = if default_shell_is_powershell() {+ "Copy-Item \"$env:PI_PROJECT_ROOT/.env\" .env; \+ Set-Content -NoNewline -Path port.txt -Value $env:PI_PORT; \+ Write-Output prepared"+ } else {+ "cp \"$PI_PROJECT_ROOT/.env\" .env && printf %s \"$PI_PORT\" > port.txt && echo prepared"+ };+ assert!(set_setup_command(&st.db, &env.project.to_string_lossy(), Some(command)).unwrap());+ }+ let (session, created, root) = isolated(&env).await;+ assert_eq!(created.worktree.setup_status, Some(SetupStatus::Running));+ let row = wait_for_setup(&env, &session).await;+ assert_eq!(+ row.setup_status,+ Some(SetupStatus::Ok),+ "{:?}",+ row.setup_log+ );+ assert!(row.setup_log.unwrap().contains("prepared"));+ assert_eq!(fs::read_to_string(root.join(".env")).unwrap(), "SECRET=1\n");+ assert_eq!(+ fs::read_to_string(root.join("port.txt")).unwrap(),+ row.port_base.unwrap().to_string()+ );++ {+ let st = env.state.lock().await;+ let failing = if default_shell_is_powershell() {+ "[Console]::Error.WriteLine('broken'); exit 3"+ } else {+ "echo broken >&2; exit 3"+ };+ set_setup_command(&st.db, &env.project.to_string_lossy(), Some(failing)).unwrap();+ }+ let (failing, _, _) = isolated(&env).await;+ let row = wait_for_setup(&env, &failing).await;+ assert_eq!(row.setup_status, Some(SetupStatus::Failed));+ assert!(row.setup_log.unwrap().contains("broken"));+ assert!(tool_root(&env.state.lock().await.db, &failing)+ .unwrap()+ .is_some());++ {+ let st = env.state.lock().await;+ set_setup_command(&st.db, &env.project.to_string_lossy(), None).unwrap();+ }+ let (_quiet, created, _) = isolated(&env).await;+ assert_eq!(created.worktree.setup_status, Some(SetupStatus::None));+}++fn new_session_blocking(db: &Database, project: &Path) -> String {+ sessions::create_session_with_options(+ db,+ sessions::SessionCreateOptions {+ title: None,+ mode: None,+ provider_id: None,+ model_id: None,+ project_path: Some(project.to_string_lossy().into_owned()),+ thinking_level: None,+ permission_mode: None,+ },+ )+ .unwrap()+ .id+}++/// AC20: a project that is a repository subdirectory keeps its scope, and+/// `.worktreeinclude` at the repository top level is honored.+#[tokio::test]+async fn a_subdirectory_project_keeps_its_scope_in_the_worktree() {+ let env = env();+ let app = env.project.join("packages/app");+ fs::create_dir_all(&app).unwrap();+ fs::write(app.join("a.txt"), "app\n").unwrap();+ fs::write(env.project.join(".gitignore"), ".env\n").unwrap();+ fs::write(env.project.join(".worktreeinclude"), ".env\n").unwrap();+ git_cmd(&env.project, &["add", "-A"]);+ git_cmd(&env.project, &["commit", "-q", "-m", "app"]);+ fs::write(env.project.join(".env"), "TOP=1\n").unwrap();++ let (_session, created, root) = isolated_in(&env, &app).await;+ assert!(root.ends_with("packages/app"));+ assert!(root.join("a.txt").is_file());+ assert_eq!(created.included.copied, vec![".env"]);+ assert!(root+ .parent()+ .unwrap()+ .parent()+ .unwrap()+ .join(".env")+ .is_file());+}++/// AC8: deleting removes the worktree and branch; pending work is reported+/// first. AC17: a session deleted by another path leaves no orphan behind.+#[tokio::test]+async fn deletion_removes_worktrees_by_any_path() {+ let env = env();+ let (session, created, root) = isolated(&env).await;+ fs::write(root.join("f.txt"), "edit\n").unwrap();+ git_cmd(&root, &["commit", "-q", "-am", "work"]);+ fs::write(root.join("extra.txt"), "x").unwrap();+ let pending = pending_work(&env.state, &env.git, &session).await.unwrap();+ assert_eq!(pending.unmerged_commits, 1);+ assert!(pending.uncommitted_changes);++ remove_session_worktrees(&env.state, &env.git, &session)+ .await+ .unwrap();+ assert!(!root.exists());+ assert!(!git_cmd(&env.project, &["branch", "--list"]).contains(&created.worktree.branch));+ assert_eq!(+ fs::read_to_string(env.project.join("f.txt")).unwrap(),+ "base\n"+ );++ let (other, other_created, other_root) = isolated(&env).await;+ sessions::delete_session(&env.state.lock().await.db, &other).unwrap();+ assert_eq!(cleanup_orphans(&env.state, &env.git).await, 1);+ assert!(!other_root.exists());+ assert!(!git_cmd(&env.project, &["branch", "--list"]).contains(&other_created.worktree.branch));+ assert!(registry::orphans(&env.state.lock().await.db)+ .unwrap()+ .is_empty());+}++#[tokio::test]+async fn startup_reconcile_drops_partial_rows_and_marks_vanished_worktrees() {+ let env = env();+ let (session, _, root) = isolated(&env).await;+ let partial_session = new_session(&env, &env.project).await;+ let partial_path = env._dir.path().join("partial");+ {+ let st = env.state.lock().await;+ registry::insert(+ &st.db,+ &NewWorktree {+ session_id: &partial_session,+ delegation_id: None,+ path: &partial_path.to_string_lossy(),+ common_dir: &env.project.join(".git").to_string_lossy(),+ prefix: "",+ branch: "pi-desktop/partial",+ owner_branch: "main",+ port_base: None,+ },+ )+ .unwrap();+ }+ git_cmd(+ &env.project,+ &["worktree", "unlock", root.to_str().unwrap()],+ );+ fs::remove_dir_all(&root).unwrap();++ reconcile(env.state.clone(), env.git.clone()).await;++ let st = env.state.lock().await;+ assert!(registry::for_owner(&st.db, &partial_session, None)+ .unwrap()+ .is_none());+ let row = registry::for_owner(&st.db, &session, None)+ .unwrap()+ .unwrap();+ assert_eq!(row.status, WorktreeStatus::Missing);+ assert_eq!(+ tool_root(&st.db, &session).unwrap_err().code,+ "WORKTREE_MISSING"+ );+}++#[tokio::test]+async fn projects_that_cannot_host_a_worktree_leave_nothing_behind() {+ let env = env();+ let plain = env._dir.path().join("plain");+ fs::create_dir_all(&plain).unwrap();+ let session = new_session(&env, &plain).await;+ let error = create_session_worktree(&env.state, &env.git, &session, &plain.to_string_lossy())+ .await+ .unwrap_err();+ assert_eq!(error.code, "WORKTREE_NOT_GIT");+ assert!(registry::for_session(&env.state.lock().await.db, &session)+ .unwrap()+ .is_empty());+}++#[tokio::test]+async fn a_running_session_is_neither_merged_nor_deleted() {+ let env = env();+ let (session, _, _) = isolated(&env).await;+ {+ let st = env.state.lock().await;+ st.db+ .conn()+ .execute(+ "INSERT INTO turns (id, session_id, status, started_at) VALUES ('t1', ?1, 'running', 1)",+ params![session],+ )+ .unwrap();+ }+ assert_eq!(+ remove_session_worktrees(&env.state, &env.git, &session)+ .await+ .unwrap_err()+ .code,+ "WORKTREE_BUSY"+ );+ assert_eq!(+ merge_session(&env.state, &env.git, &session, "token")+ .await+ .unwrap_err()+ .code,+ "WORKTREE_BUSY"+ );+}++/// A pre-existing branch with the session's name is refused, and the failed+/// creation never deletes it.+#[tokio::test]+async fn an_existing_branch_blocks_creation_without_being_deleted() {+ let env = env();+ let session = new_session(&env, &env.project).await;+ let branch = format!("{BRANCH_NAMESPACE}/{}", short_id(&session));+ git_cmd(&env.project, &["branch", &branch]);++ let error = create_session_worktree(+ &env.state,+ &env.git,+ &session,+ &env.project.to_string_lossy(),+ )+ .await+ .unwrap_err();+ assert_eq!(error.code, "WORKTREE_PATH_EXISTS");+ assert!(git_cmd(&env.project, &["branch", "--list"]).contains(&branch));+ assert!(registry::for_session(&env.state.lock().await.db, &session)+ .unwrap()+ .is_empty());+}++/// When the owner branch is gone, unmerged session commits are still+/// reported for the delete confirmation instead of counting as zero.+#[tokio::test]+async fn pending_work_counts_commits_after_the_owner_branch_is_renamed() {+ let env = env();+ let (session, _created, root) = isolated(&env).await;+ fs::write(root.join("f.txt"), "edit\n").unwrap();+ git_cmd(&root, &["commit", "-q", "-am", "work"]);+ git_cmd(&env.project, &["branch", "-m", "main", "renamed"]);++ let pending = pending_work(&env.state, &env.git, &session).await.unwrap();+ assert_eq!(pending.unmerged_commits, 1);+}++/// The conflict badge clears once the agent resolved every conflict or+/// abandoned the merge, not only after the next successful merge.+#[tokio::test]+async fn the_conflict_badge_clears_when_the_conflict_is_resolved() {+ let env = env();+ fs::write(env.project.join("g.txt"), "base\n").unwrap();+ git_cmd(&env.project, &["add", "g.txt"]);+ git_cmd(&env.project, &["commit", "-q", "-m", "g"]);+ let (session, _created, root) = isolated(&env).await;+ for file in ["f.txt", "g.txt"] {+ fs::write(root.join(file), "session\n").unwrap();+ fs::write(env.project.join(file), "project\n").unwrap();+ }+ git_cmd(&env.project, &["commit", "-q", "-am", "project"]);+ let status = |env: &Env| {+ let st = env.state.try_lock().unwrap();+ registry::for_owner(&st.db, &session, None)+ .unwrap()+ .unwrap()+ .status+ };+ let merge_now = || async {+ let token = preview_session(&env.state, &env.git, &session)+ .await+ .unwrap()+ .preview_token;+ merge_session(&env.state, &env.git, &session, &token).await+ };+ assert_eq!(merge_now().await.unwrap_err().code, "WORKTREE_CONFLICT");+ assert_eq!(status(&env), WorktreeStatus::Conflict);++ // Half resolved: still a conflict.+ fs::write(root.join("f.txt"), "both\n").unwrap();+ refresh_conflict_status(&env.state, &env.git, &session).await;+ assert_eq!(status(&env), WorktreeStatus::Conflict);++ fs::write(root.join("g.txt"), "both\n").unwrap();+ refresh_conflict_status(&env.state, &env.git, &session).await;+ assert_eq!(status(&env), WorktreeStatus::Active);+ // The pending resolution still concludes on the next merge.+ assert!(matches!(+ merge_now().await.unwrap(),+ MergeOutcome::Merged { .. }+ ));+ assert_eq!(+ fs::read_to_string(env.project.join("g.txt")).unwrap(),+ "both\n"+ );++ // Abandoning a merge clears the badge too.+ fs::write(root.join("f.txt"), "again\n").unwrap();+ fs::write(env.project.join("f.txt"), "other\n").unwrap();+ git_cmd(&env.project, &["commit", "-q", "-am", "other"]);+ assert_eq!(merge_now().await.unwrap_err().code, "WORKTREE_CONFLICT");+ git_cmd(&root, &["merge", "--abort"]);+ refresh_conflict_status(&env.state, &env.git, &session).await;+ assert_eq!(status(&env), WorktreeStatus::Active);+}++/// The user's scenario: session 1 merges, session 2 merges after resolving a+/// conflict with it. "Sync from project" brings that resolution into session+/// 1, so its later edits on the same line merge without a repeat conflict.+#[tokio::test]+async fn syncing_brings_another_sessions_resolution_into_the_session() {+ let env = env();+ let (one, _c1, root1) = isolated(&env).await;+ let (two, _c2, root2) = isolated(&env).await;+ let merge_now = |session: String| {+ let env = &env;+ async move {+ let token = preview_session(&env.state, &env.git, &session)+ .await+ .unwrap()+ .preview_token;+ merge_session(&env.state, &env.git, &session, &token).await+ }+ };+ fs::write(root1.join("f.txt"), "A\n").unwrap();+ merge_now(one.clone()).await.unwrap();+ fs::write(root2.join("f.txt"), "B\n").unwrap();+ assert_eq!(+ merge_now(two.clone()).await.unwrap_err().code,+ "WORKTREE_CONFLICT"+ );+ fs::write(root2.join("f.txt"), "AB\n").unwrap();+ merge_now(two.clone()).await.unwrap();++ // Session 1 still has its old code and knows it is behind.+ assert_eq!(fs::read_to_string(root1.join("f.txt")).unwrap(), "A\n");+ assert!(behind_session(&env.state, &env.git, &one).await.unwrap() > 0);+ let synced = sync_session(&env.state, &env.git, &one).await.unwrap();+ assert!(matches!(synced, SyncOutcome::Synced { .. }));+ assert_eq!(fs::read_to_string(root1.join("f.txt")).unwrap(), "AB\n");+ assert_eq!(behind_session(&env.state, &env.git, &one).await.unwrap(), 0);+ assert_eq!(+ sync_session(&env.state, &env.git, &one).await.unwrap(),+ SyncOutcome::UpToDate+ );+ // Syncing never touches the project.+ assert_eq!(git_cmd(&env.project, &["status", "--porcelain"]), "");++ fs::write(root1.join("f.txt"), "AB2\n").unwrap();+ assert!(matches!(+ merge_now(one.clone()).await.unwrap(),+ MergeOutcome::Merged { .. }+ ));+ assert_eq!(+ fs::read_to_string(env.project.join("f.txt")).unwrap(),+ "AB2\n"+ );+}++/// A sync conflict stays in the session worktree, marks the session, and+/// leaves the project untouched; resolving it clears the mark.+#[tokio::test]+async fn a_sync_conflict_stays_in_the_session() {+ let env = env();+ let (session, _created, root) = isolated(&env).await;+ fs::write(env.project.join("f.txt"), "project\n").unwrap();+ git_cmd(&env.project, &["commit", "-q", "-am", "project"]);+ fs::write(root.join("f.txt"), "session\n").unwrap();++ let error = sync_session(&env.state, &env.git, &session)+ .await+ .unwrap_err();+ assert_eq!(error.code, "WORKTREE_CONFLICT");+ assert_eq!(error.files, vec!["f.txt"]);+ let status = |env: &Env| {+ let st = env.state.try_lock().unwrap();+ registry::for_owner(&st.db, &session, None)+ .unwrap()+ .unwrap()+ .status+ };+ assert_eq!(status(&env), WorktreeStatus::Conflict);+ assert_eq!(+ fs::read_to_string(env.project.join("f.txt")).unwrap(),+ "project\n"+ );+ assert_eq!(git_cmd(&env.project, &["status", "--porcelain"]), "");++ fs::write(root.join("f.txt"), "both\n").unwrap();+ // Sync again concludes the resolution; nothing else is behind.+ assert_eq!(+ sync_session(&env.state, &env.git, &session).await.unwrap(),+ SyncOutcome::UpToDate+ );+ assert_eq!(status(&env), WorktreeStatus::Active);+ assert_eq!(fs::read_to_string(root.join("f.txt")).unwrap(), "both\n");+}++/// The sidebar marker: after one session merges, the other is behind and the+/// merged one is not; a vanished worktree is left out.+#[tokio::test]+async fn behind_all_counts_what_each_session_lacks() {+ let env = env();+ let (one, _c1, root1) = isolated(&env).await;+ let (two, _c2, _root2) = isolated(&env).await;+ let (gone, _c3, root3) = isolated(&env).await;+ let counts = behind_all(&env.state, &env.git).await.unwrap().counts;+ assert_eq!(counts.get(&one), Some(&0));+ assert_eq!(counts.get(&two), Some(&0));++ fs::write(root1.join("f.txt"), "A\n").unwrap();+ let token = preview_session(&env.state, &env.git, &one)+ .await+ .unwrap()+ .preview_token;+ merge_session(&env.state, &env.git, &one, &token)+ .await+ .unwrap();+ crate::session_worktrees::remove::clear_contents(&root3).unwrap();+ fs::remove_dir_all(&root3).unwrap();++ let counts = behind_all(&env.state, &env.git).await.unwrap().counts;+ assert_eq!(counts.get(&one), Some(&0));+ assert_eq!(counts.get(&two), Some(&1));+ assert!(!counts.contains_key(&gone));+}++/// A merge that concludes the resolution and then fails (dirty project)+/// must not leave a stale conflict badge; a conflict resolved outside the+/// app is picked up by the background behind check.+#[tokio::test]+async fn failed_merges_and_outside_resolutions_do_not_leave_a_stale_badge() {+ let env = env();+ let (session, _created, root) = isolated(&env).await;+ let status = |env: &Env| {+ let st = env.state.try_lock().unwrap();+ registry::for_owner(&st.db, &session, None)+ .unwrap()+ .unwrap()+ .status+ };+ let merge_now = || async {+ let token = preview_session(&env.state, &env.git, &session)+ .await+ .unwrap()+ .preview_token;+ merge_session(&env.state, &env.git, &session, &token).await+ };+ let make_conflict = |line: &str| {+ fs::write(root.join("f.txt"), format!("session {line}\n")).unwrap();+ fs::write(env.project.join("f.txt"), format!("project {line}\n")).unwrap();+ git_cmd(&env.project, &["commit", "-q", "-am", line]);+ };++ make_conflict("1");+ assert_eq!(merge_now().await.unwrap_err().code, "WORKTREE_CONFLICT");+ fs::write(root.join("f.txt"), "both 1\n").unwrap();+ fs::write(env.project.join("f.txt"), "local edit\n").unwrap();+ assert_eq!(+ merge_now().await.unwrap_err().code,+ "WORKTREE_PROJECT_DIRTY"+ );+ assert_eq!(status(&env), WorktreeStatus::Active);+ git_cmd(&env.project, &["checkout", "--", "f.txt"]);+ assert!(matches!(+ merge_now().await.unwrap(),+ MergeOutcome::Merged { .. }+ ));++ make_conflict("2");+ assert_eq!(merge_now().await.unwrap_err().code, "WORKTREE_CONFLICT");+ // Resolved by hand in an editor, without any tool call of the session.+ fs::write(root.join("f.txt"), "both 2\n").unwrap();+ let behind = behind_all(&env.state, &env.git).await.unwrap();+ assert!(behind.statuses_changed);+ assert_eq!(status(&env), WorktreeStatus::Active);+}diff --git a/crates/host-core/src/session_worktrees/merge.rs b/crates/host-core/src/session_worktrees/merge.rsnew file mode 100644index 000000000..fbaf00510--- /dev/null+++ b/crates/host-core/src/session_worktrees/merge.rs@@ -0,0 +1,1003 @@+//! Preview and "Merge into project" (ADR 0328 decision 4, PRD R4).+//!+//! The project never enters a merge-in-progress state: the owner branch is+//! merged into the session branch inside the worktree, where conflicts stay,+//! and the project branch is only fast-forwarded. git itself refuses a+//! fast-forward that would overwrite uncommitted or untracked project files.++use std::collections::BTreeMap;+use std::path::Path;++use serde::Serialize;++use super::git::GitRunner;+use super::registry::WorktreeRow;+use super::{fnv1a64, WorktreeError};++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PreviewCommit {+ pub sha: String,+ pub subject: String,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct PreviewFile {+ /// `A`, `M`, `D`, ... for committed changes; `?` for untracked files.+ pub status: String,+ pub path: String,+ /// Not committed yet; committed on the session branch when merging.+ pub uncommitted: bool,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct MergePreview {+ pub branch: String,+ pub owner_branch: String,+ pub commits: Vec<PreviewCommit>,+ pub files: Vec<PreviewFile>,+ /// True when the worktree holds an unfinished conflict resolution.+ pub conflict: bool,+ /// Opaque; `merge` refuses when the session changed since this preview.+ pub preview_token: String,+}++impl MergePreview {+ pub fn is_empty(&self) -> bool {+ self.commits.is_empty() && self.files.is_empty() && !self.conflict+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase", tag = "result")]+pub enum MergeOutcome {+ Merged { commits: usize, files: usize },+ NothingToMerge,+}++pub async fn preview(git: &GitRunner, row: &WorktreeRow) -> Result<MergePreview, WorktreeError> {+ let worktree = Path::new(&row.path);+ let range = format!("{}..{}", head_ref(&row.owner_branch), head_ref(&row.branch));+ let log = git+ .run(worktree, &["log", "-z", "--format=%H%x1f%s", &range])+ .await?;+ let commits = log+ .split('\0')+ .filter(|record| !record.trim().is_empty())+ .filter_map(|record| {+ let (sha, subject) = record.trim_start_matches('\n').split_once('\u{1f}')?;+ Some(PreviewCommit {+ sha: sha.to_string(),+ subject: subject.to_string(),+ })+ })+ .collect();++ let symmetric = format!(+ "{}...{}",+ head_ref(&row.owner_branch),+ head_ref(&row.branch)+ );+ let diff = git+ .run(+ worktree,+ &["diff", "-z", "--no-renames", "--name-status", &symmetric],+ )+ .await?;+ let mut files: Vec<PreviewFile> = Vec::new();+ let mut fields = diff.split('\0').filter(|field| !field.is_empty());+ while let (Some(status), Some(path)) = (fields.next(), fields.next()) {+ files.push(PreviewFile {+ status: status.chars().take(1).collect(),+ path: path.to_string(),+ uncommitted: false,+ });+ }++ let status = worktree_status(git, worktree).await?;+ for (code, path) in parse_porcelain(&status) {+ let entry = PreviewFile {+ status: code,+ path,+ uncommitted: true,+ };+ match files.iter_mut().find(|file| file.path == entry.path) {+ Some(existing) => *existing = entry,+ None => files.push(entry),+ }+ }+ files.sort_by(|a, b| a.path.cmp(&b.path));++ let conflict = merge_in_progress(git, worktree).await?;+ let head = git.run(worktree, &["rev-parse", "HEAD"]).await?;+ let content = content_fingerprint(git, worktree, &status).await?;+ let token = format!(+ "{:016x}",+ fnv1a64(+ format!(+ "{}\n{}\n{}\n{:016x}",+ head.trim(),+ conflict,+ status,+ content+ )+ .as_bytes()+ )+ );+ Ok(MergePreview {+ branch: row.branch.clone(),+ owner_branch: row.owner_branch.clone(),+ commits,+ files,+ conflict,+ preview_token: token,+ })+}++/// Merge the session branch into the project's current branch. `project` is+/// the project directory (any directory of the main checkout).+pub async fn merge(+ git: &GitRunner,+ row: &WorktreeRow,+ project: &Path,+ title: &str,+ preview_token: &str,+) -> Result<MergeOutcome, WorktreeError> {+ let current = preview(git, row).await?;+ if current.preview_token != preview_token {+ return Err(WorktreeError::new(+ "WORKTREE_CHANGED_SINCE_PREVIEW",+ "the session changed after the preview; review the changes again",+ ));+ }+ if current.is_empty() {+ return Ok(MergeOutcome::NothingToMerge);+ }+ land(git, row, project, &commit_message(title)).await?;+ Ok(MergeOutcome::Merged {+ commits: current.commits.len(),+ files: current.files.len(),+ })+}++/// Land `row`'s branch on its owner branch, which is checked out in+/// `owner_checkout` (the project for a session, the session worktree for a+/// subagent). Uncommitted work is committed with `message` first; the owner+/// branch is merged into `row`'s branch inside its own worktree, where a+/// conflict stays; the owner checkout is only fast-forwarded, and git refuses+/// to overwrite uncommitted files there. Shared by "Merge into project" and+/// the subagent merge-back (ADR 0328).+pub async fn land(+ git: &GitRunner,+ row: &WorktreeRow,+ owner_checkout: &Path,+ message: &str,+) -> Result<(), WorktreeError> {+ let worktree = Path::new(&row.path);+ // Checked before anything is committed, so a refusal changes nothing.+ let checked_out = git+ .output(owner_checkout, &["symbolic-ref", "--quiet", "HEAD"])+ .await?;+ if !checked_out.success() || checked_out.stdout.trim() != head_ref(&row.owner_branch) {+ return Err(WorktreeError::new(+ "WORKTREE_OWNER_BRANCH_CHANGED",+ format!(+ "the target is no longer on `{}`; check that branch out again to merge",+ row.owner_branch+ ),+ ));+ }++ if merge_in_progress(git, worktree).await? {+ conclude_resolved_merge(git, worktree).await?;+ }+ commit_all(git, worktree, message).await?;++ // One retry covers the owner branch moving between the two steps.+ for attempt in 0..2 {+ sync_owner_into_session(git, worktree, &row.owner_branch).await?;+ let forwarded = git+ .output(+ owner_checkout,+ &["merge", "--ff-only", "--no-edit", &head_ref(&row.branch)],+ )+ .await?;+ if forwarded.success() {+ return Ok(());+ }+ let owner_contained = git+ .output(+ owner_checkout,+ &[+ "merge-base",+ "--is-ancestor",+ &head_ref(&row.owner_branch),+ &head_ref(&row.branch),+ ],+ )+ .await?+ .success();+ if owner_contained || attempt == 1 {+ return Err(WorktreeError::new(+ "WORKTREE_PROJECT_DIRTY",+ format!(+ "uncommitted changes in the target would be overwritten: {}",+ forwarded.stderr.trim()+ ),+ ));+ }+ }+ unreachable!("the loop returns on its second attempt")+}++/// Commit every change in `worktree` with `message`; nothing to do when clean.+pub async fn commit_all(+ git: &GitRunner,+ worktree: &Path,+ message: &str,+) -> Result<bool, WorktreeError> {+ if worktree_status(git, worktree).await?.is_empty() {+ return Ok(false);+ }+ git.run(worktree, &["add", "-A"]).await?;+ git.run(worktree, &["commit", "-q", "-m", message])+ .await+ .map_err(|error| WorktreeError::new("WORKTREE_COMMIT_FAILED", error.to_string()))?;+ Ok(true)+}++/// Commits on `row`'s branch that its owner branch does not have yet.+pub async fn commits_ahead(git: &GitRunner, row: &WorktreeRow) -> Result<u64, WorktreeError> {+ let range = format!("{}..{}", head_ref(&row.owner_branch), head_ref(&row.branch));+ let count = git+ .run(Path::new(&row.path), &["rev-list", "--count", &range])+ .await?;+ Ok(count.trim().parse().unwrap_or(0))+}++/// Commits on `row`'s owner branch that its branch does not have yet, that+/// is, what "Sync from project" would bring in.+pub async fn commits_behind(git: &GitRunner, row: &WorktreeRow) -> Result<u64, WorktreeError> {+ let range = format!("{}..{}", head_ref(&row.branch), head_ref(&row.owner_branch));+ let count = git+ .run(Path::new(&row.path), &["rev-list", "--count", &range])+ .await?;+ Ok(count.trim().parse().unwrap_or(0))+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase", tag = "result")]+pub enum SyncOutcome {+ /// The owner branch's new commits are now on the session branch.+ Synced {+ commits: u64,+ },+ UpToDate,+}++/// "Sync from project": bring the owner branch's new commits into `row`'s+/// branch without touching the owner checkout. Uncommitted session work is+/// committed with `message` first; a conflict stays in the worktree, and an+/// unfinished resolution is concluded first (the same rules as `land`).+pub async fn sync_from_owner(+ git: &GitRunner,+ row: &WorktreeRow,+ message: &str,+) -> Result<SyncOutcome, WorktreeError> {+ let worktree = Path::new(&row.path);+ if merge_in_progress(git, worktree).await? {+ conclude_resolved_merge(git, worktree).await?;+ }+ let behind = commits_behind(git, row).await?;+ if behind == 0 {+ return Ok(SyncOutcome::UpToDate);+ }+ commit_all(git, worktree, message).await?;+ sync_owner_into_session(git, worktree, &row.owner_branch).await?;+ Ok(SyncOutcome::Synced { commits: behind })+}++/// Merge the owner branch into the session branch inside the worktree. A+/// conflict stays in the worktree and is reported with its files.+async fn sync_owner_into_session(+ git: &GitRunner,+ worktree: &Path,+ owner_branch: &str,+) -> Result<(), WorktreeError> {+ let merged = git+ .output(worktree, &["merge", "--no-edit", &head_ref(owner_branch)])+ .await?;+ if merged.success() {+ return Ok(());+ }+ let files = unmerged_files(git, worktree).await?;+ if !files.is_empty() {+ return Err(WorktreeError::conflict(files));+ }+ // Not a content conflict (for example an untracked file in the way):+ // leave the worktree as it was.+ let _ = git.output(worktree, &["merge", "--abort"]).await;+ Err(WorktreeError::new(+ "WORKTREE_MERGE_FAILED",+ merged.stderr.trim().to_string(),+ ))+}++/// Finish a merge whose conflicts were resolved in the worktree. Text files+/// the agent edited but did not `git add` count as resolved once they no+/// longer contain conflict markers (see `resolved_by_edit`).+async fn conclude_resolved_merge(git: &GitRunner, worktree: &Path) -> Result<(), WorktreeError> {+ let stages = conflict_stages(git, worktree).await?;+ let mut unresolved = Vec::new();+ for file in unmerged_files(git, worktree).await? {+ let file_stages = stages.get(&file).map(Vec::as_slice).unwrap_or(&[]);+ if resolved_by_edit(git, worktree, &file, file_stages).await? {+ git.run(worktree, &["add", "--", &file]).await?;+ } else {+ unresolved.push(file);+ }+ }+ if !unresolved.is_empty() {+ return Err(WorktreeError::conflict(unresolved));+ }+ git.run(worktree, &["add", "-A"]).await?;+ git.run(worktree, &["commit", "-q", "--no-edit"])+ .await+ .map_err(|error| WorktreeError::new("WORKTREE_COMMIT_FAILED", error.to_string()))?;+ Ok(())+}++/// Whether every conflict of an unfinished merge in `worktree` is resolved,+/// by the same rule `land` uses to conclude it (`resolved_by_edit`).+pub async fn conflicts_resolved(git: &GitRunner, worktree: &Path) -> Result<bool, WorktreeError> {+ let stages = conflict_stages(git, worktree).await?;+ for file in unmerged_files(git, worktree).await? {+ let file_stages = stages.get(&file).map(Vec::as_slice).unwrap_or(&[]);+ if !resolved_by_edit(git, worktree, &file, file_stages).await? {+ return Ok(false);+ }+ }+ Ok(true)+}++pub async fn unmerged_files(+ git: &GitRunner,+ worktree: &Path,+) -> Result<Vec<String>, WorktreeError> {+ let output = git+ .run(worktree, &["diff", "-z", "--name-only", "--diff-filter=U"])+ .await?;+ let mut files: Vec<String> = output+ .split('\0')+ .filter(|file| !file.is_empty())+ .map(str::to_string)+ .collect();+ files.dedup();+ Ok(files)+}++pub async fn merge_in_progress(git: &GitRunner, worktree: &Path) -> Result<bool, WorktreeError> {+ Ok(git+ .output(worktree, &["rev-parse", "-q", "--verify", "MERGE_HEAD"])+ .await?+ .success())+}++pub async fn worktree_status(git: &GitRunner, worktree: &Path) -> Result<String, WorktreeError> {+ Ok(git+ .run(+ worktree,+ &["status", "--porcelain=v1", "-z", "--untracked-files=all"],+ )+ .await?)+}++/// `XY path\0` entries; renames and copies carry the source as an extra field.+fn parse_porcelain(status: &str) -> Vec<(String, String)> {+ let mut entries = Vec::new();+ let mut fields = status.split('\0').filter(|field| !field.is_empty());+ while let Some(field) = fields.next() {+ if field.len() < 4 {+ continue;+ }+ let (code, path) = field.split_at(3);+ let code = code.trim();+ if code.contains('R') || code.contains('C') {+ fields.next();+ }+ let short = if code == "??" {+ "?".to_string()+ } else {+ code.chars().find(|c| *c != ' ').unwrap_or('M').to_string()+ };+ entries.push((short, path.to_string()));+ }+ entries+}++/// Default length of git's conflict markers (`conflict-marker-size`).+const MARKER_SIZE: usize = 7;++fn has_conflict_markers(content: &[u8], size: usize) -> bool {+ let text = String::from_utf8_lossy(content);+ let is_marker = |line: &str, mark: char| {+ let run = line.chars().take_while(|c| *c == mark).count();+ run == size && matches!(line[run..].chars().next(), None | Some(' ') | Some('\r'))+ };+ text.lines()+ .any(|line| is_marker(line, '<') || is_marker(line, '>'))+}++/// How git merged `path`: whether it writes conflict markers (the default+/// text driver) and with which marker length. `merge=binary`, `-merge`, and+/// custom drivers leave one side in the file without markers.+async fn marker_rules(+ git: &GitRunner,+ worktree: &Path,+ path: &str,+) -> Result<Option<usize>, WorktreeError> {+ let output = git+ .run(+ worktree,+ &[+ "check-attr",+ "-z",+ "merge",+ "conflict-marker-size",+ "--",+ path,+ ],+ )+ .await?;+ let fields: Vec<&str> = output.split('\0').collect();+ let mut merge = "unspecified";+ let mut size = MARKER_SIZE;+ for entry in fields.chunks(3) {+ if let [_, attribute, value] = entry {+ match *attribute {+ "merge" => merge = value,+ "conflict-marker-size" => {+ if let Ok(parsed) = value.parse::<usize>() {+ if parsed > 0 {+ size = parsed;+ }+ }+ }+ _ => {}+ }+ }+ }+ Ok(matches!(merge, "unspecified" | "set" | "text").then_some(size))+}++/// Full ref of a local branch, so a tag with the same short name is never+/// picked instead (git resolves `refs/tags/<name>` before `refs/heads/`).+pub fn head_ref(branch: &str) -> String {+ format!("refs/heads/{branch}")+}++/// Conflict stages (1 base, 2 ours, 3 theirs) of each unmerged path.+async fn conflict_stages(+ git: &GitRunner,+ worktree: &Path,+) -> Result<BTreeMap<String, Vec<char>>, WorktreeError> {+ let output = git.run(worktree, &["ls-files", "-u", "-z"]).await?;+ let mut stages: BTreeMap<String, Vec<char>> = BTreeMap::new();+ for record in output.split('\0').filter(|record| !record.is_empty()) {+ // `<mode> <object> <stage>\t<path>`+ let Some((meta, path)) = record.split_once('\t') else {+ continue;+ };+ if let Some(stage) = meta.rsplit(' ').next().and_then(|s| s.chars().next()) {+ stages.entry(path.to_string()).or_default().push(stage);+ }+ }+ Ok(stages)+}++/// Whether an unstaged conflicted file may be treated as resolved: only a+/// text file changed on both sides and merged by git's text driver, which+/// fills it with conflict markers, once those markers are gone. Binary,+/// delete/modify, add/delete, and `merge=binary` / `-merge` / custom-driver+/// conflicts leave no markers, so they need an explicit `git add`/`git rm`.+async fn resolved_by_edit(+ git: &GitRunner,+ worktree: &Path,+ path: &str,+ stages: &[char],+) -> Result<bool, WorktreeError> {+ if !(stages.contains(&'2') && stages.contains(&'3')) {+ return Ok(false);+ }+ let file = worktree.join(path);+ match std::fs::symlink_metadata(&file) {+ Ok(metadata) if metadata.is_file() => {}+ _ => return Ok(false),+ }+ let Some(size) = marker_rules(git, worktree, path).await? else {+ return Ok(false);+ };+ Ok(match std::fs::read(&file) {+ Ok(content) => !content.contains(&0) && !has_conflict_markers(&content, size),+ Err(_) => false,+ })+}++/// Hash of the worktree's uncommitted content: the tracked diff against+/// `HEAD` plus every untracked file, so a re-edit that leaves `git status`+/// unchanged still invalidates a preview.+async fn content_fingerprint(+ git: &GitRunner,+ worktree: &Path,+ status: &str,+) -> Result<u64, WorktreeError> {+ let diff = git+ .run(+ worktree,+ &["diff", "HEAD", "--binary", "--no-ext-diff", "--no-textconv"],+ )+ .await?;+ let untracked: Vec<String> = parse_porcelain(status)+ .into_iter()+ .filter(|(code, _)| code == "?")+ .map(|(_, path)| path)+ .collect();+ let worktree = worktree.to_path_buf();+ // File reads block, so they run off the async workers.+ tokio::task::spawn_blocking(move || {+ let mut hash = fnv1a64(diff.as_bytes());+ for path in untracked {+ hash = fnv_extend(hash, path.as_bytes());+ hash = fnv_extend(hash, &[0]);+ hash = untracked_entry_hash(hash, &worktree.join(&path));+ }+ hash+ })+ .await+ .map_err(|error| WorktreeError::new("WORKTREE_INTERNAL", error.to_string()))+}++/// Bytes of one untracked file read into a preview token. Larger files add+/// their size and modification time instead, so a huge file cannot stall the+/// host; the agent cannot change one without changing either.+const FINGERPRINT_FILE_LIMIT: u64 = 16 * 1024 * 1024;++fn fnv_extend(mut hash: u64, bytes: &[u8]) -> u64 {+ for byte in bytes {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);+ }+ hash+}++/// Never follows a link and never opens anything but a regular file, so a+/// link to `/dev/zero` or a FIFO cannot hang or exhaust the host.+fn untracked_entry_hash(hash: u64, path: &Path) -> u64 {+ use std::io::Read;+ let Ok(metadata) = std::fs::symlink_metadata(path) else {+ return fnv_extend(hash, b"missing");+ };+ if metadata.file_type().is_symlink() {+ let target = std::fs::read_link(path).unwrap_or_default();+ return fnv_extend(+ fnv_extend(hash, b"link:"),+ target.to_string_lossy().as_bytes(),+ );+ }+ if !metadata.is_file() {+ return fnv_extend(hash, b"special");+ }+ let modified = metadata+ .modified()+ .ok()+ .and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())+ .map_or(0, |duration| duration.as_nanos());+ let hash = fnv_extend(hash, &metadata.len().to_le_bytes());+ if metadata.len() > FINGERPRINT_FILE_LIMIT {+ return fnv_extend(hash, &modified.to_le_bytes());+ }+ let Ok(file) = std::fs::File::open(path) else {+ return fnv_extend(hash, b"unreadable");+ };+ let mut reader = file.take(FINGERPRINT_FILE_LIMIT);+ let mut buffer = [0u8; 64 * 1024];+ let mut hash = hash;+ loop {+ match reader.read(&mut buffer) {+ Ok(0) | Err(_) => break hash,+ Ok(read) => hash = fnv_extend(hash, &buffer[..read]),+ }+ }+}++pub fn commit_message(title: &str) -> String {+ let title = title.trim();+ if title.is_empty() {+ "pi: session changes".to_string()+ } else {+ format!("pi: {}", title.chars().take(72).collect::<String>())+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::registry::WorktreeStatus;+ use crate::session_worktrees::test_support::{git_cmd, init_repo};+ use std::fs;++ struct Fixture {+ _dir: tempfile::TempDir,+ repo: std::path::PathBuf,+ row: WorktreeRow,+ }++ fn fixture(lines: &str) -> Fixture {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ fs::write(repo.join("f.txt"), lines).unwrap();+ git_cmd(&repo, &["add", "f.txt"]);+ git_cmd(&repo, &["commit", "-q", "-m", "f"]);+ let worktree = dir.path().join("wt");+ git_cmd(+ &repo,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ "pi-desktop/s1",+ worktree.to_str().unwrap(),+ "main",+ ],+ );+ let row = WorktreeRow {+ id: "w".into(),+ session_id: Some("s".into()),+ delegation_id: None,+ path: worktree.to_string_lossy().into_owned(),+ common_dir: repo.join(".git").to_string_lossy().into_owned(),+ prefix: String::new(),+ branch: "pi-desktop/s1".into(),+ owner_branch: "main".into(),+ status: WorktreeStatus::Active,+ setup_status: None,+ setup_log: None,+ port_base: None,+ created_at: 0,+ updated_at: 0,+ };+ Fixture {+ _dir: dir,+ repo,+ row,+ }+ }++ fn wt(f: &Fixture) -> &Path {+ Path::new(&f.row.path)+ }++ async fn merge_now(f: &Fixture) -> Result<MergeOutcome, WorktreeError> {+ let git = GitRunner::default();+ let token = preview(&git, &f.row).await.unwrap().preview_token;+ merge(&git, &f.row, &f.repo, "Session title", &token).await+ }++ /// AC5 + AC5a: the preview lists committed and uncommitted work, and the+ /// merge lands every session commit on the project branch.+ #[tokio::test]+ async fn preview_then_merge_lands_session_commits_and_uncommitted_work() {+ let f = fixture("a\nb\n");+ fs::write(wt(&f).join("f.txt"), "A\nb\n").unwrap();+ git_cmd(wt(&f), &["commit", "-q", "-am", "edit f"]);+ fs::write(wt(&f).join("new.txt"), "n").unwrap();++ let git = GitRunner::default();+ let preview = preview(&git, &f.row).await.unwrap();+ assert_eq!(preview.commits.len(), 1);+ assert_eq!(preview.commits[0].subject, "edit f");+ let summary: Vec<_> = preview+ .files+ .iter()+ .map(|file| (file.status.as_str(), file.path.as_str(), file.uncommitted))+ .collect();+ assert_eq!(summary, vec![("M", "f.txt", false), ("?", "new.txt", true)]);++ let outcome = merge(+ &git,+ &f.row,+ &f.repo,+ "Session title",+ &preview.preview_token,+ )+ .await+ .unwrap();+ assert_eq!(+ outcome,+ MergeOutcome::Merged {+ commits: 1,+ files: 2+ }+ );+ assert_eq!(fs::read_to_string(f.repo.join("f.txt")).unwrap(), "A\nb\n");+ assert_eq!(fs::read_to_string(f.repo.join("new.txt")).unwrap(), "n");+ let log = git_cmd(&f.repo, &["log", "--format=%s", "-3"]);+ assert!(+ log.contains("edit f") && log.contains("pi: Session title"),+ "{log}"+ );+ assert_eq!(git_cmd(&f.repo, &["status", "--porcelain"]), "");+ }++ #[tokio::test]+ async fn a_change_after_the_preview_stops_the_merge() {+ let f = fixture("a\n");+ fs::write(wt(&f).join("f.txt"), "A\n").unwrap();+ let git = GitRunner::default();+ let token = preview(&git, &f.row).await.unwrap().preview_token;+ fs::write(wt(&f).join("later.txt"), "x").unwrap();+ let error = merge(&git, &f.row, &f.repo, "t", &token).await.unwrap_err();+ assert_eq!(error.code, "WORKTREE_CHANGED_SINCE_PREVIEW");+ assert_eq!(fs::read_to_string(f.repo.join("f.txt")).unwrap(), "a\n");+ }++ /// AC6: the conflict stays in the worktree; the project never has+ /// MERGE_HEAD; a second merge after resolution succeeds, including a+ /// resolution that was edited but not staged.+ #[tokio::test]+ async fn conflicts_stay_in_the_worktree_and_resolve_on_retry() {+ let f = fixture("a\nb\n");+ fs::write(wt(&f).join("f.txt"), "SESSION\nb\n").unwrap();+ git_cmd(wt(&f), &["commit", "-q", "-am", "session"]);+ fs::write(f.repo.join("f.txt"), "PROJECT\nb\n").unwrap();+ git_cmd(&f.repo, &["commit", "-q", "-am", "project"]);++ let error = merge_now(&f).await.unwrap_err();+ assert_eq!(error.code, "WORKTREE_CONFLICT");+ assert_eq!(error.files, vec!["f.txt"]);+ assert!(!f.repo.join(".git/MERGE_HEAD").exists());+ assert_eq!(git_cmd(&f.repo, &["status", "--porcelain"]), "");+ assert_eq!(+ fs::read_to_string(f.repo.join("f.txt")).unwrap(),+ "PROJECT\nb\n"+ );++ // Still unresolved: a second click reports the same conflict.+ assert_eq!(merge_now(&f).await.unwrap_err().code, "WORKTREE_CONFLICT");++ // The agent edits the file without staging it.+ fs::write(wt(&f).join("f.txt"), "BOTH\nb\n").unwrap();+ assert!(matches!(+ merge_now(&f).await.unwrap(),+ MergeOutcome::Merged { .. }+ ));+ assert_eq!(+ fs::read_to_string(f.repo.join("f.txt")).unwrap(),+ "BOTH\nb\n"+ );+ }++ /// AC7: overlapping uncommitted or untracked project files refuse the+ /// merge and leave both checkouts unchanged; unrelated dirty files stay.+ #[tokio::test]+ async fn dirty_project_files_refuse_the_merge_without_changes() {+ let f = fixture("a\n");+ fs::write(wt(&f).join("f.txt"), "A\n").unwrap();+ fs::write(wt(&f).join("n.txt"), "session").unwrap();+ git_cmd(wt(&f), &["add", "-A"]);+ git_cmd(wt(&f), &["commit", "-q", "-m", "s"]);++ fs::write(f.repo.join("f.txt"), "local edit\n").unwrap();+ let error = merge_now(&f).await.unwrap_err();+ assert_eq!(error.code, "WORKTREE_PROJECT_DIRTY");+ assert_eq!(+ fs::read_to_string(f.repo.join("f.txt")).unwrap(),+ "local edit\n"+ );+ git_cmd(&f.repo, &["checkout", "--", "f.txt"]);++ fs::write(f.repo.join("n.txt"), "mine").unwrap();+ assert_eq!(+ merge_now(&f).await.unwrap_err().code,+ "WORKTREE_PROJECT_DIRTY"+ );+ assert_eq!(fs::read_to_string(f.repo.join("n.txt")).unwrap(), "mine");+ fs::remove_file(f.repo.join("n.txt")).unwrap();++ fs::write(f.repo.join("README.md"), "unrelated\n").unwrap();+ assert!(matches!(+ merge_now(&f).await.unwrap(),+ MergeOutcome::Merged { .. }+ ));+ assert_eq!(+ fs::read_to_string(f.repo.join("README.md")).unwrap(),+ "unrelated\n"+ );+ assert_eq!(fs::read_to_string(f.repo.join("f.txt")).unwrap(), "A\n");+ }++ #[tokio::test]+ async fn switching_the_project_branch_blocks_the_merge() {+ let f = fixture("a\n");+ fs::write(wt(&f).join("f.txt"), "A\n").unwrap();+ git_cmd(&f.repo, &["checkout", "-q", "-b", "other"]);+ assert_eq!(+ merge_now(&f).await.unwrap_err().code,+ "WORKTREE_OWNER_BRANCH_CHANGED"+ );+ assert_eq!(fs::read_to_string(f.repo.join("f.txt")).unwrap(), "a\n");+ // The refusal did not commit the session's work either.+ assert_eq!(git_cmd(wt(&f), &["status", "--porcelain"]), " M f.txt\n");+ }++ #[tokio::test]+ async fn an_unchanged_session_has_nothing_to_merge() {+ let f = fixture("a\n");+ assert_eq!(merge_now(&f).await.unwrap(), MergeOutcome::NothingToMerge);+ }++ /// A re-edit that leaves `git status` unchanged still invalidates the+ /// preview, so the merge never lands content the user did not review.+ #[tokio::test]+ async fn re_editing_a_modified_file_after_the_preview_stops_the_merge() {+ let f = fixture("a\n");+ fs::write(wt(&f).join("f.txt"), "A\n").unwrap();+ fs::write(wt(&f).join("new.txt"), "one").unwrap();+ let git = GitRunner::default();+ let token = preview(&git, &f.row).await.unwrap().preview_token;+ fs::write(wt(&f).join("f.txt"), "unreviewed\n").unwrap();+ let error = merge(&git, &f.row, &f.repo, "t", &token).await.unwrap_err();+ assert_eq!(error.code, "WORKTREE_CHANGED_SINCE_PREVIEW");++ let token = preview(&git, &f.row).await.unwrap().preview_token;+ fs::write(wt(&f).join("new.txt"), "two").unwrap();+ let error = merge(&git, &f.row, &f.repo, "t", &token).await.unwrap_err();+ assert_eq!(error.code, "WORKTREE_CHANGED_SINCE_PREVIEW");+ assert_eq!(fs::read_to_string(f.repo.join("f.txt")).unwrap(), "a\n");+ }++ /// Binary and modify/delete conflicts leave no markers; a retry must not+ /// silently take the session's side, only an explicit `git add`/`git rm`.+ #[tokio::test]+ async fn markerless_conflicts_stay_unresolved_until_staged() {+ let f = fixture("a\n");+ fs::write(f.repo.join("bin.dat"), b"\0base").unwrap();+ git_cmd(&f.repo, &["add", "bin.dat"]);+ git_cmd(&f.repo, &["commit", "-q", "-m", "bin"]);+ git_cmd(wt(&f), &["merge", "-q", "main"]);++ fs::write(wt(&f).join("bin.dat"), b"\0session").unwrap();+ fs::remove_file(wt(&f).join("f.txt")).unwrap();+ git_cmd(wt(&f), &["commit", "-q", "-am", "session"]);+ fs::write(f.repo.join("bin.dat"), b"\0project").unwrap();+ fs::write(f.repo.join("f.txt"), "project\n").unwrap();+ git_cmd(&f.repo, &["commit", "-q", "-am", "project"]);++ let error = merge_now(&f).await.unwrap_err();+ assert_eq!(error.code, "WORKTREE_CONFLICT");+ let error = merge_now(&f).await.unwrap_err();+ assert_eq!(error.code, "WORKTREE_CONFLICT");+ assert_eq!(error.files, vec!["bin.dat", "f.txt"]);+ assert_eq!(+ fs::read(f.repo.join("bin.dat")).unwrap(),+ b"\0project".to_vec()+ );++ git_cmd(wt(&f), &["add", "bin.dat"]);+ git_cmd(wt(&f), &["rm", "-q", "f.txt"]);+ assert!(matches!(+ merge_now(&f).await.unwrap(),+ MergeOutcome::Merged { .. }+ ));+ assert!(!f.repo.join("f.txt").exists());+ }++ /// Conflicts git resolves without markers by attribute (`merge=binary`,+ /// for example lock files) and custom marker sizes are not mistaken for+ /// resolved edits.+ #[tokio::test]+ async fn attribute_driven_conflicts_need_an_explicit_add() {+ for attributes in ["f.txt merge=binary\n", "f.txt conflict-marker-size=10\n"] {+ let f = fixture("a\n");+ fs::write(f.repo.join(".gitattributes"), attributes).unwrap();+ git_cmd(&f.repo, &["add", ".gitattributes"]);+ git_cmd(&f.repo, &["commit", "-q", "-m", "attributes"]);+ git_cmd(wt(&f), &["merge", "-q", "main"]);+ fs::write(wt(&f).join("f.txt"), "SESSION\n").unwrap();+ git_cmd(wt(&f), &["commit", "-q", "-am", "session"]);+ fs::write(f.repo.join("f.txt"), "PROJECT\n").unwrap();+ git_cmd(&f.repo, &["commit", "-q", "-am", "project"]);++ assert_eq!(+ merge_now(&f).await.unwrap_err().code,+ "WORKTREE_CONFLICT",+ "{attributes}"+ );+ // A retry must not take the session's side silently.+ assert_eq!(+ merge_now(&f).await.unwrap_err().code,+ "WORKTREE_CONFLICT",+ "{attributes}"+ );+ assert!(!conflicts_resolved(&GitRunner::default(), wt(&f))+ .await+ .unwrap());+ assert_eq!(+ fs::read_to_string(f.repo.join("f.txt")).unwrap(),+ "PROJECT\n"+ );++ fs::write(wt(&f).join("f.txt"), "BOTH\n").unwrap();+ git_cmd(wt(&f), &["add", "f.txt"]);+ assert!(matches!(+ merge_now(&f).await.unwrap(),+ MergeOutcome::Merged { .. }+ ));+ assert_eq!(fs::read_to_string(f.repo.join("f.txt")).unwrap(), "BOTH\n");+ }+ }++ /// A preview never follows an untracked link or opens a special file, so+ /// a link to `/dev/zero` or a FIFO cannot hang the host.+ #[cfg(unix)]+ #[tokio::test]+ async fn previews_do_not_read_through_links_or_special_files() {+ let f = fixture("a\n");+ std::os::unix::fs::symlink("/dev/zero", wt(&f).join("zero")).unwrap();+ let status = std::process::Command::new("mkfifo")+ .arg(wt(&f).join("pipe"))+ .status()+ .unwrap();+ assert!(status.success());+ let git = GitRunner::default();+ let first = tokio::time::timeout(std::time::Duration::from_secs(20), preview(&git, &f.row))+ .await+ .expect("preview must not block")+ .unwrap();+ // The link target is part of the token: retargeting it invalidates it.+ fs::remove_file(wt(&f).join("zero")).unwrap();+ std::os::unix::fs::symlink("/dev/null", wt(&f).join("zero")).unwrap();+ let second = preview(&git, &f.row).await.unwrap();+ assert_ne!(first.preview_token, second.preview_token);+ }++ /// A tag named like the owner branch does not redirect the merge.+ #[tokio::test]+ async fn a_tag_named_like_the_owner_branch_is_ignored() {+ let f = fixture("a\n");+ git_cmd(&f.repo, &["tag", "main"]);+ fs::write(f.repo.join("later.txt"), "later\n").unwrap();+ git_cmd(&f.repo, &["add", "later.txt"]);+ git_cmd(&f.repo, &["commit", "-q", "-m", "later"]);+ fs::write(wt(&f).join("f.txt"), "A\n").unwrap();++ let git = GitRunner::default();+ let preview = preview(&git, &f.row).await.unwrap();+ assert_eq!(preview.files.len(), 1, "{:?}", preview.files);+ assert!(matches!(+ merge_now(&f).await.unwrap(),+ MergeOutcome::Merged { .. }+ ));+ assert_eq!(+ fs::read_to_string(f.repo.join("later.txt")).unwrap(),+ "later\n"+ );+ assert_eq!(fs::read_to_string(f.repo.join("f.txt")).unwrap(), "A\n");+ }++ #[test]+ fn porcelain_entries_keep_rename_targets_and_mark_untracked() {+ let parsed = parse_porcelain("R new.txt\0old.txt\0?? x.txt\0 M y.txt\0");+ assert_eq!(+ parsed,+ vec![+ ("R".to_string(), "new.txt".to_string()),+ ("?".to_string(), "x.txt".to_string()),+ ("M".to_string(), "y.txt".to_string()),+ ]+ );+ }+}diff --git a/crates/host-core/src/session_worktrees/mod.rs b/crates/host-core/src/session_worktrees/mod.rsnew file mode 100644index 000000000..92cdbaddd--- /dev/null+++ b/crates/host-core/src/session_worktrees/mod.rs@@ -0,0 +1,90 @@+//! Git worktrees for isolated sessions and their Write/Edit delegates+//! (ADR 0328). host-core owns every worktree path and every git command; the+//! renderer and the agent runtime only name a session or delegation.++pub mod delegate;+pub mod git;+pub mod include;+pub mod lifecycle;+pub mod merge;+pub mod probe;+pub mod registry;+pub mod remove;+mod repo_lock;++#[cfg(test)]+pub(crate) mod test_support;++use git::GitError;+use probe::ProbeError;++/// A failure that reaches the RPC surface with a stable `WORKTREE_*` code.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct WorktreeError {+ pub code: &'static str,+ pub message: String,+ /// Conflicting files for `WORKTREE_CONFLICT`; empty otherwise.+ pub files: Vec<String>,+}++impl WorktreeError {+ pub fn new(code: &'static str, message: impl Into<String>) -> Self {+ Self {+ code,+ message: message.into(),+ files: Vec::new(),+ }+ }++ pub fn conflict(files: Vec<String>) -> Self {+ Self {+ code: "WORKTREE_CONFLICT",+ message: format!(+ "merge conflict in {} file(s); resolve them in the session and merge again",+ files.len()+ ),+ files,+ }+ }+}++impl std::fmt::Display for WorktreeError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}: {}", self.code, self.message)+ }+}++impl From<GitError> for WorktreeError {+ fn from(error: GitError) -> Self {+ Self::new(error.code(), error.to_string())+ }+}++impl From<ProbeError> for WorktreeError {+ fn from(error: ProbeError) -> Self {+ Self::new(error.code(), error.to_string())+ }+}++impl From<anyhow::Error> for WorktreeError {+ fn from(error: anyhow::Error) -> Self {+ Self::new("WORKTREE_INTERNAL", error.to_string())+ }+}++impl From<std::io::Error> for WorktreeError {+ fn from(error: std::io::Error) -> Self {+ Self::new("WORKTREE_IO", error.to_string())+ }+}++/// FNV-1a: a stable hash for directory names and preview tokens. The std+/// hasher is not stable across Rust releases, and these values persist.+pub(crate) fn fnv1a64(bytes: &[u8]) -> u64 {+ let mut hash: u64 = 0xcbf2_9ce4_8422_2325;+ for byte in bytes {+ hash ^= u64::from(*byte);+ hash = hash.wrapping_mul(0x0000_0100_0000_01b3);+ }+ hash+}diff --git a/crates/host-core/src/session_worktrees/probe.rs b/crates/host-core/src/session_worktrees/probe.rsnew file mode 100644index 000000000..943f93473--- /dev/null+++ b/crates/host-core/src/session_worktrees/probe.rs@@ -0,0 +1,191 @@+//! Decide whether a project can host isolated sessions, and where its+//! repository lives (ADR 0328, PRD R6).++use std::path::{Path, PathBuf};++use serde::Serialize;++use super::git::{parse_version, GitError, GitRunner};++/// `git worktree repair` (used after a project or data directory moves) was+/// added in git 2.29.0.+pub const MIN_GIT_VERSION: (u32, u32) = (2, 29);++/// Every branch host-core creates lives under this namespace.+pub const BRANCH_NAMESPACE: &str = "pi-desktop";++/// Where an isolatable project lives inside its repository.+#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct RepoInfo {+ /// Canonical repository top level (`git rev-parse --show-toplevel`).+ pub toplevel: PathBuf,+ /// Project directory relative to `toplevel`, `/`-separated with a+ /// trailing slash, empty when the project is the top level.+ pub prefix: String,+ /// Canonical common git directory; the key for per-repository+ /// serialization of mutating git commands.+ pub common_dir: PathBuf,+ /// Branch currently checked out in the project.+ pub branch: String,+}++#[derive(Debug, thiserror::Error)]+pub enum ProbeError {+ #[error("git {found_major}.{found_minor} is older than the required 2.29")]+ GitTooOld { found_major: u32, found_minor: u32 },+ #[error("the project is not inside a git working tree")]+ NotGit,+ #[error("the repository has no commits yet")]+ NoCommits,+ #[error("the project is on a detached HEAD; check out a branch first")]+ DetachedHead,+ #[error("a branch named `pi-desktop` exists, so `pi-desktop/...` branches cannot be created")]+ BranchNamespaceTaken,+ #[error(transparent)]+ Git(#[from] GitError),+}++impl ProbeError {+ pub fn code(&self) -> &'static str {+ match self {+ ProbeError::GitTooOld { .. } => "WORKTREE_GIT_TOO_OLD",+ ProbeError::NotGit => "WORKTREE_NOT_GIT",+ ProbeError::NoCommits => "WORKTREE_NO_COMMITS",+ ProbeError::DetachedHead => "WORKTREE_DETACHED_HEAD",+ ProbeError::BranchNamespaceTaken => "WORKTREE_BRANCH_NAMESPACE_TAKEN",+ ProbeError::Git(error) => error.code(),+ }+ }+}++pub async fn probe(git: &GitRunner, project: &Path) -> Result<RepoInfo, ProbeError> {+ let version = git.run(project, &["--version"]).await?;+ if let Some((major, minor)) = parse_version(&version) {+ if (major, minor) < MIN_GIT_VERSION {+ return Err(ProbeError::GitTooOld {+ found_major: major,+ found_minor: minor,+ });+ }+ }++ let inside = git+ .output(project, &["rev-parse", "--is-inside-work-tree"])+ .await?;+ if !inside.success() || inside.stdout.trim() != "true" {+ return Err(ProbeError::NotGit);+ }++ let has_commit = git+ .output(+ project,+ &["rev-parse", "--verify", "--quiet", "HEAD^{commit}"],+ )+ .await?;+ if !has_commit.success() {+ return Err(ProbeError::NoCommits);+ }++ // The full ref, not `--short`: that prints `heads/<name>` when a tag+ // shares the branch's name.+ let head = git+ .output(project, &["symbolic-ref", "--quiet", "HEAD"])+ .await?;+ let branch = match head.stdout.trim().strip_prefix("refs/heads/") {+ Some(branch) if head.success() => branch.to_string(),+ _ => return Err(ProbeError::DetachedHead),+ };++ let namespace = git+ .output(+ project,+ &[+ "show-ref",+ "--verify",+ "--quiet",+ &format!("refs/heads/{BRANCH_NAMESPACE}"),+ ],+ )+ .await?;+ if namespace.success() {+ return Err(ProbeError::BranchNamespaceTaken);+ }++ let toplevel = git.run(project, &["rev-parse", "--show-toplevel"]).await?;+ let prefix = git.run(project, &["rev-parse", "--show-prefix"]).await?;+ let common_dir = git.run(project, &["rev-parse", "--git-common-dir"]).await?;+ Ok(RepoInfo {+ toplevel: canonical(Path::new(toplevel.trim())),+ prefix: prefix.trim().to_string(),+ // Relative from a subdirectory (for example `../../.git`); git 2.29+ // has no `--path-format=absolute`, so resolve it here.+ common_dir: canonical(&project.join(common_dir.trim())),+ branch,+ })+}++fn canonical(path: &Path) -> PathBuf {+ crate::workspace::simple_canonicalize(path).unwrap_or_else(|_| path.to_path_buf())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::test_support::{git_cmd, init_repo};++ async fn probe_code(path: &Path) -> &'static str {+ probe(&GitRunner::default(), path)+ .await+ .map(|_| "OK")+ .unwrap_or_else(|error| error.code())+ }++ #[tokio::test]+ async fn rejects_projects_that_cannot_host_a_worktree() {+ let dir = tempfile::tempdir().unwrap();+ let plain = dir.path().join("plain");+ std::fs::create_dir_all(&plain).unwrap();+ assert_eq!(probe_code(&plain).await, "WORKTREE_NOT_GIT");++ let empty = dir.path().join("empty");+ std::fs::create_dir_all(&empty).unwrap();+ git_cmd(&empty, &["init", "-q", "-b", "main"]);+ assert_eq!(probe_code(&empty).await, "WORKTREE_NO_COMMITS");++ let detached = init_repo(&dir.path().join("detached"));+ git_cmd(&detached, &["checkout", "-q", "--detach"]);+ assert_eq!(probe_code(&detached).await, "WORKTREE_DETACHED_HEAD");++ let taken = init_repo(&dir.path().join("taken"));+ git_cmd(&taken, &["branch", "pi-desktop"]);+ assert_eq!(probe_code(&taken).await, "WORKTREE_BRANCH_NAMESPACE_TAKEN");+ }++ #[tokio::test]+ async fn reports_root_prefix_branch_and_absolute_common_dir() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ let info = probe(&GitRunner::default(), &repo).await.unwrap();+ assert_eq!(info.toplevel, canonical(&repo));+ assert_eq!(info.prefix, "");+ assert_eq!(info.branch, "main");+ assert_eq!(info.common_dir, canonical(&repo.join(".git")));+ }++ /// AC20 / design §15 F1–F3: a project that is a monorepo subdirectory.+ #[tokio::test]+ async fn a_repository_subdirectory_reports_its_prefix_and_shared_common_dir() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("mono"));+ let app = repo.join("packages/app");+ std::fs::create_dir_all(&app).unwrap();+ std::fs::write(app.join("a.txt"), "a").unwrap();+ git_cmd(&repo, &["add", "-A"]);+ git_cmd(&repo, &["commit", "-q", "-m", "app"]);+ let info = probe(&GitRunner::default(), &app).await.unwrap();+ assert_eq!(info.toplevel, canonical(&repo));+ assert_eq!(info.prefix, "packages/app/");+ assert_eq!(info.common_dir, canonical(&repo.join(".git")));+ }+}diff --git a/crates/host-core/src/session_worktrees/registry.rs b/crates/host-core/src/session_worktrees/registry.rsnew file mode 100644index 000000000..126118877--- /dev/null+++ b/crates/host-core/src/session_worktrees/registry.rs@@ -0,0 +1,377 @@+//! Rows of the `worktrees` table (schema v24, ADR 0328).++use anyhow::{anyhow, Result};+use rusqlite::{params, OptionalExtension, Row};+use serde::Serialize;++use crate::db::{now_ms, Database};++/// Each worktree owns `PORT_BLOCK` consecutive ports starting at its base.+pub const PORT_BLOCK: i64 = 10;+pub const PORT_RANGE_START: i64 = 41_000;+/// Base of the last block; the range ends at `PORT_RANGE_LAST_BASE + 9`.+pub const PORT_RANGE_LAST_BASE: i64 = 48_990;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum WorktreeStatus {+ Creating,+ Active,+ Conflict,+ Merged,+ Missing,+}++impl WorktreeStatus {+ pub fn as_str(self) -> &'static str {+ match self {+ WorktreeStatus::Creating => "creating",+ WorktreeStatus::Active => "active",+ WorktreeStatus::Conflict => "conflict",+ WorktreeStatus::Merged => "merged",+ WorktreeStatus::Missing => "missing",+ }+ }++ pub(crate) fn parse(value: &str) -> Result<Self> {+ Ok(match value {+ "creating" => WorktreeStatus::Creating,+ "active" => WorktreeStatus::Active,+ "conflict" => WorktreeStatus::Conflict,+ "merged" => WorktreeStatus::Merged,+ "missing" => WorktreeStatus::Missing,+ other => return Err(anyhow!("unknown worktree status {other}")),+ })+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, serde::Deserialize)]+#[serde(rename_all = "camelCase")]+pub enum SetupStatus {+ None,+ Running,+ Ok,+ Failed,+}++impl SetupStatus {+ pub fn as_str(self) -> &'static str {+ match self {+ SetupStatus::None => "none",+ SetupStatus::Running => "running",+ SetupStatus::Ok => "ok",+ SetupStatus::Failed => "failed",+ }+ }++ pub(crate) fn parse(value: &str) -> Result<Self> {+ Ok(match value {+ "none" => SetupStatus::None,+ "running" => SetupStatus::Running,+ "ok" => SetupStatus::Ok,+ "failed" => SetupStatus::Failed,+ other => return Err(anyhow!("unknown worktree setup status {other}")),+ })+ }+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct WorktreeRow {+ pub id: String,+ /// `None` once the owning session was deleted (orphan awaiting cleanup).+ pub session_id: Option<String>,+ /// `None` for the session's own worktree.+ pub delegation_id: Option<String>,+ /// Worktree root (the directory `git worktree add` created).+ pub path: String,+ pub common_dir: String,+ /// Project directory relative to the repository top level.+ pub prefix: String,+ pub branch: String,+ pub owner_branch: String,+ pub status: WorktreeStatus,+ pub setup_status: Option<SetupStatus>,+ /// Bounded tail of the setup command output.+ pub setup_log: Option<String>,+ pub port_base: Option<i64>,+ pub created_at: i64,+ pub updated_at: i64,+}++impl WorktreeRow {+ /// The tool root: the worktree plus the project's repository prefix, so an+ /// isolated session sees the same scope as a non-isolated one.+ pub fn workspace_root(&self) -> std::path::PathBuf {+ let root = std::path::Path::new(&self.path);+ if self.prefix.is_empty() {+ root.to_path_buf()+ } else {+ root.join(self.prefix.trim_end_matches('/'))+ }+ }+}++pub struct NewWorktree<'a> {+ pub session_id: &'a str,+ pub delegation_id: Option<&'a str>,+ pub path: &'a str,+ pub common_dir: &'a str,+ pub prefix: &'a str,+ pub branch: &'a str,+ pub owner_branch: &'a str,+ pub port_base: Option<i64>,+}++const COLUMNS: &str = "id, session_id, delegation_id, path, common_dir, prefix, branch,+ owner_branch, status, setup_status, setup_log, port_base,+ created_at, updated_at";++fn from_row(row: &Row<'_>) -> rusqlite::Result<(WorktreeRow, String, Option<String>)> {+ Ok((+ WorktreeRow {+ id: row.get(0)?,+ session_id: row.get(1)?,+ delegation_id: row.get(2)?,+ path: row.get(3)?,+ common_dir: row.get(4)?,+ prefix: row.get(5)?,+ branch: row.get(6)?,+ owner_branch: row.get(7)?,+ status: WorktreeStatus::Creating,+ setup_status: None,+ setup_log: row.get(10)?,+ port_base: row.get(11)?,+ created_at: row.get(12)?,+ updated_at: row.get(13)?,+ },+ row.get(8)?,+ row.get(9)?,+ ))+}++fn finish(raw: (WorktreeRow, String, Option<String>)) -> Result<WorktreeRow> {+ let (mut row, status, setup) = raw;+ row.status = WorktreeStatus::parse(&status)?;+ row.setup_status = setup.as_deref().map(SetupStatus::parse).transpose()?;+ Ok(row)+}++fn query_many(db: &Database, sql: &str, args: impl rusqlite::Params) -> Result<Vec<WorktreeRow>> {+ let mut statement = db.conn().prepare_cached(sql)?;+ let rows = statement+ .query_map(args, from_row)?+ .collect::<rusqlite::Result<Vec<_>>>()?;+ rows.into_iter().map(finish).collect()+}++/// Insert a row in `creating` state. The unique indexes reject a second+/// worktree for the same owner and a port block already held by another row.+pub fn insert(db: &Database, new: &NewWorktree<'_>) -> Result<WorktreeRow> {+ let id = uuid::Uuid::new_v4().to_string();+ let now = now_ms();+ db.conn().execute(+ "INSERT INTO worktrees (id, session_id, delegation_id, path, common_dir, prefix,+ branch, owner_branch, status, setup_status, port_base,+ created_at, updated_at)+ VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, 'creating', NULL, ?9, ?10, ?10)",+ params![+ id,+ new.session_id,+ new.delegation_id,+ new.path,+ new.common_dir,+ new.prefix,+ new.branch,+ new.owner_branch,+ new.port_base,+ now+ ],+ )?;+ get(db, &id)?.ok_or_else(|| anyhow!("inserted worktree {id} not found"))+}++pub fn get(db: &Database, id: &str) -> Result<Option<WorktreeRow>> {+ let raw = db+ .conn()+ .prepare_cached(&format!("SELECT {COLUMNS} FROM worktrees WHERE id = ?1"))?+ .query_row(params![id], from_row)+ .optional()?;+ raw.map(finish).transpose()+}++/// The worktree of a session (`delegation_id = None`) or of one delegation.+pub fn for_owner(+ db: &Database,+ session_id: &str,+ delegation_id: Option<&str>,+) -> Result<Option<WorktreeRow>> {+ let raw = db+ .conn()+ .prepare_cached(&format!(+ "SELECT {COLUMNS} FROM worktrees+ WHERE session_id = ?1 AND IFNULL(delegation_id, '') = IFNULL(?2, '')"+ ))?+ .query_row(params![session_id, delegation_id], from_row)+ .optional()?;+ raw.map(finish).transpose()+}++/// Every worktree of a session, its own first, then delegations by age.+pub fn for_session(db: &Database, session_id: &str) -> Result<Vec<WorktreeRow>> {+ query_many(+ db,+ &format!(+ "SELECT {COLUMNS} FROM worktrees WHERE session_id = ?1+ ORDER BY delegation_id IS NOT NULL, created_at"+ ),+ params![session_id],+ )+}++/// Rows whose session was deleted by any path; awaiting link-safe removal.+pub fn orphans(db: &Database) -> Result<Vec<WorktreeRow>> {+ query_many(+ db,+ &format!("SELECT {COLUMNS} FROM worktrees WHERE session_id IS NULL ORDER BY updated_at"),+ [],+ )+}++pub fn set_status(db: &Database, id: &str, status: WorktreeStatus) -> Result<bool> {+ Ok(db.conn().execute(+ "UPDATE worktrees SET status = ?2, updated_at = ?3 WHERE id = ?1",+ params![id, status.as_str(), now_ms()],+ )? > 0)+}++pub fn set_setup_status(+ db: &Database,+ id: &str,+ status: SetupStatus,+ log: Option<&str>,+) -> Result<bool> {+ Ok(db.conn().execute(+ "UPDATE worktrees SET setup_status = ?2, setup_log = COALESCE(?3, setup_log),+ updated_at = ?4+ WHERE id = ?1",+ params![id, status.as_str(), log, now_ms()],+ )? > 0)+}++/// Every row, for startup reconciliation.+pub fn all(db: &Database) -> Result<Vec<WorktreeRow>> {+ query_many(+ db,+ &format!("SELECT {COLUMNS} FROM worktrees ORDER BY created_at"),+ [],+ )+}++pub fn remove(db: &Database, id: &str) -> Result<bool> {+ Ok(db+ .conn()+ .execute("DELETE FROM worktrees WHERE id = ?1", params![id])?+ > 0)+}++/// Lowest port block not held by any row whose first port `is_free` accepts.+/// The unique index on `port_base` still guards the insert against a race.+pub fn next_port_base(db: &Database, is_free: impl Fn(u16) -> bool) -> Result<Option<i64>> {+ let used: std::collections::HashSet<i64> = db+ .conn()+ .prepare_cached("SELECT port_base FROM worktrees WHERE port_base IS NOT NULL")?+ .query_map([], |row| row.get(0))?+ .collect::<rusqlite::Result<_>>()?;+ let mut base = PORT_RANGE_START;+ while base <= PORT_RANGE_LAST_BASE {+ if !used.contains(&base) && u16::try_from(base).is_ok_and(&is_free) {+ return Ok(Some(base));+ }+ base += PORT_BLOCK;+ }+ Ok(None)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn db_with_session() -> (tempfile::TempDir, Database, String) {+ let dir = tempfile::tempdir().unwrap();+ let db = Database::open(&dir.path().join("pi.sqlite")).unwrap();+ let session = crate::sessions::create_session(&db, None, None, None, None, None).unwrap();+ (dir, db, session.id)+ }++ fn new<'a>(session: &'a str, delegation: Option<&'a str>, path: &'a str) -> NewWorktree<'a> {+ NewWorktree {+ session_id: session,+ delegation_id: delegation,+ path,+ common_dir: "/repo/.git",+ prefix: "",+ branch: "pi-desktop/x",+ owner_branch: "main",+ port_base: None,+ }+ }++ #[test]+ fn rows_round_trip_by_owner_and_status() {+ let (_dir, db, session) = db_with_session();+ let own = insert(&db, &new(&session, None, "/w/own")).unwrap();+ let delegate = insert(&db, &new(&session, Some("d1"), "/w/d1")).unwrap();+ assert_eq!(own.status, WorktreeStatus::Creating);+ assert_eq!(for_owner(&db, &session, None).unwrap().unwrap().id, own.id);+ assert_eq!(+ for_owner(&db, &session, Some("d1")).unwrap().unwrap().id,+ delegate.id+ );+ assert!(set_status(&db, &own.id, WorktreeStatus::Conflict).unwrap());+ assert!(set_setup_status(&db, &own.id, SetupStatus::Failed, Some("boom")).unwrap());+ let reloaded = get(&db, &own.id).unwrap().unwrap();+ assert_eq!(reloaded.status, WorktreeStatus::Conflict);+ assert_eq!(reloaded.setup_status, Some(SetupStatus::Failed));+ assert_eq!(reloaded.setup_log.as_deref(), Some("boom"));+ let listed: Vec<_> = for_session(&db, &session)+ .unwrap()+ .into_iter()+ .map(|row| row.id)+ .collect();+ assert_eq!(listed, vec![own.id.clone(), delegate.id]);+ assert!(remove(&db, &own.id).unwrap());+ assert!(get(&db, &own.id).unwrap().is_none());+ }++ #[test]+ fn deleted_sessions_leave_listed_orphans() {+ let (_dir, db, session) = db_with_session();+ let row = insert(&db, &new(&session, None, "/w/own")).unwrap();+ assert!(orphans(&db).unwrap().is_empty());+ crate::sessions::delete_session(&db, &session).unwrap();+ let orphaned = orphans(&db).unwrap();+ assert_eq!(orphaned.len(), 1);+ assert_eq!(orphaned[0].id, row.id);+ assert_eq!(orphaned[0].session_id, None);+ }++ #[test]+ fn port_blocks_skip_held_and_busy_bases() {+ let (_dir, db, session) = db_with_session();+ assert_eq!(+ next_port_base(&db, |_| true).unwrap(),+ Some(PORT_RANGE_START)+ );+ let mut held = new(&session, None, "/w/own");+ held.port_base = Some(PORT_RANGE_START);+ insert(&db, &held).unwrap();+ // The second block is held by another program right now.+ let busy = (PORT_RANGE_START + PORT_BLOCK) as u16;+ assert_eq!(+ next_port_base(&db, |port| port != busy).unwrap(),+ Some(PORT_RANGE_START + 2 * PORT_BLOCK)+ );+ assert_eq!(next_port_base(&db, |_| false).unwrap(), None);+ }+}diff --git a/crates/host-core/src/session_worktrees/remove.rs b/crates/host-core/src/session_worktrees/remove.rsnew file mode 100644index 000000000..8a4714d8e--- /dev/null+++ b/crates/host-core/src/session_worktrees/remove.rs@@ -0,0 +1,241 @@+//! Link-safe removal of a worktree and its branch (ADR 0328 decision 6).+//!+//! Git for Windows follows a directory junction inside the worktree during+//! `git worktree remove --force` and deletes the junction target's files+//! (openai/codex#34702, #49995). host-core therefore empties the worktree+//! itself first, removing every symbolic link or junction as a link, and only+//! then lets git drop the (now link-free) directory and its metadata.++use std::fs;+use std::io;+use std::path::Path;++use super::git::GitRunner;+use super::registry::WorktreeRow;+use super::WorktreeError;++/// Delete everything inside `root` except its `.git` link file. Links are+/// removed as links; their targets are never traversed.+pub fn clear_contents(root: &Path) -> io::Result<()> {+ let entries = match fs::read_dir(root) {+ Ok(entries) => entries,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error),+ };+ for entry in entries {+ let entry = entry?;+ if entry.file_name() == ".git" {+ continue;+ }+ remove_entry(&entry.path())?;+ }+ Ok(())+}++fn remove_entry(path: &Path) -> io::Result<()> {+ let metadata = fs::symlink_metadata(path)?;+ if metadata.file_type().is_symlink() || is_reparse_point(&metadata) {+ remove_link(path, &metadata)+ } else if metadata.is_dir() {+ // Documented not to follow symbolic links, and protected against+ // symlink TOCTOU races on the supported platforms.+ fs::remove_dir_all(path)+ } else {+ fs::remove_file(path)+ }+}++#[cfg(windows)]+fn is_reparse_point(metadata: &fs::Metadata) -> bool {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;+ metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0+}++#[cfg(not(windows))]+fn is_reparse_point(_metadata: &fs::Metadata) -> bool {+ false+}++#[cfg(windows)]+fn remove_link(path: &Path, metadata: &fs::Metadata) -> io::Result<()> {+ use std::os::windows::fs::MetadataExt;+ const FILE_ATTRIBUTE_DIRECTORY: u32 = 0x10;+ // Directory symlinks and junctions are directory entries; removing the+ // entry removes the link, not the target.+ if metadata.file_attributes() & FILE_ATTRIBUTE_DIRECTORY != 0 {+ fs::remove_dir(path)+ } else {+ fs::remove_file(path)+ }+}++#[cfg(not(windows))]+fn remove_link(path: &Path, _metadata: &fs::Metadata) -> io::Result<()> {+ fs::remove_file(path)+}++/// Remove a registered worktree directory, git's metadata for it, and its+/// branch. The registry row is left to the caller.+pub async fn remove_worktree(git: &GitRunner, row: &WorktreeRow) -> Result<(), WorktreeError> {+ let root = Path::new(&row.path);+ let common_dir = Path::new(&row.common_dir);+ let repository_exists = common_dir.is_dir();+ if root.exists() {+ if repository_exists {+ // Not locked when creation failed half-way; that is fine.+ let _ = git.output(root, &["worktree", "unlock", &row.path]).await;+ }+ clear_contents(root)?;+ if repository_exists {+ git.run_git_dir(common_dir, &["worktree", "remove", "--force", &row.path])+ .await?;+ }+ if root.exists() {+ fs::remove_dir_all(root)?;+ }+ }+ if repository_exists {+ drop_admin_entry(common_dir, root)?;+ let ref_name = format!("refs/heads/{}", row.branch);+ let exists = git+ .run_git_dir(common_dir, &["show-ref", "--verify", "--quiet", &ref_name])+ .await+ .is_ok();+ if exists {+ git.run_git_dir(common_dir, &["branch", "-D", &row.branch])+ .await?;+ }+ }+ Ok(())+}++/// When the worktree directory vanished on its own, git still lists it and+/// keeps its branch "checked out". Drop only the metadata entry whose+/// `gitdir` names this worktree, which is what `git worktree prune` would do+/// for it, without pruning any other worktree.+pub(super) fn drop_admin_entry(common_dir: &Path, root: &Path) -> io::Result<()> {+ let admin = common_dir.join("worktrees");+ let entries = match fs::read_dir(&admin) {+ Ok(entries) => entries,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),+ Err(error) => return Err(error),+ };+ // git records the resolved path (for example `/private/var/...` for+ // `/var/...` on macOS); the root itself may be gone, so resolve its parent.+ let mut expected = vec![root.join(".git")];+ if let (Some(parent), Some(name)) = (root.parent(), root.file_name()) {+ if let Ok(parent) = crate::workspace::simple_canonicalize(parent) {+ expected.push(parent.join(name).join(".git"));+ }+ }+ for entry in entries {+ let entry = entry?;+ let Ok(gitdir) = fs::read_to_string(entry.path().join("gitdir")) else {+ continue;+ };+ if expected.iter().any(|path| Path::new(gitdir.trim()) == path) {+ fs::remove_dir_all(entry.path())?;+ }+ }+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::session_worktrees::registry::{WorktreeRow, WorktreeStatus};+ use crate::session_worktrees::test_support::{git_cmd, init_repo, link_dir, try_link_file};++ fn row_for(repo: &Path, worktree: &Path, branch: &str) -> WorktreeRow {+ WorktreeRow {+ id: "w".into(),+ session_id: Some("s".into()),+ delegation_id: None,+ path: worktree.to_string_lossy().into_owned(),+ common_dir: repo.join(".git").to_string_lossy().into_owned(),+ prefix: String::new(),+ branch: branch.into(),+ owner_branch: "main".into(),+ status: WorktreeStatus::Active,+ setup_status: None,+ setup_log: None,+ port_base: None,+ created_at: 0,+ updated_at: 0,+ }+ }++ /// AC14: a link to a directory outside the worktree survives removal. On+ /// Windows the directory links are junctions, which Git for Windows+ /// follows during `git worktree remove --force`.+ #[tokio::test]+ async fn removal_deletes_links_without_touching_their_targets() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ let outside = dir.path().join("outside");+ fs::create_dir_all(outside.join("nested")).unwrap();+ fs::write(outside.join("KEEP_ME.txt"), "keep").unwrap();+ fs::write(outside.join("nested/KEEP_TOO.txt"), "keep").unwrap();+ let worktree = dir.path().join("wt");+ git_cmd(+ &repo,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ "pi-desktop/t",+ worktree.to_str().unwrap(),+ "main",+ ],+ );+ link_dir(&outside, &worktree.join("linked"));+ fs::create_dir_all(worktree.join("deep")).unwrap();+ link_dir(&outside, &worktree.join("deep/linked"));+ try_link_file(&outside.join("KEEP_ME.txt"), &worktree.join("file-link"));++ remove_worktree(+ &GitRunner::default(),+ &row_for(&repo, &worktree, "pi-desktop/t"),+ )+ .await+ .unwrap();++ assert!(!worktree.exists());+ assert!(outside.join("KEEP_ME.txt").is_file());+ assert!(outside.join("nested/KEEP_TOO.txt").is_file());+ assert!(!git_cmd(&repo, &["branch", "--list", "pi-desktop/t"]).contains("pi-desktop/t"));+ assert_eq!(git_cmd(&repo, &["worktree", "list"]).lines().count(), 1);+ }++ #[tokio::test]+ async fn a_worktree_whose_directory_vanished_is_unregistered_and_its_branch_dropped() {+ let dir = tempfile::tempdir().unwrap();+ let repo = init_repo(&dir.path().join("repo"));+ let worktree = dir.path().join("wt");+ git_cmd(+ &repo,+ &[+ "worktree",+ "add",+ "-q",+ "-b",+ "pi-desktop/gone",+ worktree.to_str().unwrap(),+ "main",+ ],+ );+ fs::remove_dir_all(&worktree).unwrap();++ remove_worktree(+ &GitRunner::default(),+ &row_for(&repo, &worktree, "pi-desktop/gone"),+ )+ .await+ .unwrap();++ assert_eq!(git_cmd(&repo, &["worktree", "list"]).lines().count(), 1);+ assert!(!git_cmd(&repo, &["branch", "--list"]).contains("pi-desktop/gone"));+ }+}diff --git a/crates/host-core/src/session_worktrees/repo_lock.rs b/crates/host-core/src/session_worktrees/repo_lock.rsnew file mode 100644index 000000000..80619ea3b--- /dev/null+++ b/crates/host-core/src/session_worktrees/repo_lock.rs@@ -0,0 +1,44 @@+//! One async lock per repository: every mutating git command host-core runs+//! for a repository is serialized under its canonical common git directory,+//! because worktrees share refs, the object store, and worktree metadata.++use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock};++use tokio::sync::{Mutex as AsyncMutex, OwnedMutexGuard};++static LOCKS: OnceLock<Mutex<HashMap<PathBuf, Arc<AsyncMutex<()>>>>> = OnceLock::new();++pub async fn lock(common_dir: &Path) -> OwnedMutexGuard<()> {+ let entry = {+ let mut locks = LOCKS+ .get_or_init(Default::default)+ .lock()+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ locks+ .entry(common_dir.to_path_buf())+ .or_insert_with(|| Arc::new(AsyncMutex::new(())))+ .clone()+ };+ entry.lock_owned().await+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn one_repository_is_serialized_and_others_are_not() {+ let first = lock(Path::new("/repo-a/.git")).await;+ // A different repository is independent.+ let other = lock(Path::new("/repo-b/.git")).await;+ drop(other);+ // The same repository waits until the first guard is released.+ let waiting = tokio::spawn(async { lock(Path::new("/repo-a/.git")).await });+ tokio::task::yield_now().await;+ assert!(!waiting.is_finished());+ drop(first);+ waiting.await.unwrap();+ }+}diff --git a/crates/host-core/src/session_worktrees/test_support.rs b/crates/host-core/src/session_worktrees/test_support.rsnew file mode 100644index 000000000..582471663--- /dev/null+++ b/crates/host-core/src/session_worktrees/test_support.rs@@ -0,0 +1,80 @@+//! Real temporary git repositories for worktree tests. Identity is set in the+//! repository config so tests never depend on the developer's global config.++use std::path::{Path, PathBuf};++pub fn git_cmd(dir: &Path, args: &[&str]) -> String {+ let output = std::process::Command::new("git")+ .arg("-C")+ .arg(dir)+ .args(args)+ .env("GIT_TERMINAL_PROMPT", "0")+ .env("LC_ALL", "C")+ .output()+ .expect("git runs");+ assert!(+ output.status.success(),+ "git {args:?} failed: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ String::from_utf8_lossy(&output.stdout).into_owned()+}++/// A repository on `main` with one commit.+pub fn init_repo(path: &Path) -> PathBuf {+ std::fs::create_dir_all(path).unwrap();+ git_cmd(path, &["init", "-q", "-b", "main"]);+ git_cmd(path, &["config", "user.name", "PI Test"]);+ git_cmd(path, &["config", "user.email", "[email protected]"]);+ git_cmd(path, &["config", "commit.gpgsign", "false"]);+ std::fs::write(path.join("README.md"), "init\n").unwrap();+ git_cmd(path, &["add", "README.md"]);+ git_cmd(path, &["commit", "-q", "-m", "init"]);+ path.to_path_buf()+}++/// A directory link: a symbolic link on Unix, a junction on Windows. Junctions+/// need no privilege, and they are the link Git for Windows follows during+/// `git worktree remove --force`.+pub fn link_dir(target: &Path, link: &Path) {+ #[cfg(unix)]+ std::os::unix::fs::symlink(target, link).unwrap();+ #[cfg(windows)]+ {+ // `mklink` reads a `/` inside a path as a switch.+ let native = |path: &Path| path.to_string_lossy().replace('/', "\\");+ let output = std::process::Command::new("cmd.exe")+ .args(["/d", "/c", "mklink", "/J"])+ .arg(native(link))+ .arg(native(target))+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "junction creation failed: {output:?}"+ );+ }+}++/// A file symbolic link. Windows allows it only with Developer Mode or+/// elevation; without that privilege this returns false so the caller skips+/// just its file-link assertions.+pub fn try_link_file(target: &Path, link: &Path) -> bool {+ #[cfg(unix)]+ {+ std::os::unix::fs::symlink(target, link).unwrap();+ true+ }+ #[cfg(windows)]+ {+ const ERROR_PRIVILEGE_NOT_HELD: i32 = 1314;+ match std::os::windows::fs::symlink_file(target, link) {+ Ok(()) => true,+ Err(error) if error.raw_os_error() == Some(ERROR_PRIVILEGE_NOT_HELD) => {+ eprintln!("file symlinks need Developer Mode; skipping that case");+ false+ }+ Err(error) => panic!("file symlink failed: {error}"),+ }+ }+}diff --git a/crates/host-core/src/sessions.rs b/crates/host-core/src/sessions.rsindex 5ea64fea6..0a3b7ff5f 100644--- a/crates/host-core/src/sessions.rs+++ b/crates/host-core/src/sessions.rs@@ -137,6 +137,10 @@ pub struct SessionSummary {/// deleting the task frees its sessions back into the ordinary lists.#[serde(default)]pub scheduled_run: bool,+ /// The session's isolated worktree (ADR 0328); absent for every other+ /// session. Filled in by the list and single-summary reads.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub worktree: Option<crate::session_worktrees::lifecycle::WorktreeSummary>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -1305,9 +1309,22 @@ pub(crate) fn summary_from_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<Sess// Read by name: search and listing build their own column lists, so the// alias keeps this mapper independent of any one query's column order.scheduled_run: row.get("scheduled_run")?,+ worktree: None,})}+/// Attach isolated-worktree badges. Sessions without a worktree are untouched.+fn attach_worktrees(db: &Database, summaries: &mut [SessionSummary]) -> Result<()> {+ let mut worktrees = crate::session_worktrees::lifecycle::summaries(db)?;+ if worktrees.is_empty() {+ return Ok(());+ }+ for summary in summaries {+ summary.worktree = worktrees.remove(&summary.id);+ }+ Ok(())+}+// ---- sessions ---------------------------------------------------------------pub fn list_sessions(db: &Database) -> Result<Vec<SessionSummary>> {@@ -1318,6 +1335,7 @@ pub fn list_sessions(db: &Database) -> Result<Vec<SessionSummary>> {for row in rows {out.push(row?);}+ attach_worktrees(db, &mut out)?;Ok(out)}@@ -1446,6 +1464,8 @@ pub fn create_session_with_options(created_at: ms_to_ts(now),// The run row that owns this transcript is written after creation.scheduled_run: false,+ // A new or forked session starts without a worktree (ADR 0328).+ worktree: None,})}@@ -1492,11 +1512,15 @@ pub fn get_session(db: &Database, id: &str) -> Result<Option<SessionDetail>> {/// `SUMMARY_SELECT`, so this is one indexed row.pub fn session_summary(db: &Database, id: &str) -> Result<Option<SessionSummary>> {let sql = format!("{SUMMARY_SELECT} AND s.id = ?1");- Ok(db+ let mut summary = db.conn().prepare_cached(&sql)?.query_row(params![id], summary_from_row)- .optional()?)+ .optional()?;+ if let Some(summary) = summary.as_mut() {+ attach_worktrees(db, std::slice::from_mut(summary))?;+ }+ Ok(summary)}/// Load a session detail with an optional renderer-facing message window.@@ -1804,6 +1828,8 @@ pub fn fork_session_through(created_at,// A fork is the user's own conversation, not the automation's transcript.scheduled_run: false,+ // A new or forked session starts without a worktree (ADR 0328).+ worktree: None,};let messages = records.into_iter().map(record_to_ui).collect();Ok(ForkSessionResult::Created(Box::new(SessionDetail {@@ -5005,6 +5031,7 @@ mod tests {permission_mode: "inherit".into(),// Ownership is derived from `task_runs`, so an import is never one.scheduled_run: false,+ worktree: None,created_at: "2025-01-01T00:00:00Z".into(),updated_at: "2025-01-02T00:00:00Z".into(),};@@ -5057,6 +5084,7 @@ mod tests {permission_mode: "inherit".into(),// Ownership is derived from `task_runs`, so an import is never one.scheduled_run: false,+ worktree: None,created_at: "2025-01-01T00:00:00Z".into(),updated_at: "2025-01-01T00:00:00Z".into(),};@@ -5998,6 +6026,7 @@ mod tests {permission_mode: "inherit".into(),// Ownership is derived from `task_runs`, so an import is never one.scheduled_run: false,+ worktree: None,created_at: "2025-01-01T00:00:00Z".into(),updated_at: "2025-01-01T00:00:00Z".into(),};diff --git a/crates/host-core/src/tool_budget.rs b/crates/host-core/src/tool_budget.rsindex 1fef9e988..d42ce6de3 100644--- a/crates/host-core/src/tool_budget.rs+++ b/crates/host-core/src/tool_budget.rs@@ -1,4 +1,4 @@-use std::collections::{HashMap, VecDeque};+use std::collections::{HashMap, HashSet, VecDeque};use std::sync::{Arc, Mutex, MutexGuard};use std::time::Duration;@@ -71,6 +71,60 @@ impl Drop for ToolPermit {let mut state = self.budget.lock();state.release(&self.request);state.dispatch();+ drop(state);+ self.budget.released.notify_waiters();+ }+}++/// Marks a session whose exclusive permit is awaited; see `BudgetState::+/// exclusive_pending`.+struct PendingExclusive {+ budget: ToolBudget,+ session_id: String,+}++impl PendingExclusive {+ fn register(budget: &ToolBudget, session_id: &str) -> Self {+ *budget+ .lock()+ .exclusive_pending+ .entry(session_id.to_string())+ .or_default() += 1;+ Self {+ budget: budget.clone(),+ session_id: session_id.to_string(),+ }+ }+}++impl Drop for PendingExclusive {+ fn drop(&mut self) {+ let mut state = self.budget.lock();+ if let Some(count) = state.exclusive_pending.get_mut(&self.session_id) {+ *count -= 1;+ if *count == 0 {+ state.exclusive_pending.remove(&self.session_id);+ }+ }+ // Calls held back while the permit was awaited may run now (or+ // stay held by the granted exclusive permit).+ state.dispatch();+ }+}++/// See `ToolBudget::acquire_session_exclusive`.+pub struct SessionExclusivePermit {+ budget: ToolBudget,+ session_id: String,+}++impl Drop for SessionExclusivePermit {+ fn drop(&mut self) {+ let mut state = self.budget.lock();+ state.exclusive.remove(&self.session_id);+ state.dispatch();+ drop(state);+ self.budget.released.notify_waiters();}}@@ -89,12 +143,17 @@ pub struct ToolBudgetSnapshot {struct Request {session_id: String,class: ToolClass,+ /// Runs in a subagent's own worktree (ADR 0328), so holding the session+ /// for work in the session worktree does not need to stop it.+ own_worktree: bool,}#[derive(Default)]struct SessionUsage {active: usize,mutations: usize,+ /// Of `active`, calls rooted in a subagent's own worktree.+ own_worktree: usize,}struct WaitingRequest {@@ -112,6 +171,11 @@ struct BudgetState {waiting: VecDeque<WaitingRequest>,queued: usize,next_id: u64,+ /// Sessions held by a `SessionExclusivePermit`.+ exclusive: HashSet<String>,+ /// Sessions whose exclusive permit is being awaited; their new calls wait+ /// too, so steady traffic cannot keep the session from ever going quiet.+ exclusive_pending: HashMap<String, usize>,}impl ToolClass {@@ -132,6 +196,12 @@ impl BudgetState {{return false;}+ if !request.own_worktree+ && (self.exclusive.contains(&request.session_id)+ || self.exclusive_pending.contains_key(&request.session_id))+ {+ return false;+ }self.sessions.get(&request.session_id).is_none_or(|usage| {usage.active < MAX_IN_FLIGHT_PER_SESSION&& (request.class != ToolClass::Mutation@@ -147,6 +217,9 @@ impl BudgetState {if request.class == ToolClass::Mutation {usage.mutations += 1;}+ if request.own_worktree {+ usage.own_worktree += 1;+ }}fn release(&mut self, request: &Request) {@@ -160,6 +233,9 @@ impl BudgetState {if request.class == ToolClass::Mutation {usage.mutations -= 1;}+ if request.own_worktree {+ usage.own_worktree -= 1;+ }if usage.active == 0 {self.sessions.remove(&request.session_id);}@@ -224,18 +300,26 @@ impl Drop for QueueGuard {.position(|entry| entry.id == id).expect("waiting request remains registered until cleanup");let entry = state.waiting.remove(index).expect("queue index exists");- if entry.granted {+ let released = entry.granted;+ if released {state.release(&entry.request);} else {state.queued -= 1;}state.dispatch();+ drop(state);+ if released {+ self.budget.released.notify_waiters();+ }}}#[derive(Clone, Default)]pub struct ToolBudget {state: Arc<Mutex<BudgetState>>,+ /// Woken whenever a session's last tool finishes or an exclusive permit+ /// drops, for `acquire_session_exclusive`.+ released: Arc<Notify>,}impl ToolBudget {@@ -256,7 +340,18 @@ impl ToolBudget {session_id: &str,tool_name: &str,) -> Result<ToolPermit, AdmissionError> {- self.acquire_with_timeout(session_id, tool_name, QUEUE_WAIT)+ self.acquire_with_timeout(session_id, tool_name, false, QUEUE_WAIT)+ .await+ }++ /// `acquire` for a call rooted in a subagent's own worktree: a session+ /// hold for the session worktree does not stop it.+ pub async fn acquire_in_own_worktree(+ &self,+ session_id: &str,+ tool_name: &str,+ ) -> Result<ToolPermit, AdmissionError> {+ self.acquire_with_timeout(session_id, tool_name, true, QUEUE_WAIT).await}@@ -264,11 +359,13 @@ impl ToolBudget {&self,session_id: &str,tool_name: &str,+ own_worktree: bool,wait: Duration,) -> Result<ToolPermit, AdmissionError> {let request = Request {session_id: session_id.to_string(),class: ToolClass::from_name(tool_name),+ own_worktree,};let ready = Arc::new(Notify::new());let guard = {@@ -304,6 +401,45 @@ impl ToolBudget {}}+ /// Hold `session_id` alone: wait (at most `wait`) until none of its tools+ /// is in flight, then keep every new tool of that session queued until+ /// the permit drops. Used around git operations on an isolated session's+ /// worktree (ADR 0328) so a Bash or Write call cannot interleave with+ /// them. `None` when the session stayed busy; other sessions and global+ /// capacity are unaffected either way.+ pub async fn acquire_session_exclusive(+ &self,+ session_id: &str,+ wait: Duration,+ ) -> Option<SessionExclusivePermit> {+ let deadline = tokio::time::Instant::now() + wait;+ // Dropped on every exit, including cancellation of this future.+ let _pending = PendingExclusive::register(self, session_id);+ loop {+ // Registered before the check, so a release in between still wakes us.+ let released = self.released.notified();+ tokio::pin!(released);+ released.as_mut().enable();+ {+ let mut state = self.lock();+ let busy = state+ .sessions+ .get(session_id)+ .is_some_and(|usage| usage.active > usage.own_worktree);+ if !busy && !state.exclusive.contains(session_id) {+ state.exclusive.insert(session_id.to_string());+ return Some(SessionExclusivePermit {+ budget: self.clone(),+ session_id: session_id.to_string(),+ });+ }+ }+ if tokio::time::timeout_at(deadline, released).await.is_err() {+ return None;+ }+ }+ }+pub fn snapshot(&self) -> ToolBudgetSnapshot {let state = self.lock();ToolBudgetSnapshot {diff --git a/crates/host-core/src/tool_budget/tests.rs b/crates/host-core/src/tool_budget/tests.rsindex 599c41afc..4545ab1f4 100644--- a/crates/host-core/src/tool_budget/tests.rs+++ b/crates/host-core/src/tool_budget/tests.rs@@ -369,7 +369,7 @@ async fn timeout_removes_only_its_queue_entry_and_preserves_running_capacity() {let mut older = Box::pin(budget.acquire("older", "Bash"));assert!(poll_once(older.as_mut()).is_pending());let result = budget- .acquire_with_timeout("timed-out", "Bash", Duration::ZERO)+ .acquire_with_timeout("timed-out", "Bash", false, Duration::ZERO).await;match result {Err(error @ AdmissionError::QueueWaitTimeout) => {@@ -419,3 +419,98 @@ async fn dispatch_skips_a_blocked_class_for_the_oldest_runnable_request() {drop((write_permit, shell_permit, running));assert_eq!(budget.snapshot().active, 0);}++#[tokio::test]+async fn session_exclusive_waits_for_in_flight_tools_and_holds_new_ones() {+ let budget = ToolBudget::new();+ let bash = budget.acquire("session-a", "Bash").await.unwrap();+ let other = budget.acquire("session-b", "Write").await.unwrap();++ let mut exclusive =+ Box::pin(budget.acquire_session_exclusive("session-a", Duration::from_secs(30)));+ assert!(poll_once(exclusive.as_mut()).is_pending());+ drop(bash);+ let held = match poll_once(exclusive.as_mut()) {+ Poll::Ready(Some(permit)) => permit,+ _ => panic!("the session became quiet, so the permit must be granted"),+ };++ // The held session's new tools queue; other sessions are unaffected.+ let mut queued = Box::pin(budget.acquire("session-a", "Read"));+ assert!(poll_once(queued.as_mut()).is_pending());+ drop(budget.acquire("session-b", "Read").await.unwrap());+ drop(held);+ drop(admitted(queued.as_mut()));+ drop(other);+ assert_eq!(budget.snapshot().active, 0);+}++#[tokio::test]+async fn session_exclusive_gives_up_while_a_long_tool_runs() {+ let budget = ToolBudget::new();+ let _long = budget.acquire("session-a", "Bash").await.unwrap();+ assert!(budget+ .acquire_session_exclusive("session-a", Duration::from_millis(20))+ .await+ .is_none());+ // Giving up holds nothing: the session still admits tools.+ drop(budget.acquire("session-a", "Read").await.unwrap());+}++#[tokio::test]+async fn a_session_hold_spares_calls_in_a_subagents_own_worktree() {+ let budget = ToolBudget::new();+ // A subagent tool already running in its own worktree does not delay it.+ let delegate = budget+ .acquire_in_own_worktree("session-a", "Bash")+ .await+ .unwrap();+ let held = budget+ .acquire_session_exclusive("session-a", Duration::from_millis(20))+ .await+ .expect("own-worktree calls do not keep the session busy");+ drop(+ budget+ .acquire_in_own_worktree("session-a", "Write")+ .await+ .unwrap(),+ );+ let mut parent = Box::pin(budget.acquire("session-a", "Read"));+ assert!(poll_once(parent.as_mut()).is_pending());+ drop(held);+ drop(admitted(parent.as_mut()));+ drop(delegate);+}++#[tokio::test]+async fn new_session_calls_wait_while_a_hold_is_pending() {+ let budget = ToolBudget::new();+ let running = budget.acquire("session-a", "Bash").await.unwrap();+ let mut hold = Box::pin(budget.acquire_session_exclusive("session-a", Duration::from_secs(30)));+ assert!(poll_once(hold.as_mut()).is_pending());+ // Steady traffic cannot keep the session from going quiet.+ let mut late = Box::pin(budget.acquire("session-a", "Read"));+ assert!(poll_once(late.as_mut()).is_pending());+ drop(running);+ let held = match poll_once(hold.as_mut()) {+ Poll::Ready(Some(permit)) => permit,+ _ => panic!("the hold must be granted once the session is quiet"),+ };+ assert!(poll_once(late.as_mut()).is_pending());+ drop(held);+ drop(admitted(late.as_mut()));+ assert_eq!(budget.snapshot().active, 0);+}++#[tokio::test]+async fn an_abandoned_hold_releases_waiting_calls() {+ let budget = ToolBudget::new();+ let running = budget.acquire("session-a", "Bash").await.unwrap();+ let mut hold = Box::pin(budget.acquire_session_exclusive("session-a", Duration::from_secs(30)));+ assert!(poll_once(hold.as_mut()).is_pending());+ let mut late = Box::pin(budget.acquire("session-a", "Read"));+ assert!(poll_once(late.as_mut()).is_pending());+ drop(hold);+ drop(admitted(late.as_mut()));+ drop(running);+}diff --git a/crates/host-core/src/tools/mod.rs b/crates/host-core/src/tools/mod.rsindex a57f182d3..64d8e9176 100644--- a/crates/host-core/src/tools/mod.rs+++ b/crates/host-core/src/tools/mod.rs@@ -214,6 +214,10 @@ struct ToolRunnerStartConfig {scratch_dir: Option<PathBuf>,#[serde(default)]env_path: Option<String>,+ /// Session-scoped variables such as `PI_PORT` for an isolated worktree+ /// (ADR 0328). Empty for every other call.+ #[serde(default)]+ extra_env: Vec<(String, String)>,}fn path_has_nul(path: &Path) -> bool {@@ -397,6 +401,9 @@ pub async fn run_internal_tool_runner() -> Result<i32> {if let Some(path) = config.env_path.as_deref() {command.env("PATH", path);}+ for (name, value) in &config.extra_env {+ command.env(name, value);+ }#[cfg(windows)]{command.creation_flags(0x0800_0000);@@ -564,6 +571,10 @@ pub struct ToolsExecuteParams {/// permission mode. `inherit` and absent behave identically.#[serde(default)]pub permission_scope: Option<String>,+ /// Chain id of a Write/Edit subagent with its own worktree (ADR 0328).+ /// host-core resolves it against its registry; an unknown id is ignored.+ #[serde(default)]+ pub delegation_id: Option<String>,#[serde(default)]pub expected_command_shell_id: Option<String>,#[serde(default)]@@ -761,6 +772,8 @@ pub struct BashExecutionOptions {pub timeout_ms: Option<u64>,pub cancellation: Option<watch::Receiver<bool>>,pub output_tx: Option<mpsc::UnboundedSender<String>>,+ /// Extra environment for the command, e.g. `PI_PORT` (ADR 0328).+ pub extra_env: Vec<(String, String)>,}impl BashExecutionOptions {@@ -772,6 +785,7 @@ impl BashExecutionOptions {timeout_ms,cancellation: None,output_tx: None,+ extra_env: Vec::new(),}}}@@ -2579,6 +2593,9 @@ async fn spawn_tool_runner(if let Some(path) = config.env_path.as_deref() {command.env("PATH", path);}+ for (name, value) in &config.extra_env {+ command.env(name, value);+ }}#[cfg(not(test))]@@ -2777,6 +2794,7 @@ async fn tool_bash()}),env_path: shell::user_login_path().map(str::to_string),+ extra_env: options.extra_env.clone(),};let SpawnedToolRunner {pid,@@ -3241,6 +3259,7 @@ mod tests {workspace: PathBuf::from("workspace"),scratch_dir: None,env_path: None,+ extra_env: Vec::new(),};let frame = encode_runner_config(&config).unwrap();assert_eq!(decode_runner_config(&frame).unwrap().args, config.args);@@ -3259,6 +3278,7 @@ mod tests {workspace: PathBuf::from("workspace"),scratch_dir: None,env_path: None,+ extra_env: Vec::new(),};assert!(encode_runner_config(&nul_config).is_err());}@@ -4726,6 +4746,7 @@ mod tests {timeout_ms: Some(1_000),cancellation: None,output_tx: None,+ extra_env: Vec::new(),}),).await;@@ -4767,6 +4788,7 @@ mod tests {timeout_ms: Some(15_000),cancellation: None,output_tx: None,+ extra_env: Vec::new(),}),).await;@@ -4803,6 +4825,7 @@ mod tests {timeout_ms: Some(15_000),cancellation: None,output_tx: None,+ extra_env: Vec::new(),}),).await;@@ -4872,6 +4895,7 @@ mod tests {timeout_ms: None,cancellation: None,output_tx: Some(tx),+ extra_env: Vec::new(),};let mut notifier = OutputNotifier::new(&options);for _ in 0..(MAX_OUTPUT_NOTIFICATIONS + 100) {@@ -4897,6 +4921,7 @@ mod tests {timeout_ms: Some(5_000),cancellation: None,output_tx: None,+ extra_env: Vec::new(),};let output = execute_tool_with_options(diff --git a/crates/host-core/src/turn_queue.rs b/crates/host-core/src/turn_queue.rsindex 9addb58bd..92e9b3733 100644--- a/crates/host-core/src/turn_queue.rs+++ b/crates/host-core/src/turn_queue.rs@@ -532,7 +532,7 @@ mod tests {assert_eq!(entries[0].content, "existing");assert!(entries[0].user_message_id.is_none());assert!(entries[0].voice_origin.is_none());- assert_eq!(crate::db::SCHEMA_VERSION, 23);+ assert_eq!(crate::db::SCHEMA_VERSION, 24);}#[test]diff --git a/docs/adr/0328-session-worktree-isolation.md b/docs/adr/0328-session-worktree-isolation.mdnew file mode 100644index 000000000..cd57384f7--- /dev/null+++ b/docs/adr/0328-session-worktree-isolation.md@@ -0,0 +1,129 @@+# ADR 0328: Isolate parallel sessions of one project in git worktrees++- Status: Accepted+- Date: 2026-10-12+- Deciders: PI-Desktop maintainers+- Related: ADR 0062 (parallel delegates), ADR 0089 (delegation tools),+ D114 (per-session scratch), `docs/spec/03-runtime/03-tools-and-permissions.md` §4d++## Context++Several sessions of one project can run at the same time, but they all+resolve the same tool root (`resolve_tool_workspace`, `crates/host-core/src/rpc/mod.rs`).+Writes are serialized only per session; two sessions editing one file are+guarded only by the Edit content tag, and they share one build tree and one+git state. Subagents of one session share the same root as well.++Every mainstream agent product that offers parallel local work isolates it in+a git worktree: Claude Code (`--worktree`, subagent `isolation: worktree`),+Cursor (Agents Window, `/worktree`), Codex (Local / Worktree with Handoff),+VS Code (Agents window "New Worktree"), Windsurf / Devin Desktop, Conductor,+and JetBrains IDEs. Four of the six desktop products place worktrees outside+the project directory.++## Decision++1. An isolated session is opt-in per new session, default off. It owns one git+ worktree on branch `pi-desktop/<id>`, created by host-core under+ `~/.pi-desktop/worktrees/<project-key>/` from the project's current branch+ tip. Uncommitted project changes are not carried over.+2. host-core owns all git execution, worktree paths, and the `worktrees`+ registry (schema v24). The renderer and the agent runtime send only a+ session id and, for subagents, a delegation id; they never send a worktree+ path.+3. Tool containment is unchanged in mechanism: the isolated session's root is+ its worktree (or `<worktree>/<prefix>` when the project is a repository+ subdirectory), so the main checkout is "outside workspace" and needs the+ existing permission. Project identity (skills, plugins, MCP, memory,+ subagent catalog, group context) stays keyed by the project path; only+ files, instruction files, and the shell run in the worktree.+4. "Merge into project" preserves the session's commits. It first shows the+ commit count and changed files for confirmation, then merges the project+ branch into the session branch inside the worktree (conflicts stay there),+ then fast-forwards the project branch. The project never enters a+ merge-in-progress state and git refuses to overwrite uncommitted project+ changes.+5. Inside an isolated session, a subagent whose tools include Write or Edit+ gets its own temporary worktree and is merged back automatically with the+ same algorithm; a conflict is reported to the parent, which can resume the+ subagent to resolve it. Other subagents share the session worktree.+6. Deleting an isolated session removes its worktrees and branches after a+ loss warning; there is no separate discard. Removal deletes links as links+ before calling git, because Git for Windows follows directory junctions+ during `git worktree remove --force` (openai/codex#34702, #49995).+7. Every git command host-core runs disables hooks and `core.fsmonitor` and+ sets `safe.bareRepository=explicit`. A relative `core.hooksPath` resolves+ inside the worktree, so a hook written with Write/Edit alone would+ otherwise run when host-core commits or merges, bypassing the Bash+ permission.+8. New worktrees copy ignored files listed in `.worktreeinclude` (the format+ Claude Code and Conductor read), then run an optional per-project setup+ command with `PI_PROJECT_ROOT`, `PI_WORKTREE_ROOT`, and `PI_PORT` (a block+ of 10 ports per worktree, after Conductor's `CONDUCTOR_PORT`).+9. Minimum git version is 2.29 (`git worktree repair`). Relative worktree+ links are not used because they raise the repository format version.+10. "Sync from project" merges the project branch into an isolated session's+ worktree with the rules of decision 4 (pending session work is committed+ first, conflicts stay in the worktree) and never touches the project.+ Without it a session only receives other sessions' work, including their+ conflict resolutions, when it is merged, so it keeps working on stale+ code. The sidebar marks a session that lacks project commits (`↓N`); the+ counts come from one background host call (`worktree.behindAll`) when+ isolated sessions change, after a merge or sync, and on window focus, so+ rendering the list never waits for git.+11. The conflict status follows the worktree, not only the next merge: after+ each Write, Edit, or Bash call of a conflicted session, after a failed+ merge or sync, when the session menu opens, and in the background behind+ check, host-core clears the status once every conflict is resolved (by+ the rule the merge uses to conclude it) or the merge was aborted. Text+ conflicts merged by git's text driver count as resolved when their+ markers (of the file's `conflict-marker-size`) are gone; binary,+ add/delete, modify/delete, and `merge=binary` / `-merge` / custom-driver+ conflicts need an explicit `git add` or `git rm`.+12. While host-core commits or merges in a session worktree for a subagent,+ it holds the session's own tools (new calls queue, also while the hold is+ awaited). Calls of subagents rooted in their own worktrees are not held.+ It waits at most five seconds for tools already running, then falls back+ to holding only the session's write permit, so a long Bash run never+ blocks subagents. The runtime gives these host calls a 10-minute+ deadline so it never reports a merge that is still running as failed.++## Alternatives considered++- Worktrees inside the project (`.pi/worktrees/`, Claude Code's choice):+ rejected after verification; test runners (vitest default `exclude`),+ `tsc` (default `include: **/*`), watchers, and `git clean -ffdx` see or+ delete the copies.+- Apply changes as uncommitted edits instead of merging the branch: rejected+ by the user in favor of keeping history.+- Merging directly in the project: rejected; a conflict would leave the+ project half-merged.+- No automatic subagent merge-back (Claude Code, VS Code, Codex): rejected by+ the user in favor of zero-click integration, with serialization and a+ no-force fallback as safeguards.+- Per-project file locks without worktrees: rejected; it cannot isolate builds+ or git state.++## Consequences++- Project history contains "Merge branch …" and checkpoint commits.+- Automatic commits do not run the project's pre-commit hooks.+- MCP stdio servers stay per project with the main checkout as cwd, so MCP+ tools are not isolated.+- Builds that reach outside the repository by relative path need links made+ by the setup command.+- Isolation is a development boundary, not a security boundary; Bash can+ still reach the main checkout through absolute paths.++## Validation++host-core tests against real temporary git repositories cover creation,+merge (including conflicts, markerless conflicts, and dirty-project refusal),+sync from project, behind counts, conflict-status refresh, the session hold,+hook suppression, link-safe removal, orphan cleanup, `.worktreeinclude`, port+assignment, and repository-subdirectory projects; IPC, renderer, and Electron+user-path tests cover the sidebar. `pnpm test:e2e:worktree-live` runs the+lifecycle against a real model. The hook-suppression, link-safe removal, and+`.worktreeinclude` link tests also run on Windows with directory junctions,+where Git for Windows runs hooks without an executable bit and lists files+inside a junction. Long paths and locked-file removal require Windows E2E.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 9f7da18d9..2dbc6dea1 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -373,6 +373,7 @@ Each ADR includes:| 0325 | [Smooth Windows main-window corner compositing](0325-windows-window-corner-compositing.md) | Proposed (implementation candidate; Windows E2E pending) || 0326 | [Verified SSH Host installation and daily startup](0326-verified-ssh-host-installation.md) | Accepted for experimental implementation (amends ADR 0292; Linux SSH qualification and publication pending) || 0327 | [Automatic remote Host version realignment](0327-remote-host-version-realignment.md) | Accepted for experimental implementation (amends ADR 0326 item 6; Linux SSH qualification pending) |+| 0328 | [Isolate parallel sessions of one project in git worktrees](0328-session-worktree-isolation.md) | Accepted (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/spec/03-runtime/01-ipc-protocol.md b/docs/spec/03-runtime/01-ipc-protocol.mdindex ee14880fc..ce1286ecc 100644--- a/docs/spec/03-runtime/01-ipc-protocol.md+++ b/docs/spec/03-runtime/01-ipc-protocol.md@@ -943,6 +943,12 @@ type SessionSummary = {supportedThinkingLevels?: ThinkingLevel[];updatedAt: string;createdAt: string;+ /** Isolated sessions only (ADR 0328); never carries a filesystem path. */+ worktree?: {+ branch: string;+ status: "creating" | "active" | "conflict" | "merged" | "missing";+ setupStatus?: "none" | "running" | "ok" | "failed" | null;+ };};type SessionMessageOrigin = {@@ -1056,7 +1062,9 @@ through one Electron-only allowlisted channel:Minimal interface:- `session/list`-- `session/create`+- `session/create` — optional `isolated: true` with a `projectPath` creates+ the session in its own git worktree (ADR 0328); a refusal surfaces the host's+ `WORKTREE_*` code- `session/open(sessionId)` — validate and select an existing durable sessionthrough the reviewed desktop-control path; it does not create or mutate thesession@@ -1406,6 +1414,25 @@ type ProjectMemoryEntry = {};```+## 9a. Session worktree API (ADR 0328)++Thin forwards to the host `worktree.*` methods+(06-host-rpc-protocol §4); errors keep the host's `WORKTREE_*` code.++- `worktree/probe({ projectPath })` → whether the project can host isolated+ sessions, with the refusal code, or whether it has uncommitted changes+- `worktree/preview({ sessionId })` / `worktree/merge({ sessionId, previewToken })`+- `worktree/behind({ sessionId })` → commit count, and+ `worktree/sync({ sessionId })` — "Sync from project"; `worktree/behindAll()`+ → `{ counts: { [sessionId]: count }, statusesChanged }` for the sidebar marker+- `worktree/pendingWork({ sessionId })` — unmerged work a delete discards+- `worktree/setupLog({ sessionId })`+- `worktree/reveal({ sessionId })` — Electron Main resolves the folder with+ `worktree.location` and opens it in the OS file manager; the path is never+ returned to the renderer+- `worktree/setupCommand/get({ projectPath })` /+ `worktree/setupCommand/set({ projectPath, command })`+## 10. Tool Permission APIWhen a tool requires confirmation:diff --git a/docs/spec/03-runtime/02-agent-runtime.md b/docs/spec/03-runtime/02-agent-runtime.mdindex fdecbb81f..07a4042fe 100644--- a/docs/spec/03-runtime/02-agent-runtime.md+++ b/docs/spec/03-runtime/02-agent-runtime.md@@ -1191,6 +1191,20 @@ turn open and delivers the reports when they finish. User Stop, `TaskStop`,runtime dispose, or a parent fatal error (D352) abort a still-runningdelegate.+**Isolated worktrees (ADR 0328).** In an isolated session, a delegate whose+tools include `Write` or `Edit` gets its own worktree before its first turn+(`worktree.delegate.create`, keyed by the delegation chain id, so a resumed+delegate reuses it), and its `tools.execute` calls carry that id as+`delegationId`. When the run ends the runtime calls+`worktree.delegate.settle` before publishing the report: a completed run is+merged back into the session worktree, a failed or stopped run keeps its+changes, and the outcome (merged, no changes, conflict with files, not merged+with reason, or kept) is appended to the report so the parent knows whether to+resume the delegate. Host-core briefly holds the session's own tools while it+commits and merges in the session worktree, waiting at most a few seconds for+tools already running. Read-only and Bash-only delegates, and every delegate+of a non-isolated session, are unchanged.+### 5f.1 Delegate permission scope (ADR 0089)A delegate's tool calls flow through the same host `tools.execute` path as the@@ -1652,6 +1666,15 @@ view project-list menu provides an `AGENTS.md` editor for its correspondingregistered project root. Its IPC does not accept arbitrary renderer file paths.Saves affect the next prompt without restarting the application.+For an isolated session (ADR 0328) the launch metadata carries a separate+`workspaceRoot`, its git worktree: the instruction chain and its path+resolution are rooted there, so the agent follows the worktree's own+`AGENTS.md` files. `projectPath` stays the project identity for memory,+skills, plugins, MCP servers, subagent definitions, the custom system prompt,+and group context. The system prompt adds a short isolated-workspace note+(work only in the worktree, use the `PI_PORT` block, leave branch changes and+merging to the user, and how to resolve a merge conflict).+## 8. Concurrency| Scope | MVP policy |diff --git a/docs/spec/03-runtime/03-tools-and-permissions.md b/docs/spec/03-runtime/03-tools-and-permissions.mdindex 61793d533..c4005863f 100644--- a/docs/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/spec/03-runtime/03-tools-and-permissions.md@@ -364,6 +364,37 @@ Serialization also protects the snapshot store, which both producers and `Edit`mutate: without the per-session permit, a concurrent record could land between avalidation and its write.+## 4e. Isolated session worktrees (ADR 0328)++A session created with `isolated: true` in a git project owns a dedicated+worktree at `<data_dir>/worktrees/<project-key>/<id>` on branch+`pi-desktop/<id>`, created from the project's current `HEAD` (uncommitted+project changes are not copied; git-ignored files listed in+`.worktreeinclude` are, without following links). For such a session:++- the worktree replaces the project path as `workspaceRoot` for every rule in+ §4–§5, so file tools, Bash's working directory, review snapshots, and+ artifacts resolve inside it; it never falls back to the main checkout+ (a missing worktree fails with a `WORKTREE_*` error);+- `AGENTS.md` instructions are read from the worktree, while project identity+ (memory, skills, plugins, MCP, subagents) stays keyed to the project path;+- Bash receives `PI_PORT` (first port of a 10-port block in 41000–48999),+ `PI_PROJECT_ROOT`, and `PI_WORKTREE_ROOT`;+- the optional per-project setup command runs once in each new worktree, with+ the same variables, in the user's default command shell+ (`defaultCommandShell`, otherwise the platform default: Windows PowerShell on+ Windows, bash elsewhere). It is not translated between dialects, so on+ Windows it must use PowerShell syntax (`$env:PI_PORT`, `;` rather than+ `&&` on Windows PowerShell 5.1) unless a POSIX shell such as Git Bash is+ the configured default;+- git hooks and fsmonitor are disabled for host-run git commands in the+ worktree, and removal never follows links out of it.++Merging into the project is an explicit user action (preview, then merge with+the preview token); it syncs the project branch into the worktree and only+fast-forwards the project, so conflicts stay in the worktree. Deleting an+isolated session discards its worktree and branch.+## 5. Bash RulesHost execution baseline:@@ -639,6 +670,16 @@ Session-scoped `allow-session` grants are still per `toolName` and per session:one delegate's approval of `Bash` applies to the whole session, including theparent and other delegates.+Inside an isolated session (§4e), a delegate whose tools include `Write` or+`Edit` runs in its own worktree, branched from the session worktree after the+session's pending edits are checkpointed; its `tools.execute` calls carry the+delegation chain id as `delegationId`, which re-roots path rules and Bash to+that worktree. A completed run is merged back with the same algorithm as+"Merge into project"; a conflict, failure, or stop keeps the delegate branch+and the report tells the parent to resume it. Read-only and Bash-only+delegates, and every delegate of a non-isolated session, share the owning+session's root unchanged.+## 11. Plugin ToolsPlugins can contribute tools via `agentTools`. Agent mode sees every registereddiff --git a/docs/spec/03-runtime/06-host-rpc-protocol.md b/docs/spec/03-runtime/06-host-rpc-protocol.mdindex 1016141ea..f1b11c0cc 100644--- a/docs/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/spec/03-runtime/06-host-rpc-protocol.md@@ -296,6 +296,10 @@ to later refresh and inference; the vendor picker does not collect them.`inheritPermissionFromSessionId`; when present, the host copies the existingsession's persisted permission mode atomically, while omission preserves theexisting `inherit` default. Missing/null thinking level defaults to `off`.+ Optional `isolated: true` (ADR 0328) also requires `projectPath` and gives+ the new session its own git worktree before it returns; if the worktree+ cannot be created the session is deleted again and the call fails with a+ `WORKTREE_*` error (§7).- `session.fork` — accepts `sessionId`, an optional caller-provided display`title`, and optional `throughMessageId`; createsone independent session from the source's current active canonical@@ -329,7 +333,8 @@ to later refresh and inference; the vendor picker does not collect them.contains the latest matching Task tool-call projection from the same canonicaltranscript. It is capped separately and does not widen the window or alter itscursors. Ordinary and uncapped reads omit this navigation-only field.-- `session.delete`+- `session.delete` — for an isolated session, also removes its worktree and+ branch (discarding unmerged work)- `session.getScratchPath` — the session's scratch directory (D114), createdon demand- `session.rename({ id, title })` trims and validates the title at the host@@ -358,6 +363,7 @@ to later refresh and inference; the vendor picker does not collect them.data stay with the session. Blank ids or paths are `INVALID_PARAMS`, anunknown session is `NOT_FOUND`, and a session with a running turn is`CONFLICT` so a live agent never switches instruction roots mid-turn.+ An isolated session is refused with `WORKTREE_MOVE_UNSUPPORTED`.Additive RPC; no protocol version bump.- `session.appendMessage`- `session.saveInflightMessage` — Electron-main-only checkpoint of the@@ -597,6 +603,51 @@ Session summaries/details always return `thinkingLevel`. Assistant messagesmay return `thinking`; host storage maps it to a canonical content block ratherthan appending it to answer `content`.+### Session worktrees (ADR 0328)++Additive `worktree.*` methods; no protocol version bump. Failures use code+1025 with a `WORKTREE_*` string code.++- `worktree.probe({ projectPath })` → `{ available, uncommittedChanges }`, or+ `{ available: false, errorCode, message }` when the project cannot host+ isolated sessions (not git, no commits, detached `HEAD`, git missing or+ older than 2.29, a remote-host project — `WORKTREE_REMOTE_UNSUPPORTED`, …).+ `session.create` refuses `isolated: true` for a remote-host project with the+ same code before any session is created.+- `worktree.preview({ sessionId })` → `{ preview }` with the commits and files+ that would land and a `previewToken`.+- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`. A stale token+ is `WORKTREE_CHANGED_SINCE_PREVIEW`; a dirty project is+ `WORKTREE_PROJECT_DIRTY`; a conflict is `WORKTREE_CONFLICT` and leaves the+ worktree conflicted and the project untouched.+- `worktree.behind({ sessionId })` → `{ commits }`, project-branch commits the+ session does not have yet.+- `worktree.behindAll()` → `{ counts, statusesChanged }`: the same count for+ every isolated session keyed by session id (sessions whose count cannot be+ read are omitted), computed a few sessions at a time. Conflicted sessions+ are checked for a resolution first; `statusesChanged` asks the renderer to+ refresh its session list. The renderer reads it in the background for the+ sidebar marker.+- `worktree.sync({ sessionId })` → `{ outcome }` (`synced` with `commits`, or+ `upToDate`): "Sync from project" merges the project branch into the session+ worktree after committing pending session work. The project checkout is not+ touched; a conflict is `WORKTREE_CONFLICT`, stays in the worktree, and marks+ the session like a merge conflict.+- `worktree.pendingWork({ sessionId })` → `{ pending }`, the unmerged work a+ delete would discard.+- `worktree.setupLog({ sessionId })` → `{ setupStatus, log }`.+- `worktree.location({ sessionId })` → `{ path }`; Electron Main uses it for+ "Reveal in folder" and never forwards it to the renderer.+- `worktree.setupCommand.get({ projectPath })` → `{ command }`;+ `worktree.setupCommand.set({ projectPath, command })` → `{ ok }` (unknown+ project is `NOT_FOUND`). The command runs once in each new worktree.+- `worktree.delegate.create({ sessionId, delegationId })` → `{ worktree }` and+ `worktree.delegate.settle({ sessionId, delegationId, merge })` →+ `{ settlement }` — agent-runtime only, for `Write`/`Edit` delegates of an+ isolated session (03-tools-and-permissions §10.2). Both use a 10-minute+ transport deadline (`WORKTREE_DELEGATE_RPC_TIMEOUT_MS`) because they may+ wait for the session's tools before committing and merging.+### Tools- `tools.list`- `tools.execute`@@ -826,6 +877,9 @@ type ToolsExecuteParams = {expectedCommandShellDialect?: "powershell" | "cmd" | "posix"/** Bash only: host default 60000; accepted override 1000..21600000. */timeoutMs?: number+ /** Isolated `Write`/`Edit` delegate chain id; re-roots the call to that+ * delegate's worktree (ADR 0328). Omitted for every other call. */+ delegationId?: string}```@@ -1178,6 +1232,7 @@ numeric slot; the string is the contract, the number is transport detail.| 1022 | PLUGIN_MARKET_NOT_FOUND | the platform does not have that plugin or version || 1023 | PLUGIN_MARKET_RATE_LIMITED | the download endpoint asked the client to wait || 1024 | PLUGIN_MARKET_NO_SOURCE | no distribution target can serve the package |+| 1025 | WORKTREE_* | every isolated-session worktree failure (`WORKTREE_NOT_GIT`, `WORKTREE_CONFLICT`, `WORKTREE_PROJECT_DIRTY`, `WORKTREE_MISSING`, …) shares this slot; the string code distinguishes them || -32029 | HOST_OVERLOADED | RPC dispatcher capacity exhausted || -32601 | — | unknown method || -32700 | — | unparseable request line |diff --git a/docs/spec/04-ux/01-ui-ia.md b/docs/spec/04-ux/01-ui-ia.mdindex 352c54a71..993b37094 100644--- a/docs/spec/04-ux/01-ui-ia.md+++ b/docs/spec/04-ux/01-ui-ia.md@@ -235,6 +235,28 @@ destination, chat as the home surface, tools and permissions inline.delete remain separate actions. Rename edits the task label only; archivenever removes the transcript. Open folder is a project action, not aconversation action.+- **Isolated sessions** (ADR 0328): the project menu offers **New isolated+ session**. Opening the menu probes the project: the item stays disabled+ until the answer arrives, and for an unsuitable project (not git, no+ commits, detached `HEAD`, missing or old git) it stays disabled with the+ reason shown under it. Creating probes again; a dirty project gets an info+ toast that uncommitted changes are not included. The menu also+ holds **Worktree setup command…**. An isolated row shows an `Isolated` badge+ (or `Conflict`, `Folder missing`, `Setup failed`) and adds **Merge into+ project…** (preview of commits and files, then merge; conflicting files are+ listed and stay in the session; the `Conflict` badge clears as soon as the+ session resolves or abandons the conflict, and the next merge concludes it),+ **Sync from project** (labelled with the number of new project commits+ when the menu opens, disabled when there are none or while the session is+ conflicted, which also hides the `↓N` marker; it merges the project's+ branch into the session so the session continues on current code, and a+ conflict stays in the session like a merge conflict; a row that lacks project+ commits shows a `↓N` marker next to its badge, read in the background when+ isolated sessions change, after a merge or sync, and on window focus at most+ every 15 seconds, so rendering the list never waits for git), **Show worktree folder**, and **Setup log**.+ Its delete confirmation states that unmerged work will be lost. Isolated+ sessions are never reused as the empty draft and cannot move to another+ project; forks are ordinary sessions.- **Temporary-task attachments**: selecting a saved attachment opens its filepreview even without an open project. Back returns to the no-project browsingstate. Branches preserve referenced pasted/imported inputs as child-owneddiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex e9357dd67..91091187f 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -340,6 +340,49 @@session IPC contract tests, and real-model desktop acceptance. A local modelfixture or mocked component result is not real-model acceptance evidence.+### E2E-WORKTREE-isolated-session-lifecycle++- **Preconditions:** Isolated desktop profile and data directory, git 2.29+, a+ git project on a branch with at least one commit, a configured model, and an+ optional `.worktreeinclude` listing one ignored file.+- **Steps:** Create two isolated sessions from the project menu and run a+ file-editing prompt in each at the same time. Run a Bash command that prints+ `PI_PORT` / `PI_WORKTREE_ROOT`. Merge the first session into the project;+ edit the same line in the project and in the second session, then merge the+ second. Resolve the conflict in the second session and merge again, then+ use **Sync from project** in the first session. In one+ isolated session, start two writing subagents in parallel. Finally delete+ an isolated session with unmerged work, and restart the app once while a+ session exists. Open the menu of a non-git project.+- **Expected:** Each session's edits land only in its own worktree; the project+ checkout and `git status` stay clean until a merge, and the ignored include+ file is present in each worktree. The two sessions get distinct ports. The+ first merge fast-forwards the project and a success toast names the branch.+ The conflicting merge lists the files, leaves the project untouched, and+ marks the row `Conflict`; after resolution the badge clears and the merge+ lands. The first session's row shows `↓N`; Sync from project shows the new+ commits, clears the marker, and brings the resolution+ into the first session without touching the project. Writing+ subagents edit in separate worktrees and completed runs merge back into the+ session. Delete warns about unmerged work and removes the worktree folder+ and `pi-desktop/<id>` branch without touching files linked from it. After+ restart the session reopens in its worktree; a manually removed worktree+ shows `Folder missing` and never falls back to the project. In the non-git+ project **New isolated session** is disabled with the reason under it.+- **Windows checks:** a worktree containing a directory junction is deleted+ without following the junction; a deep path beyond 260 characters is+ created and removed; deleting while a file in the worktree is locked fails+ visibly and can be retried.+- **Specs linked:** `03-runtime/03-tools-and-permissions.md` §4e, §10.2;+ `03-runtime/06-host-rpc-protocol.md`; `04-ux/01-ui-ia.md` §3.2; ADR 0328.+- **Coverage:** host-core `session_worktrees` tests (create, merge, conflict,+ removal, link safety, reconcile, delegates), worktree IPC contract tests,+ renderer `worktree-ui` tests, and agent-runtime delegate tests. The Windows+ checks need a Windows host. `pnpm test:e2e:worktree-live`+ (`scripts/e2e-worktree-live.mjs`) runs the steps above against a real model+ at protocol level, without the renderer.+- **Status:** Partially automated+### E2E-CONVERSATION-minimap-jump-leaves-follow- **Preconditions:** One Desktop conversation long enough that the transcriptdiff --git a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.mdindex 05c0dd23c..1121e74e7 100644--- a/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/01-ipc-protocol.md@@ -770,6 +770,12 @@ type SessionSummary = {supportedThinkingLevels?: ThinkingLevel[];updatedAt: string;createdAt: string;+ /** Isolated sessions only (ADR 0328); never carries a filesystem path. */+ worktree?: {+ branch: string;+ status: "creating" | "active" | "conflict" | "merged" | "missing";+ setupStatus?: "none" | "running" | "ok" | "failed" | null;+ };};type UiMessage = {@@ -863,7 +869,8 @@ ID、或会话无法解析出默认目标时,得到 `supportsReasoning: false`最小接口:- `session/list`-- `session/create`+- `session/create` — 可选的 `isolated: true` 配合 `projectPath` 会在专属 git worktree 中创建+ 会话(ADR 0328);拒绝时返回主机的 `WORKTREE_*` 代码- `session/fork({ sessionId, title?, throughMessageId? }) -> { session: SessionDetail }`- `session/get`- `session/delete`@@ -1107,6 +1114,23 @@ type ProjectRecord = {};```+## 9a. 会话 worktree API(ADR 0328)++对主机 `worktree.*` 方法的薄转发(06-host-rpc-protocol §4);错误保留主机的+`WORKTREE_*` 代码。++- `worktree/probe({ projectPath })` → 项目能否承载隔离会话(不能时给出拒绝代码),以及是否+ 有未提交改动+- `worktree/preview({ sessionId })` / `worktree/merge({ sessionId, previewToken })`+- `worktree/behind({ sessionId })` → 提交数,以及 `worktree/sync({ sessionId })` — “从项目同步”;`worktree/behindAll()`+ → `{ counts: { [sessionId]: count }, statusesChanged }`,用于侧边栏标记+- `worktree/pendingWork({ sessionId })` — 删除时会丢弃的未合并工作+- `worktree/setupLog({ sessionId })`+- `worktree/reveal({ sessionId })` — Electron Main 通过 `worktree.location` 解析文件夹并在+ 系统文件管理器中打开;路径绝不返回给渲染器+- `worktree/setupCommand/get({ projectPath })` /+ `worktree/setupCommand/set({ projectPath, command })`+## 10. 工具权限 API当工具需要确认时:diff --git a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md b/docs/zh-CN/spec/03-runtime/02-agent-runtime.mdindex 0a71c906d..53956a9cc 100644--- a/docs/zh-CN/spec/03-runtime/02-agent-runtime.md+++ b/docs/zh-CN/spec/03-runtime/02-agent-runtime.md@@ -835,6 +835,14 @@ details 会说明该委托丢失了历史,而不是把一个不完整的答案跑时停止调用工具,运行时保持持久回合打开,并在它们完成时交回报告。用户Stop、`TaskStop`、运行时销毁或父级终态错误(D352)会中止仍在运行的委托。+**隔离 worktree(ADR 0328)。** 在隔离会话中,工具包含 `Write` 或 `Edit` 的委托在首个回合+前获得自己的 worktree(`worktree.delegate.create`,以委托链 id 为键,续跑的委托会复用它),+其 `tools.execute` 调用以 `delegationId` 携带该 id。运行结束时,运行时在发布报告前调用+`worktree.delegate.settle`:完成的运行合回会话 worktree,失败或停止的运行保留改动,结果+(已合并、无改动、冲突及文件、未合并及原因、已保留)附加到报告中,让父级知道是否需要+续跑该委托。host-core 在会话 worktree 中提交和合并时,会短暂挡住会话自己的工具,对已经+在运行的工具最多等待几秒。只读和仅 Bash 的委托,以及非隔离会话的所有委托,行为不变。+### 5f.1 委托权限作用域(ADR 0089)委托的工具调用与父级走同一条 host `tools.execute` 路径。当定义声明了@@ -1142,6 +1150,12 @@ sidecar 从不直接读取工作区指令。改变的根链注册的项目根。其 IPC 不接受任意渲染器文件路径。保存会影响下一个提示,而无需重新启动应用程序。+对隔离会话(ADR 0328),启动元数据另带 `workspaceRoot`,即其 git worktree:指令链及其+路径解析都以它为根,代理因此遵循 worktree 自己的 `AGENTS.md`。`projectPath` 仍是记忆、+技能、插件、MCP 服务器、子代理定义、自定义系统提示和分组上下文的项目身份。系统提示会+增加一段简短的隔离工作区说明(只在 worktree 中工作、使用 `PI_PORT` 端口块、把切换分支和+合并留给用户,以及如何解决合并冲突)。+## 8. 并发| 适用范围 | MVP 政策 |diff --git a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.mdindex a96854fed..6e781ecf0 100644--- a/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md+++ b/docs/zh-CN/spec/03-runtime/03-tools-and-permissions.md@@ -302,6 +302,32 @@ type ReviewChange = {`patch`)——返回带有错误专属恢复提示的终止工具结果,代理随后停止并报告准确的不匹配。不要手动编辑旧的 unified-diff 块头,也不要继续修复循环。+## 4e. 隔离会话 worktree(ADR 0328)++在 git 项目中以 `isolated: true` 创建的会话拥有专属 worktree,位于+`<data_dir>/worktrees/<project-key>/<id>`,分支为 `pi-desktop/<id>`,从项目当前+`HEAD` 创建(项目中未提交的改动不会被复制;`.worktreeinclude` 列出的 git 忽略文件会被+复制,且不跟随链接)。对这类会话:++- worktree 取代项目路径成为 §4–§5 所有规则的 `workspaceRoot`,文件工具、Bash 工作+ 目录、审阅快照和产物都在其中解析;绝不回退到主检出(worktree 丢失时返回+ `WORKTREE_*` 错误);+- `AGENTS.md` 指令从 worktree 读取,而项目身份(记忆、技能、插件、MCP、子代理)仍以+ 项目路径为键;+- Bash 获得 `PI_PORT`(41000–48999 中一个 10 端口块的首端口)、`PI_PROJECT_ROOT`+ 和 `PI_WORKTREE_ROOT`;+- 可选的项目初始化命令在每个新 worktree 中运行一次,带同样的变量,使用用户的默认命令+ shell(`defaultCommandShell`,未设置时用平台默认:Windows 上为 Windows PowerShell,+ 其他平台为 bash)。命令不会在方言之间转换,因此在 Windows 上必须使用 PowerShell 语法+ (`$env:PI_PORT`;Windows PowerShell 5.1 用 `;` 而不是 `&&`),除非默认 shell 配置为+ Git Bash 等 POSIX shell;+- 宿主在 worktree 中运行的 git 命令禁用 hooks 和 fsmonitor,删除时绝不跟随链接越出+ worktree。++合并到项目是显式的用户操作(先预览,再携带预览令牌合并):先把项目分支同步进+worktree,项目只做快进,因此冲突留在 worktree 中。删除隔离会话即丢弃其 worktree+和分支。+## 5. Bash 规则主机执行基线:@@ -551,6 +577,12 @@ sidecar 不附加覆盖,委托使用会话的有效权限模式;因此父会一名代表对 `Bash` 的批准适用于整个会议,包括家长和其他代表。+在隔离会话(§4e)中,工具包含 `Write` 或 `Edit` 的子代理在自己的 worktree 中运行:+先为会话的未提交编辑建立检查点,再从会话 worktree 分出分支;它的 `tools.execute`+调用携带委派链 id `delegationId`,路径规则和 Bash 因此以该 worktree 为根。运行完成后+用与“合并到项目”相同的算法合回;冲突、失败或停止时保留子代理分支,报告会提示父代理+续跑处理。只读和仅 Bash 的子代理,以及非隔离会话的所有子代理,仍共享所属会话的根目录。+## 11. 插件工具插件可通过 `agentTools` 贡献工具。Agent 模式能看到每一个已注册的diff --git a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.mdindex 0d6cf9393..e9df69a66 100644--- a/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md+++ b/docs/zh-CN/spec/03-runtime/06-host-rpc-protocol.md@@ -226,7 +226,8 @@ type ToolBudgetHealth = {### 会议- `session.list`- `session.create` — 接受可选的 `thinkingLevel`; missing/null 默认值-至 `off`+至 `off`。可选的 `isolated: true`(ADR 0328)同时要求 `projectPath`,并在返回前为新会话+创建专属 git worktree;无法创建时会话会被删除,调用以 `WORKTREE_*` 错误(§7)失败。- `session.fork` — accepts `sessionId`, an optional caller-provided display`title`, and optional `throughMessageId`; createsone independent session from the source's current active canonical@@ -241,7 +242,7 @@ type ToolBudgetHealth = {`CONFLICT`, normalized by Electron to `AGENT_BUSY`. The source turn continueswithout sharing runtime state with the child.- `session.get`-- `session.delete`+- `session.delete` — 对隔离会话还会删除其 worktree 和分支(丢弃未合并的工作)- `session.getScratchPath` — 会话的 scratch 目录(D114),按需创建- `session.rename` — 在主机边界裁剪并校验标题,接受 1–80 个 Unicode 码点;成功后将标题来源标记为 `manual`,但不更新 `updated_at`、转录内容、消息数或历史通知标题快照。@@ -409,6 +410,40 @@ off | minimal | low | medium | high | xhigh | max可能会返回 `thinking`;主机存储将其映射到规范内容块,而不是而不是将其附加到答案 `content` 中。+### 会话 worktree(ADR 0328)++新增的 `worktree.*` 方法为增量 RPC,不升协议版本。失败使用代码 1025 及 `WORKTREE_*`+字符串代码。++- `worktree.probe({ projectPath })` → `{ available, uncommittedChanges }`;项目无法承载+ 隔离会话时(非 git、无提交、分离 `HEAD`、缺少 git 或低于 2.29、远程主机项目——+ `WORKTREE_REMOTE_UNSUPPORTED` 等)返回+ `{ available: false, errorCode, message }`。`session.create` 对远程主机项目的 `isolated: true` 以同一代码拒绝,+ 不会创建任何会话。+- `worktree.preview({ sessionId })` → `{ preview }`,包含将要合入的提交、文件及+ `previewToken`。+- `worktree.merge({ sessionId, previewToken })` → `{ outcome }`。令牌过期为+ `WORKTREE_CHANGED_SINCE_PREVIEW`;项目有未提交改动为 `WORKTREE_PROJECT_DIRTY`;冲突为+ `WORKTREE_CONFLICT`,worktree 保持冲突状态,项目不受影响。+- `worktree.behind({ sessionId })` → `{ commits }`,即会话尚未包含的项目分支提交数。+- `worktree.behindAll()` → `{ counts, statusesChanged }`:以会话 id 为键给出每个隔离会话的同一计数+ (读不到的会话省略),每次并发检查少量会话。处于冲突状态的会话会先检查是否已解决;+ `statusesChanged` 提示渲染层刷新会话列表。渲染层在后台读取,用于侧边栏标记。+- `worktree.sync({ sessionId })` → `{ outcome }`(`synced` 及 `commits`,或 `upToDate`):+ “从项目同步”先提交会话中待提交的工作,再把项目分支合入会话 worktree。不改动项目检出;+ 冲突为 `WORKTREE_CONFLICT`,留在 worktree 中,并像合并冲突一样标记会话。+- `worktree.pendingWork({ sessionId })` → `{ pending }`,即删除会丢弃的未合并工作。+- `worktree.setupLog({ sessionId })` → `{ setupStatus, log }`。+- `worktree.location({ sessionId })` → `{ path }`;仅供 Electron Main 的“在文件夹中显示”+ 使用,绝不转发给渲染器。+- `worktree.setupCommand.get({ projectPath })` → `{ command }`;+ `worktree.setupCommand.set({ projectPath, command })` → `{ ok }`(未知项目为+ `NOT_FOUND`)。该命令在每个新 worktree 中运行一次。+- `worktree.delegate.create({ sessionId, delegationId })` → `{ worktree }` 和+ `worktree.delegate.settle({ sessionId, delegationId, merge })` → `{ settlement }`——仅供+ agent-runtime 为隔离会话中的 `Write`/`Edit` 子代理使用(03-tools-and-permissions §10.2)。两者使用+ 10 分钟的传输期限(`WORKTREE_DELEGATE_RPC_TIMEOUT_MS`),因为提交和合并前可能要等待会话的工具。+### 工具- `tools.list`- `tools.execute`@@ -576,6 +611,9 @@ type ToolsExecuteParams = {expectedCommandShellDialect?: "powershell" | "cmd" | "posix"/** Bash only: host default 60000; accepted override 1000..21600000. */timeoutMs?: number+ /** Isolated `Write`/`Edit` delegate chain id; re-roots the call to that+ * delegate's worktree (ADR 0328). Omitted for every other call. */+ delegationId?: string}```@@ -923,6 +961,7 @@ JSON-RPC 错误携带一个数字 `code` 以及 `data.errorCode`,后者是来| 1022 | PLUGIN_MARKET_NOT_FOUND | 平台没有该插件或该版本 || 1023 | PLUGIN_MARKET_RATE_LIMITED | 下载接口要求客户端等待后重试 || 1024 | PLUGIN_MARKET_NO_SOURCE | 没有任何分发目标能提供该包 |+| 1025 | WORKTREE_* | 所有隔离会话 worktree 失败(`WORKTREE_NOT_GIT`、`WORKTREE_CONFLICT`、`WORKTREE_PROJECT_DIRTY`、`WORKTREE_MISSING` 等)共用此槽位,以字符串代码区分 || -32029 | HOST_OVERLOADED | RPC 调度程序容量已耗尽 || -32601 | — | 未知方法 || -32700 | — | 无法解析的请求行 |diff --git a/docs/zh-CN/spec/04-ux/01-ui-ia.md b/docs/zh-CN/spec/04-ux/01-ui-ia.mdindex acf539e48..3dcee9621 100644--- a/docs/zh-CN/spec/04-ux/01-ui-ia.md+++ b/docs/zh-CN/spec/04-ux/01-ui-ia.md@@ -185,6 +185,15 @@- **对话操作**:pin/unpin、archive/restore 和删除保留单独的行动。存档永远不会删除文字记录。打开的文件夹是项目行动,而不是对话行动。+- **隔离会话**(ADR 0328):项目菜单提供 **新建隔离会话**。打开菜单时探测项目:结果返回前该项+ 保持置灰;对不适用的项目(非 git、无提交、分离 `HEAD`、缺少 git 或版本过旧)保持置灰,+ 并在下方显示原因。创建时会再次探测;项目有未提交改动时显示信息提示,说明这些改动不会+ 带入。菜单还包含+ **Worktree 初始化命令…**。隔离会话行显示 `Isolated` 徽标(或 `Conflict`、+ `Folder missing`、`Setup failed`),并增加 **合并到项目…**(先预览提交和文件,再合并;+ 冲突文件会列出并留在会话中;会话一旦解决或放弃冲突,`Conflict` 徽标即消失,下次合并时完成该合并)、**从项目同步**(打开菜单时显示项目新提交的数量,没有新提交或会话处于冲突状态时置灰,冲突状态下也不显示 `↓N` 标记;把项目分支合入会话,让会话基于最新代码继续开发,冲突像合并冲突一样留在会话中;缺少项目提交的会话行在徽标旁显示 `↓N` 标记,它在隔离会话变化、合并或同步之后以及窗口获得焦点时(最多每 15 秒一次)于后台读取,渲染列表从不等待 git)、**显示 worktree 文件夹** 和 **初始化日志**。删除确认会说明+ 未合并的工作将丢失。隔离会话不会被当作空草稿复用,也不能移动到其他项目;分叉得到的+ 是普通会话。- **排序**:面向用户的模式为最近更新、创建日期、最旧首先是姓名。固定的行先于未固定的行。项目组通过拖动标题或在该标题上按 `ArrowUp`/`ArrowDown` 切换到 `manual`。会话 `manual` 仍是兼容性值。diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex 1fa1ae828..965f7c07b 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -9385,6 +9385,33 @@ Follow the [current S3 acceptance scenario](/spec/06-delivery/04-e2e-test-plan#esession IPC contract tests, and real-model desktop acceptance. A local modelfixture or mocked component result is not real-model acceptance evidence.+### E2E-WORKTREE-isolated-session-lifecycle++- **前置条件:** 隔离的桌面配置和数据目录、git 2.29+、一个处于分支上且至少有一次提交的+ git 项目、已配置的模型,以及可选的 `.worktreeinclude`(列出一个被忽略的文件)。+- **步骤:** 从项目菜单创建两个隔离会话,同时在两者中运行修改文件的提示。运行打印+ `PI_PORT` / `PI_WORKTREE_ROOT` 的 Bash 命令。把第一个会话合并到项目;在项目和第二个+ 会话中修改同一行,再合并第二个会话。在第二个会话中解决冲突后再次合并,然后在第一个会话中使用**从项目同步**。在一个隔离会话+ 中并行启动两个写文件的子代理。最后删除一个含未合并工作的隔离会话,并在会话存在时重启+ 一次应用。打开一个非 git 项目的菜单。+- **预期:** 每个会话的修改只落在自己的 worktree 中;在合并前项目检出和 `git status`+ 保持干净,每个 worktree 中都有被 include 的忽略文件。两个会话获得不同端口。第一次合并+ 快进项目,成功提示中给出分支名。冲突的合并会列出文件、不改动项目,并把该行标为+ `Conflict`;解决后徽标消失、合并成功。第一个会话行显示 `↓N`;从项目同步会显示新提交数并清除该标记,并把冲突解决结果带入第一个会话,不改动项目。写文件的子代理在各自的 worktree 中编辑,完成的运行合回会话。+ 删除时提示未合并工作将丢失,并删除 worktree 文件夹和 `pi-desktop/<id>` 分支,不触碰其中+ 链接指向的文件。重启后会话在其 worktree 中重新打开;被手动删除的 worktree 显示+ `Folder missing`,且绝不回退到项目目录。在非 git 项目中 **新建隔离会话** 置灰,并在下方+ 显示原因。+- **Windows 检查:** 含目录 junction 的 worktree 删除时不跟随 junction;超过 260 字符的深+ 路径能创建和删除;worktree 中有文件被锁定时删除会明确失败并可重试。+- **关联规范:** `03-runtime/03-tools-and-permissions.md` §4e、§10.2;+ `03-runtime/06-host-rpc-protocol.md`;`04-ux/01-ui-ia.md` §3.2;ADR 0328。+- **覆盖:** host-core `session_worktrees` 测试(创建、合并、冲突、删除、链接安全、启动+ 对账、子代理)、worktree IPC 契约测试、渲染层 `worktree-ui` 测试和 agent-runtime 子代理+ 测试。Windows 检查需要 Windows 主机。`pnpm test:e2e:worktree-live`+ (`scripts/e2e-worktree-live.mjs`)在协议层用真实模型执行上述步骤,不经过渲染层。+- **状态:** Partially automated+### E2E-HOOKS-cancel-and-dispose- **#816 扩展验收:** 命令弹窗显示期间 Stop,真实渲染层移除弹窗,后续弹窗和 execdiff --git a/package.json b/package.jsonindex 98a60bda8..f26dc165c 100644--- a/package.json+++ b/package.json@@ -24,6 +24,7 @@"test:e2e:jev": "node --test apps/desktop/test/jev-api-key-check.test.mjs apps/desktop/test/jev-config.test.mjs apps/desktop/test/jev-settings-user-path.test.mjs apps/desktop/test/jev-service-setup-user-path.test.mjs apps/desktop/test/jev-session-launch.test.mjs && node packages/agent-runtime/node_modules/vitest/vitest.mjs run packages/agent-runtime/src/jev-classifier-tool.test.ts packages/agent-runtime/src/runtime.test.ts -t Jev --config packages/agent-runtime/vitest.config.ts","test:e2e:storage": "node scripts/e2e-storage-settings.mjs && node scripts/e2e-storage-migration.mjs && node scripts/e2e-storage-bootstrap.mjs","test:e2e:asktool-card": "node scripts/e2e-asktool-card.mjs",+ "test:e2e:worktree-live": "node scripts/e2e-worktree-live.mjs","test:e2e:scheduled": "node scripts/e2e-scheduled.mjs","test:e2e:keep-awake": "node scripts/e2e-keep-awake.mjs","test:e2e:live-voice": "node scripts/e2e-live-voice.mjs",diff --git a/packages/agent-runtime/src/runtime.test.ts b/packages/agent-runtime/src/runtime.test.tsindex 4764d1347..fa020cec5 100644--- a/packages/agent-runtime/src/runtime.test.ts+++ b/packages/agent-runtime/src/runtime.test.ts@@ -1,7 +1,7 @@import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";-import { describe, expect, it, vi } from "vitest";+import { describe, expect, it, vi, beforeEach } from "vitest";import { type Agent, type AgentMessage, type AgentTool } from "@earendil-works/pi-agent-core";import {createAssistantMessageEventStream,@@ -18,6 +18,8 @@ import {COMPACTION_FALLBACK_MARKER,DesktopAgentRuntime,PATH_INSTRUCTION_RESOLUTION_TIMEOUT_MS,+ isolatedWorkspaceGuidance,+ delegateWorktreeNote,looksLikePseudoToolCall,toolResultFromUi,type CompactionStrategy,@@ -168,6 +170,7 @@ function createRuntime(compactionStrategy: CompactionStrategy;projectPath: string;remoteWorkspace: { hostKey: string; path: string };+ workspaceRoot: string;scratchDir: string;customSystemPrompt: import("./custom-system-prompt.js").CustomSystemPrompt;projectInstructions: import("./project-instructions.js").ProjectInstructions;@@ -199,6 +202,7 @@ function createRuntime(compactionStrategy: overrides.compactionStrategy,projectPath: overrides.projectPath,remoteWorkspace: overrides.remoteWorkspace,+ workspaceRoot: overrides.workspaceRoot,scratchDir: overrides.scratchDir,customSystemPrompt: overrides.customSystemPrompt,pluginTools: overrides.pluginTools,@@ -259,6 +263,7 @@ function runtimeMatches(customSystemPrompt: (runtime as any).customSystemPrompt,projectMemory: (runtime as any).projectMemory,projectPath: (runtime as any).projectPath,+ workspaceRoot: (runtime as any).workspaceRoot,commandShell: (runtime as any).commandShell,subagents: (runtime as any).subagents,subagentProviders: (runtime as any).subagentProviders,@@ -11755,3 +11760,181 @@ describe("local runtime with a remote tool workspace", () => {await runtime.dispose();});});++describe("isolated session workspace (ADR 0328)", () => {+ const systemPrompt = (runtime: DesktopAgentRuntime): string =>+ (runtime as unknown as { agent: { state: { systemPrompt: string } } }).agent.state+ .systemPrompt;++ it("tells the model about the worktree only in an isolated session", () => {+ const isolated = createRuntime({ projectPath: "/work/app", workspaceRoot: "/data/wt/app/s1" });+ const ordinary = createRuntime({ projectPath: "/work/app" });+ expect(systemPrompt(isolated)).toContain(isolatedWorkspaceGuidance());+ expect(systemPrompt(isolated)).toContain("PI_PORT");+ expect(systemPrompt(ordinary)).not.toContain("Isolated session:");+ });++ it("works in the worktree while the project stays its identity", () => {+ const runtime = createRuntime({ projectPath: "/work/app", workspaceRoot: "/data/wt/app/s1" });+ const internals = runtime as unknown as { extensionCwd(): string; projectPath?: string };+ expect(internals.extensionCwd()).toBe("/data/wt/app/s1");+ expect(internals.projectPath).toBe("/work/app");+ expect(+ (createRuntime({ projectPath: "/work/app" }) as unknown as { extensionCwd(): string })+ .extensionCwd(),+ ).toBe("/work/app");+ });++ it("is not reused for another worktree or for a non-isolated launch", () => {+ const runtime = createRuntime({ projectPath: "/work/app", workspaceRoot: "/data/wt/app/s1" });+ expect(runtimeMatches(runtime)).toBe(true);+ expect(runtimeMatches(runtime, { workspaceRoot: "/data/wt/app/s2" })).toBe(false);+ expect(runtimeMatches(runtime, { workspaceRoot: undefined })).toBe(false);+ });+});++describe("isolated-session subagent worktrees (ADR 0328)", () => {+ const writer: SubagentDefinition = {+ name: "fixer",+ description: "Implement a change.",+ tools: ["Read", "Edit", "Write"],+ prompt: "Implement it.",+ source: "builtin",+ };+ const shellOnly: SubagentDefinition = {+ name: "test-runner",+ description: "Run tests.",+ tools: ["Read", "Grep", "Bash"],+ prompt: "Run them.",+ source: "builtin",+ };+ const tool = (runtime: DesktopAgentRuntime, name: string) =>+ (runtime as any).agent.state.tools.find((entry: any) => entry.name === name);++ function worktreeHost(settlement: unknown, createError?: Error) {+ return {+ call: vi.fn(async (method: string, _params?: unknown) => {+ if (method === "worktree.delegate.create") {+ if (createError) throw createError;+ return { worktree: { branch: "pi-desktop/s-d", status: "active" } };+ }+ if (method === "worktree.delegate.settle") return { settlement };+ if (method === "tools.execute") return { ok: true, content: {} };+ return undefined;+ }),+ onNotification: vi.fn(() => () => {}),+ };+ }+ const calls = (host: ReturnType<typeof worktreeHost>, method: string) =>+ host.call.mock.calls.filter(([name]) => name === method).map(([, params]) => params as any);++ async function runToEnd(runtime: DesktopAgentRuntime, agent: string, id: string) {+ const started = await tool(runtime, "Task").execute(id, { agent, task: "Do it." });+ const delegationId = (started.details as any).delegationId as string;+ const waited = await tool(runtime, "TaskWait").execute(`${id}-wait`, { delegationIds: [delegationId] });+ return { started, delegationId, text: waited.content[0].text as string };+ }++ beforeEach(() => {+ subagentRuns.calls.length = 0;+ subagentRuns.deferred = false;+ subagentRuns.constructorError = undefined;+ subagentRuns.result = undefined;+ });++ it("gives a writing delegate its own worktree, routes its tools there, and reports the merge", async () => {+ const host = worktreeHost({ result: "merged", commits: 2 });+ const runtime = createRuntime({+ subagents: [writer, shellOnly],+ host: host as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ const { delegationId, text } = await runToEnd(runtime, "fixer", "task-w");+ const [create] = calls(host, "worktree.delegate.create");+ expect(create).toEqual({ sessionId: "session-1", delegationId });++ const write = subagentRuns.calls[0].tools.find((entry: any) => entry.name === "Write");+ await write.execute("write-1", { path: "a.txt", content: "x" }, undefined, undefined);+ expect(calls(host, "tools.execute").at(-1)).toEqual(+ expect.objectContaining({ delegationId }),+ );+ expect((runtime as any).delegateWorktrees.size).toBe(0);++ expect(calls(host, "worktree.delegate.settle")).toEqual([+ { sessionId: "session-1", delegationId, merge: true },+ ]);+ expect(text).toContain("Isolated worktree: merged 2 commit(s) into the session workspace.");+ await runtime.dispose();+ });++ it("leaves Bash-only delegates and non-isolated sessions on the shared workspace", async () => {+ const host = worktreeHost({ result: "merged", commits: 1 });+ const isolated = createRuntime({+ subagents: [writer, shellOnly],+ host: host as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ await runToEnd(isolated, "test-runner", "task-b");+ const ordinary = createRuntime({ subagents: [writer], host: host as never, projectPath: "/work/app" });+ await runToEnd(ordinary, "fixer", "task-o");+ expect(calls(host, "worktree.delegate.create")).toEqual([]);+ expect(calls(host, "worktree.delegate.settle")).toEqual([]);+ const write = subagentRuns.calls[1].tools.find((entry: any) => entry.name === "Write");+ await write.execute("write-o", { path: "a.txt", content: "x" }, undefined, undefined);+ expect(calls(host, "tools.execute").at(-1)).not.toHaveProperty("delegationId");+ await isolated.dispose();+ await ordinary.dispose();+ });++ it("keeps an unfinished run's work and tells the parent how to resolve a conflict", async () => {+ const conflictHost = worktreeHost({ result: "conflict", files: ["src/a.ts"] });+ const runtime = createRuntime({+ subagents: [writer],+ host: conflictHost as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ const { delegationId, text } = await runToEnd(runtime, "fixer", "task-c");+ expect(text).toContain("NOT merged");+ expect(text).toContain("src/a.ts");+ expect(text).toContain(`Task(resume: "${delegationId}")`);++ const keptHost = worktreeHost({ result: "kept" });+ const failing = createRuntime({+ subagents: [writer],+ host: keptHost as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ subagentRuns.result = { agentName: "fixer", status: "failed", report: "boom", turns: 1, toolCalls: 1 };+ const failed = await runToEnd(failing, "fixer", "task-f");+ expect(calls(keptHost, "worktree.delegate.settle")[0].merge).toBe(false);+ expect(failed.text).toContain("changes were kept unmerged");+ await runtime.dispose();+ await failing.dispose();+ });++ it("does not start a writing delegate whose worktree cannot be created", async () => {+ const host = worktreeHost({ result: "none" }, new Error("the session has an unfinished merge conflict"));+ const runtime = createRuntime({+ subagents: [writer],+ host: host as never,+ projectPath: "/work/app",+ workspaceRoot: "/data/wt/app/s1",+ });+ const result = await tool(runtime, "Task").execute("task-x", { agent: "fixer", task: "Do it." });+ expect(result.details.error).toContain("Could not prepare an isolated worktree");+ expect(result.details.error).toContain("unfinished merge conflict");+ expect(subagentRuns.calls).toHaveLength(0);+ await runtime.dispose();+ });++ it("describes every settlement in the report", () => {+ const resume = 'Task(resume: "d1")';+ expect(delegateWorktreeNote({ result: "noChanges" }, resume)).toContain("no file changes");+ expect(delegateWorktreeNote({ result: "notMerged", reason: "busy" }, resume)).toContain("busy");+ expect(delegateWorktreeNote({ result: "none" }, resume)).toBe("");+ });+});diff --git a/packages/agent-runtime/src/runtime.ts b/packages/agent-runtime/src/runtime.tsindex 8d5311fa5..7e51c5872 100644--- a/packages/agent-runtime/src/runtime.ts+++ b/packages/agent-runtime/src/runtime.ts@@ -511,6 +511,11 @@ export type DelegationStatus =*/export type DelegationRecord = {delegationId: string;+ /**+ * Chain id under which host-core keeps this Write/Edit subagent's own git+ * worktree in an isolated session (ADR 0328); absent otherwise.+ */+ worktreeKey?: string;/** Original Task transcript snapshot, available after its immediate result. */taskMessage?: UiMessage;taskTurnId?: string;@@ -979,6 +984,11 @@ export type AgentRuntimeOptions = {projectPath?: string;/** Remote tool root. Model requests and runtime state remain on this machine. */remoteWorkspace?: { hostKey: string; path: string };+ /**+ * An isolated session's git worktree (ADR 0328). Files, the extension cwd,+ * and edit bookkeeping use it; `projectPath` stays the project identity.+ */+ workspaceRoot?: string;/** Instructions resolved from the session's workspace. */projectInstructions?: ProjectInstructions;/** Durable project context loaded from host-owned project memory. */@@ -1048,6 +1058,7 @@ export type RuntimeMatchConfig = {projectPath?: string;/** Remote tool root. Model requests and runtime state remain on this machine. */remoteWorkspace?: { hostKey: string; path: string };+ workspaceRoot?: string;commandShell: CommandShellOption;subagents?: SubagentDefinition[];subagentProviders?: Record<string, RuntimeProviderConfig>;@@ -1719,6 +1730,50 @@ function estimateVisibleResponseOutputTokens(return Math.max(1, Math.ceil(Array.from(visible).length / 4));}+/** host-core's `worktree.delegate.settle` result (ADR 0328). */+export type DelegateWorktreeSettlement =+ | { result: "none" }+ | { result: "noChanges" }+ | { result: "merged"; commits: number }+ | { result: "conflict"; files: string[] }+ | { result: "notMerged"; reason: string }+ | { result: "kept" };++/** The line appended to a delegate's report about its worktree. */+export function delegateWorktreeNote(settlement: DelegateWorktreeSettlement, resume: string): string {+ switch (settlement.result) {+ case "merged":+ return `Isolated worktree: merged ${settlement.commits} commit(s) into the session workspace.`;+ case "noChanges":+ return "Isolated worktree: no file changes; the worktree was removed.";+ case "conflict":+ return `Isolated worktree: NOT merged. These files conflict with the session workspace: ${settlement.files.join(", ")}. Continue with ${resume} to resolve them in the subagent's worktree; the merge is retried when it ends.`;+ case "notMerged":+ return `Isolated worktree: not merged yet (${settlement.reason}). Continue with ${resume} to retry.`;+ case "kept":+ return `Isolated worktree: the run did not complete, so its changes were kept unmerged. Continue with ${resume} to finish them.`;+ default:+ return "";+ }+}++/**+ * System-prompt rules for an isolated session (ADR 0328): the workspace is a+ * separate git worktree that the user merges from the app.+ */+export function isolatedWorkspaceGuidance(): string {+ return [+ "Isolated session: the advertised workspace is a separate git worktree on its own branch; the user's main project checkout is outside it.",+ "Edit, build, and test only inside this workspace and never change files in the main checkout.",+ "The worktree is a fresh checkout, so install dependencies first when a build or test needs them.",+ "Start dev servers only on the 10 ports beginning at the PI_PORT environment variable.",+ "Do not switch branches, rebase, or reset in this worktree; the user merges its branch into the project from the app.",+ "To resolve a merge conflict here, remove the conflict markers from text files, and stage binary or deleted files with git add or git rm.",+ "MCP tools act on the main project, not on this workspace.",+ "Subagents that can Write or Edit work in their own worktrees and are merged back when they finish; their report states the merge result.",+ ].join(" ");+}+export class DesktopAgentRuntime {private agent: Agent;private models: Models;@@ -1786,6 +1841,8 @@ export class DesktopAgentRuntime {* resolves the delegate's permission under it instead of the session mode.*/private delegatePermissionScopes = new Map<string, SubagentPermission>();+ /** Worktree key of the delegate executing one tool call (ADR 0328). */+ private delegateWorktrees = new Map<string, string>();/** Serializes same-path mutations across the parent and its delegates. */private writeLocks = new PathMutex();/** Complete tool registry; only the active subset is sent to the provider. */@@ -1800,6 +1857,8 @@ export class DesktopAgentRuntime {private scratchDir?: string;private projectPath?: string;private remoteWorkspace?: { hostKey: string; path: string };+ /** Set only for an isolated session; see `RuntimeConfig.workspaceRoot`. */+ private workspaceRoot?: string;private commandShell: CommandShellOption;private baseProjectInstructions?: ProjectInstructions;private projectInstructions?: ProjectInstructions;@@ -1982,6 +2041,8 @@ export class DesktopAgentRuntime {this.remoteWorkspace = opts.remoteWorkspace;this.scratchDir = opts.remoteWorkspace ? undefined : opts.scratchDir;this.projectPath = opts.remoteWorkspace?.path ?? (opts.projectPath?.trim() || undefined);+ // Remote workspaces are never isolated (ADR 0328).+ this.workspaceRoot = opts.remoteWorkspace ? undefined : opts.workspaceRoot?.trim() || undefined;this.customSystemPrompt = opts.customSystemPrompt;this.baseProjectInstructions = opts.projectInstructions;this.projectInstructions = opts.projectInstructions;@@ -2033,6 +2094,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the`Your scratch directory for this session is \`${formatScratchDirForShell(this.commandShell, this.scratchDir)}\` (in Bash: ${shellScratchVariable(this.commandShell)}). Store ad-hoc temporary and intermediate files there using absolute paths. Workspace writes must be task-related project files or required toolchain outputs. Scratch persists across turns and is deleted with the session.`,]: []),+ // Isolated session (ADR 0328).+ ...(this.workspaceRoot ? [isolatedWorkspaceGuidance()] : []),];// A custom SYSTEM.md replaces only the product persona line, never the// operational rules in the default parts: tool guidance, delegation@@ -2644,6 +2707,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the(this.projectMemory ?? "") === (config.projectMemory?.trim() ?? "") &&(this.projectPath ?? "") === (config.remoteWorkspace?.path ?? config.projectPath?.trim() ?? "") &&safeJson(this.remoteWorkspace ?? null) === safeJson(config.remoteWorkspace ?? null) &&+ (this.workspaceRoot ?? "") === (config.workspaceRoot?.trim() ?? "") &&// 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.@@ -2797,7 +2861,8 @@ Do not invent objections or turn speculative risks into blockers. Stop when the* path in place, because loading extensions must not fail the session.*/private extensionCwd(): string {- if (this.projectPath) return this.projectPath;+ const root = this.workspaceRoot ?? this.projectPath;+ if (root) return root;if (!this.scratchDir) return process.cwd();try {mkdirSync(this.scratchDir, { recursive: true });@@ -3327,7 +3392,10 @@ Do not invent objections or turn speculative risks into blockers. Stop when theconst mutationPath = PATH_MUTATING_TOOLS.has(toolName) && isRecord(params) && typeof params.path === "string"? this.remoteWorkspace? remoteMutationIdentity(this.remoteWorkspace, params.path)- : await mutationFailureKey(params.path, this.projectPath ?? this.scratchDir)+ : await mutationFailureKey(+ params.path,+ this.workspaceRoot ?? this.projectPath ?? this.scratchDir,+ ): undefined;await this.loadPathInstructions(toolName, params);const isBash = toolName === "Bash";@@ -3465,6 +3533,11 @@ Do not invent objections or turn speculative risks into blockers. Stop when the...(this.delegatePermissionScopes.has(toolCallId)? { permissionScope: this.delegatePermissionScopes.get(toolCallId) }: {}),+ // A Write/Edit delegate of an isolated session runs in its own+ // worktree; host-core resolves the key against its registry.+ ...(this.delegateWorktrees.has(toolCallId)+ ? { delegationId: this.delegateWorktrees.get(toolCallId) }+ : {}),});} catch (error) {executionFailed = true;@@ -4702,6 +4775,30 @@ Do not invent objections or turn speculative risks into blockers. Stop when the);}const delegationId = randomUUID();+ // ADR 0328: in an isolated session a delegate that can write files gets+ // its own worktree, keyed by its chain so a resume reuses it.+ const worktreeKey = this.delegateNeedsWorktree(declaredToolNames)+ ? resumedChain?.delegateSessionId ?? delegationId+ : undefined;+ if (worktreeKey) {+ try {+ await this.host.call("worktree.delegate.create", {+ sessionId: this.sessionId,+ delegationId: worktreeKey,+ });+ } catch (error) {+ return this.subagentToolError(+ toolCallId,+ `Could not prepare an isolated worktree for the ${definition.name} subagent: ${+ error instanceof Error ? error.message : String(error)+ }. No work was started.`,+ );+ }+ if (this.disposed || this.runCancelled || this.turnHadError || resumeEpoch !== this.turnEpoch) {+ void this.settleDelegateWorktree(worktreeKey, false, delegationId);+ return this.subagentToolError(toolCallId, "The parent turn ended before delegation could start.");+ }+ }const controller = new AbortController();const thinkingLevel: SubagentThinkingLevel =definition.thinkingLevel === "omit"@@ -4754,13 +4851,14 @@ Do not invent objections or turn speculative risks into blockers. Stop when thestartedEpoch: this.turnEpoch,reportDelivered: false,delegateSessionId: chain.delegateSessionId,+ ...(worktreeKey ? { worktreeKey } : {}),...(resumedChain ? { resumedFrom: resume } : {}),...(modelChangedFrom ? { modelChangedFrom } : {}),};this.delegations.set(delegationId, record);let subagentRun: SubagentRun;try {- const scopedTools = this.scopeDelegateTools(tools, definition, delegationId);+ const scopedTools = this.scopeDelegateTools(tools, definition, delegationId, worktreeKey);subagentRun = new SubagentRun({definition,sessionId: this.sessionId,@@ -4808,6 +4906,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when the// it terminal before returning or idle auto-resume will await a// completion promise for a worker that never existed.record.reportDelivered = true;+ if (worktreeKey) void this.settleDelegateWorktree(worktreeKey, false, delegationId);this.settleDelegation(record, {agentName: definition.name,modelId: provider.modelId,@@ -4834,9 +4933,9 @@ Do not invent objections or turn speculative risks into blockers. Stop when therunPromise = Promise.reject(error);}void runPromise- .then((result) => this.settleDelegation(record, result))+ .then((result) => this.finishDelegation(record, result)).catch((error: unknown) => {- this.settleDelegation(record, {+ void this.finishDelegation(record, {agentName: definition.name,modelId: provider.modelId,thinkingLevel,@@ -4882,6 +4981,7 @@ Do not invent objections or turn speculative risks into blockers. Stop when thetools: AgentTool[],definition: SubagentDefinition,mutationOwner: string,+ worktreeKey?: string,): AgentTool[] {const scope = definition.permission ?? DEFAULT_SUBAGENT_PERMISSION;return tools.map((tool) => ({@@ -4891,16 +4991,70 @@ Do not invent objections or turn speculative risks into blockers. Stop when theif (scope !== DEFAULT_SUBAGENT_PERMISSION) {this.delegatePermissionScopes.set(toolCallId, scope);}+ if (worktreeKey) this.delegateWorktrees.set(toolCallId, worktreeKey);try {return await tool.execute(toolCallId, args, signal, onUpdate);} finally {this.delegatePermissionScopes.delete(toolCallId);+ this.delegateWorktrees.delete(toolCallId);this.mutationOwners.delete(toolCallId);}},}));}+ /**+ * Only inside an isolated session, and only for delegates that can edit+ * files (Write/Edit); Bash-only and read-only delegates share the session+ * worktree (ADR 0328, Q11).+ */+ private delegateNeedsWorktree(toolNames: readonly string[]): boolean {+ return (+ this.workspaceRoot !== undefined &&+ toolNames.some((name) => name === "Write" || name === "Edit")+ );+ }++ /**+ * Settle a delegate's worktree before its report is published: a completed+ * run is merged back into the session worktree, anything else is kept for a+ * resume. The outcome is appended to the report the parent reads.+ */+ private async finishDelegation(+ record: DelegationRecord,+ result: SubagentRunResult,+ ): Promise<void> {+ if (record.worktreeKey && record.status === "running") {+ const note = await this.settleDelegateWorktree(+ record.worktreeKey,+ result.status === "completed",+ record.delegationId,+ );+ if (note) result = { ...result, report: result.report ? `${result.report}\n\n${note}` : note };+ }+ this.settleDelegation(record, result);+ }++ /** Ask host-core to settle a delegate worktree; returns a report note. */+ private async settleDelegateWorktree(+ worktreeKey: string,+ merge: boolean,+ delegationId: string,+ ): Promise<string> {+ const resume = `Task(resume: "${delegationId}")`;+ try {+ const { settlement } = await this.host.call<{ settlement: DelegateWorktreeSettlement }>(+ "worktree.delegate.settle",+ { sessionId: this.sessionId, delegationId: worktreeKey, merge },+ );+ return delegateWorktreeNote(settlement, resume);+ } catch (error) {+ return `Isolated worktree: merge-back failed (${+ error instanceof Error ? error.message : String(error)+ }); the subagent's changes are kept. Continue with ${resume} to retry.`;+ }+ }+/** Records a settled run and wakes every TaskWait waiting on it. */private settleDelegation(record: DelegationRecord,diff --git a/packages/agent-runtime/src/sidecar.ts b/packages/agent-runtime/src/sidecar.tsindex 980fdb2ed..4bcf17145 100644--- a/packages/agent-runtime/src/sidecar.ts+++ b/packages/agent-runtime/src/sidecar.ts@@ -124,6 +124,8 @@ type RuntimeParams = {/** Session-bound workspace root supplied by Electron main. */projectPath?: string;remoteWorkspace?: { hostKey: string; path: string };+ /** An isolated session's worktree root, supplied by Electron main (ADR 0328). */+ workspaceRoot?: string;customSystemPrompt?: CustomSystemPrompt;projectInstructions?: ProjectInstructions;projectMemory?: string;@@ -238,6 +240,7 @@ async function runtimeFor(projectMemory: params.projectMemory,projectPath: params.projectPath,remoteWorkspace: params.remoteWorkspace,+ workspaceRoot: params.workspaceRoot,commandShell: params.commandShell,})? existing@@ -310,6 +313,7 @@ async function runtimeFor(subagentModelKeys,projectPath: params.projectPath,remoteWorkspace: params.remoteWorkspace,+ workspaceRoot: params.workspaceRoot,customSystemPrompt: params.customSystemPrompt,projectInstructions: params.projectInstructions,projectMemory: params.projectMemory,diff --git a/packages/i18n/src/locales/de/index.ts b/packages/i18n/src/locales/de/index.tsindex 6892caeab..87c5013f4 100644--- a/packages/i18n/src/locales/de/index.ts+++ b/packages/i18n/src/locales/de/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const de = {+ "worktree": {+ "newIsolatedSession": "Neue isolierte Sitzung",+ "uncommittedNotIncluded": "Nicht committete Änderungen im Projekt werden nicht in die isolierte Sitzung übernommen.",+ "reveal": "Worktree-Ordner anzeigen",+ "deleteLoss": "Nicht zusammengeführte Arbeit geht verloren",+ "badge": {+ "isolated": "Isoliert",+ "conflict": "Konflikt",+ "missing": "Ordner fehlt",+ "setupFailed": "Einrichtung fehlgeschlagen",+ "title": "Läuft in einem eigenen git-Worktree auf {{branch}}",+ "behind": "↓{{count}}",+ "behindTitle": "Das Projekt hat {{count}} neue(n) Commit(s). Übernimm sie mit „Aus Projekt synchronisieren“ in diese Sitzung.",+ },+ "merge": {+ "menu": "In Projekt zusammenführen…",+ "title": "In Projekt zusammenführen",+ "description": "Übernimmt die Commits von {{branch}} in {{ownerBranch}} des Projekts.",+ "commits": "Commits: {{count}}",+ "files": "Geänderte Dateien: {{count}}",+ "uncommittedFile": "noch nicht committet",+ "uncommittedNote": "Nicht committete Änderungen werden zuerst im Sitzungs-Branch committet.",+ "resolving": "In der Sitzung läuft eine Konfliktlösung; sie wird beim Zusammenführen abgeschlossen.",+ "confirm": "Zusammenführen",+ "merging": "Wird zusammengeführt…",+ "success": "In {{branch}} zusammengeführt",+ "nothing": "Es gibt nichts zusammenzuführen.",+ "conflict": "Diese Dateien stehen im Konflikt mit dem Projekt. Löse sie in der Sitzung und führe dann erneut zusammen:",+ },+ "sync": {+ "menu": "Aus Projekt synchronisieren",+ "menuBehind": "Aus Projekt synchronisieren ({{count}} neu)",+ "upToDate": "Die Sitzung hat bereits den neuesten Projektstand.",+ "resolveFirst": "Löse zuerst den Konflikt in der Sitzung und führe dann erneut zusammen oder synchronisiere.",+ "success": "{{count}} neue Projekt-Commit(s) in die Sitzung übernommen.",+ "conflict": "Diese Dateien stehen im Konflikt mit dem Projekt. Löse sie in der Sitzung: {{files}}",+ },+ "setupCommand": {+ "menu": "Worktree-Einrichtungsbefehl…",+ "title": "Worktree-Einrichtungsbefehl",+ "description": "Läuft in jedem neuen isolierten Worktree dieses Projekts, etwa um Abhängigkeiten zu installieren. Ein Fehler wird angezeigt, stoppt die Sitzung aber nicht.",+ "label": "Befehl",+ "hint": "Variablen: PI_PROJECT_ROOT, PI_WORKTREE_ROOT, PI_PORT. In .worktreeinclude aufgeführte ignorierte Dateien werden zuerst kopiert.",+ "placeholder": "pnpm install",+ "saved": "Einrichtungsbefehl gespeichert",+ },+ "setupLog": {+ "menu": "Einrichtungsprotokoll",+ "title": "Worktree-Einrichtungsprotokoll",+ "running": "Der Einrichtungsbefehl läuft.",+ "ok": "Der Einrichtungsbefehl ist fertig.",+ "failed": "Der Einrichtungsbefehl ist fehlgeschlagen.",+ "none": "Es wurde kein Einrichtungsbefehl ausgeführt.",+ },+ "errors": {+ "notGit": "Dieses Projekt ist kein git-Repository.",+ "noCommits": "Das Repository hat noch keine Commits. Erstelle einen ersten Commit, um isolierte Sitzungen zu nutzen.",+ "detachedHead": "Das Projekt ist auf keinem Branch. Checke zuerst einen Branch aus.",+ "gitMissing": "Git wurde nicht gefunden. Installiere Git, um isolierte Sitzungen zu nutzen.",+ "gitTooOld": "Isolierte Sitzungen benötigen Git 2.29 oder neuer.",+ "branchNamespaceTaken": "Ein Branch namens pi-desktop existiert. Benenne ihn um, um isolierte Sitzungen zu nutzen.",+ "busy": "Die Sitzung läuft noch. Warte, bis sie fertig ist.",+ "changedSincePreview": "Die Sitzung hat sich nach der Vorschau geändert. Prüfe die aktualisierten Änderungen.",+ "ownerBranchChanged": "Das Projekt ist nicht mehr auf dem Branch, auf dem diese Sitzung begann. Wechsle zurück, um zusammenzuführen.",+ "projectDirty": "Nicht committete Projektänderungen würden überschrieben. Committe oder stashe sie und führe dann erneut zusammen.",+ "missing": "Der isolierte Worktree-Ordner existiert nicht mehr. Lösche diese Sitzung.",+ "commitFailed": "Git konnte die Änderungen der Sitzung nicht committen.",+ "moveUnsupported": "Eine isolierte Sitzung kann nicht in ein anderes Projekt verschoben werden.",+ "mergeFailed": "Git konnte die Projektänderungen nicht mit der Sitzung zusammenführen, etwa weil eine Datei im Weg ist. Die Sitzung blieb unverändert.",+ "pathExists": "Ein Worktree oder Branch mit diesem Namen existiert bereits. Versuche es erneut oder entferne den Rest.",+ "notReady": "Der isolierte Worktree wird noch vorbereitet. Versuche es gleich noch einmal.",+ "notIsolated": "Diese Sitzung hat keinen isolierten Worktree.",+ "gitFailed": "Ein Git-Befehl ist fehlgeschlagen. Prüfe das Repository und versuche es erneut.",+ "gitTimeout": "Git hat nicht rechtzeitig geantwortet. Versuche es erneut.",+ "remoteUnsupported": "Isolierte Sitzungen sind für Remote-Projekte nicht verfügbar.",+ },+ },"app": {"shellName": "PI-Desktop","tagline": "Lokaler AI-Codierungspartner",diff --git a/packages/i18n/src/locales/en/index.ts b/packages/i18n/src/locales/en/index.tsindex 5d0f49987..580c5e512 100644--- a/packages/i18n/src/locales/en/index.ts+++ b/packages/i18n/src/locales/en/index.ts@@ -1,4 +1,81 @@export const en = {+ worktree: {+ newIsolatedSession: "New isolated session",+ uncommittedNotIncluded: "Uncommitted changes in the project are not included in the isolated session.",+ reveal: "Show worktree folder",+ deleteLoss: "Unmerged work will be lost",+ badge: {+ isolated: "Isolated",+ conflict: "Conflict",+ missing: "Folder missing",+ setupFailed: "Setup failed",+ title: "Runs in its own git worktree on {{branch}}",+ behind: "↓{{count}}",+ behindTitle: "The project has {{count}} new commit(s). Use \"Sync from project\" to bring them into this session.",+ },+ merge: {+ menu: "Merge into project…",+ title: "Merge into project",+ description: "Lands the commits of {{branch}} on {{ownerBranch}} in the project.",+ commits: "Commits: {{count}}",+ files: "Changed files: {{count}}",+ uncommittedFile: "not committed yet",+ uncommittedNote: "Uncommitted changes are committed on the session branch first.",+ resolving: "The session has a conflict resolution in progress; it is finished when you merge.",+ confirm: "Merge",+ merging: "Merging…",+ success: "Merged into {{branch}}",+ nothing: "There is nothing to merge.",+ conflict: "These files conflict with the project. Resolve them in the session, then merge again:",+ },+ sync: {+ menu: "Sync from project",+ menuBehind: "Sync from project ({{count}} new)",+ upToDate: "The session already has the project's latest code.",+ resolveFirst: "Resolve the conflict in the session first, then merge or sync again.",+ success: "Brought {{count}} new project commit(s) into the session.",+ conflict: "These files conflict with the project. Resolve them in the session: {{files}}",+ },+ setupCommand: {+ menu: "Worktree setup command…",+ title: "Worktree setup command",+ description: "Runs in every new isolated worktree of this project, for example to install dependencies. A failure is shown but does not stop the session.",+ label: "Command",+ hint: "Variables: PI_PROJECT_ROOT, PI_WORKTREE_ROOT, PI_PORT. Ignored files listed in .worktreeinclude are copied first.",+ placeholder: "pnpm install",+ saved: "Setup command saved",+ },+ setupLog: {+ menu: "Setup log",+ title: "Worktree setup log",+ running: "The setup command is running.",+ ok: "The setup command finished.",+ failed: "The setup command failed.",+ none: "No setup command ran.",+ },+ errors: {+ notGit: "This project is not a git repository.",+ noCommits: "The repository has no commits yet. Make a first commit to use isolated sessions.",+ detachedHead: "The project is not on a branch. Check out a branch first.",+ gitMissing: "Git was not found. Install Git to use isolated sessions.",+ gitTooOld: "Isolated sessions need Git 2.29 or newer.",+ branchNamespaceTaken: "A branch named pi-desktop exists. Rename it to use isolated sessions.",+ busy: "The session is still running. Wait for it to finish.",+ changedSincePreview: "The session changed after the preview. Review the updated changes.",+ ownerBranchChanged: "The project is no longer on the branch this session started from. Switch back to merge.",+ projectDirty: "Uncommitted project changes would be overwritten. Commit or stash them, then merge again.",+ missing: "The isolated worktree folder no longer exists. Delete this session.",+ commitFailed: "Git could not commit the session's changes.",+ moveUnsupported: "An isolated session cannot move to another project.",+ mergeFailed: "Git could not combine the project's changes with the session, for example because a file is in the way. The session was left unchanged.",+ pathExists: "A worktree or branch with this name already exists. Try again or delete the leftover.",+ notReady: "The isolated worktree is still being prepared. Try again in a moment.",+ notIsolated: "This session has no isolated worktree.",+ gitFailed: "A git command failed. Check the repository and try again.",+ gitTimeout: "Git did not respond in time. Try again.",+ remoteUnsupported: "Isolated sessions are not available for remote projects.",+ },+ },app: {shellName: "PI-Desktop",tagline: "Local AI coding partner",diff --git a/packages/i18n/src/locales/es/index.ts b/packages/i18n/src/locales/es/index.tsindex 27c6bfcf9..9a536b22f 100644--- a/packages/i18n/src/locales/es/index.ts+++ b/packages/i18n/src/locales/es/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const es = {+ "worktree": {+ "newIsolatedSession": "Nueva sesión aislada",+ "uncommittedNotIncluded": "Los cambios sin confirmar del proyecto no se incluyen en la sesión aislada.",+ "reveal": "Mostrar carpeta del worktree",+ "deleteLoss": "Se perderá el trabajo sin fusionar",+ "badge": {+ "isolated": "Aislada",+ "conflict": "Conflicto",+ "missing": "Falta la carpeta",+ "setupFailed": "Falló la preparación",+ "title": "Se ejecuta en su propio worktree de git en {{branch}}",+ "behind": "↓{{count}}",+ "behindTitle": "El proyecto tiene {{count}} commit(s) nuevo(s). Usa «Sincronizar desde el proyecto» para traerlos a esta sesión.",+ },+ "merge": {+ "menu": "Fusionar en el proyecto…",+ "title": "Fusionar en el proyecto",+ "description": "Lleva los commits de {{branch}} a {{ownerBranch}} del proyecto.",+ "commits": "Commits: {{count}}",+ "files": "Archivos modificados: {{count}}",+ "uncommittedFile": "aún sin confirmar",+ "uncommittedNote": "Los cambios sin confirmar se confirman primero en la rama de la sesión.",+ "resolving": "La sesión tiene una resolución de conflictos en curso; se completa al fusionar.",+ "confirm": "Fusionar",+ "merging": "Fusionando…",+ "success": "Fusionado en {{branch}}",+ "nothing": "No hay nada que fusionar.",+ "conflict": "Estos archivos entran en conflicto con el proyecto. Resuélvelos en la sesión y vuelve a fusionar:",+ },+ "sync": {+ "menu": "Sincronizar desde el proyecto",+ "menuBehind": "Sincronizar desde el proyecto ({{count}} nuevos)",+ "upToDate": "La sesión ya tiene el código más reciente del proyecto.",+ "resolveFirst": "Resuelve primero el conflicto en la sesión y luego vuelve a fusionar o sincronizar.",+ "success": "Se incorporaron {{count}} commit(s) nuevos del proyecto a la sesión.",+ "conflict": "Estos archivos entran en conflicto con el proyecto. Resuélvelos en la sesión: {{files}}",+ },+ "setupCommand": {+ "menu": "Comando de preparación del worktree…",+ "title": "Comando de preparación del worktree",+ "description": "Se ejecuta en cada nuevo worktree aislado de este proyecto, por ejemplo para instalar dependencias. Un fallo se muestra, pero no detiene la sesión.",+ "label": "Comando",+ "hint": "Variables: PI_PROJECT_ROOT, PI_WORKTREE_ROOT, PI_PORT. Primero se copian los archivos ignorados listados en .worktreeinclude.",+ "placeholder": "pnpm install",+ "saved": "Comando de preparación guardado",+ },+ "setupLog": {+ "menu": "Registro de preparación",+ "title": "Registro de preparación del worktree",+ "running": "El comando de preparación se está ejecutando.",+ "ok": "El comando de preparación terminó.",+ "failed": "El comando de preparación falló.",+ "none": "No se ejecutó ningún comando de preparación.",+ },+ "errors": {+ "notGit": "Este proyecto no es un repositorio git.",+ "noCommits": "El repositorio aún no tiene commits. Haz un primer commit para usar sesiones aisladas.",+ "detachedHead": "El proyecto no está en una rama. Cambia primero a una rama.",+ "gitMissing": "No se encontró Git. Instala Git para usar sesiones aisladas.",+ "gitTooOld": "Las sesiones aisladas requieren Git 2.29 o posterior.",+ "branchNamespaceTaken": "Existe una rama llamada pi-desktop. Cámbiale el nombre para usar sesiones aisladas.",+ "busy": "La sesión sigue en ejecución. Espera a que termine.",+ "changedSincePreview": "La sesión cambió después de la vista previa. Revisa los cambios actualizados.",+ "ownerBranchChanged": "El proyecto ya no está en la rama donde empezó esta sesión. Vuelve a ella para fusionar.",+ "projectDirty": "Se sobrescribirían cambios sin confirmar del proyecto. Confírmalos o guárdalos con stash y vuelve a fusionar.",+ "missing": "La carpeta del worktree aislado ya no existe. Elimina esta sesión.",+ "commitFailed": "Git no pudo confirmar los cambios de la sesión.",+ "moveUnsupported": "Una sesión aislada no se puede mover a otro proyecto.",+ "mergeFailed": "Git no pudo combinar los cambios del proyecto con la sesión, por ejemplo porque un archivo lo impide. La sesión no cambió.",+ "pathExists": "Ya existe un worktree o una rama con este nombre. Vuelve a intentarlo o elimina el resto.",+ "notReady": "El worktree aislado aún se está preparando. Vuelve a intentarlo en un momento.",+ "notIsolated": "Esta sesión no tiene un worktree aislado.",+ "gitFailed": "Falló un comando de git. Revisa el repositorio y vuelve a intentarlo.",+ "gitTimeout": "Git no respondió a tiempo. Vuelve a intentarlo.",+ "remoteUnsupported": "Las sesiones aisladas no están disponibles para proyectos remotos.",+ },+ },"app": {"shellName": "PI-Desktop","tagline": "Socio de codificación de IA local",diff --git a/packages/i18n/src/locales/fr/index.ts b/packages/i18n/src/locales/fr/index.tsindex 1eccc83db..3aa5cfc2e 100644--- a/packages/i18n/src/locales/fr/index.ts+++ b/packages/i18n/src/locales/fr/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const fr = {+ "worktree": {+ "newIsolatedSession": "Nouvelle session isolée",+ "uncommittedNotIncluded": "Les modifications non validées du projet ne sont pas incluses dans la session isolée.",+ "reveal": "Afficher le dossier du worktree",+ "deleteLoss": "Le travail non fusionné sera perdu",+ "badge": {+ "isolated": "Isolée",+ "conflict": "Conflit",+ "missing": "Dossier manquant",+ "setupFailed": "Échec de la préparation",+ "title": "S'exécute dans son propre worktree git sur {{branch}}",+ "behind": "↓{{count}}",+ "behindTitle": "Le projet a {{count}} nouveau(x) commit(s). Utilisez « Synchroniser depuis le projet » pour les intégrer à cette session.",+ },+ "merge": {+ "menu": "Fusionner dans le projet…",+ "title": "Fusionner dans le projet",+ "description": "Intègre les commits de {{branch}} dans {{ownerBranch}} du projet.",+ "commits": "Commits : {{count}}",+ "files": "Fichiers modifiés : {{count}}",+ "uncommittedFile": "pas encore validé",+ "uncommittedNote": "Les modifications non validées sont d'abord validées sur la branche de la session.",+ "resolving": "Une résolution de conflits est en cours dans la session ; elle est terminée lors de la fusion.",+ "confirm": "Fusionner",+ "merging": "Fusion…",+ "success": "Fusionné dans {{branch}}",+ "nothing": "Il n'y a rien à fusionner.",+ "conflict": "Ces fichiers sont en conflit avec le projet. Résolvez-les dans la session, puis fusionnez à nouveau :",+ },+ "sync": {+ "menu": "Synchroniser depuis le projet",+ "menuBehind": "Synchroniser depuis le projet ({{count}} nouveaux)",+ "upToDate": "La session contient déjà le code le plus récent du projet.",+ "resolveFirst": "Résolvez d'abord le conflit dans la session, puis fusionnez ou synchronisez à nouveau.",+ "success": "{{count}} nouveau(x) commit(s) du projet intégré(s) à la session.",+ "conflict": "Ces fichiers sont en conflit avec le projet. Résolvez-les dans la session : {{files}}",+ },+ "setupCommand": {+ "menu": "Commande de préparation du worktree…",+ "title": "Commande de préparation du worktree",+ "description": "S'exécute dans chaque nouveau worktree isolé de ce projet, par exemple pour installer les dépendances. Un échec est signalé mais n'arrête pas la session.",+ "label": "Commande",+ "hint": "Variables : PI_PROJECT_ROOT, PI_WORKTREE_ROOT, PI_PORT. Les fichiers ignorés listés dans .worktreeinclude sont copiés d'abord.",+ "placeholder": "pnpm install",+ "saved": "Commande de préparation enregistrée",+ },+ "setupLog": {+ "menu": "Journal de préparation",+ "title": "Journal de préparation du worktree",+ "running": "La commande de préparation est en cours.",+ "ok": "La commande de préparation est terminée.",+ "failed": "La commande de préparation a échoué.",+ "none": "Aucune commande de préparation n'a été exécutée.",+ },+ "errors": {+ "notGit": "Ce projet n'est pas un dépôt git.",+ "noCommits": "Le dépôt n'a encore aucun commit. Créez un premier commit pour utiliser les sessions isolées.",+ "detachedHead": "Le projet n'est sur aucune branche. Basculez d'abord sur une branche.",+ "gitMissing": "Git est introuvable. Installez Git pour utiliser les sessions isolées.",+ "gitTooOld": "Les sessions isolées nécessitent Git 2.29 ou plus récent.",+ "branchNamespaceTaken": "Une branche nommée pi-desktop existe. Renommez-la pour utiliser les sessions isolées.",+ "busy": "La session est toujours en cours. Attendez qu'elle se termine.",+ "changedSincePreview": "La session a changé après l'aperçu. Vérifiez les modifications mises à jour.",+ "ownerBranchChanged": "Le projet n'est plus sur la branche de départ de cette session. Revenez-y pour fusionner.",+ "projectDirty": "Des modifications non validées du projet seraient écrasées. Validez-les ou mettez-les de côté, puis fusionnez à nouveau.",+ "missing": "Le dossier du worktree isolé n'existe plus. Supprimez cette session.",+ "commitFailed": "Git n'a pas pu valider les modifications de la session.",+ "moveUnsupported": "Une session isolée ne peut pas être déplacée vers un autre projet.",+ "mergeFailed": "Git n'a pas pu intégrer les modifications du projet à la session, par exemple parce qu'un fichier gêne. La session est inchangée.",+ "pathExists": "Un worktree ou une branche portant ce nom existe déjà. Réessayez ou supprimez le reste.",+ "notReady": "Le worktree isolé est encore en préparation. Réessayez dans un instant.",+ "notIsolated": "Cette session n'a pas de worktree isolé.",+ "gitFailed": "Une commande git a échoué. Vérifiez le dépôt et réessayez.",+ "gitTimeout": "Git n'a pas répondu à temps. Réessayez.",+ "remoteUnsupported": "Les sessions isolées ne sont pas disponibles pour les projets distants.",+ },+ },"app": {"shellName": "PI-Desktop","tagline": "Partenaire de codage IA local",diff --git a/packages/i18n/src/locales/ko/index.ts b/packages/i18n/src/locales/ko/index.tsindex 0381cda6b..6d9e25cc8 100644--- a/packages/i18n/src/locales/ko/index.ts+++ b/packages/i18n/src/locales/ko/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const ko = {+ worktree: {+ newIsolatedSession: "새 격리 세션",+ uncommittedNotIncluded: "프로젝트의 커밋되지 않은 변경 사항은 격리 세션에 포함되지 않습니다.",+ reveal: "worktree 폴더 보기",+ deleteLoss: "병합되지 않은 작업이 사라집니다",+ badge: {+ isolated: "격리",+ conflict: "충돌",+ missing: "폴더 없음",+ setupFailed: "설정 실패",+ title: "{{branch}} 브랜치의 별도 git worktree에서 실행됩니다",+ behind: "↓{{count}}",+ behindTitle: "프로젝트에 새 커밋이 {{count}}개 있습니다. '프로젝트에서 동기화'로 이 세션에 가져오세요.",+ },+ merge: {+ menu: "프로젝트에 병합…",+ title: "프로젝트에 병합",+ description: "{{branch}}의 커밋을 프로젝트의 {{ownerBranch}}에 반영합니다.",+ commits: "커밋: {{count}}",+ files: "변경된 파일: {{count}}",+ uncommittedFile: "아직 커밋되지 않음",+ uncommittedNote: "커밋되지 않은 변경 사항은 먼저 세션 브랜치에 커밋됩니다.",+ resolving: "세션에 진행 중인 충돌 해결이 있으며, 병합할 때 완료됩니다.",+ confirm: "병합",+ merging: "병합 중…",+ success: "{{branch}}에 병합했습니다",+ nothing: "병합할 내용이 없습니다.",+ conflict: "다음 파일이 프로젝트와 충돌합니다. 세션에서 해결한 뒤 다시 병합하세요:",+ },+ sync: {+ menu: "프로젝트에서 동기화",+ menuBehind: "프로젝트에서 동기화 (새 커밋 {{count}}개)",+ upToDate: "세션에 이미 프로젝트의 최신 코드가 있습니다.",+ resolveFirst: "먼저 세션에서 충돌을 해결한 다음 다시 병합하거나 동기화하세요.",+ success: "프로젝트의 새 커밋 {{count}}개를 세션에 가져왔습니다.",+ conflict: "이 파일들이 프로젝트와 충돌합니다. 세션에서 해결하세요: {{files}}",+ },+ setupCommand: {+ menu: "Worktree 설정 명령…",+ title: "Worktree 설정 명령",+ description: "이 프로젝트의 새 격리 worktree마다 실행됩니다(예: 의존성 설치). 실패해도 알림만 표시되고 세션은 계속 사용할 수 있습니다.",+ label: "명령",+ hint: "변수: PI_PROJECT_ROOT, PI_WORKTREE_ROOT, PI_PORT. .worktreeinclude에 나열된 무시된 파일이 먼저 복사됩니다.",+ placeholder: "pnpm install",+ saved: "설정 명령을 저장했습니다",+ },+ setupLog: {+ menu: "설정 로그",+ title: "Worktree 설정 로그",+ running: "설정 명령이 실행 중입니다.",+ ok: "설정 명령이 완료되었습니다.",+ failed: "설정 명령이 실패했습니다.",+ none: "실행된 설정 명령이 없습니다.",+ },+ errors: {+ notGit: "이 프로젝트는 git 저장소가 아닙니다.",+ noCommits: "저장소에 아직 커밋이 없습니다. 첫 커밋 후 격리 세션을 사용하세요.",+ detachedHead: "프로젝트가 브랜치에 있지 않습니다. 먼저 브랜치를 체크아웃하세요.",+ gitMissing: "Git을 찾을 수 없습니다. Git을 설치한 뒤 격리 세션을 사용하세요.",+ gitTooOld: "격리 세션에는 Git 2.29 이상이 필요합니다.",+ branchNamespaceTaken: "pi-desktop이라는 브랜치가 있습니다. 이름을 바꾼 뒤 격리 세션을 사용하세요.",+ busy: "세션이 아직 실행 중입니다. 끝날 때까지 기다리세요.",+ changedSincePreview: "미리보기 이후 세션이 변경되었습니다. 업데이트된 변경 사항을 확인하세요.",+ ownerBranchChanged: "프로젝트가 이 세션이 시작된 브랜치에 있지 않습니다. 원래 브랜치로 전환한 뒤 병합하세요.",+ projectDirty: "프로젝트의 커밋되지 않은 변경 사항을 덮어쓰게 됩니다. 커밋하거나 stash한 뒤 다시 병합하세요.",+ missing: "격리 worktree 폴더가 더 이상 없습니다. 이 세션을 삭제하세요.",+ commitFailed: "Git이 세션의 변경 사항을 커밋하지 못했습니다.",+ moveUnsupported: "격리 세션은 다른 프로젝트로 옮길 수 없습니다.",+ mergeFailed: "파일이 가로막는 등의 이유로 Git이 프로젝트 변경 사항을 세션에 합치지 못했습니다. 세션은 변경되지 않았습니다.",+ pathExists: "같은 이름의 worktree 또는 브랜치가 이미 있습니다. 다시 시도하거나 남은 항목을 삭제하세요.",+ notReady: "격리된 worktree를 아직 준비 중입니다. 잠시 후 다시 시도하세요.",+ notIsolated: "이 세션에는 격리된 worktree가 없습니다.",+ gitFailed: "git 명령이 실패했습니다. 저장소를 확인하고 다시 시도하세요.",+ gitTimeout: "Git이 제때 응답하지 않았습니다. 다시 시도하세요.",+ remoteUnsupported: "원격 프로젝트에서는 격리된 세션을 사용할 수 없습니다.",+ },+ },app: {shellName: "PI-Desktop",tagline: "로컬 AI 코딩 파트너",diff --git a/packages/i18n/src/locales/pt-BR/index.ts b/packages/i18n/src/locales/pt-BR/index.tsindex da771c4b1..2237f83b9 100644--- a/packages/i18n/src/locales/pt-BR/index.ts+++ b/packages/i18n/src/locales/pt-BR/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const ptBR = {+ worktree: {+ newIsolatedSession: "Nova sessão isolada",+ uncommittedNotIncluded: "Alterações não confirmadas do projeto não são incluídas na sessão isolada.",+ reveal: "Mostrar pasta do worktree",+ deleteLoss: "O trabalho não mesclado será perdido",+ badge: {+ isolated: "Isolada",+ conflict: "Conflito",+ missing: "Pasta ausente",+ setupFailed: "Falha na preparação",+ title: "Executa no próprio worktree git em {{branch}}",+ behind: "↓{{count}}",+ behindTitle: "O projeto tem {{count}} commit(s) novo(s). Use “Sincronizar do projeto” para trazê-los a esta sessão.",+ },+ merge: {+ menu: "Mesclar no projeto…",+ title: "Mesclar no projeto",+ description: "Leva os commits de {{branch}} para {{ownerBranch}} do projeto.",+ commits: "Commits: {{count}}",+ files: "Arquivos alterados: {{count}}",+ uncommittedFile: "ainda não confirmado",+ uncommittedNote: "Alterações não confirmadas são confirmadas primeiro no branch da sessão.",+ resolving: "A sessão tem uma resolução de conflitos em andamento; ela é concluída ao mesclar.",+ confirm: "Mesclar",+ merging: "Mesclando…",+ success: "Mesclado em {{branch}}",+ nothing: "Não há nada para mesclar.",+ conflict: "Estes arquivos entram em conflito com o projeto. Resolva-os na sessão e mescle novamente:",+ },+ sync: {+ menu: "Sincronizar do projeto",+ menuBehind: "Sincronizar do projeto ({{count}} novos)",+ upToDate: "A sessão já tem o código mais recente do projeto.",+ resolveFirst: "Resolva primeiro o conflito na sessão e depois mescle ou sincronize de novo.",+ success: "{{count}} commit(s) novo(s) do projeto trazido(s) para a sessão.",+ conflict: "Estes arquivos conflitam com o projeto. Resolva-os na sessão: {{files}}",+ },+ setupCommand: {+ menu: "Comando de preparação do worktree…",+ title: "Comando de preparação do worktree",+ description: "Executa em cada novo worktree isolado deste projeto, por exemplo para instalar dependências. Uma falha é exibida, mas não interrompe a sessão.",+ label: "Comando",+ hint: "Variáveis: PI_PROJECT_ROOT, PI_WORKTREE_ROOT, PI_PORT. Arquivos ignorados listados em .worktreeinclude são copiados primeiro.",+ placeholder: "pnpm install",+ saved: "Comando de preparação salvo",+ },+ setupLog: {+ menu: "Log de preparação",+ title: "Log de preparação do worktree",+ running: "O comando de preparação está em execução.",+ ok: "O comando de preparação terminou.",+ failed: "O comando de preparação falhou.",+ none: "Nenhum comando de preparação foi executado.",+ },+ errors: {+ notGit: "Este projeto não é um repositório git.",+ noCommits: "O repositório ainda não tem commits. Faça um primeiro commit para usar sessões isoladas.",+ detachedHead: "O projeto não está em um branch. Faça checkout de um branch primeiro.",+ gitMissing: "O Git não foi encontrado. Instale o Git para usar sessões isoladas.",+ gitTooOld: "Sessões isoladas exigem Git 2.29 ou mais recente.",+ branchNamespaceTaken: "Existe um branch chamado pi-desktop. Renomeie-o para usar sessões isoladas.",+ busy: "A sessão ainda está em execução. Aguarde ela terminar.",+ changedSincePreview: "A sessão mudou depois da prévia. Revise as alterações atualizadas.",+ ownerBranchChanged: "O projeto não está mais no branch em que esta sessão começou. Volte para ele para mesclar.",+ projectDirty: "Alterações não confirmadas do projeto seriam sobrescritas. Confirme ou guarde com stash e mescle novamente.",+ missing: "A pasta do worktree isolado não existe mais. Exclua esta sessão.",+ commitFailed: "O Git não conseguiu confirmar as alterações da sessão.",+ moveUnsupported: "Uma sessão isolada não pode ser movida para outro projeto.",+ mergeFailed: "O Git não conseguiu combinar as alterações do projeto com a sessão, por exemplo porque um arquivo atrapalha. A sessão não mudou.",+ pathExists: "Já existe um worktree ou branch com este nome. Tente de novo ou remova o que sobrou.",+ notReady: "O worktree isolado ainda está sendo preparado. Tente de novo em instantes.",+ notIsolated: "Esta sessão não tem um worktree isolado.",+ gitFailed: "Um comando git falhou. Verifique o repositório e tente de novo.",+ gitTimeout: "O Git não respondeu a tempo. Tente de novo.",+ remoteUnsupported: "Sessões isoladas não estão disponíveis para projetos remotos.",+ },+ },app: {shellName: "PI-Desktop",tagline: "Parceiro local de programação com IA",diff --git a/packages/i18n/src/locales/tr/index.ts b/packages/i18n/src/locales/tr/index.tsindex 65d6146bd..71b1b54f9 100644--- a/packages/i18n/src/locales/tr/index.ts+++ b/packages/i18n/src/locales/tr/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const tr = {+ worktree: {+ newIsolatedSession: "Yeni yalıtılmış oturum",+ uncommittedNotIncluded: "Projedeki commit edilmemiş değişiklikler yalıtılmış oturuma dahil edilmez.",+ reveal: "Worktree klasörünü göster",+ deleteLoss: "Birleştirilmemiş çalışma kaybolacak",+ badge: {+ isolated: "Yalıtılmış",+ conflict: "Çakışma",+ missing: "Klasör yok",+ setupFailed: "Hazırlık başarısız",+ title: "{{branch}} üzerinde kendi git worktree'sinde çalışır",+ behind: "↓{{count}}",+ behindTitle: "Projede {{count}} yeni commit var. Bunları bu oturuma almak için \"Projeden eşitle\" seçeneğini kullanın.",+ },+ merge: {+ menu: "Projeye birleştir…",+ title: "Projeye birleştir",+ description: "{{branch}} commit'lerini projedeki {{ownerBranch}} dalına aktarır.",+ commits: "Commit'ler: {{count}}",+ files: "Değişen dosyalar: {{count}}",+ uncommittedFile: "henüz commit edilmedi",+ uncommittedNote: "Commit edilmemiş değişiklikler önce oturum dalına commit edilir.",+ resolving: "Oturumda süren bir çakışma çözümü var; birleştirirken tamamlanır.",+ confirm: "Birleştir",+ merging: "Birleştiriliyor…",+ success: "{{branch}} dalına birleştirildi",+ nothing: "Birleştirilecek bir şey yok.",+ conflict: "Bu dosyalar projeyle çakışıyor. Oturumda çözün, ardından yeniden birleştirin:",+ },+ sync: {+ menu: "Projeden eşitle",+ menuBehind: "Projeden eşitle ({{count}} yeni)",+ upToDate: "Oturum zaten projenin en güncel koduna sahip.",+ resolveFirst: "Önce oturumdaki çakışmayı çözün, ardından yeniden birleştirin veya eşitleyin.",+ success: "Projeden {{count}} yeni commit oturuma alındı.",+ conflict: "Bu dosyalar projeyle çakışıyor. Bunları oturumda çözün: {{files}}",+ },+ setupCommand: {+ menu: "Worktree hazırlık komutu…",+ title: "Worktree hazırlık komutu",+ description: "Bu projenin her yeni yalıtılmış worktree'sinde çalışır, örneğin bağımlılıkları kurmak için. Hata gösterilir ancak oturumu durdurmaz.",+ label: "Komut",+ hint: "Değişkenler: PI_PROJECT_ROOT, PI_WORKTREE_ROOT, PI_PORT. .worktreeinclude içinde listelenen yok sayılan dosyalar önce kopyalanır.",+ placeholder: "pnpm install",+ saved: "Hazırlık komutu kaydedildi",+ },+ setupLog: {+ menu: "Hazırlık günlüğü",+ title: "Worktree hazırlık günlüğü",+ running: "Hazırlık komutu çalışıyor.",+ ok: "Hazırlık komutu tamamlandı.",+ failed: "Hazırlık komutu başarısız oldu.",+ none: "Hazırlık komutu çalıştırılmadı.",+ },+ errors: {+ notGit: "Bu proje bir git deposu değil.",+ noCommits: "Depoda henüz commit yok. Yalıtılmış oturumları kullanmak için ilk commit'i yapın.",+ detachedHead: "Proje bir dalda değil. Önce bir dala geçin.",+ gitMissing: "Git bulunamadı. Yalıtılmış oturumlar için Git'i kurun.",+ gitTooOld: "Yalıtılmış oturumlar Git 2.29 veya daha yenisini gerektirir.",+ branchNamespaceTaken: "pi-desktop adlı bir dal var. Yalıtılmış oturumları kullanmak için yeniden adlandırın.",+ busy: "Oturum hâlâ çalışıyor. Bitmesini bekleyin.",+ changedSincePreview: "Oturum önizlemeden sonra değişti. Güncellenen değişiklikleri inceleyin.",+ ownerBranchChanged: "Proje artık bu oturumun başladığı dalda değil. Birleştirmek için o dala geri dönün.",+ projectDirty: "Projedeki commit edilmemiş değişikliklerin üzerine yazılır. Önce commit edin veya stash'leyin, sonra yeniden birleştirin.",+ missing: "Yalıtılmış worktree klasörü artık yok. Bu oturumu silin.",+ commitFailed: "Git oturumun değişikliklerini commit edemedi.",+ moveUnsupported: "Yalıtılmış bir oturum başka bir projeye taşınamaz.",+ mergeFailed: "Git, örneğin yolda bir dosya olduğu için proje değişikliklerini oturumla birleştiremedi. Oturum değişmedi.",+ pathExists: "Bu adda bir worktree veya dal zaten var. Yeniden deneyin ya da kalıntıyı silin.",+ notReady: "Yalıtılmış worktree hâlâ hazırlanıyor. Birazdan yeniden deneyin.",+ notIsolated: "Bu oturumun yalıtılmış worktree'si yok.",+ gitFailed: "Bir git komutu başarısız oldu. Depoyu kontrol edip yeniden deneyin.",+ gitTimeout: "Git zamanında yanıt vermedi. Yeniden deneyin.",+ remoteUnsupported: "Yalıtılmış oturumlar uzak projelerde kullanılamaz.",+ },+ },app: {shellName: "PI-Desktop",tagline: "Yerel AI kodlama ortağı",diff --git a/packages/i18n/src/locales/zh-CN/index.ts b/packages/i18n/src/locales/zh-CN/index.tsindex 91d3e7817..23a40d3b8 100644--- a/packages/i18n/src/locales/zh-CN/index.ts+++ b/packages/i18n/src/locales/zh-CN/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const zhCN = {+ worktree: {+ newIsolatedSession: "新建隔离会话",+ uncommittedNotIncluded: "项目中未提交的改动不会带入隔离会话。",+ reveal: "显示 worktree 文件夹",+ deleteLoss: "未合并的工作将丢失",+ badge: {+ isolated: "隔离",+ conflict: "冲突",+ missing: "文件夹缺失",+ setupFailed: "初始化失败",+ title: "在独立的 git worktree 中运行,分支 {{branch}}",+ behind: "↓{{count}}",+ behindTitle: "项目有 {{count}} 个新提交,可用“从项目同步”带入此会话。",+ },+ merge: {+ menu: "合并到项目…",+ title: "合并到项目",+ description: "把 {{branch}} 的提交合入项目的 {{ownerBranch}}。",+ commits: "提交:{{count}}",+ files: "改动文件:{{count}}",+ uncommittedFile: "尚未提交",+ uncommittedNote: "未提交的改动会先提交到会话分支。",+ resolving: "会话中有未完成的冲突解决,合并时会一并完成。",+ confirm: "合并",+ merging: "正在合并…",+ success: "已合并到 {{branch}}",+ nothing: "没有需要合并的内容。",+ conflict: "以下文件与项目冲突。请在会话中解决后再次合并:",+ },+ sync: {+ menu: "从项目同步",+ menuBehind: "从项目同步({{count}} 个新提交)",+ upToDate: "会话已包含项目的最新代码。",+ resolveFirst: "请先在会话中解决冲突,再合并或同步。",+ success: "已把项目的 {{count}} 个新提交同步到会话。",+ conflict: "这些文件与项目冲突,请在会话中解决:{{files}}",+ },+ setupCommand: {+ menu: "Worktree 初始化命令…",+ title: "Worktree 初始化命令",+ description: "在本项目每个新的隔离 worktree 中运行,例如安装依赖。失败会提示,但不影响会话使用。",+ label: "命令",+ hint: "可用变量:PI_PROJECT_ROOT、PI_WORKTREE_ROOT、PI_PORT。.worktreeinclude 中列出的被忽略文件会先被复制。",+ placeholder: "pnpm install",+ saved: "初始化命令已保存",+ },+ setupLog: {+ menu: "初始化日志",+ title: "Worktree 初始化日志",+ running: "初始化命令正在运行。",+ ok: "初始化命令已完成。",+ failed: "初始化命令失败。",+ none: "没有运行初始化命令。",+ },+ errors: {+ notGit: "该项目不是 git 仓库。",+ noCommits: "仓库还没有提交。请先提交一次再使用隔离会话。",+ detachedHead: "项目不在任何分支上。请先检出一个分支。",+ gitMissing: "未找到 Git。请安装 Git 后使用隔离会话。",+ gitTooOld: "隔离会话需要 Git 2.29 或更高版本。",+ branchNamespaceTaken: "已存在名为 pi-desktop 的分支。请重命名后再使用隔离会话。",+ busy: "会话仍在运行,请等待其结束。",+ changedSincePreview: "预览后会话有了变化,请查看更新后的改动。",+ ownerBranchChanged: "项目已不在本会话创建时的分支上。请切回该分支再合并。",+ projectDirty: "项目中未提交的改动会被覆盖。请先提交或暂存后再合并。",+ missing: "隔离 worktree 文件夹已不存在,请删除该会话。",+ commitFailed: "Git 无法提交会话的改动。",+ moveUnsupported: "隔离会话不能移到其他项目。",+ mergeFailed: "Git 无法把项目的改动合入会话(例如有文件挡住了合并),会话保持不变。",+ pathExists: "同名的 worktree 或分支已存在。请重试,或删除残留的 worktree/分支。",+ notReady: "隔离 worktree 仍在准备中,请稍后再试。",+ notIsolated: "此会话没有隔离 worktree。",+ gitFailed: "Git 命令执行失败,请检查仓库后重试。",+ gitTimeout: "Git 响应超时,请重试。",+ remoteUnsupported: "远程项目不支持隔离会话。",+ },+ },app: {shellName: "PI-Desktop",tagline: "本地 AI 编程助手",diff --git a/packages/i18n/src/locales/zh-TW/index.ts b/packages/i18n/src/locales/zh-TW/index.tsindex 9f1a16b1f..77a478d35 100644--- a/packages/i18n/src/locales/zh-TW/index.ts+++ b/packages/i18n/src/locales/zh-TW/index.ts@@ -1,6 +1,83 @@import { en, type EnglishCatalog } from "../en/index.js";export const zhTW = {+ worktree: {+ newIsolatedSession: "新增隔離工作階段",+ uncommittedNotIncluded: "專案中未提交的變更不會帶入隔離工作階段。",+ reveal: "顯示 worktree 資料夾",+ deleteLoss: "未合併的工作將會遺失",+ badge: {+ isolated: "隔離",+ conflict: "衝突",+ missing: "資料夾遺失",+ setupFailed: "初始化失敗",+ title: "在獨立的 git worktree 中執行,分支 {{branch}}",+ behind: "↓{{count}}",+ behindTitle: "專案有 {{count}} 個新提交,可用「從專案同步」帶入此工作階段。",+ },+ merge: {+ menu: "合併到專案…",+ title: "合併到專案",+ description: "將 {{branch}} 的提交合入專案的 {{ownerBranch}}。",+ commits: "提交:{{count}}",+ files: "變更檔案:{{count}}",+ uncommittedFile: "尚未提交",+ uncommittedNote: "未提交的變更會先提交到工作階段分支。",+ resolving: "工作階段中有未完成的衝突解決,合併時會一併完成。",+ confirm: "合併",+ merging: "正在合併…",+ success: "已合併到 {{branch}}",+ nothing: "沒有需要合併的內容。",+ conflict: "以下檔案與專案衝突。請在工作階段中解決後再次合併:",+ },+ sync: {+ menu: "從專案同步",+ menuBehind: "從專案同步({{count}} 個新提交)",+ upToDate: "工作階段已包含專案的最新程式碼。",+ resolveFirst: "請先在工作階段中解決衝突,再合併或同步。",+ success: "已把專案的 {{count}} 個新提交同步到工作階段。",+ conflict: "這些檔案與專案衝突,請在工作階段中解決:{{files}}",+ },+ setupCommand: {+ menu: "Worktree 初始化指令…",+ title: "Worktree 初始化指令",+ description: "在本專案每個新的隔離 worktree 中執行,例如安裝相依套件。失敗會提示,但不影響工作階段使用。",+ label: "指令",+ hint: "可用變數:PI_PROJECT_ROOT、PI_WORKTREE_ROOT、PI_PORT。.worktreeinclude 中列出的被忽略檔案會先被複製。",+ placeholder: "pnpm install",+ saved: "初始化指令已儲存",+ },+ setupLog: {+ menu: "初始化記錄",+ title: "Worktree 初始化記錄",+ running: "初始化指令正在執行。",+ ok: "初始化指令已完成。",+ failed: "初始化指令失敗。",+ none: "沒有執行初始化指令。",+ },+ errors: {+ notGit: "此專案不是 git 儲存庫。",+ noCommits: "儲存庫還沒有提交。請先提交一次再使用隔離工作階段。",+ detachedHead: "專案不在任何分支上。請先簽出一個分支。",+ gitMissing: "找不到 Git。請安裝 Git 後使用隔離工作階段。",+ gitTooOld: "隔離工作階段需要 Git 2.29 或更新版本。",+ branchNamespaceTaken: "已存在名為 pi-desktop 的分支。請重新命名後再使用隔離工作階段。",+ busy: "工作階段仍在執行,請等待其結束。",+ changedSincePreview: "預覽後工作階段有了變化,請查看更新後的變更。",+ ownerBranchChanged: "專案已不在本工作階段建立時的分支上。請切回該分支再合併。",+ projectDirty: "專案中未提交的變更會被覆寫。請先提交或暫存後再合併。",+ missing: "隔離 worktree 資料夾已不存在,請刪除此工作階段。",+ commitFailed: "Git 無法提交工作階段的變更。",+ moveUnsupported: "隔離工作階段無法移到其他專案。",+ mergeFailed: "Git 無法把專案的變更合入工作階段(例如有檔案擋住了合併),工作階段保持不變。",+ pathExists: "同名的 worktree 或分支已存在。請重試,或刪除殘留的 worktree/分支。",+ notReady: "隔離 worktree 仍在準備中,請稍後再試。",+ notIsolated: "此工作階段沒有隔離 worktree。",+ gitFailed: "Git 命令執行失敗,請檢查儲存庫後重試。",+ gitTimeout: "Git 回應逾時,請重試。",+ remoteUnsupported: "遠端專案不支援隔離工作階段。",+ },+ },app: {shellName: "PI-Desktop",tagline: "本地 AI 程式設計助手",diff --git a/packages/shared/src/protocol.test.ts b/packages/shared/src/protocol.test.tsindex ae7a30f58..324b609b1 100644--- a/packages/shared/src/protocol.test.ts+++ b/packages/shared/src/protocol.test.ts@@ -19,6 +19,8 @@ import {COMPACTION_SUMMARY_MAX_RETRIES,COMPACTION_SUMMARY_RETRY_BUDGET_MS,STREAM_IDLE_TIMEOUT_MS,+ TOOL_QUEUE_WAIT_MS,+ WORKTREE_DELEGATE_RPC_TIMEOUT_MS,rpcTimeoutMs,type PlanExecution,type PlanArtifact,@@ -247,6 +249,14 @@ describe("Plan protocol contracts", () => {);});+ it("lets a subagent worktree merge outlast its permit waits (ADR 0328)", () => {+ for (const method of ["worktree.delegate.create", "worktree.delegate.settle"]) {+ expect(rpcTimeoutMs(method, {})).toBe(WORKTREE_DELEGATE_RPC_TIMEOUT_MS);+ }+ expect(WORKTREE_DELEGATE_RPC_TIMEOUT_MS).toBeGreaterThan(5_000 + TOOL_QUEUE_WAIT_MS + 3 * 120_000);+ expect(rpcTimeoutMs("worktree.merge", {})).toBe(130_000);+ });+it("outlasts the whole model request a manual compaction spends (#795)", () => {// One summary prompt plus the sidecar's retry budget: every attempt that// stops producing events is cut by the stream watchdog, and each retry paysdiff --git a/packages/shared/src/protocol.ts b/packages/shared/src/protocol.tsindex 4d094d732..727b4efff 100644--- a/packages/shared/src/protocol.ts+++ b/packages/shared/src/protocol.ts@@ -136,6 +136,21 @@ export const IPC = {/** Validate and select a durable session from a reviewed host operation. */sessionOpen: "pi-desktop/session/open",sessionDelete: "pi-desktop/session/delete",+ /** Isolated sessions in git worktrees (ADR 0328). */+ worktreeProbe: "pi-desktop/worktree/probe",+ worktreePreview: "pi-desktop/worktree/preview",+ worktreeMerge: "pi-desktop/worktree/merge",+ worktreePendingWork: "pi-desktop/worktree/pendingWork",+ /** "Sync from project": project commits the session lacks, and the sync. */+ worktreeBehind: "pi-desktop/worktree/behind",+ worktreeSync: "pi-desktop/worktree/sync",+ /** Behind counts of every isolated session, for the sidebar marker. */+ worktreeBehindAll: "pi-desktop/worktree/behindAll",+ worktreeSetupLog: "pi-desktop/worktree/setupLog",+ /** Opens the worktree folder in the OS file manager; no path is returned. */+ worktreeReveal: "pi-desktop/worktree/reveal",+ worktreeSetupCommandGet: "pi-desktop/worktree/setupCommand/get",+ worktreeSetupCommandSet: "pi-desktop/worktree/setupCommand/set",sessionRename: "pi-desktop/session/rename",/** Deterministic first-prompt title for a session that is still untitled. */sessionDeriveTitle: "pi-desktop/session/deriveTitle",diff --git a/packages/shared/src/rpc-timeouts.ts b/packages/shared/src/rpc-timeouts.tsindex 0df025f53..503894459 100644--- a/packages/shared/src/rpc-timeouts.ts+++ b/packages/shared/src/rpc-timeouts.ts@@ -55,6 +55,15 @@ export const AGENT_COMPACT_RPC_TIMEOUT_MS =COMPACTION_SUMMARY_RETRY_BUDGET_MS +COMMAND_RPC_BUFFER_MS;+/**+ * `worktree.delegate.create` / `.settle` (ADR 0328) checkpoint and merge in a+ * session worktree: up to 5s waiting for the session to go quiet, up to+ * `TOOL_QUEUE_WAIT_MS` for its write permit, then a handful of git commands,+ * each bounded by host-core. Under the flat default the runtime gave up while+ * the host was still merging and reported work as kept that had landed.+ */+export const WORKTREE_DELEGATE_RPC_TIMEOUT_MS = 10 * 60_000;+/*** `configSync.syncNow` is a Host-owned multi-step operation. It has no* whole-request deadline: individual S3 requests retain their own bounds, and@@ -85,6 +94,9 @@ export function rpcTimeoutMs(_params: unknown,): number | undefined {if (method === "agent.compact") return AGENT_COMPACT_RPC_TIMEOUT_MS;+ if (method === "worktree.delegate.create" || method === "worktree.delegate.settle") {+ return WORKTREE_DELEGATE_RPC_TIMEOUT_MS;+ }if (method === "configSync.syncNow") return undefined;if (method === "tools.execute" || method === "tools.workspaceExecute") return undefined;return DEFAULT_RPC_TIMEOUT_MS;diff --git a/packages/shared/src/types.ts b/packages/shared/src/types.tsindex 0efa0db0d..a3bfbfef9 100644--- a/packages/shared/src/types.ts+++ b/packages/shared/src/types.ts@@ -9,6 +9,7 @@ export * from "./types/models.js";export * from "./types/permissions.js";export * from "./types/messages.js";export * from "./types/sessions.js";+export * from "./types/worktree.js";export * from "./types/agent.js";export * from "./types/workspace.js";export * from "./types/providers.js";diff --git a/packages/shared/src/types/sessions.ts b/packages/shared/src/types/sessions.tsindex 34dc4b6c8..facf6ba41 100644--- a/packages/shared/src/types/sessions.ts+++ b/packages/shared/src/types/sessions.ts@@ -5,6 +5,7 @@ import type { SessionThinkingLevel, ThinkingLevel } from "./models.js";import type { PermissionMode } from "./permissions.js";import type { UiMessage } from "./messages.js";import type { PlanHistoryEntry, PlanningState } from "./plans.js";+import type { SessionWorktreeSummary } from "./worktree.js";/*** Which authority owns a session's transcript.@@ -68,6 +69,11 @@ export type SessionSummary = {* Older hosts omit it, so `undefined` means an ordinary conversation.*/scheduledRun?: boolean;+ /**+ * Present only for an isolated session (ADR 0328): its tools run in its own+ * git worktree. Older hosts and ordinary sessions omit it.+ */+ worktree?: SessionWorktreeSummary;updatedAt: string;createdAt: string;};diff --git a/packages/shared/src/types/worktree.ts b/packages/shared/src/types/worktree.tsnew file mode 100644index 000000000..b9b45af0f--- /dev/null+++ b/packages/shared/src/types/worktree.ts@@ -0,0 +1,107 @@+/**+ * Isolated sessions in git worktrees (ADR 0328). Host-core owns every+ * worktree path and git command; these shapes carry no filesystem path.+ */++export type WorktreeStatus = "creating" | "active" | "conflict" | "merged" | "missing";++export type WorktreeSetupStatus = "none" | "running" | "ok" | "failed";++/** Badge data attached to `SessionSummary.worktree` for isolated sessions. */+export type SessionWorktreeSummary = {+ branch: string;+ status: WorktreeStatus;+ setupStatus?: WorktreeSetupStatus | null;+};++/** Machine-readable `errorCode` values of `worktree.*` and isolated sessions. */+export const WorktreeErrorCodes = {+ GIT_MISSING: "WORKTREE_GIT_MISSING",+ GIT_TOO_OLD: "WORKTREE_GIT_TOO_OLD",+ GIT_FAILED: "WORKTREE_GIT_FAILED",+ GIT_TIMEOUT: "WORKTREE_GIT_TIMEOUT",+ NOT_GIT: "WORKTREE_NOT_GIT",+ NO_COMMITS: "WORKTREE_NO_COMMITS",+ DETACHED_HEAD: "WORKTREE_DETACHED_HEAD",+ BRANCH_NAMESPACE_TAKEN: "WORKTREE_BRANCH_NAMESPACE_TAKEN",+ NOT_ISOLATED: "WORKTREE_NOT_ISOLATED",+ NOT_READY: "WORKTREE_NOT_READY",+ MISSING: "WORKTREE_MISSING",+ BUSY: "WORKTREE_BUSY",+ CONFLICT: "WORKTREE_CONFLICT",+ CHANGED_SINCE_PREVIEW: "WORKTREE_CHANGED_SINCE_PREVIEW",+ OWNER_BRANCH_CHANGED: "WORKTREE_OWNER_BRANCH_CHANGED",+ PROJECT_DIRTY: "WORKTREE_PROJECT_DIRTY",+ MERGE_FAILED: "WORKTREE_MERGE_FAILED",+ COMMIT_FAILED: "WORKTREE_COMMIT_FAILED",+ MOVE_UNSUPPORTED: "WORKTREE_MOVE_UNSUPPORTED",+ PATH_EXISTS: "WORKTREE_PATH_EXISTS",+ /** The project lives on a remote host; isolation needs a local checkout. */+ REMOTE_UNSUPPORTED: "WORKTREE_REMOTE_UNSUPPORTED",+} as const;++export type WorktreeErrorCode = (typeof WorktreeErrorCodes)[keyof typeof WorktreeErrorCodes];++/** `worktree.probe`: whether a project can host isolated sessions. */+export type WorktreeProbeResult =+ | { available: true; uncommittedChanges: boolean }+ | { available: false; errorCode: WorktreeErrorCode | string; message: string };++export type WorktreeIncludeReport = {+ copied: string[];+ skippedLinks: string[];+};++/** Extra result of `session.create` with `isolated: true`. */+export type CreatedSessionWorktree = {+ worktree: SessionWorktreeSummary;+ included: WorktreeIncludeReport;+ projectHadUncommittedChanges: boolean;+};++export type WorktreePreviewCommit = { sha: string; subject: string };++export type WorktreePreviewFile = {+ /** `A`, `M`, `D`, ... for committed changes; `?` for untracked files. */+ status: string;+ path: string;+ /** Committed on the session branch when the merge runs. */+ uncommitted: boolean;+};++/** `worktree.preview`: what "Merge into project" would land. */+export type WorktreeMergePreview = {+ branch: string;+ ownerBranch: string;+ commits: WorktreePreviewCommit[];+ files: WorktreePreviewFile[];+ conflict: boolean;+ previewToken: string;+};++export type WorktreeMergeOutcome =+ | { result: "merged"; commits: number; files: number }+ | { result: "nothingToMerge" };++/** `worktree.sync`: "Sync from project" brings the project's new commits in. */+export type WorktreeSyncOutcome =+ | { result: "synced"; commits: number }+ | { result: "upToDate" };++/** `worktree.behindAll`: the sidebar's behind counts, keyed by session id. */+export type WorktreeBehindCounts = {+ counts: Record<string, number>;+ /** A conflict was found resolved; the session list should be refreshed. */+ statusesChanged: boolean;+};++/** `worktree.pendingWork`: what deleting the session would lose. */+export type WorktreePendingWork = {+ unmergedCommits: number;+ uncommittedChanges: boolean;+};++export type WorktreeSetupLog = {+ setupStatus: WorktreeSetupStatus | null;+ log: string | null;+};diff --git a/scripts/e2e-worktree-live.mjs b/scripts/e2e-worktree-live.mjsnew file mode 100644index 000000000..4c7370981--- /dev/null+++ b/scripts/e2e-worktree-live.mjs@@ -0,0 +1,328 @@+#!/usr/bin/env node+/**+ * Live-model E2E for isolated sessions (ADR 0328,+ * E2E-WORKTREE-isolated-session-lifecycle), protocol level: a real host-core+ * and agent runtime with a real model, a throwaway git project, and a+ * throwaway data directory. Nothing outside the temp directory is touched.+ *+ * Env (no defaults: this sends real prompts with a real key), either+ * PI_DESKTOP_TEST_API_KEY, PI_DESKTOP_TEST_BASE_URL (OpenAI-compatible) and+ * PI_DESKTOP_TEST_MODEL, or PI_DESKTOP_TEST_PROVIDER_DATA_DIR: a *copy* of a+ * PI-Desktop data directory whose default provider and model are used (the+ * copy may be migrated). Optional: PI_DESKTOP_HOST_BIN, PI_DESKTOP_KEEP_TEMP.+ */+import { execFileSync } from "node:child_process";+import { randomUUID } from "node:crypto";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { DesktopAgentRuntime } from "../packages/agent-runtime/dist/runtime.js";+import { PROTOCOL_VERSION } from "../packages/shared/dist/protocol.js";+import { Host, resolveHostBinary } from "./e2e/host.mjs";++/** The default provider of a copied data directory; the key stays in memory. */+async function providerFromDataDir(dir) {+ const source = new Host(resolveHostBinary(), dir, { quiet: true });+ await source.start(PROTOCOL_VERSION);+ try {+ const settings = await source.call("settings.get");+ const values = settings.settings ?? settings;+ const { providers } = await source.call("providers.list");+ const provider =+ providers.find((entry) => entry.id === values.defaultProviderId) ?? providers.find((entry) => entry.enabled);+ if (!provider) throw new Error("the data directory has no provider");+ const { value } = await source.call("providers.getSecret", { id: provider.id });+ if (!value) throw new Error(`provider ${provider.name} has no API key`);+ return {+ name: provider.name,+ baseUrl: provider.baseUrl,+ model: provider.id === values.defaultProviderId && values.defaultModelId ? values.defaultModelId : provider.defaultModelId,+ apiKey: value,+ apiStyle: provider.apiStyle ?? "chat_completions",+ protocol: provider.protocol ?? "openai_compatible",+ headers: provider.headers,+ };+ } finally {+ await source.stop();+ }+}++let live;+if (process.env.PI_DESKTOP_TEST_PROVIDER_DATA_DIR?.trim()) {+ live = await providerFromDataDir(process.env.PI_DESKTOP_TEST_PROVIDER_DATA_DIR.trim());+} else {+ const REQUIRED_ENV = ["PI_DESKTOP_TEST_API_KEY", "PI_DESKTOP_TEST_BASE_URL", "PI_DESKTOP_TEST_MODEL"];+ const missingEnv = REQUIRED_ENV.filter((name) => !process.env[name]?.trim());+ if (missingEnv.length > 0) {+ console.error(`missing required environment variables: ${missingEnv.join(", ")}`);+ process.exit(1);+ }+ live = {+ name: "Live",+ baseUrl: process.env.PI_DESKTOP_TEST_BASE_URL,+ model: process.env.PI_DESKTOP_TEST_MODEL,+ apiKey: process.env.PI_DESKTOP_TEST_API_KEY,+ apiStyle: "chat_completions",+ protocol: "openai_compatible",+ };+}+console.log(`model: ${live.name} / ${live.model} (${live.apiStyle})`);+// The host inherits this process's environment and the live model runs Bash+// with it, so the key must not be in it (`env` would print it).+for (const name of Object.keys(process.env)) {+ if (name.startsWith("PI_DESKTOP_TEST_")) delete process.env[name];+}++const temp = mkdtempSync(join(tmpdir(), "pi-worktree-live-"));+const dataDir = join(temp, "data");+const project = join(temp, "project");+mkdirSync(dataDir);+mkdirSync(project);++const git = (cwd, ...args) => execFileSync("git", args, { cwd, encoding: "utf8" });+git(project, "init", "-q", "-b", "main");+git(project, "config", "user.email", "[email protected]");+git(project, "config", "user.name", "E2E");+writeFileSync(join(project, "f.txt"), "line one\nline two\n");+writeFileSync(join(project, ".gitignore"), ".env\n");+writeFileSync(join(project, ".worktreeinclude"), ".env\n");+git(project, "add", "-A");+git(project, "commit", "-q", "-m", "base");+writeFileSync(join(project, ".env"), "SECRET=local\n");++const results = [];+function record(id, ok, detail = "") {+ results.push({ id, ok });+ console.log(`${ok ? "PASS" : "FAIL"} ${id}${detail ? ` — ${detail}` : ""}`);+}+const read = (path) => (existsSync(path) ? readFileSync(path, "utf8") : null);+const firstLine = (path) => read(path)?.split("\n")[0]?.trim();+const projectClean = () => git(project, "status", "--porcelain") === "";++const host = new Host(resolveHostBinary(), dataDir, { quiet: true });+const runtimes = new Map();+let provider;++// The platform's default command shell, as host-core resolves it: Windows+// PowerShell on Windows (the `bash` id does not exist there), bash elsewhere.+const windows = process.platform === "win32";+const commandShell = windows+ ? { id: "windows-powershell", label: "Windows PowerShell", dialect: "powershell", available: true, isDefault: true }+ : { id: "bash", label: "Bash", dialect: "posix", available: true, isDefault: true };+const portCommand = windows+ ? 'Set-Content -NoNewline -Path port.txt -Value "$env:PI_PORT|$env:PI_WORKTREE_ROOT"'+ : "printf '%s|%s' \"$PI_PORT\" \"$PI_WORKTREE_ROOT\" > port.txt";++const writer = {+ name: "writer",+ description: "Creates or edits files exactly as instructed.",+ tools: ["Read", "Write", "Edit"],+ prompt: "Do exactly the file change you are asked to do, then reply DONE.",+ source: "user",+};++async function isolatedSession(title) {+ const created = await host.call("session.create", {+ title,+ mode: "agent",+ projectPath: project,+ isolated: true,+ }, 120_000);+ const sessionId = created.session.id;+ const { path } = await host.call("worktree.location", { sessionId });+ return { sessionId, title, root: path, worktree: created.worktree };+}++async function prompt(session, text, { subagents } = {}) {+ let runtime = runtimes.get(session.sessionId);+ const turn = await host.call("session.beginTurn", { sessionId: session.sessionId });+ const userMessageId = randomUUID();+ await host.call("session.appendMessage", {+ sessionId: session.sessionId,+ turnId: turn.turnId,+ message: { id: userMessageId, role: "user", content: text, createdAt: new Date().toISOString(), status: "complete" },+ });+ const events = [];+ if (!runtime) {+ runtime = new DesktopAgentRuntime({+ host,+ sessionId: session.sessionId,+ turnId: turn.turnId,+ mode: "agent",+ projectPath: project,+ workspaceRoot: session.root,+ subagents,+ provider: {+ id: provider.provider.id,+ name: live.name,+ baseUrl: live.baseUrl,+ modelId: live.model,+ apiKey: live.apiKey,+ authKind: "api_key_and_base_url",+ apiStyle: live.apiStyle,+ ...(live.headers ? { headers: live.headers } : {}),+ supportsReasoning: false,+ supportedThinkingLevels: ["off"],+ },+ thinkingLevel: "off",+ commandShell,+ onEvent: (e) => session.events?.push(e.event),+ });+ runtimes.set(session.sessionId, runtime);+ }+ session.events = events;+ let status = "completed";+ try {+ await runtime.prompt(text, userMessageId, turn.turnId);+ if (events.some((event) => event.type === "error")) status = "error";+ } catch (error) {+ status = "error";+ console.error(`prompt failed in ${session.sessionId}:`, error instanceof Error ? error.message : error);+ } finally {+ for (const event of events) {+ if (event.type === "message_end" && event.message.role === "assistant") {+ await host.call("session.appendMessage", { sessionId: session.sessionId, turnId: turn.turnId, message: event.message }).catch(() => {});+ }+ }+ await host.call("session.endTurn", { turnId: turn.turnId, status, createNotification: false });+ const tools = events.filter((event) => event.type === "tool_start").map((event) => event.toolName ?? event.name);+ const errors = events.filter((event) => event.type === "error").map((event) => event.error?.code ?? event.error?.message ?? "error");+ const reply = events.findLast((event) => event.type === "message_end" && event.message.role === "assistant")?.message.content;+ console.log(` [${session.title}] ${status}; events=${events.length}; tools=${tools.join(",") || "-"}; errors=${errors.join(",") || "-"}; reply=${String(reply ?? "").slice(0, 120).replace(/\s+/g, " ")}`);+ }+ return events;+}++async function merge(session) {+ const { preview } = await host.call("worktree.preview", { sessionId: session.sessionId }, 120_000);+ return host.call("worktree.merge", { sessionId: session.sessionId, previewToken: preview.previewToken }, 120_000);+}++try {+ await host.start(PROTOCOL_VERSION);+ provider = await host.call("providers.create", {+ name: live.name,+ baseUrl: live.baseUrl,+ defaultModelId: live.model,+ secretValue: live.apiKey,+ type: "openai_compatible",+ protocol: live.protocol,+ apiStyle: live.apiStyle,+ authKind: "api_key_and_base_url",+ });++ // Throwaway profile: tools run without approval cards (session.create does+ // not accept a permission mode of its own).+ await host.call("settings.set", { defaultPermissionMode: "auto" });++ const probe = await host.call("worktree.probe", { projectPath: project });+ record("probe-git-project", probe.available === true && probe.uncommittedChanges === false);++ // 1. Two isolated sessions edit the same file at the same time.+ const a = await isolatedSession("Session A");+ const b = await isolatedSession("Session B");+ record("worktrees-outside-project", !a.root.startsWith(project) && !b.root.startsWith(project) && a.root !== b.root);+ record("include-file-copied", read(join(a.root, ".env")) === "SECRET=local\n" && read(join(b.root, ".env")) === "SECRET=local\n");+ const task = (letter) =>+ `In the current workspace: 1) Use Edit or Write so that the first line of f.txt is exactly "${letter}" ` ++ `(keep the second line). 2) Create ${letter.toLowerCase()}.txt containing exactly "from-${letter.toLowerCase()}". ` ++ `3) Run this Bash command: ${portCommand} . Then reply DONE.`;+ await Promise.all([prompt(a, task("A")), prompt(b, task("B"))]);+ record("parallel-edits-isolated",+ firstLine(join(a.root, "f.txt")) === "A" && firstLine(join(b.root, "f.txt")) === "B" &&+ read(join(a.root, "a.txt"))?.trim() === "from-a" && read(join(b.root, "b.txt"))?.trim() === "from-b" &&+ !existsSync(join(a.root, "b.txt")) && !existsSync(join(b.root, "a.txt")),+ `A=${firstLine(join(a.root, "f.txt"))} B=${firstLine(join(b.root, "f.txt"))}`);+ record("project-untouched", projectClean() && firstLine(join(project, "f.txt")) === "line one");+ const [portA, rootA] = (read(join(a.root, "port.txt")) ?? "").split("|");+ const [portB] = (read(join(b.root, "port.txt")) ?? "").split("|");+ record("distinct-ports-and-root", Boolean(portA) && Boolean(portB) && portA !== portB && rootA === a.root,+ `A=${portA} B=${portB}`);++ // 2. Merge A, then B conflicts on the same line.+ const mergedA = await merge(a);+ record("merge-a", mergedA.outcome?.result === "merged" && firstLine(join(project, "f.txt")) === "A" &&+ read(join(project, "a.txt"))?.trim() === "from-a");+ const { counts } = await host.call("worktree.behindAll", {});+ record("behind-marker-after-merge", counts[b.sessionId] >= 1 && counts[a.sessionId] === 0, JSON.stringify(counts));+ let conflict;+ try {+ await merge(b);+ } catch (error) {+ conflict = error;+ }+ record("merge-b-conflicts-in-worktree",+ conflict?.errorCode === "WORKTREE_CONFLICT" && projectClean() && firstLine(join(project, "f.txt")) === "A" &&+ !existsSync(join(project, ".git", "MERGE_HEAD")),+ conflict?.errorCode ?? "no conflict");++ // 3. The agent resolves the conflict in its worktree; the merge lands.+ // Both sessions wrote port.txt too, so it conflicts alongside f.txt.+ const conflictFiles = conflict?.rpc?.data?.files ?? [];+ record("conflict-lists-files", conflictFiles.includes("f.txt") && conflictFiles.includes("port.txt"), conflictFiles.join(","));+ await prompt(b,+ "The workspace has unresolved git merge conflicts in: " + conflictFiles.join(", ") + ". Resolve all of them: " ++ 'f.txt must be exactly two lines, "AB" and "line two"; for every other conflicted file keep this session\'s ' ++ "own version. Remove every conflict marker. Do not run git commands. Then reply DONE.");+ let mergedB;+ try {+ mergedB = await merge(b);+ } catch (error) {+ console.error(error.message);+ }+ record("merge-b-after-resolution", mergedB?.outcome?.result === "merged" && firstLine(join(project, "f.txt")) === "AB" &&+ read(join(project, "b.txt"))?.trim() === "from-b" && projectClean());++ // 3b. Session A still has its pre-resolution code; "Sync from project"+ // brings B's resolution in without touching the project.+ const { commits: behindA } = await host.call("worktree.behind", { sessionId: a.sessionId });+ const syncA = await host.call("worktree.sync", { sessionId: a.sessionId }, 120_000);+ record("sync-brings-resolution-into-a",+ behindA > 0 && syncA.outcome?.result === "synced" && firstLine(join(a.root, "f.txt")) === "AB" && projectClean(),+ `behind=${behindA} A=${firstLine(join(a.root, "f.txt"))}`);++ // 4. Two writing subagents in parallel inside one isolated session.+ const c = await isolatedSession("Session C");+ await prompt(c,+ "Use the Task tool to start two `writer` subagents in parallel (two Task calls in one message). " ++ 'The first creates c1.txt containing exactly "one"; the second creates c2.txt containing exactly "two". ' ++ "Wait for both reports with TaskWait, then reply DONE. Do not create the files yourself.",+ { subagents: [writer] });+ // Project plus the three session worktrees; no subagent worktree is left.+ const worktreeCount = git(project, "worktree", "list").split("\n").filter(Boolean).length;+ const delegateRows = { length: worktreeCount - 4 };+ record("subagents-merged-back",+ read(join(c.root, "c1.txt"))?.trim() === "one" && read(join(c.root, "c2.txt"))?.trim() === "two" && delegateRows.length === 0,+ `c1=${read(join(c.root, "c1.txt"))?.trim()} c2=${read(join(c.root, "c2.txt"))?.trim()} delegates=${delegateRows.length}`);++ // 5. Delete with unmerged work discards worktree and branch only.+ const { pending } = await host.call("worktree.pendingWork", { sessionId: c.sessionId });+ record("pending-work-reported", pending.unmergedCommits > 0 || pending.uncommittedChanges === true);+ const branchC = c.worktree?.worktree?.branch;+ await runtimes.get(c.sessionId)?.dispose();+ runtimes.delete(c.sessionId);+ await host.call("session.delete", { id: c.sessionId }, 120_000);+ record("delete-discards-worktree", !existsSync(c.root) && !git(project, "branch", "--list").includes(branchC ?? "pi-desktop/none") &&+ !existsSync(join(project, "c1.txt")));++ // 6. Restart keeps an isolated session in its worktree.+ for (const runtime of runtimes.values()) await runtime.dispose();+ runtimes.clear();+ await host.restart(PROTOCOL_VERSION);+ const { path: afterRestart } = await host.call("worktree.location", { sessionId: a.sessionId });+ record("restart-keeps-worktree", afterRestart === a.root && existsSync(afterRestart));+} catch (error) {+ console.error(error instanceof Error ? error.stack : error);+ record("harness", false, error instanceof Error ? error.message : String(error));+} finally {+ for (const runtime of runtimes.values()) await runtime.dispose().catch(() => {});+ await host.stop().catch(() => {});+ if (process.env.PI_DESKTOP_KEEP_TEMP) {+ console.log(`kept ${temp} (its data directory holds the provider key; delete it when done)`);+ }+ else rmSync(temp, { recursive: true, force: true });+}++const failed = results.filter((result) => !result.ok);+console.log(`\nSummary: ${results.length - failed.length} / ${results.length} passed`);+process.exit(failed.length === 0 ? 0 : 1);