Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat: support local working directory for projects (MUL-2618 v1) (#3283)
Bohan Jiang341ce7bfa515
diff --git a/apps/desktop/src/main/index.ts b/apps/desktop/src/main/index.tsindex b10ea57c41..3edd88fa4c 100644--- a/apps/desktop/src/main/index.ts+++ b/apps/desktop/src/main/index.ts@@ -5,6 +5,7 @@ import { electronApp, optimizer, is } from "@electron-toolkit/utils";import fixPath from "fix-path";import { setupAutoUpdater } from "./updater";import { setupDaemonManager } from "./daemon-manager";+import { setupLocalDirectory } from "./local-directory";import { openExternalSafely, downloadURLSafely } from "./external-url";import { installContextMenu } from "./context-menu";import { handleAppShortcut } from "./keyboard-shortcuts";@@ -460,6 +461,7 @@ if (!gotTheLock) {setupAutoUpdater(() => mainWindow);setupDaemonManager(() => mainWindow);+ setupLocalDirectory(() => mainWindow);// macOS: deep link arrives via open-url eventapp.on("open-url", (_event, url) => {diff --git a/apps/desktop/src/main/local-directory.ts b/apps/desktop/src/main/local-directory.tsnew file mode 100644index 0000000000..2b9ac6884e--- /dev/null+++ b/apps/desktop/src/main/local-directory.ts@@ -0,0 +1,93 @@+import { ipcMain, dialog, BrowserWindow } from "electron";+import { access, stat } from "fs/promises";+import { constants as fsConstants } from "fs";+import { basename, isAbsolute } from "path";++export interface PickDirectoryResult {+ ok: boolean;+ path?: string;+ basename?: string;+ /** Set when ok=false. "cancelled" = user dismissed; otherwise an error blurb. */+ reason?: "cancelled" | "no_window" | "error";+ error?: string;+}++export interface ValidateLocalDirectoryResult {+ ok: boolean;+ /** When ok=false, identifies which check failed so the renderer can render a+ * specific message without parsing free-form text. */+ reason?:+ | "not_absolute"+ | "not_found"+ | "not_a_directory"+ | "not_readable"+ | "not_writable"+ | "error";+ error?: string;+}++async function validateLocalDirectory(+ path: string,+): Promise<ValidateLocalDirectoryResult> {+ if (!path || !isAbsolute(path)) {+ return { ok: false, reason: "not_absolute" };+ }+ try {+ const st = await stat(path);+ if (!st.isDirectory()) return { ok: false, reason: "not_a_directory" };+ } catch (err) {+ const code = (err as NodeJS.ErrnoException).code;+ if (code === "ENOENT") return { ok: false, reason: "not_found" };+ return { ok: false, reason: "error", error: errorMessage(err) };+ }+ try {+ await access(path, fsConstants.R_OK);+ } catch {+ return { ok: false, reason: "not_readable" };+ }+ try {+ await access(path, fsConstants.W_OK);+ } catch {+ return { ok: false, reason: "not_writable" };+ }+ return { ok: true };+}++function errorMessage(err: unknown): string {+ return err instanceof Error ? err.message : String(err);+}++export function setupLocalDirectory(+ windowGetter: () => BrowserWindow | null,+): void {+ ipcMain.handle(+ "local-directory:pick",+ async (_event, defaultPath?: string): Promise<PickDirectoryResult> => {+ const win = windowGetter();+ if (!win) return { ok: false, reason: "no_window" };+ try {+ const result = await dialog.showOpenDialog(win, {+ // Multiple-selection is intentionally disabled — a project_resource+ // points at a single directory, and the create flow expects one+ // path per click. Multi-add would have to be a separate UX.+ properties: ["openDirectory", "createDirectory"],+ ...(defaultPath ? { defaultPath } : {}),+ });+ if (result.canceled || result.filePaths.length === 0) {+ return { ok: false, reason: "cancelled" };+ }+ const picked = result.filePaths[0];+ if (!picked) return { ok: false, reason: "cancelled" };+ return { ok: true, path: picked, basename: basename(picked) };+ } catch (err) {+ return { ok: false, reason: "error", error: errorMessage(err) };+ }+ },+ );++ ipcMain.handle(+ "local-directory:validate",+ (_event, path: string): Promise<ValidateLocalDirectoryResult> =>+ validateLocalDirectory(path),+ );+}diff --git a/apps/desktop/src/preload/index.d.ts b/apps/desktop/src/preload/index.d.tsindex 73b96e201e..a130402f2e 100644--- a/apps/desktop/src/preload/index.d.ts+++ b/apps/desktop/src/preload/index.d.ts@@ -45,6 +45,32 @@ interface DesktopAPI {) => () => void;/** Listen for native macOS back/forward swipe gestures. Returns an unsubscribe function. */onNavigationGesture: (callback: (gesture: NavigationGesture) => void) => () => void;+ /** Open the OS folder picker and return the chosen absolute path.+ * Used by the Project settings "Add local directory" flow. */+ pickDirectory: (+ defaultPath?: string,+ ) => Promise<{+ ok: boolean;+ path?: string;+ basename?: string;+ reason?: "cancelled" | "no_window" | "error";+ error?: string;+ }>;+ /** Validate that a path is an existing readable+writable directory.+ * Mirrors the daemon's runtime check so the user sees errors before submit. */+ validateLocalDirectory: (+ path: string,+ ) => Promise<{+ ok: boolean;+ reason?:+ | "not_absolute"+ | "not_found"+ | "not_a_directory"+ | "not_readable"+ | "not_writable"+ | "error";+ error?: string;+ }>;}interface DaemonStatus {diff --git a/apps/desktop/src/preload/index.ts b/apps/desktop/src/preload/index.tsindex 096abfd580..1f25e1a33b 100644--- a/apps/desktop/src/preload/index.ts+++ b/apps/desktop/src/preload/index.ts@@ -156,6 +156,12 @@ const desktopAPI = {ipcRenderer.removeListener(NAVIGATION_GESTURE_CHANNEL, handler);};},+ /** Open the OS folder picker and return the chosen absolute path. */+ pickDirectory: (defaultPath?: string) =>+ ipcRenderer.invoke("local-directory:pick", defaultPath),+ /** Validate that a path is an existing readable+writable directory. */+ validateLocalDirectory: (path: string) =>+ ipcRenderer.invoke("local-directory:validate", path),};interface DaemonStatus {diff --git a/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx b/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsxindex 4f6689208d..e6e6d4251a 100644--- a/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx+++ b/apps/mobile/app/(app)/[workspace]/issue/[id]/runs.tsx@@ -30,6 +30,7 @@ const PAST_STATUS_ORDER: Record<AgentTask["status"], number> = {completed: 2,queued: 99,dispatched: 99,+ waiting_local_directory: 99,running: 99,};diff --git a/apps/mobile/components/issue/run-row.tsx b/apps/mobile/components/issue/run-row.tsxindex 46b5d9d28e..de53d76bbd 100644--- a/apps/mobile/components/issue/run-row.tsx+++ b/apps/mobile/components/issue/run-row.tsx@@ -133,6 +133,7 @@ function fallbackSummary(task: AgentTask): string {const STATUS_LABEL: Record<AgentTask["status"], string> = {queued: "Queued",dispatched: "Starting",+ waiting_local_directory: "Waiting for directory",running: "Running",completed: "Done",failed: "Failed",@@ -142,6 +143,7 @@ const STATUS_LABEL: Record<AgentTask["status"], string> = {const STATUS_CLASS: Record<AgentTask["status"], string> = {queued: "text-muted-foreground",dispatched: "text-brand",+ waiting_local_directory: "text-muted-foreground",running: "text-brand",completed: "text-muted-foreground",failed: "text-destructive",diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.tsindex 4d41761907..2ed04f6151 100644--- a/packages/core/agents/derive-presence.test.ts+++ b/packages/core/agents/derive-presence.test.ts@@ -171,6 +171,21 @@ describe("deriveWorkloadDetail", () => {expect(r.queuedCount).toBe(2);});+ it("counts waiting_local_directory as queued (daemon parked on a path lock)", () => {+ // waiting_local_directory is the daemon-side "blocked on a busy+ // local_directory" hold state. It is still on the agent's plate —+ // the chip must not flip to idle just because the run phase hasn't+ // started yet — and is grouped with queued/dispatched in the+ // presence verdict so the user sees "Queued · 1" rather than+ // "Idle".+ const r = deriveWorkloadDetail([+ makeTask({ status: "waiting_local_directory" }),+ ]);+ expect(r.workload).toBe("queued");+ expect(r.runningCount).toBe(0);+ expect(r.queuedCount).toBe(1);+ });+it("returns working when running coexists with queued (overflow)", () => {// Capacity-saturated agent: still running, but with a queue building.// The chip says "Working" with the queue expressed as a `+Nq` badge.diff --git a/packages/core/agents/derive-presence.ts b/packages/core/agents/derive-presence.tsindex 5c72398651..c0b0d5d3bf 100644--- a/packages/core/agents/derive-presence.ts+++ b/packages/core/agents/derive-presence.ts@@ -62,7 +62,14 @@ export function deriveWorkloadDetail(tasks: readonly AgentTask[]): WorkloadDetaifor (const t of tasks) {if (t.status === "running") {runningCount += 1;- } else if (t.status === "queued" || t.status === "dispatched") {+ } else if (+ t.status === "queued" ||+ t.status === "dispatched" ||+ // The daemon parked this task on a busy local_directory path. It's+ // still on the agent's plate (counts toward "queued" presence), but+ // it hasn't reached the run phase yet.+ t.status === "waiting_local_directory"+ ) {queuedCount += 1;}// Terminal statuses (completed / failed / cancelled) intentionallydiff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 92f9907fce..52092b8b49 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -70,6 +70,7 @@ import type {ListProjectsResponse,ProjectResource,CreateProjectResourceRequest,+ UpdateProjectResourceRequest,ListProjectResourcesResponse,Label,CreateLabelRequest,@@ -1549,6 +1550,17 @@ export class ApiClient {});}+ async updateProjectResource(+ projectId: string,+ resourceId: string,+ data: UpdateProjectResourceRequest,+ ): Promise<ProjectResource> {+ return this.fetch(`/api/projects/${projectId}/resources/${resourceId}`, {+ method: "PUT",+ body: JSON.stringify(data),+ });+ }+async deleteProjectResource(projectId: string,resourceId: string,diff --git a/packages/core/projects/index.ts b/packages/core/projects/index.tsindex 151407e3d8..a93f334331 100644--- a/packages/core/projects/index.ts+++ b/packages/core/projects/index.ts@@ -6,5 +6,6 @@ export {projectResourceKeys,projectResourcesOptions,useCreateProjectResource,+ useUpdateProjectResource,useDeleteProjectResource,} from "./resource-queries";diff --git a/packages/core/projects/resource-queries.ts b/packages/core/projects/resource-queries.tsindex e5293069ad..85ac92f437 100644--- a/packages/core/projects/resource-queries.ts+++ b/packages/core/projects/resource-queries.ts@@ -5,6 +5,7 @@ import type {CreateProjectResourceRequest,ListProjectResourcesResponse,ProjectResource,+ UpdateProjectResourceRequest,} from "../types";export const projectResourceKeys = {@@ -46,6 +47,38 @@ export function useCreateProjectResource(wsId: string, projectId: string) {});}+export function useUpdateProjectResource(wsId: string, projectId: string) {+ const qc = useQueryClient();+ return useMutation({+ mutationFn: ({+ resourceId,+ data,+ }: {+ resourceId: string;+ data: UpdateProjectResourceRequest;+ }) => api.updateProjectResource(projectId, resourceId, data),+ onSuccess: (updated) => {+ qc.setQueryData<ListProjectResourcesResponse>(+ projectResourceKeys.list(wsId, projectId),+ (old) =>+ old+ ? {+ ...old,+ resources: old.resources.map((r) =>+ r.id === updated.id ? updated : r,+ ),+ }+ : old,+ );+ },+ onSettled: () => {+ qc.invalidateQueries({+ queryKey: projectResourceKeys.list(wsId, projectId),+ });+ },+ });+}+export function useDeleteProjectResource(wsId: string, projectId: string) {const qc = useQueryClient();return useMutation({diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 309bd4ede9..fb49d1ef5e 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -62,6 +62,8 @@ import type {TaskMessagePayload,TaskQueuedPayload,TaskDispatchPayload,+ TaskRunningPayload,+ TaskWaitingLocalDirectoryPayload,TaskCompletedPayload,TaskFailedPayload,TaskCancelledPayload,@@ -785,6 +787,43 @@ export function useRealtimeSync();});+ // task:running fires when the daemon transitions a previously-parked task+ // (waiting_local_directory) back into the run phase. The dispatch→running+ // path is collapsed in the handler above, so this handler exists mainly to+ // clear a stale `waiting_local_directory` pill — without it, the pill+ // would stay parked even after the daemon resumed work.+ const unsubTaskRunning = ws.on("task:running", (p) => {+ const payload = p as TaskRunningPayload;+ if (!payload.chat_session_id) return;+ qc.setQueryData<ChatPendingTask>(+ chatKeys.pendingTask(payload.chat_session_id),+ (old) => {+ if (!old || old.task_id !== payload.task_id) return old;+ return { ...old, status: "running" };+ },+ );+ });++ // task:waiting_local_directory fires when the daemon dequeues a task but+ // can't acquire the local_directory path lock — another task on this+ // daemon is in the same directory. Write the status so TaskStatusPill+ // can render the "Waiting for local directory" stage instead of pinning+ // a stale "Starting / Thinking" frame.+ const unsubTaskWaitingLocalDir = ws.on(+ "task:waiting_local_directory",+ (p) => {+ const payload = p as TaskWaitingLocalDirectoryPayload;+ if (!payload.chat_session_id) return;+ qc.setQueryData<ChatPendingTask>(+ chatKeys.pendingTask(payload.chat_session_id),+ (old) => {+ if (!old || old.task_id !== payload.task_id) return old;+ return { ...old, status: "waiting_local_directory" };+ },+ );+ },+ );+// task:cancelled reaches us when:// 1. handleStop already cleared the cache locally (this is a no-op confirm)// 2. another tab / admin / system cancels — this is the only path that@@ -926,6 +965,8 @@ export function useRealtimeSync(unsubChatDone();unsubTaskQueued();unsubTaskDispatch();+ unsubTaskRunning();+ unsubTaskWaitingLocalDir();unsubTaskCancelled();unsubTaskCompleted();unsubTaskFailed();diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 61a7d880d2..fb5af1868e 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -70,7 +70,19 @@ export interface AgentTask {// autopilot-spawned. Check chat_session_id / autopilot_run_id to tell// which source produced it.issue_id: string;- status: "queued" | "dispatched" | "running" | "completed" | "failed" | "cancelled";+ // `waiting_local_directory` is the daemon-emitted hold state for the+ // local_directory flow: a task that has been dispatched but is parked+ // because another task currently owns the same on-disk path lock.+ // Treated as an active (non-terminal) state alongside queued/dispatched/+ // running by every consumer that buckets tasks into "active vs done".+ status:+ | "queued"+ | "dispatched"+ | "waiting_local_directory"+ | "running"+ | "completed"+ | "failed"+ | "cancelled";priority: number;dispatched_at: string | null;started_at: string | null;diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 68d2d5d5b2..5d5d0d8af2 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -23,6 +23,8 @@ export type WSEventType =| "agent:restored"| "task:queued"| "task:dispatch"+ | "task:running"+ | "task:waiting_local_directory"| "task:progress"| "task:completed"| "task:failed"@@ -239,6 +241,28 @@ export interface TaskDispatchPayload {chat_session_id?: string;}+export interface TaskRunningPayload {+ task_id: string;+ agent_id: string;+ issue_id: string;+ chat_session_id?: string;+ status: string;+}++// task:waiting_local_directory fires when the daemon dequeues a task but+// can't immediately acquire the on-disk path lock — another task on this+// daemon is already executing in the same local_directory. The optional+// `wait_reason` mirrors the server-side hint (path / holder task id), but+// is not yet surfaced end-to-end; the UI today only reads the status.+export interface TaskWaitingLocalDirectoryPayload {+ task_id: string;+ agent_id: string;+ issue_id: string;+ chat_session_id?: string;+ status: string;+ wait_reason?: string;+}+export interface TaskCompletedPayload {task_id: string;agent_id: string;@@ -385,6 +409,8 @@ export interface WSEventPayloadMap {"agent:restored": AgentRestoredPayload;"task:queued": TaskQueuedPayload;"task:dispatch": TaskDispatchPayload;+ "task:running": TaskRunningPayload;+ "task:waiting_local_directory": TaskWaitingLocalDirectoryPayload;"task:completed": TaskCompletedPayload;"task:failed": TaskFailedPayload;"task:message": TaskMessagePayload;diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 5d09cb2d81..84e6d2afd8 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -76,8 +76,11 @@ export type {ListProjectsResponse,ProjectResource,ProjectResourceType,+ ProjectResourceRef,GithubRepoResourceRef,+ LocalDirectoryResourceRef,CreateProjectResourceRequest,+ UpdateProjectResourceRequest,ListProjectResourcesResponse,} from "./project";export type { PinnedItem, PinnedItemType, CreatePinRequest, ReorderPinsRequest } from "./pin";diff --git a/packages/core/types/project.ts b/packages/core/types/project.tsindex c31d4b20db..6855f8e891 100644--- a/packages/core/types/project.ts+++ b/packages/core/types/project.ts@@ -48,23 +48,37 @@ export interface ListProjectsResponse {}// ProjectResource is a typed pointer from a project to an external resource.-// The resource_ref shape depends on resource_type (e.g. github_repo carries-// { url, default_branch_hint? }). New types add a case in-// validateAndNormalizeResourceRef on the server and a renderer in the UI;-// no schema or type changes required.-export type ProjectResourceType = "github_repo";+// The resource_ref shape depends on resource_type. New types add a case in+// validateAndNormalizeResourceRef on the server and a renderer in the UI.+//+// Known types (UI must default-case unknown server-side additions):+// - github_repo: cloud-side git checkout, ref = { url, default_branch_hint? }+// - local_directory: in-place agent execution on a specific daemon,+// ref = { local_path, daemon_id, label? }+export type ProjectResourceType = "github_repo" | "local_directory";export interface GithubRepoResourceRef {url: string;default_branch_hint?: string;}+export interface LocalDirectoryResourceRef {+ local_path: string;+ daemon_id: string;+ label?: string;+}++export type ProjectResourceRef =+ | GithubRepoResourceRef+ | LocalDirectoryResourceRef+ | Record<string, unknown>;+export interface ProjectResource {id: string;project_id: string;workspace_id: string;resource_type: ProjectResourceType;- resource_ref: GithubRepoResourceRef | Record<string, unknown>;+ resource_ref: ProjectResourceRef;label: string | null;position: number;created_at: string;@@ -73,11 +87,20 @@ export interface ProjectResource {export interface CreateProjectResourceRequest {resource_type: ProjectResourceType;- resource_ref: GithubRepoResourceRef | Record<string, unknown>;+ resource_ref: ProjectResourceRef;label?: string;position?: number;}+// resource_type is immutable server-side; partial-update payload mirrors that.+// Sending only the field(s) you want to change is fine — the server merges+// the request body with the existing row, including resource_ref shortcuts.+export interface UpdateProjectResourceRequest {+ resource_ref?: ProjectResourceRef;+ label?: string | null;+ position?: number;+}+export interface ListProjectResourcesResponse {resources: ProjectResource[];total: number;diff --git a/packages/views/chat/components/task-status-pill.test.ts b/packages/views/chat/components/task-status-pill.test.tsnew file mode 100644index 0000000000..894019a3e1--- /dev/null+++ b/packages/views/chat/components/task-status-pill.test.ts@@ -0,0 +1,40 @@+import { describe, it, expect } from "vitest";+import { pickStageKeys } from "./task-status-pill";++describe("pickStageKeys", () => {+ it("returns queued when status is queued and agent is online", () => {+ expect(pickStageKeys("queued", [], "online")).toEqual({ stageKey: "queued" });+ });++ it("returns offline when status is queued and agent is offline", () => {+ expect(pickStageKeys("queued", [], "offline")).toEqual({+ stageKey: "offline",+ static: true,+ });+ });++ it("returns waiting_local_directory on the daemon-emitted hold status", () => {+ // Daemon publishes this when it dequeues a task but another task owns the+ // local_directory's lock. The pill becomes static (no shimmer) because+ // nothing is actively happening from the user's point of view.+ expect(pickStageKeys("waiting_local_directory", [], "online")).toEqual({+ stageKey: "waiting_local_directory",+ static: true,+ });+ });++ it("waiting_local_directory wins over availability hints", () => {+ // Even if availability says reconnecting/offline, the directory-release+ // status is the more specific signal — surface it.+ expect(+ pickStageKeys("waiting_local_directory", [], "unstable"),+ ).toEqual({ stageKey: "waiting_local_directory", static: true });+ expect(+ pickStageKeys("waiting_local_directory", [], "offline"),+ ).toEqual({ stageKey: "waiting_local_directory", static: true });+ });++ it("returns thinking for running with no messages", () => {+ expect(pickStageKeys("running", [], "online")).toEqual({ stageKey: "thinking" });+ });+});diff --git a/packages/views/chat/components/task-status-pill.tsx b/packages/views/chat/components/task-status-pill.tsxindex fb83be3f22..befd0e97a2 100644--- a/packages/views/chat/components/task-status-pill.tsx+++ b/packages/views/chat/components/task-status-pill.tsx@@ -26,6 +26,7 @@ type StageKey =| "offline"| "reconnecting"| "queued"+ | "waiting_local_directory"| "starting_up"| "thinking"| "typing";@@ -56,7 +57,7 @@ const TOOL_KEY_BY_SLUG: Record<string, Exclude<ToolKey, "fallback">> = {// Pure stage decision returning translation keys. The hook below maps these// keys into localized labels — keeping the decision pure makes it easy to// follow the priority rules without translation noise.-function pickStageKeys(+export function pickStageKeys(status: string | undefined,taskMessages: readonly TaskMessagePayload[],availability: AgentAvailability | undefined,@@ -73,6 +74,14 @@ function pickStageKeys() {return { stageKey: "reconnecting" };}+ // Daemon-emitted hold state for the local_directory flow: the project is+ // pinned to a path that another task currently owns. The daemon publishes+ // this status string when it dequeues a task but can't acquire the path+ // lock; the renderer surfaces a dedicated label so the user understands+ // why a queued task isn't moving.+ if (status === "waiting_local_directory") {+ return { stageKey: "waiting_local_directory", static: true };+ }if (status === "queued") return { stageKey: "queued" };if (status === "dispatched") return { stageKey: "starting_up" };diff --git a/packages/views/issues/components/agent-live-card.tsx b/packages/views/issues/components/agent-live-card.tsxindex 06f002352c..ed0b474290 100644--- a/packages/views/issues/components/agent-live-card.tsx+++ b/packages/views/issues/components/agent-live-card.tsx@@ -211,21 +211,30 @@ export function AgentLiveCard({ issueId }: AgentLiveCardProps) {useWSEvent("task:queued", handleTaskActive);useWSEvent("task:dispatch", handleTaskActive);+ // The daemon publishes these two transitions while a task moves through+ // the dispatch → waiting_local_directory → running sequence on a busy+ // local_directory path. Without subscribing here, the sticky banner+ // would stay stuck on the optimistic dispatch state instead of flipping+ // to "waiting" then resuming "is working".+ useWSEvent("task:waiting_local_directory", handleTaskActive);+ useWSEvent("task:running", handleTaskActive);if (taskStates.size === 0) return null;- // Order: running → dispatched → queued. The most-active task takes the- // sticky slot; queued tasks sit below so the "is working" banner isn't- // pushed off by a freshly-enqueued sibling. ListActiveTasksByIssue's- // server-side ORDER BY is created_at DESC, which doesn't reflect lifecycle- // priority, so we re-sort on the client.+ // Order: running → dispatched → waiting → queued. The most-active task+ // takes the sticky slot; the parked / queued tasks sit below so the+ // "is working" banner isn't pushed off by a freshly-enqueued or+ // path-parked sibling. ListActiveTasksByIssue's server-side ORDER BY is+ // created_at DESC, which doesn't reflect lifecycle priority, so we+ // re-sort on the client.const statusRank: Record<AgentTask["status"], number> = {running: 0,dispatched: 1,- queued: 2,- completed: 3,- failed: 3,- cancelled: 3,+ waiting_local_directory: 2,+ queued: 3,+ completed: 4,+ failed: 4,+ cancelled: 4,};const entries = Array.from(taskStates.values()).sort((a, b) => statusRank[a.task.status] - statusRank[b.task.status],@@ -278,6 +287,14 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLivconst [confirmOpen, setConfirmOpen] = useState(false);const isQueued = task.status === "queued";+ // `waiting_local_directory` is the daemon-parked stage of an otherwise-+ // active task: it's been dispatched (no longer pure-queued) but hasn't+ // entered the running phase yet because another task on this daemon+ // holds the same local_directory lock.+ const isWaitingLocalDirectory = task.status === "waiting_local_directory";+ // Treat parked + queued the same visually (non-shimmering, muted accent),+ // but the label below is distinct so the user sees the specific reason.+ const isParked = isQueued || isWaitingLocalDirectory;// Elapsed time — ticks every second so users see the agent is alive.// For queued tasks neither started_at nor dispatched_at is set yet, so@@ -308,10 +325,11 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLivconst toolCount = items.filter((i) => i.type === "tool_use").length;- // Queued tasks render with a non-spinning Clock and dimmer accent so the- // banner reads as "waiting" rather than "working" at a glance.+ // Queued / waiting tasks render with a non-spinning Clock and dimmer+ // accent so the banner reads as "waiting" rather than "working" at a+ // glance.return (- <div className={isQueued ? "rounded-lg border border-border bg-muted/30" : "rounded-lg border border-info/20 bg-info/5"}>+ <div className={isParked ? "rounded-lg border border-border bg-muted/30" : "rounded-lg border border-info/20 bg-info/5"}><div className="flex items-center gap-2 px-3 py-2 text-muted-foreground">{task.agent_id ? (<ActorAvatar actorType="agent" actorId={task.agent_id} size={20} enableHoverCard showStatusDot />@@ -321,27 +339,29 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLiv</div>)}<div className="flex items-center gap-1.5 text-xs min-w-0">- {isQueued ? (+ {isParked ? (<Clock className="h-3 w-3 text-muted-foreground shrink-0" />) : (<Loader2 className="h-3 w-3 animate-spin text-info shrink-0" />)}<span className="font-medium text-foreground truncate">- {isQueued- ? t(($) => $.agent_live.is_queued, { name: agentName })- : t(($) => $.agent_live.is_working, { name: agentName })}+ {isWaitingLocalDirectory+ ? t(($) => $.agent_live.is_waiting_local_directory, { name: agentName })+ : isQueued+ ? t(($) => $.agent_live.is_queued, { name: agentName })+ : t(($) => $.agent_live.is_working, { name: agentName })}</span><span className="text-muted-foreground tabular-nums shrink-0">- {isQueued+ {isParked? t(($) => $.agent_live.queued_elapsed_prefix, { elapsed }): elapsed}</span>- {!isQueued && toolCount > 0 && (+ {!isParked && toolCount > 0 && (<span className="text-muted-foreground shrink-0">{t(($) => $.agent_live.tool_count, { count: toolCount })}</span>)}</div><div className="ml-auto flex items-center gap-1 shrink-0">- {!isQueued && (+ {!isParked && (<TranscriptButtontask={task}agentName={agentName}@@ -365,7 +385,7 @@ function SingleAgentLiveCard({ task, items, issueId, agentName }: SingleAgentLivopen={confirmOpen}onOpenChange={setConfirmOpen}onConfirm={() => void handleCancel()}- showRunningNote={!isQueued}+ showRunningNote={!isParked}/></div>);diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex 19c7736474..576060a3c3 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -89,6 +89,10 @@ export function ExecutionLogSection({ issueId }: ExecutionLogSectionProps) {(t) =>t.status === "queued" ||t.status === "dispatched" ||+ // Daemon-parked task on a busy local_directory — still active+ // (waiting on a path lock), not terminal. Surfacing it here is+ // what tells the user the agent is alive and will resume.+ t.status === "waiting_local_directory" ||t.status === "running",),[tasks],@@ -200,6 +204,9 @@ export function ExecutionLogSection({ issueId }: ExecutionLogSectionProps) {const STATUS_TONE: Record<AgentTask["status"], string> = {queued: "text-warning",dispatched: "text-warning",+ // Same tone as queued/dispatched — visually "stopped" so users see the+ // task is parked, but distinguished by the status label.+ waiting_local_directory: "text-warning",running: "text-info",completed: "text-success",failed: "text-destructive",@@ -213,7 +220,10 @@ function activeTimeText(task: AgentTask, timeAgo: (dateStr: string) => string):if (task.status === "running" && task.started_at) {return timeAgo(task.started_at);}- if (task.status === "dispatched" && task.dispatched_at) {+ if (+ (task.status === "dispatched" || task.status === "waiting_local_directory") &&+ task.dispatched_at+ ) {return timeAgo(task.dispatched_at);}return timeAgo(task.created_at);@@ -248,6 +258,8 @@ function useStatusLabel(status: AgentTask["status"]): string {switch (status) {case "queued": return t(($) => $.execution_log.status_queued);case "dispatched": return t(($) => $.execution_log.status_dispatched);+ case "waiting_local_directory":+ return t(($) => $.execution_log.status_waiting_local_directory);case "running": return t(($) => $.execution_log.status_running);case "completed": return t(($) => $.execution_log.status_completed);case "failed": return t(($) => $.execution_log.status_failed);@@ -265,9 +277,10 @@ function ActiveRow({ task, issueId }: { task: AgentTask; issueId: string }) {const trigger = useTriggerText(task);const time = activeTimeText(task, timeAgo);- // Transcript only meaningful once messages exist — pure-queued tasks- // have nothing to show yet.- const showTranscript = task.status !== "queued";+ // Transcript only meaningful once messages exist — pure-queued and+ // waiting_local_directory tasks haven't streamed any agent output yet.+ const showTranscript =+ task.status !== "queued" && task.status !== "waiting_local_directory";const handleCancel = async () => {if (cancelling) return;@@ -328,7 +341,11 @@ function ActiveRow({ task, issueId }: { task: AgentTask; issueId: string }) {open={confirmOpen}onOpenChange={setConfirmOpen}onConfirm={() => void handleCancel()}- showRunningNote={task.status === "running" || task.status === "dispatched"}+ showRunningNote={+ task.status === "running" ||+ task.status === "dispatched" ||+ task.status === "waiting_local_directory"+ }/></RowShell>);diff --git a/packages/views/issues/components/issue-agent-activity-indicator.tsx b/packages/views/issues/components/issue-agent-activity-indicator.tsxindex b2dea3498e..226c46521f 100644--- a/packages/views/issues/components/issue-agent-activity-indicator.tsx+++ b/packages/views/issues/components/issue-agent-activity-indicator.tsx@@ -60,7 +60,14 @@ export const IssueAgentActivityIndicator = memo(function IssueAgentActivityIndicfor (const task of snapshot) {if (task.issue_id !== issueId) continue;if (task.status === "running") running.push(task);- else if (task.status === "queued" || task.status === "dispatched")+ else if (+ task.status === "queued" ||+ task.status === "dispatched" ||+ // waiting_local_directory is the daemon-parked variant of "queued"+ // — the agent is still actively waiting on a path lock, so it+ // belongs in the active hover stack rather than dropping out.+ task.status === "waiting_local_directory"+ )queued.push(task);// Terminal statuses are intentionally ignored — they belong on the// issue history, not the live indicator.diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex e291982d7a..97a60334af 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -49,6 +49,7 @@ import { toast } from "sonner";import { StatusIcon, PriorityIcon, StatusPicker, PriorityPicker, StartDatePicker, DueDatePicker, AssigneePicker, LabelPicker } from ".";import { IssueActionsDropdown, useIssueActions } from "../actions";import { ProjectPicker } from "../../projects/components/project-picker";+import { LocalDirectoryHint } from "../../projects/components/local-directory-hint";import { CommentCard } from "./comment-card";import { CommentInput } from "./comment-input";import { ResolvedThreadBar } from "./resolved-thread-bar";@@ -2017,6 +2018,7 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr{/* Bottom comment input — no avatar, full width */}<div className="mt-4">+ <LocalDirectoryHint projectId={issue?.project_id} />{/* key={id}: web's /issues/[id] route doesn't remount onissueId change, so without an explicit key the editorkeeps the previous issue's in-memory content and thediff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex 75e687cc20..4d1d81c9d5 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -102,6 +102,7 @@"offline": "Offline","reconnecting": "Reconnecting","queued": "Queued",+ "waiting_local_directory": "Waiting for local directory","starting_up": "Starting up","thinking": "Thinking","typing": "Typing"diff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 5168bd3ccf..cef5ee7e9e 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -306,6 +306,7 @@"agent_live": {"is_working": "{{name}} is working","is_queued": "{{name}} is queued",+ "is_waiting_local_directory": "{{name}} is waiting for the local directory","queued_elapsed_prefix": "queued for {{elapsed}}","fallback_name": "Agent","tool_count_one": "{{count}} tool",@@ -335,6 +336,7 @@"trigger_initial": "Initial run","status_queued": "Queued","status_dispatched": "Starting",+ "status_waiting_local_directory": "Waiting for local directory","status_running": "Working","status_completed": "Completed","status_failed": "Failed",diff --git a/packages/views/locales/en/modals.json b/packages/views/locales/en/modals.jsonindex efc7f8d19b..f76c0c8fe6 100644--- a/packages/views/locales/en/modals.json+++ b/packages/views/locales/en/modals.json@@ -109,7 +109,21 @@"repos_search_empty": "No repositories match your search.","repos_url_placeholder": "https://github.com/owner/repo or [email protected]:owner/repo.git","repos_add": "Add",- "repos_selected": "Selected"+ "repos_selected": "Selected",+ "source_pill_local": "Local directory",+ "source_tab_repos": "GitHub repos",+ "source_tab_local": "Local directory",+ "local_heading": "Use a local working directory on this machine",+ "local_on_device": "Bound to {{device}}",+ "local_this_machine": "this machine",+ "local_daemon_offline": "Daemon offline — start it to bind a local directory.",+ "local_pick": "Choose directory…",+ "local_picking": "Opening picker…",+ "local_change": "Change directory…",+ "local_clear": "Clear",+ "local_pick_failed": "Could not open the directory picker.",+ "local_invalid_dir": "This directory can't be used. Pick another.",+ "local_hint": "Agents on other machines won't see this path — they'll fail to start. Use repos for shared work."},"create_issue": {"sr_manual": "New Issue",diff --git a/packages/views/locales/en/projects.json b/packages/views/locales/en/projects.jsonindex 524ece9bdd..51f40647b8 100644--- a/packages/views/locales/en/projects.json+++ b/packages/views/locales/en/projects.json@@ -80,7 +80,28 @@"toast_attached": "Repository attached","toast_attach_failed": "Failed to attach","toast_removed": "Resource removed",- "toast_remove_failed": "Failed to remove resource"+ "toast_remove_failed": "Failed to remove resource",+ "add_local_directory_button": "Add local directory",+ "local_daemon_offline_hint": "Start the local daemon to attach a directory on this machine.",+ "local_daemon_already_attached_hint": "This machine already has a local directory attached. Remove it before adding another.",+ "local_rename_tooltip": "Rename",+ "local_rename_label": "Local directory label",+ "local_no_daemon_tooltip": "Local daemon isn't reporting an ID yet — the agent can't open this directory.",+ "local_other_machine_tooltip": "Only available on the machine that registered this directory.",+ "chat_hint_prefix": "Agent will work in-place at",+ "toast_local_attached": "Local directory attached",+ "toast_local_renamed": "Renamed",+ "toast_local_rename_failed": "Failed to rename",+ "toast_local_pick_failed": "Failed to pick directory",+ "toast_local_already_attached": "This directory is already attached to the project on this machine.",+ "toast_local_daemon_already_attached": "This machine already has a local directory attached to this project. Remove it before adding another.",+ "toast_local_daemon_not_running": "Local daemon isn't running.",+ "local_validate_not_absolute": "Pick an absolute path.",+ "local_validate_not_found": "Path doesn't exist.",+ "local_validate_not_a_directory": "Path is not a directory.",+ "local_validate_not_readable": "Directory is not readable.",+ "local_validate_not_writable": "Directory is not writable.",+ "local_validate_unsupported": "Local directories can only be picked on the desktop app."},"delete_dialog": {"title": "Delete project",diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex fc90233ffd..c4e440b038 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -98,6 +98,7 @@"offline": "离线","reconnecting": "重连中","queued": "排队中",+ "waiting_local_directory": "等待本地目录释放","starting_up": "启动中","thinking": "思考中","typing": "输入中"diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex f1a4ddec08..52fd0cb812 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -300,6 +300,7 @@"agent_live": {"is_working": "{{name}} 正在处理","is_queued": "{{name}} 排队中",+ "is_waiting_local_directory": "{{name}} 正在等待本地目录","queued_elapsed_prefix": "已排队 {{elapsed}}","fallback_name": "智能体","tool_count_other": "{{count}} 次工具调用",@@ -328,6 +329,7 @@"trigger_initial": "首次运行","status_queued": "排队中","status_dispatched": "启动中",+ "status_waiting_local_directory": "等待本地目录释放","status_running": "处理中","status_completed": "已完成","status_failed": "失败",diff --git a/packages/views/locales/zh-Hans/modals.json b/packages/views/locales/zh-Hans/modals.jsonindex 57a91ce431..872f8ccd10 100644--- a/packages/views/locales/zh-Hans/modals.json+++ b/packages/views/locales/zh-Hans/modals.json@@ -109,7 +109,21 @@"repos_search_empty": "没有匹配的仓库。","repos_url_placeholder": "https://github.com/owner/repo 或 [email protected]:owner/repo.git","repos_add": "添加",- "repos_selected": "已选"+ "repos_selected": "已选",+ "source_pill_local": "本地目录",+ "source_tab_repos": "GitHub 仓库",+ "source_tab_local": "本地目录",+ "local_heading": "使用本机的本地工作目录",+ "local_on_device": "绑定到 {{device}}",+ "local_this_machine": "本机",+ "local_daemon_offline": "Daemon 未运行 —— 启动后才能绑定本地目录。",+ "local_pick": "选择目录…",+ "local_picking": "正在打开选择器…",+ "local_change": "更换目录…",+ "local_clear": "清除",+ "local_pick_failed": "无法打开目录选择器。",+ "local_invalid_dir": "该目录不可用,请重新选择。",+ "local_hint": "其他机器上的 agent 看不到这个路径,会启动失败。需要协作请用仓库模式。"},"create_issue": {"sr_manual": "新建 issue",diff --git a/packages/views/locales/zh-Hans/projects.json b/packages/views/locales/zh-Hans/projects.jsonindex 44d905bd96..6f8ff926b3 100644--- a/packages/views/locales/zh-Hans/projects.json+++ b/packages/views/locales/zh-Hans/projects.json@@ -80,7 +80,28 @@"toast_attached": "已关联仓库","toast_attach_failed": "关联失败","toast_removed": "已移除资源",- "toast_remove_failed": "移除资源失败"+ "toast_remove_failed": "移除资源失败",+ "add_local_directory_button": "添加本地目录",+ "local_daemon_offline_hint": "启动本地 daemon 后才能添加本机目录。",+ "local_daemon_already_attached_hint": "本机已经关联了一个本地目录到该项目,先移除现有目录再添加新目录。",+ "local_rename_tooltip": "重命名",+ "local_rename_label": "本地目录显示名",+ "local_no_daemon_tooltip": "尚未识别到本机 daemon,agent 暂时无法打开此目录。",+ "local_other_machine_tooltip": "此目录仅在最初注册它的电脑上可用。",+ "chat_hint_prefix": "Agent 将在",+ "toast_local_attached": "已添加本地目录",+ "toast_local_renamed": "已重命名",+ "toast_local_rename_failed": "重命名失败",+ "toast_local_pick_failed": "选择目录失败",+ "toast_local_already_attached": "该目录已经在本机关联到此项目。",+ "toast_local_daemon_already_attached": "本机已经关联了一个本地目录到该项目,先移除现有目录再添加新目录。",+ "toast_local_daemon_not_running": "本地 daemon 未运行。",+ "local_validate_not_absolute": "请选择绝对路径。",+ "local_validate_not_found": "目录不存在。",+ "local_validate_not_a_directory": "该路径不是目录。",+ "local_validate_not_readable": "目录不可读。",+ "local_validate_not_writable": "目录不可写。",+ "local_validate_unsupported": "本地目录仅能在桌面端选择。"},"delete_dialog": {"title": "删除项目",diff --git a/packages/views/modals/create-project.tsx b/packages/views/modals/create-project.tsxindex d783956f92..b03f9ecc99 100644--- a/packages/views/modals/create-project.tsx+++ b/packages/views/modals/create-project.tsx@@ -1,7 +1,7 @@"use client";import { useState, useRef } from "react";-import { ChevronRight, Maximize2, Minimize2, Search, X as XIcon, UserMinus } from "lucide-react";+import { ChevronRight, FolderOpen, Maximize2, Minimize2, Search, X as XIcon, UserMinus } from "lucide-react";/*** GitHub mark — lucide-react v1 dropped brand icons, so we inline the@@ -57,6 +57,12 @@ import {useProjectStatusLabels,useProjectPriorityLabels,} from "../projects/components/labels";+import {+ isDesktopShell,+ pickDirectory,+ validateLocalDirectory,+} from "../platform/local-directory";+import { useLocalDaemonStatus } from "../platform/use-local-daemon-status";function PillButton({children,@@ -144,6 +150,59 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {repo.url.toLowerCase().includes(repoQuery),);+ // A project's source is binary: either a set of GitHub repos OR a local+ // working directory — never both. Mode is the source of truth for what+ // gets persisted on submit; switching mode does NOT clear the other+ // side's stash, so toggling back and forth restores the user's prior+ // selection. Only the mode-matching side is sent to the API. Local mode+ // is hidden entirely on web (no daemon to bind the path to).+ const desktop = isDesktopShell();+ const daemonStatus = useLocalDaemonStatus();+ const [sourceMode, setSourceMode] = useState<"repos" | "local">("repos");+ const [selectedLocalPath, setSelectedLocalPath] = useState<string | null>(null);+ const [selectedLocalLabel, setSelectedLocalLabel] = useState<string | null>(null);+ const [localPickError, setLocalPickError] = useState<string | null>(null);+ const [localPicking, setLocalPicking] = useState(false);++ const handleSourceModeChange = (mode: "repos" | "local") => {+ setSourceMode(mode);+ setLocalPickError(null);+ };++ const handlePickLocalDirectory = async () => {+ if (localPicking) return;+ setLocalPickError(null);+ setLocalPicking(true);+ try {+ const picked = await pickDirectory(selectedLocalPath ?? undefined);+ if (!picked.ok || !picked.path) {+ if (picked.reason && picked.reason !== "cancelled") {+ setLocalPickError(+ picked.error ?? t(($) => $.create_project.local_pick_failed),+ );+ }+ return;+ }+ const validation = await validateLocalDirectory(picked.path);+ if (!validation.ok) {+ setLocalPickError(+ validation.error ?? t(($) => $.create_project.local_invalid_dir),+ );+ return;+ }+ setSelectedLocalPath(picked.path);+ setSelectedLocalLabel(picked.basename ?? null);+ } finally {+ setLocalPicking(false);+ }+ };++ const clearLocalDirectory = () => {+ setSelectedLocalPath(null);+ setSelectedLocalLabel(null);+ setLocalPickError(null);+ };+// Sync field changes to draft storeconst updateTitle = (v: string) => { setTitle(v); setDraft({ title: v }); };const updateStatus = (v: ProjectStatus) => { setStatus(v); setDraft({ status: v }); };@@ -170,6 +229,33 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {const handleSubmit = async () => {if (!title.trim() || submitting) return;+ // `sourceMode` decides which side's stash gets persisted — the other+ // side is silently dropped, so repos picked then abandoned for local+ // mode don't leak into the project.+ let resources:+ | Array<{ resource_type: "github_repo" | "local_directory"; resource_ref: Record<string, unknown> }>+ | undefined;+ if (sourceMode === "repos" && selectedRepos.length > 0) {+ resources = selectedRepos.map((url) => ({+ resource_type: "github_repo" as const,+ resource_ref: { url },+ }));+ } else if (+ sourceMode === "local" &&+ selectedLocalPath &&+ daemonStatus.daemonId+ ) {+ resources = [+ {+ resource_type: "local_directory" as const,+ resource_ref: {+ local_path: selectedLocalPath,+ daemon_id: daemonStatus.daemonId,+ ...(selectedLocalLabel ? { label: selectedLocalLabel } : {}),+ },+ },+ ];+ }setSubmitting(true);try {const project = await createProject.mutateAsync({@@ -181,13 +267,7 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {lead_type: leadType,lead_id: leadId,// Server attaches these in the same transaction as the project.- resources:- selectedRepos.length > 0- ? selectedRepos.map((url) => ({- resource_type: "github_repo" as const,- resource_ref: { url },- }))- : undefined,+ resources,});clearDraft();onClose();@@ -466,114 +546,241 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {<PopoverTriggerrender={<PillButton>- <GithubIcon className="size-3" />- <span>- {selectedRepos.length === 0- ? t(($) => $.create_project.repos_pill)- : t(($) => $.create_project.repos_pill_count, { count: selectedRepos.length })}- </span>+ {sourceMode === "local" ? (+ <>+ <FolderOpen className="size-3" />+ <span className="max-w-[12rem] truncate">+ {selectedLocalPath+ ? selectedLocalLabel ?? selectedLocalPath+ : t(($) => $.create_project.source_pill_local)}+ </span>+ </>+ ) : (+ <>+ <GithubIcon className="size-3" />+ <span>+ {selectedRepos.length === 0+ ? t(($) => $.create_project.repos_pill)+ : t(($) => $.create_project.repos_pill_count, { count: selectedRepos.length })}+ </span>+ </>+ )}</PillButton>}/><PopoverContent align="start" className="w-72 p-2 space-y-2">- <div className="text-xs font-medium text-muted-foreground">- {t(($) => $.create_project.repos_heading)}- </div>- {workspaceRepos.length > 0 ? (+ {/* Source mode is binary — repo OR local directory, never both.+ Local option is desktop-only because a local_directory+ resource has to be pinned to a daemon_id, which doesn't+ exist on the web. */}+ {desktop && (+ <div className="grid grid-cols-2 gap-1 rounded-md bg-muted/60 p-0.5">+ <button+ type="button"+ onClick={() => handleSourceModeChange("repos")}+ className={cn(+ "rounded px-2 py-1 text-xs transition-colors",+ sourceMode === "repos"+ ? "bg-background shadow-sm font-medium"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(($) => $.create_project.source_tab_repos)}+ </button>+ <button+ type="button"+ onClick={() => handleSourceModeChange("local")}+ className={cn(+ "rounded px-2 py-1 text-xs transition-colors",+ sourceMode === "local"+ ? "bg-background shadow-sm font-medium"+ : "text-muted-foreground hover:text-foreground",+ )}+ >+ {t(($) => $.create_project.source_tab_local)}+ </button>+ </div>+ )}++ {sourceMode === "repos" ? (<>- <div className="relative">- <Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <div className="text-xs font-medium text-muted-foreground">+ {t(($) => $.create_project.repos_heading)}+ </div>+ {workspaceRepos.length > 0 ? (+ <>+ <div className="relative">+ <Search className="pointer-events-none absolute left-2 top-1/2 size-3.5 -translate-y-1/2 text-muted-foreground" />+ <input+ type="text"+ value={repoSearch}+ onChange={(e) => setRepoSearch(e.target.value)}+ aria-label={t(($) => $.create_project.repos_search_placeholder)}+ placeholder={t(($) => $.create_project.repos_search_placeholder)}+ className="h-8 w-full rounded-md border bg-transparent pl-7 pr-2 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring"+ />+ </div>+ <div className="max-h-48 space-y-1 overflow-y-auto">+ {filteredWorkspaceRepos.length === 0 && repoQuery && (+ <p className="py-2 text-center text-xs text-muted-foreground">+ {t(($) => $.create_project.repos_search_empty)}+ </p>+ )}+ {filteredWorkspaceRepos.map((repo) => {+ const checked = selectedRepos.includes(repo.url);+ return (+ <button+ type="button"+ key={repo.url}+ onClick={() => toggleRepo(repo.url)}+ className={cn(+ "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-accent transition-colors",+ checked && "bg-accent",+ )}+ >+ <input+ type="checkbox"+ checked={checked}+ readOnly+ className="size-3.5"+ />+ <GithubIcon className="size-3.5" />+ <RepoUrlText url={repo.url} />+ </button>+ );+ })}+ </div>+ </>+ ) : (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.create_project.repos_empty)}+ </p>+ )}+ <form+ onSubmit={(e) => {+ e.preventDefault();+ addCustomRepo();+ }}+ className="flex items-center gap-1.5 pt-1 border-t"+ ><inputtype="text"- value={repoSearch}- onChange={(e) => setRepoSearch(e.target.value)}- aria-label={t(($) => $.create_project.repos_search_placeholder)}- placeholder={t(($) => $.create_project.repos_search_placeholder)}- className="h-8 w-full rounded-md border bg-transparent pl-7 pr-2 text-xs outline-none placeholder:text-muted-foreground focus-visible:ring-1 focus-visible:ring-ring"+ value={customRepoUrl}+ onChange={(e) => setCustomRepoUrl(e.target.value)}+ placeholder={t(($) => $.create_project.repos_url_placeholder)}+ className="flex-1 bg-transparent text-xs px-2 py-1 outline-none placeholder:text-muted-foreground"/>+ <Button+ type="submit"+ size="sm"+ variant="ghost"+ className="h-6 px-2 text-xs"+ disabled={!customRepoUrl.trim()}+ >+ {t(($) => $.create_project.repos_add)}+ </Button>+ </form>+ {selectedRepos.length > 0 && (+ <div className="space-y-1 pt-1 border-t">+ <div className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">+ {t(($) => $.create_project.repos_selected)}+ </div>+ {selectedRepos.map((url) => (+ <div+ key={url}+ className="flex items-center gap-2 text-xs"+ >+ <GithubIcon className="size-3 text-muted-foreground" />+ <RepoUrlText url={url} />+ <button+ type="button"+ onClick={() => toggleRepo(url)}+ className="text-muted-foreground hover:text-foreground"+ >+ <XIcon className="size-3" />+ </button>+ </div>+ ))}+ </div>+ )}+ </>+ ) : (+ <>+ <div className="text-xs font-medium text-muted-foreground">+ {t(($) => $.create_project.local_heading)}</div>- <div className="max-h-48 space-y-1 overflow-y-auto">- {filteredWorkspaceRepos.length === 0 && repoQuery && (- <p className="py-2 text-center text-xs text-muted-foreground">- {t(($) => $.create_project.repos_search_empty)}- </p>- )}- {filteredWorkspaceRepos.map((repo) => {- const checked = selectedRepos.includes(repo.url);- return (+ {/* Daemon must be online — daemon_id is required to bind+ the resource. If it's offline, surface why and disable+ the picker; once it boots we re-render automatically+ via useLocalDaemonStatus. */}+ {daemonStatus.daemonId && daemonStatus.running ? (+ <p className="text-[11px] text-muted-foreground">+ {t(($) => $.create_project.local_on_device, {+ device: daemonStatus.deviceName ?? t(($) => $.create_project.local_this_machine),+ })}+ </p>+ ) : (+ <p className="text-[11px] text-amber-600 dark:text-amber-400">+ {t(($) => $.create_project.local_daemon_offline)}+ </p>+ )}++ {selectedLocalPath ? (+ <div className="rounded-md border px-2 py-2 space-y-1">+ <div className="flex items-start gap-2 text-xs">+ <FolderOpen className="mt-0.5 size-3.5 shrink-0 text-muted-foreground" />+ <div className="min-w-0 flex-1">+ {selectedLocalLabel && (+ <div className="font-medium truncate">{selectedLocalLabel}</div>+ )}+ <div className="font-mono text-[10px] text-muted-foreground break-all">+ {selectedLocalPath}+ </div>+ </div><buttontype="button"- key={repo.url}- onClick={() => toggleRepo(repo.url)}- className={cn(- "flex w-full items-center gap-2 rounded-md px-2 py-1.5 text-xs hover:bg-accent transition-colors",- checked && "bg-accent",- )}+ onClick={clearLocalDirectory}+ className="text-muted-foreground hover:text-foreground"+ aria-label={t(($) => $.create_project.local_clear)}>- <input- type="checkbox"- checked={checked}- readOnly- className="size-3.5"- />- <GithubIcon className="size-3.5" />- <RepoUrlText url={repo.url} />+ <XIcon className="size-3" /></button>- );- })}- </div>- </>- ) : (- <p className="text-xs text-muted-foreground">- {t(($) => $.create_project.repos_empty)}- </p>- )}- <form- onSubmit={(e) => {- e.preventDefault();- addCustomRepo();- }}- className="flex items-center gap-1.5 pt-1 border-t"- >- <input- type="text"- value={customRepoUrl}- onChange={(e) => setCustomRepoUrl(e.target.value)}- placeholder={t(($) => $.create_project.repos_url_placeholder)}- className="flex-1 bg-transparent text-xs px-2 py-1 outline-none placeholder:text-muted-foreground"- />- <Button- type="submit"- size="sm"- variant="ghost"- className="h-6 px-2 text-xs"- disabled={!customRepoUrl.trim()}- >- {t(($) => $.create_project.repos_add)}- </Button>- </form>- {selectedRepos.length > 0 && (- <div className="space-y-1 pt-1 border-t">- <div className="text-[10px] font-medium text-muted-foreground uppercase tracking-wider">- {t(($) => $.create_project.repos_selected)}- </div>- {selectedRepos.map((url) => (- <div- key={url}- className="flex items-center gap-2 text-xs"- >- <GithubIcon className="size-3 text-muted-foreground" />- <RepoUrlText url={url} />- <button+ </div>+ <Buttontype="button"- onClick={() => toggleRepo(url)}- className="text-muted-foreground hover:text-foreground"+ size="sm"+ variant="ghost"+ className="h-6 w-full text-xs"+ onClick={handlePickLocalDirectory}+ disabled={localPicking || !daemonStatus.running}>- <XIcon className="size-3" />- </button>+ {t(($) => $.create_project.local_change)}+ </Button></div>- ))}- </div>+ ) : (+ <Button+ type="button"+ size="sm"+ variant="outline"+ className="w-full text-xs"+ onClick={handlePickLocalDirectory}+ disabled={localPicking || !daemonStatus.running}+ >+ <FolderOpen className="size-3" />+ {localPicking+ ? t(($) => $.create_project.local_picking)+ : t(($) => $.create_project.local_pick)}+ </Button>+ )}++ {localPickError && (+ <p className="text-[11px] text-destructive">{localPickError}</p>+ )}++ <p className="text-[10px] text-muted-foreground leading-snug">+ {t(($) => $.create_project.local_hint)}+ </p>+ </>)}</PopoverContent></Popover>diff --git a/packages/views/platform/index.ts b/packages/views/platform/index.tsindex 6ae77075b7..c902cfa7ec 100644--- a/packages/views/platform/index.ts+++ b/packages/views/platform/index.ts@@ -2,3 +2,14 @@ export { useImmersiveMode } from "./use-immersive-mode";export { useDesktopUnreadBadge } from "./use-desktop-unread-badge";export { DragStrip } from "./drag-strip";export { openExternal } from "./open-external";+export {+ isDesktopShell,+ pickDirectory,+ validateLocalDirectory,+ type PickDirectoryResult,+ type ValidateLocalDirectoryResult,+} from "./local-directory";+export {+ useLocalDaemonStatus,+ type LocalDaemonStatus,+} from "./use-local-daemon-status";diff --git a/packages/views/platform/local-directory.ts b/packages/views/platform/local-directory.tsnew file mode 100644index 0000000000..fb119901a8--- /dev/null+++ b/packages/views/platform/local-directory.ts@@ -0,0 +1,64 @@+// Desktop-only helpers for the project_resource local_directory flow.+//+// These wrap the preload `desktopAPI` surface so view components can+// SSR-render on web (where `window.desktopAPI` is undefined) and degrade+// gracefully to no-op promises instead of crashing.++export type PickDirectoryResult = {+ ok: boolean;+ path?: string;+ basename?: string;+ reason?: "cancelled" | "no_window" | "error" | "unsupported";+ error?: string;+};++export type ValidateLocalDirectoryResult = {+ ok: boolean;+ reason?:+ | "not_absolute"+ | "not_found"+ | "not_a_directory"+ | "not_readable"+ | "not_writable"+ | "error"+ | "unsupported";+ error?: string;+};++interface DesktopLocalDirectoryAPI {+ pickDirectory?: (defaultPath?: string) => Promise<PickDirectoryResult>;+ validateLocalDirectory?: (+ path: string,+ ) => Promise<ValidateLocalDirectoryResult>;+}++function readDesktopAPI(): DesktopLocalDirectoryAPI | undefined {+ if (typeof window === "undefined") return undefined;+ const api = (window as unknown as { desktopAPI?: DesktopLocalDirectoryAPI })+ .desktopAPI;+ return api;+}++/** True when the renderer is running inside the Electron desktop shell, as+ * evidenced by the preload-exposed pickDirectory bridge. Avoids hard-coding+ * navigator/process checks — those vary across electron-vite + jsdom tests. */+export function isDesktopShell(): boolean {+ const api = readDesktopAPI();+ return typeof api?.pickDirectory === "function";+}++export async function pickDirectory(+ defaultPath?: string,+): Promise<PickDirectoryResult> {+ const api = readDesktopAPI();+ if (!api?.pickDirectory) return { ok: false, reason: "unsupported" };+ return api.pickDirectory(defaultPath);+}++export async function validateLocalDirectory(+ path: string,+): Promise<ValidateLocalDirectoryResult> {+ const api = readDesktopAPI();+ if (!api?.validateLocalDirectory) return { ok: false, reason: "unsupported" };+ return api.validateLocalDirectory(path);+}diff --git a/packages/views/platform/use-local-daemon-status.ts b/packages/views/platform/use-local-daemon-status.tsnew file mode 100644index 0000000000..ba2392b5b9--- /dev/null+++ b/packages/views/platform/use-local-daemon-status.ts@@ -0,0 +1,77 @@+"use client";++import { useEffect, useState } from "react";++/** Subset of the daemonAPI status shape that the local_directory UI consumes.+ * Redeclared here so this hook doesn't depend on the desktop preload types. */+export interface LocalDaemonStatus {+ daemonId: string | null;+ deviceName: string | null;+ running: boolean;+}++interface DaemonStatusLike {+ state: "running" | "stopped" | "starting" | "stopping" | "installing_cli" | "cli_not_found";+ daemonId?: string;+ deviceName?: string;+}++interface DaemonAPILike {+ getStatus?: () => Promise<DaemonStatusLike>;+ onStatusChange?: (cb: (s: DaemonStatusLike) => void) => () => void;+}++function readDaemonAPI(): DaemonAPILike | undefined {+ if (typeof window === "undefined") return undefined;+ return (window as unknown as { daemonAPI?: DaemonAPILike }).daemonAPI;+}++function toStatus(s: DaemonStatusLike | undefined): LocalDaemonStatus {+ if (!s) return { daemonId: null, deviceName: null, running: false };+ return {+ daemonId: s.daemonId ?? null,+ deviceName: s.deviceName ?? null,+ running: s.state === "running",+ };+}++/**+ * Live snapshot of the desktop's local daemon: the daemon_id it registers+ * under, the OS device name, and whether the supervisor is currently running.+ *+ * On web (no `window.daemonAPI`) every field is null/false — components can+ * unconditionally call this hook and branch on `daemonId` to decide whether+ * a local_directory resource matches "this machine".+ *+ * The initial paint reads `getStatus()` once so the UI doesn't flash a+ * "no daemon" state while waiting for the first push from `onStatusChange`.+ */+export function useLocalDaemonStatus(): LocalDaemonStatus {+ const [status, setStatus] = useState<LocalDaemonStatus>(() => ({+ daemonId: null,+ deviceName: null,+ running: false,+ }));++ useEffect(() => {+ const api = readDaemonAPI();+ if (!api) return;+ let cancelled = false;+ if (api.getStatus) {+ api.getStatus().then((s) => {+ if (!cancelled) setStatus(toStatus(s));+ }).catch(() => {+ // Ignore — onStatusChange will populate once the daemon comes up.+ });+ }+ const unsubscribe = api.onStatusChange?.((s) => {+ setStatus(toStatus(s));+ });+ return () => {+ cancelled = true;+ unsubscribe?.();+ };+ }, []);++ return status;+}diff --git a/packages/views/projects/components/index.ts b/packages/views/projects/components/index.tsindex e7bd5f5ebf..9f4fab9485 100644--- a/packages/views/projects/components/index.ts+++ b/packages/views/projects/components/index.ts@@ -2,3 +2,4 @@ export { ProjectsPage } from "./projects-page";export { ProjectDetail } from "./project-detail";export { ProjectPicker } from "./project-picker";export { ProjectChip } from "./project-chip";+export { LocalDirectoryHint } from "./local-directory-hint";diff --git a/packages/views/projects/components/local-directory-hint.test.tsx b/packages/views/projects/components/local-directory-hint.test.tsxnew file mode 100644index 0000000000..679fecb907--- /dev/null+++ b/packages/views/projects/components/local-directory-hint.test.tsx@@ -0,0 +1,137 @@+import { describe, it, expect, vi, beforeEach } from "vitest";+import { render, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { I18nProvider } from "@multica/core/i18n/react";+import type { ProjectResource } from "@multica/core/types";+import enCommon from "../../locales/en/common.json";+import enProjects from "../../locales/en/projects.json";++const TEST_RESOURCES = { en: { common: enCommon, projects: enProjects } };++const mockDaemonStatus = vi.hoisted(() => ({+ daemonId: null as string | null,+ deviceName: null as string | null,+ running: false,+}));++vi.mock("../../platform", () => ({+ useLocalDaemonStatus: () => mockDaemonStatus,+}));++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++const mockListResources = vi.hoisted(() => vi.fn());++vi.mock("@multica/core/api", () => ({+ api: {+ listProjectResources: (...args: unknown[]) => mockListResources(...args),+ },+}));++import { LocalDirectoryHint } from "./local-directory-hint";++function renderHint(projectId: string | null | undefined) {+ const qc = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={qc}>+ <I18nProvider locale="en" resources={TEST_RESOURCES}>+ <LocalDirectoryHint projectId={projectId} />+ </I18nProvider>+ </QueryClientProvider>,+ );+}++function makeLocalDirectoryResource(overrides: {+ daemon_id: string;+ local_path: string;+ label?: string;+}): ProjectResource {+ return {+ id: `res-${overrides.local_path}`,+ project_id: "proj-1",+ workspace_id: "ws-1",+ resource_type: "local_directory",+ resource_ref: {+ daemon_id: overrides.daemon_id,+ local_path: overrides.local_path,+ ...(overrides.label ? { label: overrides.label } : {}),+ },+ label: null,+ position: 0,+ created_at: new Date(0).toISOString(),+ created_by: null,+ };+}++describe("LocalDirectoryHint", () => {+ beforeEach(() => {+ mockDaemonStatus.daemonId = null;+ mockDaemonStatus.deviceName = null;+ mockDaemonStatus.running = false;+ mockListResources.mockReset();+ });++ it("renders nothing when project_id is null", () => {+ const { container } = renderHint(null);+ expect(container.firstChild).toBeNull();+ });++ it("renders nothing when there's no local daemon", () => {+ mockListResources.mockResolvedValue({+ resources: [+ makeLocalDirectoryResource({+ daemon_id: "daemon-A",+ local_path: "/Users/foo/work",+ label: "work",+ }),+ ],+ total: 1,+ });+ const { container } = renderHint("proj-1");+ expect(container.firstChild).toBeNull();+ });++ it("renders the hint when a local_directory resource matches this daemon", async () => {+ mockDaemonStatus.daemonId = "daemon-A";+ mockDaemonStatus.running = true;+ mockListResources.mockResolvedValue({+ resources: [+ makeLocalDirectoryResource({+ daemon_id: "daemon-A",+ local_path: "/Users/foo/work",+ label: "work",+ }),+ ],+ total: 1,+ });+ renderHint("proj-1");+ await waitFor(() => {+ expect(screen.getByText("work")).toBeInTheDocument();+ });+ expect(screen.getByText(/Users\/foo\/work/)).toBeInTheDocument();+ });++ it("ignores resources pinned to a different daemon", async () => {+ mockDaemonStatus.daemonId = "daemon-A";+ mockDaemonStatus.running = true;+ mockListResources.mockResolvedValue({+ resources: [+ makeLocalDirectoryResource({+ daemon_id: "daemon-B",+ local_path: "/Users/foo/other-machine",+ label: "elsewhere",+ }),+ ],+ total: 1,+ });+ const { container } = renderHint("proj-1");+ // Allow the query to settle; the hint should still render nothing.+ await Promise.resolve();+ await Promise.resolve();+ expect(container.querySelector("div[class*='rounded-md']")).toBeNull();+ });+});diff --git a/packages/views/projects/components/local-directory-hint.tsx b/packages/views/projects/components/local-directory-hint.tsxnew file mode 100644index 0000000000..e4daa7a610--- /dev/null+++ b/packages/views/projects/components/local-directory-hint.tsx@@ -0,0 +1,72 @@+"use client";++import { useQuery } from "@tanstack/react-query";+import { FolderOpen } from "lucide-react";+import { projectResourcesOptions } from "@multica/core/projects";+import type { LocalDirectoryResourceRef, ProjectResource } from "@multica/core/types";+import { useWorkspaceId } from "@multica/core/hooks";+import { useLocalDaemonStatus } from "../../platform";+import { useT } from "../../i18n";++/**+ * Banner shown above the chat / comment composer when the issue's project+ * is pinned to a `local_directory` resource on **this** daemon. Tells the+ * user "starting an agent here will use {label} ({path}) in-place" so they+ * notice they are not getting an isolated git worktree.+ *+ * Rendered only on desktop: web has no daemon to compare against, so the+ * "this machine" check would always fail. Web users will see local_directory+ * resources read-only in the sidebar but no chat-input hint.+ *+ * SSR-safe: the underlying hook reads `window.daemonAPI` defensively, so+ * server renders return null.+ */+export function LocalDirectoryHint({+ projectId,+}: {+ projectId: string | null | undefined;+}) {+ const { t } = useT("projects");+ const wsId = useWorkspaceId();+ const daemon = useLocalDaemonStatus();+ const { data: resources = [] } = useQuery({+ ...projectResourcesOptions(wsId, projectId ?? ""),+ enabled: Boolean(projectId),+ });++ if (!projectId) return null;+ if (!daemon.daemonId) return null;++ const matches: Array<ProjectResource & { resource_ref: LocalDirectoryResourceRef }> =+ resources+ .filter(+ (r): r is ProjectResource & { resource_ref: LocalDirectoryResourceRef } =>+ r.resource_type === "local_directory",+ )+ .filter((r) => r.resource_ref.daemon_id === daemon.daemonId);++ if (matches.length === 0) return null;++ return (+ <div className="mb-2 space-y-1 rounded-md border border-dashed bg-muted/40 px-3 py-2 text-xs text-muted-foreground">+ {matches.map((resource) => {+ const ref = resource.resource_ref;+ const label = (ref.label || resource.label || ref.local_path).trim() ||+ ref.local_path;+ return (+ <div+ key={resource.id}+ className="flex items-center gap-2"+ >+ <FolderOpen className="size-3 shrink-0" />+ <span className="truncate">+ {t(($) => $.resources.chat_hint_prefix)}+ <span className="font-medium text-foreground"> {label} </span>+ <span className="font-mono opacity-70">({ref.local_path})</span>+ </span>+ </div>+ );+ })}+ </div>+ );+}diff --git a/packages/views/projects/components/project-resources-section.tsx b/packages/views/projects/components/project-resources-section.tsxindex 6b8e986c4c..e9dfe1d8de 100644--- a/packages/views/projects/components/project-resources-section.tsx+++ b/packages/views/projects/components/project-resources-section.tsx@@ -2,17 +2,27 @@import { useState } from "react";import { useQuery } from "@tanstack/react-query";-import { ChevronRight, FolderGit, Plus, Search, Trash2 } from "lucide-react";+import {+ ChevronRight,+ FolderGit,+ FolderOpen,+ Pencil,+ Plus,+ Search,+ Trash2,+} from "lucide-react";import { toast } from "sonner";import {projectResourcesOptions,useCreateProjectResource,useDeleteProjectResource,+ useUpdateProjectResource,} from "@multica/core/projects";import { useWorkspaceId } from "@multica/core/hooks";import { useCurrentWorkspace } from "@multica/core/paths";import type {GithubRepoResourceRef,+ LocalDirectoryResourceRef,ProjectResource,} from "@multica/core/types";import { Button } from "@multica/ui/components/ui/button";@@ -26,32 +36,75 @@ import {TooltipTrigger,TooltipContent,} from "@multica/ui/components/ui/tooltip";+import {+ isDesktopShell,+ pickDirectory,+ useLocalDaemonStatus,+ validateLocalDirectory,+ type ValidateLocalDirectoryResult,+} from "../../platform";import { useT } from "../../i18n";// Project Resources sidebar section.//-// Today only renders github_repo, but the rendering layer is type-dispatched-// so adding a new type means: (1) extend the API validator, (2) add a render-// case here. No changes to the schema or query layer.+// Type-dispatched at the row + add-flow level. Add a new resource_type by:+// (1) extending the server validator+// (2) extending ProjectResourceType in @multica/core/types+// (3) adding a render case in ResourceRow and an add-control here+function isGithubRef(r: ProjectResource): r is ProjectResource & {+ resource_ref: GithubRepoResourceRef;+} {+ return r.resource_type === "github_repo";+}++function isLocalDirectoryRef(r: ProjectResource): r is ProjectResource & {+ resource_ref: LocalDirectoryResourceRef;+} {+ return r.resource_type === "local_directory";+}+export function ProjectResourcesSection({ projectId }: { projectId: string }) {const { t } = useT("projects");const wsId = useWorkspaceId();const workspace = useCurrentWorkspace();+ const daemonStatus = useLocalDaemonStatus();const [open, setOpen] = useState(true);const [addOpen, setAddOpen] = useState(false);const [repoSearch, setRepoSearch] = useState("");+ const [picking, setPicking] = useState(false);const { data: resources = [] } = useQuery(projectResourcesOptions(wsId, projectId),);const createResource = useCreateProjectResource(wsId, projectId);+ const updateResource = useUpdateProjectResource(wsId, projectId);const deleteResource = useDeleteProjectResource(wsId, projectId);+ // Desktop-only entry points. We hide (not just disable) on web so users+ // there don't see an action they can never complete — the spec calls for+ // read-only on web because the daemon-id check can't be performed in the+ // browser.+ const desktopMode = isDesktopShell();+ const localDaemonId = daemonStatus.daemonId;+const attachedUrls = new Set(+ resources.filter(isGithubRef).map((r) => r.resource_ref.url),+ );+ const attachedLocalPaths = new Set(resources- .filter((r) => r.resource_type === "github_repo")- .map((r) => (r.resource_ref as GithubRepoResourceRef).url),+ .filter(isLocalDirectoryRef)+ .filter((r) => r.resource_ref.daemon_id === localDaemonId)+ .map((r) => r.resource_ref.local_path),);+ // Per (project, daemon) we allow at most one local_directory — the+ // daemon-side resolver picks the first match by daemon_id, so two rows+ // on the same daemon would silently route the agent into one of them.+ // The server enforces this at the API boundary; the UI mirrors the+ // restriction by hiding the "Add" affordance once a row exists for the+ // current daemon, otherwise users would only discover the limit on a+ // 409 toast.+ const hasLocalDirectoryForCurrentDaemon =+ localDaemonId !== null && attachedLocalPaths.size > 0;const repoQuery = repoSearch.trim().toLowerCase();const filteredRepos =@@ -70,6 +123,72 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {}};+ const handleAttachLocalDirectory = async () => {+ if (picking) return;+ setPicking(true);+ try {+ if (!localDaemonId || !daemonStatus.running) {+ toast.error(t(($) => $.resources.toast_local_daemon_not_running));+ return;+ }+ // Race guard: the button gates on this already, but if the picker+ // is opened while a concurrent resource-create lands the user+ // would otherwise see a 409. Surface a clearer message instead.+ if (attachedLocalPaths.size > 0) {+ toast.error(t(($) => $.resources.toast_local_daemon_already_attached));+ return;+ }+ const picked = await pickDirectory();+ if (!picked.ok) {+ if (picked.reason && picked.reason !== "cancelled") {+ toast.error(+ picked.error ?? t(($) => $.resources.toast_local_pick_failed),+ );+ }+ return;+ }+ const path = picked.path ?? "";+ const fallbackLabel = picked.basename ?? path;+ if (attachedLocalPaths.has(path)) {+ toast.error(t(($) => $.resources.toast_local_already_attached));+ return;+ }+ const validation = await validateLocalDirectory(path);+ if (!validation.ok) {+ toast.error(+ localValidationMessage(validation, {+ not_absolute: t(($) => $.resources.local_validate_not_absolute),+ not_found: t(($) => $.resources.local_validate_not_found),+ not_a_directory: t(($) => $.resources.local_validate_not_a_directory),+ not_readable: t(($) => $.resources.local_validate_not_readable),+ not_writable: t(($) => $.resources.local_validate_not_writable),+ unsupported: t(($) => $.resources.local_validate_unsupported),+ fallback: t(($) => $.resources.toast_local_pick_failed),+ }),+ );+ return;+ }+ await createResource.mutateAsync({+ resource_type: "local_directory",+ resource_ref: {+ local_path: path,+ daemon_id: localDaemonId,+ label: fallbackLabel,+ },+ });+ toast.success(t(($) => $.resources.toast_local_attached));+ setAddOpen(false);+ } catch (err) {+ const msg =+ err instanceof Error+ ? err.message+ : t(($) => $.resources.toast_local_pick_failed);+ toast.error(msg);+ } finally {+ setPicking(false);+ }+ };+const handleRemove = async (resource: ProjectResource) => {try {await deleteResource.mutateAsync(resource.id);@@ -83,6 +202,33 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {}};+ const handleRenameLocalDirectory = async (+ resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },+ nextLabel: string,+ ) => {+ const trimmed = nextLabel.trim();+ const previous = resource.resource_ref.label ?? resource.label ?? "";+ if (trimmed === previous.trim()) return;+ try {+ await updateResource.mutateAsync({+ resourceId: resource.id,+ data: {+ resource_ref: {+ ...resource.resource_ref,+ label: trimmed,+ },+ },+ });+ toast.success(t(($) => $.resources.toast_local_renamed));+ } catch (err) {+ const msg =+ err instanceof Error+ ? err.message+ : t(($) => $.resources.toast_local_rename_failed);+ toast.error(msg);+ }+ };+return (<div><button@@ -107,7 +253,10 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {<ResourceRowkey={resource.id}resource={resource}+ localDaemonId={localDaemonId}+ canEdit={desktopMode}onRemove={() => handleRemove(resource)}+ onRenameLocalDirectory={handleRenameLocalDirectory}/>))}</div>@@ -200,22 +349,64 @@ export function ProjectResourcesSection({ projectId }: { projectId: string }) {/></PopoverContent></Popover>+ {desktopMode && (+ <div className="flex flex-col">+ <Button+ variant="ghost"+ size="sm"+ className="h-7 justify-start px-2 text-xs text-muted-foreground hover:text-foreground"+ disabled={+ picking ||+ createResource.isPending ||+ !daemonStatus.running ||+ hasLocalDirectoryForCurrentDaemon+ }+ onClick={() => {+ void handleAttachLocalDirectory();+ }}+ >+ <FolderOpen className="size-3" />+ {t(($) => $.resources.add_local_directory_button)}+ </Button>+ {!daemonStatus.running && (+ <p className="px-2 pt-0.5 text-[10px] text-muted-foreground">+ {t(($) => $.resources.local_daemon_offline_hint)}+ </p>+ )}+ {daemonStatus.running && hasLocalDirectoryForCurrentDaemon && (+ <p className="px-2 pt-0.5 text-[10px] text-muted-foreground">+ {t(($) => $.resources.local_daemon_already_attached_hint)}+ </p>+ )}+ </div>+ )}</div>)}</div>);}+interface ResourceRowProps {+ resource: ProjectResource;+ localDaemonId: string | null;+ canEdit: boolean;+ onRemove: () => void;+ onRenameLocalDirectory: (+ resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },+ nextLabel: string,+ ) => Promise<void>;+}+function ResourceRow({resource,+ localDaemonId,+ canEdit,onRemove,-}: {- resource: ProjectResource;- onRemove: () => void;-}) {+ onRenameLocalDirectory,+}: ResourceRowProps) {const { t } = useT("projects");- if (resource.resource_type === "github_repo") {- const ref = resource.resource_ref as GithubRepoResourceRef;+ if (isGithubRef(resource)) {+ const ref = resource.resource_ref;return (<div className="flex items-center gap-2 text-xs group"><FolderGit className="size-3.5 text-muted-foreground shrink-0" />@@ -245,6 +436,19 @@ function ResourceRow({</div>);}++ if (isLocalDirectoryRef(resource)) {+ return (+ <LocalDirectoryRow+ resource={resource}+ localDaemonId={localDaemonId}+ canEdit={canEdit}+ onRemove={onRemove}+ onRename={onRenameLocalDirectory}+ />+ );+ }+return (<div className="flex items-center gap-2 text-xs text-muted-foreground"><span className="truncate flex-1">@@ -262,6 +466,121 @@ function ResourceRow({);}+interface LocalDirectoryRowProps {+ resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef };+ localDaemonId: string | null;+ canEdit: boolean;+ onRemove: () => void;+ onRename: (+ resource: ProjectResource & { resource_ref: LocalDirectoryResourceRef },+ nextLabel: string,+ ) => Promise<void>;+}++function LocalDirectoryRow({+ resource,+ localDaemonId,+ canEdit,+ onRemove,+ onRename,+}: LocalDirectoryRowProps) {+ const { t } = useT("projects");+ const ref = resource.resource_ref;+ const display = (ref.label || resource.label || ref.local_path).trim() ||+ ref.local_path;+ const isForeignDaemon =+ localDaemonId !== null && ref.daemon_id !== localDaemonId;+ const isLocalUnknown = localDaemonId === null;+ // "disabled" in the spec sense — visual de-emphasis + no chat hint, and+ // rename is hidden on foreign / unknown-daemon rows because the label+ // belongs to the owning device. Delete stays available so the user can+ // drop a stale registration from any device.+ const mismatch = isForeignDaemon || isLocalUnknown;++ const [editing, setEditing] = useState(false);+ const [draft, setDraft] = useState(display);++ const startEdit = () => {+ setDraft(display);+ setEditing(true);+ };+ const commit = async () => {+ setEditing(false);+ await onRename(resource, draft);+ };+ const cancel = () => {+ setEditing(false);+ setDraft(display);+ };++ return (+ <div+ className={`flex items-center gap-2 text-xs group ${+ mismatch ? "opacity-60" : ""+ }`}+ >+ <FolderOpen className="size-3.5 text-muted-foreground shrink-0" />+ {editing ? (+ <input+ autoFocus+ value={draft}+ onChange={(e) => setDraft(e.target.value)}+ onBlur={() => void commit()}+ onKeyDown={(e) => {+ if (e.key === "Enter") {+ e.preventDefault();+ void commit();+ } else if (e.key === "Escape") {+ e.preventDefault();+ cancel();+ }+ }}+ className="flex-1 min-w-0 rounded-sm border bg-transparent px-1 py-0.5 text-xs outline-none focus-visible:ring-1 focus-visible:ring-ring"+ aria-label={t(($) => $.resources.local_rename_label)}+ />+ ) : (+ <Tooltip>+ <TooltipTrigger+ render={+ <span className="truncate flex-1">{display}</span>+ }+ />+ <TooltipContent side="top">+ <div className="space-y-0.5 text-[11px]">+ <div className="font-mono">{ref.local_path}</div>+ {mismatch && (+ <div className="text-muted-foreground">+ {isLocalUnknown+ ? t(($) => $.resources.local_no_daemon_tooltip)+ : t(($) => $.resources.local_other_machine_tooltip)}+ </div>+ )}+ </div>+ </TooltipContent>+ </Tooltip>+ )}+ {canEdit && !mismatch && !editing && (+ <button+ type="button"+ onClick={startEdit}+ className="opacity-0 group-hover:opacity-100 transition-opacity rounded-sm p-0.5 hover:bg-accent"+ title={t(($) => $.resources.local_rename_tooltip)}+ >+ <Pencil className="size-3 text-muted-foreground" />+ </button>+ )}+ <button+ type="button"+ onClick={onRemove}+ className="opacity-0 group-hover:opacity-100 transition-opacity rounded-sm p-0.5 hover:bg-accent"+ title={t(($) => $.resources.remove_tooltip)}+ >+ <Trash2 className="size-3 text-muted-foreground" />+ </button>+ </div>+ );+}+function CustomRepoForm({onSubmit,}: {@@ -303,3 +622,34 @@ function CustomRepoForm({</form>);}++function localValidationMessage(+ result: ValidateLocalDirectoryResult,+ strings: {+ not_absolute: string;+ not_found: string;+ not_a_directory: string;+ not_readable: string;+ not_writable: string;+ unsupported: string;+ fallback: string;+ },+): string {+ switch (result.reason) {+ case "not_absolute":+ return strings.not_absolute;+ case "not_found":+ return strings.not_found;+ case "not_a_directory":+ return strings.not_a_directory;+ case "not_readable":+ return strings.not_readable;+ case "not_writable":+ return strings.not_writable;+ case "unsupported":+ return strings.unsupported;+ case "error":+ default:+ return result.error ?? strings.fallback;+ }+}diff --git a/server/cmd/multica/cmd_project.go b/server/cmd/multica/cmd_project.goindex 40070d9450..94b113ec5b 100644--- a/server/cmd/multica/cmd_project.go+++ b/server/cmd/multica/cmd_project.go@@ -78,6 +78,13 @@ var projectResourceAddCmd = &cobra.Command{RunE: runProjectResourceAdd,}+var projectResourceUpdateCmd = &cobra.Command{+ Use: "update <project-id> <resource-id>",+ Short: "Edit an attached resource (ref payload, label, or position)",+ Args: exactArgs(2),+ RunE: runProjectResourceUpdate,+}+var projectResourceRemoveCmd = &cobra.Command{Use: "remove <project-id> <resource-id>",Short: "Detach a resource from a project",@@ -100,6 +107,7 @@ func init() {projectResourceCmd.AddCommand(projectResourceListCmd)projectResourceCmd.AddCommand(projectResourceAddCmd)+ projectResourceCmd.AddCommand(projectResourceUpdateCmd)projectResourceCmd.AddCommand(projectResourceRemoveCmd)// project list@@ -126,13 +134,29 @@ func init() {// project resource add — generic shape: any --type with a JSON --ref payload// works without further CLI changes. github_repo is supported via the// dedicated --url / --default-branch-hint shortcuts as a convenience.- projectResourceAddCmd.Flags().String("type", "github_repo", "Resource type (e.g. github_repo, notion_page — see docs)")+ projectResourceAddCmd.Flags().String("type", "github_repo", "Resource type (e.g. github_repo, local_directory — see docs)")projectResourceAddCmd.Flags().String("url", "", "Shortcut: the repo URL (only used when --type github_repo)")projectResourceAddCmd.Flags().String("default-branch-hint", "", "Shortcut: optional default branch hint (only used when --type github_repo)")+ projectResourceAddCmd.Flags().String("local-path", "", "Shortcut: absolute path to the working directory (only used when --type local_directory)")+ projectResourceAddCmd.Flags().String("daemon-id", "", "Shortcut: id of the daemon that owns the local path (only used when --type local_directory)")+ projectResourceAddCmd.Flags().String("ref-label", "", "Shortcut: optional label embedded in resource_ref (only used when --type local_directory)")projectResourceAddCmd.Flags().String("ref", "", "Generic JSON resource_ref payload — overrides the per-type shortcuts when set")projectResourceAddCmd.Flags().String("label", "", "Optional human-readable label")projectResourceAddCmd.Flags().String("output", "json", "Output format: table or json")+ // project resource update — mirrors `add` flags, but every field is+ // optional so the caller can edit one thing at a time.+ projectResourceUpdateCmd.Flags().String("url", "", "Shortcut: new repo URL (github_repo)")+ projectResourceUpdateCmd.Flags().String("default-branch-hint", "", "Shortcut: new default branch hint (github_repo)")+ projectResourceUpdateCmd.Flags().String("local-path", "", "Shortcut: new absolute local path (local_directory)")+ projectResourceUpdateCmd.Flags().String("daemon-id", "", "Shortcut: new daemon id (local_directory)")+ projectResourceUpdateCmd.Flags().String("ref-label", "", "Shortcut: new label embedded in resource_ref (local_directory)")+ projectResourceUpdateCmd.Flags().String("ref", "", "Generic JSON resource_ref payload — overrides per-type shortcuts when set")+ projectResourceUpdateCmd.Flags().String("label", "", "New human-readable label; pass an empty string to clear")+ projectResourceUpdateCmd.Flags().Bool("clear-label", false, "Clear the human-readable label")+ projectResourceUpdateCmd.Flags().Int32("position", 0, "New display position")+ projectResourceUpdateCmd.Flags().String("output", "json", "Output format: table or json")+// project resource removeprojectResourceRemoveCmd.Flags().String("output", "table", "Output format: table or json")@@ -544,6 +568,19 @@ func runProjectResourceAdd(cmd *cobra.Command, args []string) error {ref["default_branch_hint"] = strings.TrimSpace(hint)}body["resource_ref"] = ref+ case "local_directory":+ pathVal, _ := cmd.Flags().GetString("local-path")+ pathVal = strings.TrimSpace(pathVal)+ daemonVal, _ := cmd.Flags().GetString("daemon-id")+ daemonVal = strings.TrimSpace(daemonVal)+ if pathVal == "" || daemonVal == "" {+ return fmt.Errorf("local_directory requires --local-path and --daemon-id (or pass a JSON payload via --ref)")+ }+ ref := map[string]any{"local_path": pathVal, "daemon_id": daemonVal}+ if refLabel, _ := cmd.Flags().GetString("ref-label"); strings.TrimSpace(refLabel) != "" {+ ref["label"] = strings.TrimSpace(refLabel)+ }+ body["resource_ref"] = refdefault:return fmt.Errorf("type %q has no built-in CLI shortcut; pass the payload via --ref '<json>'", resourceType)}@@ -585,6 +622,217 @@ func runProjectResourceAdd(cmd *cobra.Command, args []string) error {return cli.PrintJSON(os.Stdout, result)}+func runProjectResourceUpdate(cmd *cobra.Command, args []string) error {+ client, err := newAPIClient(cmd)+ if err != nil {+ return err+ }++ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)+ defer cancel()++ projectRef, err := resolveProjectID(ctx, client, args[0])+ if err != nil {+ return fmt.Errorf("resolve project: %w", err)+ }+ resourceRef, err := resolveProjectResourceID(ctx, client, projectRef.ID, args[1])+ if err != nil {+ return fmt.Errorf("resolve project resource: %w", err)+ }++ // Fetch the existing row so per-type shortcuts know which schema to+ // emit and which fields to preserve. The server treats resource_ref as+ // opaque-replace, so a partial edit like `--default-branch-hint` has to+ // rebuild the full payload here — otherwise the unmentioned `url` would+ // vanish and the server would 400.+ var existing map[string]any+ if err := client.GetJSON(ctx, "/api/projects/"+projectRef.ID+"/resources", &existing); err != nil {+ return fmt.Errorf("list project resources: %w", err)+ }+ var resourceType string+ var existingRef map[string]any+ if list, ok := existing["resources"].([]any); ok {+ for _, raw := range list {+ row, ok := raw.(map[string]any)+ if !ok {+ continue+ }+ if strVal(row, "id") == resourceRef.ID {+ resourceType = strVal(row, "resource_type")+ if ref, ok := row["resource_ref"].(map[string]any); ok {+ existingRef = ref+ }+ break+ }+ }+ }++ body := map[string]any{}++ if rawRef, _ := cmd.Flags().GetString("ref"); strings.TrimSpace(rawRef) != "" {+ var ref any+ if err := json.Unmarshal([]byte(rawRef), &ref); err != nil {+ return fmt.Errorf("--ref is not valid JSON: %w", err)+ }+ body["resource_ref"] = ref+ } else {+ ref, has, err := buildResourceRefFromFlags(cmd, resourceType, existingRef)+ if err != nil {+ return err+ }+ if has {+ body["resource_ref"] = ref+ }+ }++ clearLabel, _ := cmd.Flags().GetBool("clear-label")+ if clearLabel {+ body["label"] = nil+ } else if cmd.Flags().Changed("label") {+ label, _ := cmd.Flags().GetString("label")+ body["label"] = label+ }++ if cmd.Flags().Changed("position") {+ pos, _ := cmd.Flags().GetInt32("position")+ body["position"] = pos+ }++ if len(body) == 0 {+ return fmt.Errorf("nothing to update — pass --ref / --url / --local-path / --label / --position / --clear-label")+ }++ var result map[string]any+ if err := client.PutJSON(ctx, "/api/projects/"+projectRef.ID+"/resources/"+resourceRef.ID, body, &result); err != nil {+ return fmt.Errorf("update project resource: %w", err)+ }++ output, _ := cmd.Flags().GetString("output")+ if output == "table" {+ headers := []string{"ID", "TYPE", "REF", "LABEL"}+ rows := [][]string{{+ strVal(result, "id"),+ strVal(result, "resource_type"),+ summarizeResourceRef(result["resource_ref"]),+ strVal(result, "label"),+ }}+ cli.PrintTable(os.Stdout, headers, rows)+ return nil+ }+ return cli.PrintJSON(os.Stdout, result)+}++// buildResourceRefFromFlags collects the per-type shortcut flags into a+// resource_ref payload, seeding from existingRef so partial edits (only+// --default-branch-hint, only --ref-label) preserve the unmentioned fields.+// Returns (ref, true) only when the caller actually set at least one shortcut+// flag — that lets the update command tell "no change requested" apart from+// "change ref to empty object". existingRef may be nil for the `add` path,+// where there is nothing to merge with; in that case partial inputs that miss+// required fields are still rejected.+func buildResourceRefFromFlags(cmd *cobra.Command, resourceType string, existingRef map[string]any) (map[string]any, bool, error) {+ switch resourceType {+ case "github_repo":+ urlSet := cmd.Flags().Changed("url")+ hintSet := cmd.Flags().Changed("default-branch-hint")+ if !urlSet && !hintSet {+ return nil, false, nil+ }+ ref := map[string]any{}+ // Seed from the existing row so a `--default-branch-hint` edit doesn't+ // clobber the `url` (server overwrites resource_ref wholesale).+ if existingRef != nil {+ if u, ok := existingRef["url"].(string); ok && strings.TrimSpace(u) != "" {+ ref["url"] = strings.TrimSpace(u)+ }+ if h, ok := existingRef["default_branch_hint"].(string); ok && strings.TrimSpace(h) != "" {+ ref["default_branch_hint"] = strings.TrimSpace(h)+ }+ }+ if urlSet {+ urlVal, _ := cmd.Flags().GetString("url")+ urlVal = strings.TrimSpace(urlVal)+ if urlVal == "" {+ return nil, false, fmt.Errorf("--url cannot be empty")+ }+ ref["url"] = urlVal+ }+ if hintSet {+ hint := strings.TrimSpace(mustString(cmd, "default-branch-hint"))+ if hint == "" {+ delete(ref, "default_branch_hint")+ } else {+ ref["default_branch_hint"] = hint+ }+ }+ if _, ok := ref["url"]; !ok {+ return nil, false, fmt.Errorf("github_repo: --url is required (no existing url to merge with)")+ }+ return ref, true, nil+ case "local_directory":+ pathSet := cmd.Flags().Changed("local-path")+ daemonSet := cmd.Flags().Changed("daemon-id")+ labelSet := cmd.Flags().Changed("ref-label")+ if !pathSet && !daemonSet && !labelSet {+ return nil, false, nil+ }+ ref := map[string]any{}+ if existingRef != nil {+ if p, ok := existingRef["local_path"].(string); ok && strings.TrimSpace(p) != "" {+ ref["local_path"] = strings.TrimSpace(p)+ }+ if d, ok := existingRef["daemon_id"].(string); ok && strings.TrimSpace(d) != "" {+ ref["daemon_id"] = strings.TrimSpace(d)+ }+ if l, ok := existingRef["label"].(string); ok && strings.TrimSpace(l) != "" {+ ref["label"] = strings.TrimSpace(l)+ }+ }+ if pathSet {+ pathVal := strings.TrimSpace(mustString(cmd, "local-path"))+ if pathVal == "" {+ return nil, false, fmt.Errorf("--local-path cannot be empty")+ }+ ref["local_path"] = pathVal+ }+ if daemonSet {+ daemonVal := strings.TrimSpace(mustString(cmd, "daemon-id"))+ if daemonVal == "" {+ return nil, false, fmt.Errorf("--daemon-id cannot be empty")+ }+ ref["daemon_id"] = daemonVal+ }+ if labelSet {+ refLabel := strings.TrimSpace(mustString(cmd, "ref-label"))+ if refLabel == "" {+ delete(ref, "label")+ } else {+ ref["label"] = refLabel+ }+ }+ if v, ok := ref["local_path"].(string); !ok || v == "" {+ return nil, false, fmt.Errorf("local_directory: --local-path is required (no existing local_path to merge with)")+ }+ if v, ok := ref["daemon_id"].(string); !ok || v == "" {+ return nil, false, fmt.Errorf("local_directory: --daemon-id is required (no existing daemon_id to merge with)")+ }+ return ref, true, nil+ default:+ // Unknown type or empty (resource not found) — caller must use --ref.+ if cmd.Flags().Changed("url") || cmd.Flags().Changed("default-branch-hint") ||+ cmd.Flags().Changed("local-path") || cmd.Flags().Changed("daemon-id") ||+ cmd.Flags().Changed("ref-label") {+ return nil, false, fmt.Errorf("no built-in shortcut for resource type %q; pass the full payload via --ref '<json>'", resourceType)+ }+ return nil, false, nil+ }+}++func mustString(cmd *cobra.Command, name string) string {+ v, _ := cmd.Flags().GetString(name)+ return v+}+func runProjectResourceRemove(cmd *cobra.Command, args []string) error {client, err := newAPIClient(cmd)if err != nil {@@ -612,7 +860,8 @@ func runProjectResourceRemove(cmd *cobra.Command, args []string) error {}// summarizeResourceRef extracts the most useful single string from a-// resource_ref object — for github_repo this is the URL.+// resource_ref object — for github_repo this is the URL; for+// local_directory it is the local path.func summarizeResourceRef(raw any) string {m, ok := raw.(map[string]any)if !ok {@@ -621,6 +870,9 @@ func summarizeResourceRef(raw any) string {if u, ok := m["url"].(string); ok && u != "" {return u}+ if p, ok := m["local_path"].(string); ok && p != "" {+ return p+ }if data, err := json.Marshal(m); err == nil {return string(data)}diff --git a/server/cmd/multica/cmd_project_test.go b/server/cmd/multica/cmd_project_test.gonew file mode 100644index 0000000000..bd4fa4c1e1--- /dev/null+++ b/server/cmd/multica/cmd_project_test.go@@ -0,0 +1,175 @@+package main++import (+ "testing"++ "github.com/spf13/cobra"+)++// newProjectResourceUpdateTestCmd mirrors the flag surface of+// projectResourceUpdateCmd so unit tests can exercise the shortcut-flag plumbing+// without spinning up a server.+func newProjectResourceUpdateTestCmd() *cobra.Command {+ c := &cobra.Command{Use: "update"}+ c.Flags().String("url", "", "")+ c.Flags().String("default-branch-hint", "", "")+ c.Flags().String("local-path", "", "")+ c.Flags().String("daemon-id", "", "")+ c.Flags().String("ref-label", "", "")+ c.Flags().String("ref", "", "")+ c.Flags().String("label", "", "")+ c.Flags().Bool("clear-label", false, "")+ c.Flags().Int32("position", 0, "")+ c.Flags().String("output", "json", "")+ return c+}++// TestBuildResourceRefFromFlagsGithubMergesHint pins the nit fix from MUL-2662+// review round 2: `multica project resource update <p> <r> --default-branch-hint x`+// must rebuild the full github_repo payload by merging the existing `url` —+// otherwise the server sees `{default_branch_hint: "x"}` and 400s.+func TestBuildResourceRefFromFlagsGithubMergesHint(t *testing.T) {+ t.Run("hint-only edit preserves existing url", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("default-branch-hint", "main")+ existing := map[string]any{"url": "https://github.com/multica-ai/multica"}++ ref, has, err := buildResourceRefFromFlags(cmd, "github_repo", existing)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true when default-branch-hint is set")+ }+ if ref["url"] != "https://github.com/multica-ai/multica" {+ t.Errorf("expected merged url, got %v", ref["url"])+ }+ if ref["default_branch_hint"] != "main" {+ t.Errorf("expected merged hint=main, got %v", ref["default_branch_hint"])+ }+ })++ t.Run("hint=empty clears the hint but keeps url", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("default-branch-hint", "")+ existing := map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "default_branch_hint": "stale",+ }+ ref, has, err := buildResourceRefFromFlags(cmd, "github_repo", existing)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true")+ }+ if ref["url"] != "https://github.com/multica-ai/multica" {+ t.Errorf("expected url to survive empty-hint clear, got %v", ref["url"])+ }+ if _, ok := ref["default_branch_hint"]; ok {+ t.Errorf("expected default_branch_hint to be cleared, got %v", ref["default_branch_hint"])+ }+ })++ t.Run("url override survives merge", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("url", "https://github.com/multica-ai/new-repo")+ existing := map[string]any{+ "url": "https://github.com/multica-ai/multica",+ "default_branch_hint": "main",+ }+ ref, has, err := buildResourceRefFromFlags(cmd, "github_repo", existing)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true")+ }+ if ref["url"] != "https://github.com/multica-ai/new-repo" {+ t.Errorf("expected overridden url, got %v", ref["url"])+ }+ if ref["default_branch_hint"] != "main" {+ t.Errorf("expected merged hint to persist, got %v", ref["default_branch_hint"])+ }+ })++ t.Run("hint-only with no existing url fails fast", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("default-branch-hint", "main")+ _, _, err := buildResourceRefFromFlags(cmd, "github_repo", nil)+ if err == nil {+ t.Fatalf("expected error when no existing url is available to merge")+ }+ })++ t.Run("no flags set returns has=false", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ ref, has, err := buildResourceRefFromFlags(cmd, "github_repo", map[string]any{"url": "https://x"})+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if has {+ t.Errorf("expected has=false when no shortcut flag is set, got ref=%v", ref)+ }+ })+}++// TestBuildResourceRefFromFlagsLocalDirectoryMerges covers the same merge+// behavior for local_directory: partial edits keep unmentioned fields from the+// existing ref.+func TestBuildResourceRefFromFlagsLocalDirectoryMerges(t *testing.T) {+ t.Run("ref-label only edit preserves existing path + daemon", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("ref-label", "renamed")+ existing := map[string]any{+ "local_path": "/Users/foo/work/a",+ "daemon_id": "d1",+ "label": "old",+ }+ ref, has, err := buildResourceRefFromFlags(cmd, "local_directory", existing)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true")+ }+ if ref["local_path"] != "/Users/foo/work/a" {+ t.Errorf("local_path missing after merge: %v", ref["local_path"])+ }+ if ref["daemon_id"] != "d1" {+ t.Errorf("daemon_id missing after merge: %v", ref["daemon_id"])+ }+ if ref["label"] != "renamed" {+ t.Errorf("label not overridden: %v", ref["label"])+ }+ })++ t.Run("local-path only without existing daemon fails", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("local-path", "/Users/foo/work/b")+ _, _, err := buildResourceRefFromFlags(cmd, "local_directory", nil)+ if err == nil {+ t.Fatalf("expected error when daemon_id is missing from both flags and existing ref")+ }+ })++ t.Run("ref-label cleared on empty input", func(t *testing.T) {+ cmd := newProjectResourceUpdateTestCmd()+ _ = cmd.Flags().Set("ref-label", "")+ existing := map[string]any{+ "local_path": "/Users/foo/work/a",+ "daemon_id": "d1",+ "label": "to-clear",+ }+ ref, has, err := buildResourceRefFromFlags(cmd, "local_directory", existing)+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if !has {+ t.Fatalf("expected has=true")+ }+ if _, ok := ref["label"]; ok {+ t.Errorf("expected embedded label to be cleared, got %v", ref["label"])+ }+ })+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex f4953d5c92..d0ae903084 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -284,6 +284,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/tasks/{taskId}/status", h.GetTaskStatus)r.Post("/tasks/{taskId}/start", h.StartTask)+ r.Post("/tasks/{taskId}/wait-local-directory", h.MarkTaskWaitingLocalDirectory)r.Post("/tasks/{taskId}/progress", h.ReportTaskProgress)r.Post("/tasks/{taskId}/complete", h.CompleteTask)r.Post("/tasks/{taskId}/fail", h.FailTask)@@ -449,6 +450,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Delete("/", h.DeleteProject)r.Get("/resources", h.ListProjectResources)r.Post("/resources", h.CreateProjectResource)+ r.Put("/resources/{resourceId}", h.UpdateProjectResource)r.Delete("/resources/{resourceId}", h.DeleteProjectResource)})})diff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex 45b4833cca..a08d6197eb 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -156,6 +156,21 @@ func (c *Client) StartTask(ctx context.Context, taskID string) error {return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/start", taskID), map[string]any{}, nil)}+// MarkTaskWaitingLocalDirectory parks a freshly-dispatched task in the+// waiting_local_directory state on the server. The daemon calls this after+// it has claimed a task whose project carries a local_directory resource+// but the path mutex is held by another in-flight task. reason is a short+// human-readable hint (e.g. "<path>") surfaced by the UI alongside the+// status. Idempotent on the daemon's side — calling twice with the same+// reason is a no-op once the row is already waiting_local_directory (the+// underlying SQL filters on status='dispatched', so the second call is a+// 400 the daemon swallows and proceeds to wait).+func (c *Client) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID, reason string) error {+ return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/wait-local-directory", taskID), map[string]any{+ "reason": reason,+ }, nil)+}+func (c *Client) ReportProgress(ctx context.Context, taskID, summary string, step, total int) error {return c.postJSON(ctx, fmt.Sprintf("/api/daemon/tasks/%s/progress", taskID), map[string]any{"summary": summary,diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 0d8db5e63a..062a68eccf 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -131,6 +131,13 @@ type Daemon struct {activeEnvRootsMu sync.MutexactiveEnvRoots map[string]int // env root path -> reference count (handles reuse paths marked twice)+ // localPathLocks serialises agent tasks whose project resource is a+ // local_directory pinned to this daemon. Two tasks targeting the same+ // on-disk path run sequentially; the second blocks on the lock and is+ // surfaced via the server-side waiting_local_directory status while it+ // waits. See MUL-2663.+ localPathLocks *LocalPathLocker+// bgSyncs tracks background goroutines started by registerTaskRepos so// callers (notably tests using t.TempDir-backed cache roots) can wait for// them to drain before tearing the daemon down. Without this the bg@@ -164,6 +171,7 @@ func New(cfg Config, logger *slog.Logger) *Daemon {agentVersions: make(map[string]string),wsHBLastAck: make(map[string]time.Time),activeEnvRoots: make(map[string]int),+ localPathLocks: NewLocalPathLocker(),runtimeGoneInflight: make(map[string]struct{}),reregisterNextAttempt: make(map[string]time.Time),reregisterLastCompletedAt: make(map[string]time.Time),@@ -2034,6 +2042,20 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {"reuse_workdir", task.PriorWorkDir != "",)+ // If the task targets a project_resource of type local_directory that+ // is pinned to this daemon, acquire the path mutex BEFORE StartTask so+ // the server-side state machine is dispatched → waiting_local_directory+ // → running rather than backwards-transitioning from running into the+ // wait state. The release is deferred so a panic or early return+ // always frees the lock for the next waiter.+ localRelease, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, taskLog)+ if abort {+ return+ }+ if localRelease != nil {+ defer localRelease()+ }+if err := d.client.StartTask(ctx, task.ID); err != nil {taskLog.Error("start task failed", "error", err)if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("start task failed: %s", err.Error()), "", "", "agent_error"); failErr != nil {@@ -2116,6 +2138,15 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {// crash leaves the directory as an orphan (cleaned up by GCOrphanTTL).if result.EnvRoot != "" {if meta, ok := gcMetaForTask(task); ok {+ // A local_directory project_resource matched this daemon+ // means the agent ran in the user's own tree. Stamp the+ // meta so the GC loop never tries to RemoveAll envRoot's+ // sibling workdir (which is the user's path) or the envRoot+ // itself (we want output/ and logs/ to linger for forensic+ // access).+ if assignment, _ := findLocalDirectoryAssignment(task.ProjectResources, d.cfg.DaemonID); assignment != nil {+ meta.LocalDirectory = true+ }if err := execenv.WriteGCMeta(result.EnvRoot, meta, taskLog); err != nil {taskLog.Warn("write gc meta failed (non-fatal)", "error", err)}@@ -2123,6 +2154,122 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {}}+// acquireLocalDirectoryLockIfNeeded inspects the task's project resources for+// a local_directory pinned to this daemon, validates the path, and takes the+// path mutex. Returns a release callback (nil when no local_directory+// resource applies) and abort=true when the caller must bail without+// starting the task (the helper has already reported the failure to the+// server).+//+// The helper covers four distinct failure modes:+//+// 1. The project_resource JSON is structurally broken — fail the task fast.+// 2. The path fails validation (missing, not a directory, no R/W, system+// blacklist) — fail the task fast with a user-facing reason.+// 3. The mutex is held by another task — call MarkTaskWaitingLocalDirectory+// so the row flips to waiting_local_directory while we block on the+// lock, then return the release callback once we win.+// 4. The blocking wait is cancelled (daemon shutdown, server-side cancel)+// — fail the task with the ctx error.+func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Task, taskLog *slog.Logger) (release func(), abort bool) {+ if len(task.ProjectResources) == 0 || d.cfg.DaemonID == "" {+ return nil, false+ }+ assignment, err := findLocalDirectoryAssignment(task.ProjectResources, d.cfg.DaemonID)+ if err != nil {+ taskLog.Error("local_directory: resolve resource failed", "error", err)+ if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "local_directory_error"); failErr != nil {+ taskLog.Error("fail task after local_directory resolve error", "error", failErr)+ }+ return nil, true+ }+ if assignment == nil {+ return nil, false+ }+ taskLog = taskLog.With("local_directory", assignment.AbsPath)+ if err := validateLocalPath(assignment.AbsPath); err != nil {+ taskLog.Error("local_directory: path validation failed", "error", err)+ if failErr := d.client.FailTask(ctx, task.ID, err.Error(), "", "", "local_directory_error"); failErr != nil {+ taskLog.Error("fail task after local_directory validation error", "error", failErr)+ }+ return nil, true+ }++ // While the lock is contended the daemon would otherwise sit blocked on+ // the path mutex with no signal back from the server — the main+ // per-task watcher only starts after StartTask. If the user cancels+ // the issue or it gets reassigned during the wait, we need to notice+ // promptly so the daemon slot isn't pinned by a phantom waiter. We+ // spin up the cancellation watcher lazily inside onWait so the+ // no-contention fast path still costs nothing.+ waitCtx, waitCancel := context.WithCancel(ctx)+ defer waitCancel()+ pollInterval := d.cancelPollInterval+ if pollInterval == 0 {+ pollInterval = 5 * time.Second+ }+ var (+ watcherOnce sync.Once+ cancelledByPoll <-chan struct{}+ )++ onWait := func(holder string) {+ reason := fmt.Sprintf("local_directory %s", assignment.AbsPath)+ if holder != "" {+ reason = fmt.Sprintf("%s (held by task %s)", reason, shortID(holder))+ }+ taskLog.Info("local_directory: waiting on path mutex", "holder", shortID(holder))+ if waitErr := d.client.MarkTaskWaitingLocalDirectory(ctx, task.ID, reason); waitErr != nil {+ // Non-fatal: even if the server-side flag fails to update,+ // we still want to block on the lock and proceed when free.+ // The UI just won't see the explicit "waiting" badge.+ taskLog.Warn("local_directory: mark waiting status failed", "error", waitErr)+ }+ // Start polling once we actually park. shouldInterruptAgent inside+ // watchTaskCancellation already handles both server-side cancel+ // (status=cancelled) and the row-deleted reassignment case (404),+ // which is the full set of "this task shouldn't run anymore"+ // signals we need to react to during the wait.+ watcherOnce.Do(func() {+ cancelledByPoll = d.watchTaskCancellation(waitCtx, task.ID, pollInterval, taskLog)+ go func() {+ select {+ case <-cancelledByPoll:+ waitCancel()+ case <-waitCtx.Done():+ }+ }()+ })+ }+ release, err = d.localPathLocks.Acquire(waitCtx, assignment.RealPath, task.ID, onWait)+ if err != nil {+ // If the wait was cut short because the server cancelled the task+ // (or deleted the row), the row is already in a terminal state —+ // return silently the same way the run-phase poller does at+ // lines ~2104. Issuing FailTask here would be a no-op at best+ // and a confusing redundant log line at worst.+ if cancelledByPoll != nil {+ select {+ case <-cancelledByPoll:+ taskLog.Info("local_directory: wait aborted by server-side cancel")+ return nil, true+ default:+ }+ }+ taskLog.Error("local_directory: lock acquire failed", "error", err)+ failureReason := "local_directory_error"+ if errors.Is(err, context.Canceled) || errors.Is(err, context.DeadlineExceeded) {+ failureReason = "cancelled"+ }+ if failErr := d.client.FailTask(ctx, task.ID, fmt.Sprintf("local_directory wait cancelled: %s", err.Error()), "", "", failureReason); failErr != nil {+ taskLog.Error("fail task after local_directory lock cancel", "error", failErr)+ }+ return nil, true+ }+ taskLog.Info("local_directory: lock acquired")+ return release, false+}+// reportTaskResult writes the final task disposition back to the server.//// Fail closed: only an explicit "completed" status is reported as success.@@ -2285,7 +2432,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif provider == "openclaw" {openclawBin = entry.Path}- if task.PriorWorkDir != "" {+ // Resolve any local_directory assignment again here so runTask can plumb+ // LocalWorkDir into execenv. handleTask already validated + locked the+ // path; this call is a pure JSON parse over the same task payload.+ localAssignment, _ := findLocalDirectoryAssignment(task.ProjectResources, d.cfg.DaemonID)+ // Reuse intentionally skipped for local_directory tasks: the prior+ // WorkDir is the user's own path (always present) but the reuse path+ // loses the envRoot association the GC loop needs, and re-running+ // Prepare against a stable user path is cheap (no clone, no copy).+ if task.PriorWorkDir != "" && localAssignment == nil {env = execenv.Reuse(execenv.ReuseParams{WorkDir: task.PriorWorkDir,Provider: provider,@@ -2296,7 +2451,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i}if env == nil {var err error- env, err = execenv.Prepare(execenv.PrepareParams{+ prepParams := execenv.PrepareParams{WorkspacesRoot: d.cfg.WorkspacesRoot,WorkspaceID: task.WorkspaceID,TaskID: task.ID,@@ -2305,7 +2460,11 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iCodexVersion: codexVersion,OpenclawBin: openclawBin,Task: taskCtx,- }, d.logger)+ }+ if localAssignment != nil {+ prepParams.LocalWorkDir = localAssignment.AbsPath+ }+ env, err = execenv.Prepare(prepParams, d.logger)if err != nil {return TaskResult{}, fmt.Errorf("prepare execution environment: %w", err)}diff --git a/server/internal/daemon/execenv/execenv.go b/server/internal/daemon/execenv/execenv.goindex 2e50921434..084de19414 100644--- a/server/internal/daemon/execenv/execenv.go+++ b/server/internal/daemon/execenv/execenv.go@@ -32,14 +32,22 @@ type ProjectResourceForEnv struct {// PrepareParams holds all inputs needed to set up an execution environment.type PrepareParams struct {- WorkspacesRoot string // base path for all envs (e.g., ~/multica_workspaces)- WorkspaceID string // workspace UUID — tasks are grouped under this- TaskID string // task UUID — used for directory name- AgentName string // for git branch naming only- Provider string // agent provider (determines runtime config and skill injection paths)- CodexVersion string // detected Codex CLI version (only used when Provider == "codex")- OpenclawBin string // resolved openclaw CLI path (only used when Provider == "openclaw"); empty = look up on PATH- Task TaskContextForEnv // context data for writing files+ WorkspacesRoot string // base path for all envs (e.g., ~/multica_workspaces)+ WorkspaceID string // workspace UUID — tasks are grouped under this+ TaskID string // task UUID — used for directory name+ AgentName string // for git branch naming only+ Provider string // agent provider (determines runtime config and skill injection paths)+ CodexVersion string // detected Codex CLI version (only used when Provider == "codex")+ OpenclawBin string // resolved openclaw CLI path (only used when Provider == "openclaw"); empty = look up on PATH+ // LocalWorkDir, when non-empty, redirects the agent's working directory+ // to a user-supplied absolute path instead of the synthesised envRoot/+ // workdir. The path is NOT copied or mounted — the agent operates on+ // the user's directory in place. The daemon still creates envRoot for+ // output/, logs/, and .gc_meta.json; only the workdir slot is+ // substituted. Used by the local_directory project_resource flow+ // (MUL-2663). When set, the envRoot/workdir directory is not created.+ LocalWorkDir string+ Task TaskContextForEnv // context data for writing files}// TaskContextForEnv is the subset of task context used for writing context files.@@ -96,8 +104,15 @@ type SkillFileContextForEnv struct {type Environment struct {// RootDir is the top-level env directory ({workspacesRoot}/{task_id_short}/).RootDir string- // WorkDir is the directory to pass as Cwd to the agent ({RootDir}/workdir/).+ // WorkDir is the directory to pass as Cwd to the agent. Normally+ // ({RootDir}/workdir/); when the task is bound to a local_directory+ // project_resource, it is the user's path instead. See LocalDirectory.WorkDir string+ // LocalDirectory is true when WorkDir points at a user-supplied path+ // outside RootDir (the local_directory flow). Callers that key behavior+ // on "may I remove WorkDir as scratch?" must check this — for example+ // the GC loop never deletes the user's directory.+ LocalDirectory bool// CodexHome is the path to the per-task CODEX_HOME directory (set only for codex provider).CodexHome string// OpenclawConfigPath is the path to the per-task synthesized OpenClaw@@ -150,18 +165,28 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {}}- // Create directory tree.+ // Create directory tree. For the standard flow the agent's workdir is+ // envRoot/workdir; for local_directory tasks the user's path takes its+ // place and we only need to create the scratch directories under+ // envRoot.workDir := filepath.Join(envRoot, "workdir")- for _, dir := range []string{workDir, filepath.Join(envRoot, "output"), filepath.Join(envRoot, "logs")} {+ scratchDirs := []string{filepath.Join(envRoot, "output"), filepath.Join(envRoot, "logs")}+ if params.LocalWorkDir == "" {+ scratchDirs = append(scratchDirs, workDir)+ } else {+ workDir = params.LocalWorkDir+ }+ for _, dir := range scratchDirs {if err := os.MkdirAll(dir, 0o755); err != nil {return nil, fmt.Errorf("execenv: create directory %s: %w", dir, err)}}env := &Environment{- RootDir: envRoot,- WorkDir: workDir,- logger: logger,+ RootDir: envRoot,+ WorkDir: workDir,+ LocalDirectory: params.LocalWorkDir != "",+ logger: logger,}// Write context files into workdir (skills go to provider-native paths).@@ -206,9 +231,15 @@ func Prepare(params PrepareParams, logger *slog.Logger) (*Environment, error) {type ReuseParams struct {WorkDir stringProvider string- CodexVersion string // only used when Provider == "codex"- OpenclawBin string // only used when Provider == "openclaw"; empty = PATH lookup- Task TaskContextForEnv // refreshed context files / skills+ CodexVersion string // only used when Provider == "codex"+ OpenclawBin string // only used when Provider == "openclaw"; empty = PATH lookup+ // LocalDirectory is true when the reused WorkDir is a user-supplied+ // directory (the local_directory flow). The flag is propagated into+ // the returned Environment so downstream callers (notably the GC+ // loop) keep the "never delete the user's directory" invariant on+ // reuse paths.+ LocalDirectory bool+ Task TaskContextForEnv // refreshed context files / skills}// Reuse wraps an existing workdir into an Environment and refreshes context files.@@ -218,10 +249,24 @@ func Reuse(params ReuseParams, logger *slog.Logger) *Environment {return nil}+ rootDir := filepath.Dir(params.WorkDir)+ if params.LocalDirectory {+ // For local_directory tasks the user's WorkDir is unrelated to+ // envRoot (envRoot still lives under workspacesRoot/{wsID}/...),+ // so reading it from filepath.Dir(WorkDir) would point at the+ // parent of the user's directory. Callers that need a real+ // RootDir on the reuse path should arrange to pass it in+ // explicitly; for v1 the daemon only ever reuses local_directory+ // workdirs after a fresh Prepare in the same task lifetime, so+ // the empty RootDir on reuse is fine for the current callers+ // (GC writes meta from Prepare's result, not Reuse's).+ rootDir = ""+ }env := &Environment{- RootDir: filepath.Dir(params.WorkDir),- WorkDir: params.WorkDir,- logger: logger,+ RootDir: rootDir,+ WorkDir: params.WorkDir,+ LocalDirectory: params.LocalDirectory,+ logger: logger,}// Refresh context files (issue_context.md, skills).@@ -325,6 +370,14 @@ type GCMeta struct {TaskID string `json:"task_id,omitempty"`WorkspaceID string `json:"workspace_id"`CompletedAt time.Time `json:"completed_at"`+ // LocalDirectory marks tasks whose WorkDir pointed at a user-owned+ // path rather than the synthesised envRoot/workdir. The GC loop honours+ // this by never falling into the gcActionClean branch (which would+ // RemoveAll envRoot — safe by structure, but we still want to keep the+ // envRoot's output/ and logs/ around longer so users can inspect what+ // the agent did in their own tree). Pattern-based artifact cleanup is+ // still allowed.+ LocalDirectory bool `json:"local_directory,omitempty"`}const gcMetaFile = ".gc_meta.json"@@ -372,11 +425,28 @@ func ReadGCMeta(envRoot string) (*GCMeta, error) {// Cleanup tears down the execution environment.// If removeAll is true, the entire env root is deleted. Otherwise, workdir is// removed but output/ and logs/ are preserved for debugging.+//+// For local_directory tasks (env.LocalDirectory==true) WorkDir is the+// user's own path — Cleanup MUST NEVER delete it, regardless of removeAll.+// In that mode we only ever delete the envRoot scratch directory.func (env *Environment) Cleanup(removeAll bool) error {if env == nil {return nil}+ if env.LocalDirectory {+ // Never touch the user's directory. RootDir is the daemon's own+ // scratch; safe to remove when the caller asked for a full+ // teardown.+ if removeAll && env.RootDir != "" {+ if err := os.RemoveAll(env.RootDir); err != nil {+ env.logger.Warn("execenv: cleanup local_directory envRoot failed", "error", err)+ return err+ }+ }+ return nil+ }+if removeAll {if err := os.RemoveAll(env.RootDir); err != nil {env.logger.Warn("execenv: cleanup removeAll failed", "error", err)diff --git a/server/internal/daemon/execenv/execenv_test.go b/server/internal/daemon/execenv/execenv_test.goindex d6f5fcccdf..e19337b859 100644--- a/server/internal/daemon/execenv/execenv_test.go+++ b/server/internal/daemon/execenv/execenv_test.go@@ -3680,3 +3680,147 @@ func TestInjectRuntimeConfigIssueMetadataCodexFormattingUnchanged(t *testing.T)}})}++// Tests below cover the local_directory flow (MUL-2663): the daemon+// substitutes LocalWorkDir for the synthesized envRoot/workdir when a+// project pins the task to a user-supplied directory. The agent runs in+// place; the daemon's envRoot still hosts output/, logs/, and .gc_meta.json+// (the daemon's logbook), but the workdir slot is the user's path.++func TestPrepareLocalWorkDir(t *testing.T) {+ t.Parallel()+ workspacesRoot := t.TempDir()+ userDir := t.TempDir()++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-local",+ TaskID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",+ AgentName: "Test Agent",+ LocalWorkDir: userDir,+ Task: TaskContextForEnv{+ IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",+ },+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }+ defer env.Cleanup(true)++ if !env.LocalDirectory {+ t.Fatal("expected env.LocalDirectory to be true")+ }+ if env.WorkDir != userDir {+ t.Errorf("WorkDir = %q, want %q (user-supplied path)", env.WorkDir, userDir)+ }++ // envRoot should still be created for scratch dirs, but the synthesised+ // workdir/ subdirectory should NOT exist (we substituted the user's+ // path for it).+ for _, sub := range []string{"output", "logs"} {+ path := filepath.Join(env.RootDir, sub)+ if _, err := os.Stat(path); err != nil {+ t.Fatalf("expected %s to exist: %v", path, err)+ }+ }+ if _, err := os.Stat(filepath.Join(env.RootDir, "workdir")); !os.IsNotExist(err) {+ t.Fatalf("expected envRoot/workdir to NOT exist for local_directory tasks; err=%v", err)+ }++ // Context files should still land in the user's directory so the+ // agent can discover them.+ contextPath := filepath.Join(userDir, ".agent_context", "issue_context.md")+ if _, err := os.Stat(contextPath); err != nil {+ t.Fatalf("expected context file in user dir: %v", err)+ }+}++func TestEnvironmentCleanupPreservesLocalDirectory(t *testing.T) {+ t.Parallel()+ workspacesRoot := t.TempDir()+ userDir := t.TempDir()++ // Drop a sentinel file inside the user's directory so we can verify+ // Cleanup never removed it.+ sentinel := filepath.Join(userDir, "user-file.txt")+ if err := os.WriteFile(sentinel, []byte("keep me"), 0o644); err != nil {+ t.Fatalf("write sentinel: %v", err)+ }++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-local",+ TaskID: "b1b2c3d4-e5f6-7890-abcd-ef1234567890",+ AgentName: "Test Agent",+ LocalWorkDir: userDir,+ Task: TaskContextForEnv{IssueID: "issue-1"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare failed: %v", err)+ }++ // removeAll=true on a local_directory env MUST NOT touch the user's+ // directory. envRoot (the daemon's logbook) is fair game.+ if err := env.Cleanup(true); err != nil {+ t.Fatalf("Cleanup: %v", err)+ }+ if _, err := os.Stat(sentinel); err != nil {+ t.Fatalf("user file removed by Cleanup: %v", err)+ }+ if _, err := os.Stat(env.RootDir); !os.IsNotExist(err) {+ t.Fatalf("expected envRoot to be cleaned, got err=%v", err)+ }++ // removeAll=false should also leave the user's directory alone (the+ // existing semantics for non-local tasks would have removed WorkDir+ // — that's exactly what we must NOT do here).+ env2, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-local-2",+ TaskID: "b2b2c3d4-e5f6-7890-abcd-ef1234567890",+ AgentName: "Test Agent",+ LocalWorkDir: userDir,+ Task: TaskContextForEnv{IssueID: "issue-1"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare 2: %v", err)+ }+ if err := env2.Cleanup(false); err != nil {+ t.Fatalf("Cleanup 2: %v", err)+ }+ if _, err := os.Stat(sentinel); err != nil {+ t.Fatalf("partial Cleanup removed user file: %v", err)+ }+}++// TestEnvironmentCleanupStandardModeRemovesWorkdir is the negative control:+// a non-local_directory env preserves its existing semantics so the+// local_directory branch can't silently regress the regular flow.+func TestEnvironmentCleanupStandardModeRemovesWorkdir(t *testing.T) {+ t.Parallel()+ workspacesRoot := t.TempDir()++ env, err := Prepare(PrepareParams{+ WorkspacesRoot: workspacesRoot,+ WorkspaceID: "ws-std",+ TaskID: "c1b2c3d4-e5f6-7890-abcd-ef1234567890",+ AgentName: "Test Agent",+ Task: TaskContextForEnv{IssueID: "issue-1"},+ }, testLogger())+ if err != nil {+ t.Fatalf("Prepare: %v", err)+ }+ if env.LocalDirectory {+ t.Fatal("expected LocalDirectory to be false for standard env")+ }+ if err := env.Cleanup(false); err != nil {+ t.Fatalf("Cleanup: %v", err)+ }+ if _, err := os.Stat(env.WorkDir); !os.IsNotExist(err) {+ t.Fatalf("expected workdir to be removed in standard mode")+ }+ // output/logs should remain.+ if _, err := os.Stat(filepath.Join(env.RootDir, "output")); err != nil {+ t.Fatalf("output/ removed by partial cleanup: %v", err)+ }+}diff --git a/server/internal/daemon/gc.go b/server/internal/daemon/gc.goindex 92c68dc36d..628a2aa0f9 100644--- a/server/internal/daemon/gc.go+++ b/server/internal/daemon/gc.go@@ -178,6 +178,40 @@ func (d *Daemon) shouldCleanTaskDir(ctx context.Context, taskDir string) gcActioreturn d.orphanByMTime(taskDir, "no meta")}+ action := d.shouldCleanTaskDirForKind(ctx, taskDir, meta)+ if !meta.LocalDirectory {+ return action+ }+ // local_directory tasks keep their envRoot indefinitely so the user+ // can inspect output/ and logs/ for forensic context. The WorkDir is+ // the user's own path and lives outside taskDir, so the envRoot+ // itself is just the daemon's logbook for the run — never large, and+ // safe to keep.+ //+ // gcActionClean → demote to artifact-pattern cleanup so envRoot+ // (and especially the logbook) survives.+ // gcActionOrphan → skip outright; we don't ever wipe a+ // local_directory envRoot via the mtime path,+ // since the parent issue / chat record going+ // away should not collateral-delete the user's+ // own audit trail.+ //+ // gcActionCleanArtifacts and gcActionSkip already obey the+ // "no full envRoot RemoveAll" rule.+ switch action {+ case gcActionClean:+ return gcActionCleanArtifacts+ case gcActionOrphan:+ return gcActionSkip+ default:+ return action+ }+}++// shouldCleanTaskDirForKind runs the per-Kind dispatch without applying the+// local_directory override. Split out so shouldCleanTaskDir can intercept+// the result.+func (d *Daemon) shouldCleanTaskDirForKind(ctx context.Context, taskDir string, meta *execenv.GCMeta) gcAction {switch meta.Kind {case execenv.GCKindIssue:return d.gcDecisionIssue(ctx, taskDir, meta)diff --git a/server/internal/daemon/gc_test.go b/server/internal/daemon/gc_test.goindex 885f0d9cae..b0e011d9d7 100644--- a/server/internal/daemon/gc_test.go+++ b/server/internal/daemon/gc_test.go@@ -969,3 +969,97 @@ func TestGCMetaForTask(t *testing.T) {}})}++// TestShouldCleanTaskDir_LocalDirectoryNeverClean confirms the GC loop+// never removes the envRoot of a local_directory task even when the parent+// issue is long-since done. Artifact-pattern cleanup is the most that+// should ever happen, so output/ and logs/ stay around for the user.+func TestShouldCleanTaskDir_LocalDirectoryNeverClean(t *testing.T) {+ t.Parallel()+ issueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa1"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "status": "done",+ "updated_at": time.Now().Add(-30 * 24 * time.Hour),+ })+ })++ d := newGCTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "local-task", &execenv.GCMeta{+ Kind: execenv.GCKindIssue,+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-30 * 24 * time.Hour),+ LocalDirectory: true,+ })++ got := d.shouldCleanTaskDir(context.Background(), taskDir)+ if got == gcActionClean {+ t.Fatalf("expected local_directory task to never return gcActionClean, got gcActionClean")+ }+ // Either skip (no patterns configured) or artifact cleanup is OK —+ // what matters is that gcActionClean never fires for local_directory.+ if got != gcActionCleanArtifacts && got != gcActionSkip {+ t.Fatalf("unexpected action for local_directory done issue: %d", got)+ }+}++// TestShouldCleanTaskDir_LocalDirectoryNeverOrphan confirms that even when+// the parent issue 404s (would normally fall through to mtime-based orphan+// cleanup) a local_directory task's envRoot is preserved.+func TestShouldCleanTaskDir_LocalDirectoryNeverOrphan(t *testing.T) {+ t.Parallel()+ issueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa2"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ http.NotFound(w, r)+ })++ d := newGCTestDaemon(t, mux)+ d.cfg.GCOrphanTTL = 0 // any age is "stale" enough to orphan+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "local-orphan", &execenv.GCMeta{+ Kind: execenv.GCKindIssue,+ IssueID: issueID,+ WorkspaceID: "ws1",+ LocalDirectory: true,+ })++ got := d.shouldCleanTaskDir(context.Background(), taskDir)+ if got == gcActionOrphan || got == gcActionClean {+ t.Fatalf("expected local_directory orphan to be skipped, got %d", got)+ }+}++// TestShouldCleanTaskDir_LocalDirectoryFalsePreservesNormalClean is the+// negative control: a regular (non-local_directory) task whose parent issue+// is done + over TTL must still be reclaimed via gcActionClean.+func TestShouldCleanTaskDir_LocalDirectoryFalsePreservesNormalClean(t *testing.T) {+ t.Parallel()+ issueID := "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa3"++ mux := http.NewServeMux()+ mux.HandleFunc(fmt.Sprintf("/api/daemon/issues/%s/gc-check", issueID), func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ json.NewEncoder(w).Encode(map[string]any{+ "status": "done",+ "updated_at": time.Now().Add(-30 * 24 * time.Hour),+ })+ })++ d := newGCTestDaemon(t, mux)+ taskDir := createTaskDir(t, d.cfg.WorkspacesRoot, "ws1", "normal-task", &execenv.GCMeta{+ Kind: execenv.GCKindIssue,+ IssueID: issueID,+ WorkspaceID: "ws1",+ CompletedAt: time.Now().Add(-30 * 24 * time.Hour),+ // LocalDirectory unset (false).+ })++ if got := d.shouldCleanTaskDir(context.Background(), taskDir); got != gcActionClean {+ t.Fatalf("expected gcActionClean for normal task, got %d", got)+ }+}diff --git a/server/internal/daemon/local_directory.go b/server/internal/daemon/local_directory.gonew file mode 100644index 0000000000..73b5438749--- /dev/null+++ b/server/internal/daemon/local_directory.go@@ -0,0 +1,482 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "os"+ "os/exec"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+)++// localDirectoryResourceType is the project_resource discriminator the daemon+// looks for when deciding whether a task should run against an existing+// user directory rather than a fresh git worktree. Mirrors the server-side+// constant — keep in sync if the type string is ever renamed.+const localDirectoryResourceType = "local_directory"++// localDirectoryRef mirrors the server-side ref shape for local_directory+// project resources. Defined locally so the daemon does not have to import+// the server handler package.+type localDirectoryRef struct {+ LocalPath string `json:"local_path"`+ DaemonID string `json:"daemon_id"`+ Label string `json:"label,omitempty"`+}++// localDirectoryAssignment is the resolved view of a task's local_directory+// resource: the absolute path the daemon will use as the agent's workdir,+// plus the underlying ref for callers that still need the raw label / daemon+// id (validation log messages, mostly). RealPath is the symlink-resolved+// absolute path; the path mutex keys on it so two different routes to the+// same directory are serialised.+type localDirectoryAssignment struct {+ Ref localDirectoryRef+ AbsPath string // user-provided path, cleaned but not symlink-resolved+ RealPath string // canonical key for the path mutex+}++// findLocalDirectoryAssignment scans the task's project resources for one of+// type local_directory whose daemon_id matches this daemon. Returns nil+// (without error) when no such resource exists — the task takes the regular+// github_repo / worktree code path. Returns an error only when the matching+// resource is structurally broken (bad JSON, missing fields) OR when more+// than one resource is pinned to this daemon — that's a server-side+// invariant violation, and silently picking the first match would let the+// agent write into an arbitrary directory the user didn't intend.+//+// Server-side `findLocalDirectoryConflict` enforces a single local_directory+// per (project, daemon), so two matches here means either the constraint+// was bypassed (older API client) or the data was corrupted. Either way,+// fail fast rather than guess.+func findLocalDirectoryAssignment(resources []ProjectResourceData, daemonID string) (*localDirectoryAssignment, error) {+ var match *localDirectoryAssignment+ for _, r := range resources {+ if r.ResourceType != localDirectoryResourceType {+ continue+ }+ var ref localDirectoryRef+ if err := json.Unmarshal(r.ResourceRef, &ref); err != nil {+ return nil, fmt.Errorf("local_directory: parse resource_ref: %w", err)+ }+ ref.DaemonID = strings.TrimSpace(ref.DaemonID)+ if ref.DaemonID == "" {+ return nil, errors.New("local_directory: resource_ref missing daemon_id")+ }+ if ref.DaemonID != daemonID {+ // A different daemon owns this resource. Skip silently; the+ // project may have multiple local_directory resources, one+ // per daemon, and other daemons will resolve their own row.+ continue+ }+ if match != nil {+ // Server-side invariant: at most one local_directory per+ // (project, daemon). Two matches here means the constraint+ // was bypassed by an older API client or by direct DB writes.+ // Either way, refuse to guess which directory the user meant.+ return nil, fmt.Errorf(+ "local_directory: project has multiple local_directory resources for this daemon (%q and %q); remove the extra in project settings",+ match.AbsPath,+ strings.TrimSpace(ref.LocalPath),+ )+ }+ absPath, err := normalizeLocalPath(ref.LocalPath)+ if err != nil {+ return nil, err+ }+ realPath, err := resolveRealPath(absPath)+ if err != nil {+ return nil, err+ }+ match = &localDirectoryAssignment{+ Ref: ref,+ AbsPath: absPath,+ RealPath: realPath,+ }+ }+ return match, nil+}++// normalizeLocalPath strips whitespace and resolves the path to an absolute+// cleaned form. It does NOT touch the filesystem (no symlink resolution, no+// existence check) — callers do that separately via validateLocalPath.+func normalizeLocalPath(p string) (string, error) {+ trimmed := strings.TrimSpace(p)+ if trimmed == "" {+ return "", errors.New("local_directory: local_path is empty")+ }+ if !filepath.IsAbs(trimmed) {+ return "", fmt.Errorf("local_directory: local_path must be absolute, got %q", trimmed)+ }+ return filepath.Clean(trimmed), nil+}++// resolveRealPath returns the symlink-resolved absolute form of path. The+// path mutex keys on this value so a task on `/Users/u/proj` and another on+// `/private/var/folders/.../proj-symlink → /Users/u/proj` collapse to one+// lock. When EvalSymlinks fails (path is missing or not yet a real link),+// fall back to the cleaned absolute form so callers can still proceed to+// the existence-check stage which surfaces a clearer error.+func resolveRealPath(absPath string) (string, error) {+ real, err := filepath.EvalSymlinks(absPath)+ if err != nil {+ // validateLocalPath will surface the underlying error with better+ // context; for the mutex key the cleaned absolute path is a safe+ // fallback (it just slightly weakens the dedup on broken symlinks).+ return absPath, nil+ }+ return real, nil+}++// validateLocalPath enforces the daemon-side preconditions for running an+// agent against a user-supplied directory:+//+// - the path is absolute and not in the system blacklist (root, $HOME,+// /Users, /home, the current user's $HOME — picking one of those would+// scope the agent to the entire account, which is never what the user+// intended);+// - the symlink-resolved target is ALSO not in the blacklist — without+// this a symlink like /Users/me/proj/home -> /Users/me would slip the+// literal-equality check above while still routing every daemon write+// into $HOME;+// - the path exists, is a directory (not a regular file or device);+// - the daemon process can read and write inside it (the agent will need+// both — read for context discovery, write for the issue's edits).+//+// Each failure returns a typed error message so the daemon can forward it+// onto the task's fail comment verbatim.+func validateLocalPath(absPath string) error {+ if absPath == "" {+ return errors.New("local_directory: local_path is empty")+ }+ if !filepath.IsAbs(absPath) {+ return fmt.Errorf("local_directory: local_path must be absolute, got %q", absPath)+ }+ if reason, blocked := isBlacklistedLocalPath(absPath); blocked {+ return fmt.Errorf("local_directory: %s (%q)", reason, absPath)+ }+ info, err := os.Stat(absPath)+ if err != nil {+ if os.IsNotExist(err) {+ return fmt.Errorf("local_directory: path does not exist: %q", absPath)+ }+ return fmt.Errorf("local_directory: stat %q: %w", absPath, err)+ }+ if !info.IsDir() {+ return fmt.Errorf("local_directory: path is not a directory: %q", absPath)+ }+ // Re-check the blacklist after resolving symlinks. Two ways the+ // literal check can be bypassed even when absPath itself is clean:+ //+ // 1. A user-created symlink (or a parent component) routes writes+ // into a banned target. Example: ~/proj/home-link -> /Users/me.+ // 2. The user directly selects a canonical OS path that aliases a+ // banned root via an OS-level symlink. Example on macOS: typing+ // /private/tmp slips past the /tmp entry because the literal+ // strings don't match, and EvalSymlinks is a no-op since the+ // input is already canonical. This must be checked+ // unconditionally — not gated on realPath != absPath — or the+ // direct-canonical case is silently allowed.+ //+ // EvalSymlinks walks intermediate components too, so a non-symlink+ // absPath whose parent is a symlink also fails closed.+ realPath, err := filepath.EvalSymlinks(absPath)+ if err != nil {+ return fmt.Errorf("local_directory: resolve symlinks for %q: %w", absPath, err)+ }+ realPath = filepath.Clean(realPath)+ if reason, blocked := isBlacklistedRealPath(realPath); blocked {+ if realPath != filepath.Clean(absPath) {+ return fmt.Errorf("local_directory: %s (symlink target of %q is %q)", reason, absPath, realPath)+ }+ return fmt.Errorf("local_directory: %s (canonical path %q)", reason, absPath)+ }+ if err := checkDirReadWrite(absPath); err != nil {+ return fmt.Errorf("local_directory: %w", err)+ }+ return nil+}++// isBlacklistedLocalPath rejects paths that map to the whole machine or an+// entire user profile. The intent is to keep the daemon from accidentally+// stamping context files (.agent_context/, .claude/skills/, .multica/) at+// the root of a user's account or the OS — a misconfiguration on the UI+// side should fail fast rather than litter the user's home.+//+// The check is by literal equality after Clean(), not prefix containment:+// a legitimate project under /Users/<user>/code/proj should pass.+func isBlacklistedLocalPath(absPath string) (reason string, blocked bool) {+ cleaned := filepath.Clean(absPath)+ if isDriveRoot(cleaned) {+ return fmt.Sprintf("path is a drive root %q", cleaned), true+ }+ for _, banned := range systemRootBlacklist() {+ if cleaned == banned {+ return fmt.Sprintf("path is a protected system root %q", banned), true+ }+ }+ if home, err := os.UserHomeDir(); err == nil {+ if cleaned == filepath.Clean(home) {+ return "path is the user's home directory", true+ }+ }+ return "", false+}++// isBlacklistedRealPath is the canonical-aware variant of+// isBlacklistedLocalPath. It compares the symlink-resolved realPath against+// the symlink-resolved form of each blacklist entry so OS-level redirects+// (notably macOS's /etc -> /private/etc, /tmp -> /private/tmp, /var ->+// /private/var) cannot be used to slip a candidate past the literal+// blacklist — whether the redirect is reached via a user-created symlink+// (~/proj/home-link -> /Users/me) or by directly typing the canonical form+// (/private/tmp), which is identical to the OS view of /tmp.+func isBlacklistedRealPath(realPath string) (reason string, blocked bool) {+ realClean := filepath.Clean(realPath)+ if isDriveRoot(realClean) {+ return fmt.Sprintf("path is a drive root %q", realClean), true+ }+ for _, banned := range systemRootBlacklist() {+ bannedClean := filepath.Clean(banned)+ if realClean == bannedClean {+ return fmt.Sprintf("path is a protected system root %q", banned), true+ }+ if r, err := filepath.EvalSymlinks(banned); err == nil {+ if filepath.Clean(r) == realClean {+ return fmt.Sprintf("path is a protected system root %q", banned), true+ }+ }+ }+ if home, err := os.UserHomeDir(); err == nil {+ homeClean := filepath.Clean(home)+ if realClean == homeClean {+ return "path is the user's home directory", true+ }+ if r, err := filepath.EvalSymlinks(home); err == nil {+ if filepath.Clean(r) == realClean {+ return "path is the user's home directory", true+ }+ }+ }+ return "", false+}++// isDriveRoot reports whether absPath is the root of a Windows volume — any+// of `C:\`, `D:\`, ..., `Z:\`, plus less common cases like `\\server\share`+// (filepath.VolumeName treats UNC roots as volumes too). On non-Windows+// this is always false because POSIX has no concept of drive letters and+// `/` is covered by systemRootBlacklist.+//+// We rely on filepath.VolumeName rather than enumerating drive letters+// statically: removable / network drives can be mounted at any letter+// (`G:\`, `H:\`, ...), and Windows installs are increasingly happy to put+// the user profile on a non-C drive. A static list (C..F) would miss them+// all.+func isDriveRoot(absPath string) bool {+ if runtime.GOOS != "windows" {+ return false+ }+ vol := filepath.VolumeName(absPath)+ if vol == "" {+ return false+ }+ // VolumeName returns the volume without trailing separator (`C:` or+ // `\\srv\share`). A drive root is volume + one separator (or, after+ // filepath.Clean, just the volume on bare-volume input).+ rest := absPath[len(vol):]+ return rest == "" || rest == `\` || rest == "/"+}++// systemRootBlacklist returns the per-OS list of paths the daemon never+// allows as a local_directory root. POSIX systems get `/`, `/Users`, `/home`+// (and macOS's `/Users/Shared` for good measure); Windows gets the+// well-known account / shared trees under C:. Drive roots themselves are+// handled by isDriveRoot so we don't have to enumerate G:\, H:\, etc.+// The list is intentionally conservative — it errs on the side of+// rejecting more, since the desktop UI is expected to surface a friendly+// picker that never produces these values.+func systemRootBlacklist() []string {+ if runtime.GOOS == "windows" {+ return []string{`C:\Users`, `C:\ProgramData`, `C:\Program Files`, `C:\Program Files (x86)`, `C:\Windows`}+ }+ return []string{"/", "/Users", "/Users/Shared", "/home", "/root", "/var", "/etc", "/tmp", "/usr", "/opt"}+}++// checkDirReadWrite verifies the daemon process can both read directory+// contents and create/remove a probe file inside dir. The probe filename is+// long, hidden, and unlikely to clash with user files; we delete it+// immediately and ignore the delete error (best-effort cleanup is fine —+// the worst case is leaving a 0-byte file the user can ignore).+func checkDirReadWrite(dir string) error {+ if _, err := os.ReadDir(dir); err != nil {+ return fmt.Errorf("read %q: %w", dir, err)+ }+ probe, err := os.CreateTemp(dir, ".multica-rwcheck-*")+ if err != nil {+ return fmt.Errorf("write %q: %w", dir, err)+ }+ probePath := probe.Name()+ _ = probe.Close()+ _ = os.Remove(probePath)+ return nil+}++// isGitWorkTree reports whether path is the working tree of a git repo. The+// daemon uses this to skip branch / worktree machinery when the user has+// already pointed the project at their own clone — the agent operates on+// the current branch in place. Returns false on any error (git not on PATH,+// path not in a repo, exec failure) so the caller can treat "not a git+// tree" and "can't tell" the same way: skip the git-specific path.+func isGitWorkTree(ctx context.Context, path string) bool {+ cmd := exec.CommandContext(ctx, "git", "-C", path, "rev-parse", "--is-inside-work-tree")+ out, err := cmd.Output()+ if err != nil {+ return false+ }+ return strings.TrimSpace(string(out)) == "true"+}++// LocalPathLocker serialises agent tasks that share the same on-disk path.+// The lock is owned for the entire lifetime of a task (claim → context+// write → agent execution → result report), not just the agent execution+// window, because the context files and skill scratch directories the+// daemon writes at task-prepare time can race with a sibling task on the+// same path.+//+// Implementation: per-key sync.Mutex inside a map guarded by mu. When a+// task can't take the lock immediately, the waiter blocks on the per-key+// Mutex itself — that gives FIFO-ish behaviour from the Go scheduler+// (sufficient for our load; the issue body asks for a wait queue, not a+// strict-priority queue). Holder bookkeeping (current holder task id) is+// surfaced via Holder so callers can build a UI-friendly wait_reason.+type LocalPathLocker struct {+ mu sync.Mutex+ locks map[string]*pathLockEntry+}++type pathLockEntry struct {+ mu sync.Mutex // serialises holders for this key+ mu2 sync.Mutex // guards holderID under contention+ holderID string // current owner, for UI hints; empty when free+}++// NewLocalPathLocker returns an empty locker. Safe for concurrent use.+func NewLocalPathLocker() *LocalPathLocker {+ return &LocalPathLocker{locks: make(map[string]*pathLockEntry)}+}++// Holder returns the task id currently holding the lock for realPath, or+// "" if no task holds it. Used to populate the wait_reason hint the daemon+// posts to the server when it parks a task — the UI then shows "waiting for+// <path> (held by task <short id>)".+func (l *LocalPathLocker) Holder(realPath string) string {+ l.mu.Lock()+ entry, ok := l.locks[realPath]+ l.mu.Unlock()+ if !ok {+ return ""+ }+ entry.mu2.Lock()+ defer entry.mu2.Unlock()+ return entry.holderID+}++// Acquire takes the lock for realPath on behalf of taskID. If the lock is+// already held, onWait is invoked (synchronously, before this goroutine+// blocks) with the current holder id so callers can flip the task into the+// server-side waiting_local_directory state. onWait may be nil for callers+// that don't need the side effect.+//+// Returns a release func that the caller must invoke (typically deferred)+// to free the lock. The release is idempotent.+//+// Acquire is cancellable via ctx. When ctx is cancelled while the goroutine+// is blocked on the lock, Acquire returns ctx.Err() and the lock is NOT+// taken. This is the same contract as sync.Mutex.Lock paired with+// context-aware cancellation — a daemon shutdown won't wedge inside the+// per-path wait queue.+func (l *LocalPathLocker) Acquire(ctx context.Context, realPath, taskID string, onWait func(holder string)) (func(), error) {+ if realPath == "" {+ return nil, errors.New("local_directory: realpath required for lock")+ }+ if taskID == "" {+ return nil, errors.New("local_directory: taskID required for lock")+ }++ l.mu.Lock()+ entry, ok := l.locks[realPath]+ if !ok {+ entry = &pathLockEntry{}+ l.locks[realPath] = entry+ }+ l.mu.Unlock()++ // Try the fast path first — no allocation, no waiter goroutine.+ if entry.mu.TryLock() {+ entry.mu2.Lock()+ entry.holderID = taskID+ entry.mu2.Unlock()+ return l.releaser(realPath, entry), nil+ }++ // Slow path: somebody else holds the lock. Fire onWait once with the+ // current holder so the daemon can stamp the server-side wait state,+ // then block until either we win the lock or ctx is cancelled.+ if onWait != nil {+ entry.mu2.Lock()+ holder := entry.holderID+ entry.mu2.Unlock()+ onWait(holder)+ }++ acquired := make(chan struct{})+ go func() {+ entry.mu.Lock()+ close(acquired)+ }()++ select {+ case <-acquired:+ entry.mu2.Lock()+ entry.holderID = taskID+ entry.mu2.Unlock()+ return l.releaser(realPath, entry), nil+ case <-ctx.Done():+ // We lost the wait — the goroutine above will still complete and+ // take the lock. Spin off a clean-up goroutine that releases it+ // the moment the acquire returns so a future caller isn't stuck+ // behind a phantom holder. The bookkeeping is best-effort: no+ // holder id is set, since this task never owned the lock.+ go func() {+ <-acquired+ entry.mu.Unlock()+ }()+ return nil, ctx.Err()+ }+}++// releaser returns the unlock callback. Idempotent via a once flag so a+// deferred release is safe even when the caller has already explicitly+// released after task completion.+func (l *LocalPathLocker) releaser(realPath string, entry *pathLockEntry) func() {+ var once sync.Once+ return func() {+ once.Do(func() {+ entry.mu2.Lock()+ entry.holderID = ""+ entry.mu2.Unlock()+ entry.mu.Unlock()+ // We deliberately keep the entry in the map even when nothing+ // is queued. The cost is one *pathLockEntry per distinct path+ // the daemon has ever served, which is bounded by the number+ // of local_directory project resources a workspace has — tiny+ // in practice. Pruning would race with a sibling caller that+ // just looked up the same entry and is about to TryLock.+ _ = realPath+ })+ }+}diff --git a/server/internal/daemon/local_directory_test.go b/server/internal/daemon/local_directory_test.gonew file mode 100644index 0000000000..5620de6025--- /dev/null+++ b/server/internal/daemon/local_directory_test.go@@ -0,0 +1,556 @@+package daemon++import (+ "context"+ "encoding/json"+ "errors"+ "log/slog"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "sync"+ "sync/atomic"+ "testing"+ "time"+)++func TestFindLocalDirectoryAssignment(t *testing.T) {+ const thisDaemon = "d-mine"+ otherDaemon := "d-other"++ mkRef := func(t *testing.T, ref localDirectoryRef) json.RawMessage {+ t.Helper()+ raw, err := json.Marshal(ref)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ return raw+ }++ tmp := t.TempDir()++ t.Run("no resources returns nil", func(t *testing.T) {+ got, err := findLocalDirectoryAssignment(nil, thisDaemon)+ if err != nil || got != nil {+ t.Fatalf("expected (nil, nil), got (%+v, %v)", got, err)+ }+ })++ t.Run("other daemon is skipped", func(t *testing.T) {+ got, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: tmp, DaemonID: otherDaemon})},+ }, thisDaemon)+ if err != nil || got != nil {+ t.Fatalf("expected (nil, nil), got (%+v, %v)", got, err)+ }+ })++ t.Run("non-matching type is skipped", func(t *testing.T) {+ got, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: "github_repo", ResourceRef: json.RawMessage(`{"url":"https://x"}`)},+ }, thisDaemon)+ if err != nil || got != nil {+ t.Fatalf("expected (nil, nil), got (%+v, %v)", got, err)+ }+ })++ t.Run("matching daemon returns assignment", func(t *testing.T) {+ got, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: tmp, DaemonID: thisDaemon})},+ }, thisDaemon)+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if got == nil {+ t.Fatalf("expected assignment, got nil")+ }+ if got.AbsPath != filepath.Clean(tmp) {+ t.Errorf("AbsPath = %q, want %q", got.AbsPath, filepath.Clean(tmp))+ }+ if got.RealPath == "" {+ t.Errorf("RealPath empty")+ }+ })++ t.Run("missing daemon_id is rejected", func(t *testing.T) {+ _, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: tmp})},+ }, thisDaemon)+ if err == nil {+ t.Fatalf("expected error for missing daemon_id")+ }+ })++ t.Run("relative path is rejected", func(t *testing.T) {+ _, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: "relative/path", DaemonID: thisDaemon})},+ }, thisDaemon)+ if err == nil {+ t.Fatalf("expected error for relative path")+ }+ })++ t.Run("malformed ref json fails", func(t *testing.T) {+ _, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: json.RawMessage(`{not json`)},+ }, thisDaemon)+ if err == nil {+ t.Fatalf("expected error for malformed json")+ }+ })++ t.Run("two local_directory rows on this daemon fail fast", func(t *testing.T) {+ // Server-side findLocalDirectoryConflict enforces one+ // local_directory per (project, daemon). If two rows are+ // somehow present (older API client, direct DB writes), the+ // daemon must refuse to guess which directory to execute in.+ tmp2 := t.TempDir()+ _, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: tmp, DaemonID: thisDaemon})},+ {ID: "r2", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: tmp2, DaemonID: thisDaemon})},+ }, thisDaemon)+ if err == nil {+ t.Fatalf("expected error for two local_directory rows pinned to this daemon")+ }+ if !strings.Contains(err.Error(), "multiple local_directory") {+ t.Errorf("error %q did not mention multiple local_directory", err)+ }+ })++ t.Run("local_directory rows on different daemons coexist", func(t *testing.T) {+ // Different daemons MAY each carry one row — same path on+ // different machines is allowed; this daemon only resolves+ // its own row regardless of how many other-daemon rows are+ // in the list.+ got, err := findLocalDirectoryAssignment([]ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: tmp, DaemonID: thisDaemon})},+ {ID: "r2", ResourceType: localDirectoryResourceType, ResourceRef: mkRef(t, localDirectoryRef{LocalPath: tmp, DaemonID: otherDaemon})},+ }, thisDaemon)+ if err != nil {+ t.Fatalf("err: %v", err)+ }+ if got == nil {+ t.Fatalf("expected assignment, got nil")+ }+ })+}++func TestValidateLocalPath(t *testing.T) {+ if runtime.GOOS == "windows" {+ t.Skip("blacklist constants are POSIX-only in this test")+ }++ dir := t.TempDir()++ t.Run("accepts a writable directory", func(t *testing.T) {+ if err := validateLocalPath(dir); err != nil {+ t.Errorf("unexpected: %v", err)+ }+ })++ t.Run("rejects relative path", func(t *testing.T) {+ if err := validateLocalPath("relative"); err == nil {+ t.Errorf("expected error")+ }+ })++ t.Run("rejects empty path", func(t *testing.T) {+ if err := validateLocalPath(""); err == nil {+ t.Errorf("expected error")+ }+ })++ t.Run("rejects system roots", func(t *testing.T) {+ for _, banned := range []string{"/", "/Users", "/home"} {+ if err := validateLocalPath(banned); err == nil {+ t.Errorf("expected error for %q", banned)+ }+ }+ })++ t.Run("rejects the user home directory", func(t *testing.T) {+ home, err := os.UserHomeDir()+ if err != nil || home == "" {+ t.Skip("no home dir")+ }+ if err := validateLocalPath(home); err == nil {+ t.Errorf("expected error for $HOME")+ }+ })++ t.Run("rejects missing path", func(t *testing.T) {+ missing := filepath.Join(dir, "does-not-exist")+ if err := validateLocalPath(missing); err == nil {+ t.Errorf("expected error")+ }+ })++ t.Run("rejects a regular file", func(t *testing.T) {+ f := filepath.Join(dir, "afile")+ if err := os.WriteFile(f, []byte("hi"), 0o644); err != nil {+ t.Fatalf("write: %v", err)+ }+ if err := validateLocalPath(f); err == nil {+ t.Errorf("expected error")+ }+ })++ t.Run("rejects an unwritable directory", func(t *testing.T) {+ // chmod-based unwritable is unreliable as root; skip when uid==0.+ if os.Getuid() == 0 {+ t.Skip("test cannot run as root; chmod is a no-op")+ }+ ro := filepath.Join(dir, "ro")+ if err := os.Mkdir(ro, 0o555); err != nil {+ t.Fatalf("mkdir: %v", err)+ }+ t.Cleanup(func() { _ = os.Chmod(ro, 0o755) })+ if err := validateLocalPath(ro); err == nil {+ t.Errorf("expected error for read-only directory")+ }+ })++ t.Run("rejects a symlink pointing at the user home", func(t *testing.T) {+ home, err := os.UserHomeDir()+ if err != nil || home == "" {+ t.Skip("no home dir")+ }+ link := filepath.Join(dir, "home-link")+ if err := os.Symlink(home, link); err != nil {+ t.Fatalf("symlink: %v", err)+ }+ // The literal cleaned path is dir/home-link, which is NOT in the+ // blacklist. Without the realpath check this used to pass.+ err = validateLocalPath(link)+ if err == nil {+ t.Fatal("expected error for symlink pointing at $HOME")+ }+ if !strings.Contains(err.Error(), "user's home directory") {+ t.Errorf("error %q did not flag the home-dir reason", err.Error())+ }+ })++ t.Run("rejects a symlink pointing at a system root", func(t *testing.T) {+ link := filepath.Join(dir, "root-link")+ // Pick a banned system root that's predictably present on the+ // host. /Users on macOS; /home on Linux. Fall back to /etc which+ // is in the blacklist and exists on both.+ target := "/etc"+ if err := os.Symlink(target, link); err != nil {+ t.Fatalf("symlink: %v", err)+ }+ err := validateLocalPath(link)+ if err == nil {+ t.Fatal("expected error for symlink pointing at a system root")+ }+ if !strings.Contains(err.Error(), "protected system root") {+ t.Errorf("error %q did not flag the system-root reason", err.Error())+ }+ })++ t.Run("accepts a symlink to a non-blacklisted directory", func(t *testing.T) {+ target := filepath.Join(dir, "real-proj")+ if err := os.Mkdir(target, 0o755); err != nil {+ t.Fatalf("mkdir: %v", err)+ }+ link := filepath.Join(dir, "proj-link")+ if err := os.Symlink(target, link); err != nil {+ t.Fatalf("symlink: %v", err)+ }+ if err := validateLocalPath(link); err != nil {+ t.Errorf("symlink to a regular directory should pass, got %v", err)+ }+ })++ // macOS aliases /tmp, /etc, /var to /private/{tmp,etc,var} via OS-level+ // symlinks. A user typing the canonical /private/... form in the picker+ // would pass the literal blacklist (it doesn't contain /private/tmp)+ // and EvalSymlinks would be a no-op (the input is already canonical),+ // so the old "only re-check when realPath != absPath" gate skipped it.+ // Cover the regression so the realpath blacklist always runs.+ t.Run("rejects canonical macOS /private/{tmp,etc,var}", func(t *testing.T) {+ if runtime.GOOS != "darwin" {+ t.Skip("macOS-only: /private/* aliases don't exist elsewhere")+ }+ for _, p := range []string{"/private/tmp", "/private/etc", "/private/var"} {+ if _, statErr := os.Stat(p); statErr != nil {+ t.Logf("skipping %q: %v", p, statErr)+ continue+ }+ err := validateLocalPath(p)+ if err == nil {+ t.Errorf("expected error for canonical %q", p)+ continue+ }+ if !strings.Contains(err.Error(), "protected system root") {+ t.Errorf("error %q for %q did not flag the system-root reason", err.Error(), p)+ }+ }+ })++}++// TestIsDriveRoot covers the Windows drive-root generalisation. Static+// enumeration in the old blacklist (C..F) missed mounts at G:\ and up; the+// new check goes through filepath.VolumeName so any drive letter (and UNC+// roots) is rejected.+func TestIsDriveRoot(t *testing.T) {+ if runtime.GOOS != "windows" {+ // filepath.VolumeName returns "" on POSIX, so isDriveRoot always+ // returns false off Windows. The semantic contract is enforced by+ // the early `runtime.GOOS != "windows"` guard; the case table+ // below is only meaningful on a Windows runner.+ t.Skip("windows-only behaviour")+ }+ cases := []struct {+ p string+ want bool+ }{+ {`C:\`, true},+ {`G:\`, true},+ {`Z:\`, true},+ {`C:/`, true},+ {`C:`, true},+ {`\\srv\share`, true},+ {`\\srv\share\`, true},+ {`C:\Users`, false},+ {`D:\proj`, false},+ {`C:\Users\me\code`, false},+ }+ for _, c := range cases {+ if got := isDriveRoot(c.p); got != c.want {+ t.Errorf("isDriveRoot(%q) = %v, want %v", c.p, got, c.want)+ }+ }+}++func TestLocalPathLockerSerializes(t *testing.T) {+ locker := NewLocalPathLocker()+ const path = "/some/path"++ rel1, err := locker.Acquire(context.Background(), path, "task-1", nil)+ if err != nil {+ t.Fatalf("acquire 1: %v", err)+ }+ if got := locker.Holder(path); got != "task-1" {+ t.Errorf("holder = %q, want task-1", got)+ }++ // task-2 must wait, with onWait fired and the holder reported.+ var waitCalls atomic.Int32+ var sawHolder atomic.Value+ done := make(chan error, 1)+ go func() {+ rel, err := locker.Acquire(context.Background(), path, "task-2", func(holder string) {+ waitCalls.Add(1)+ sawHolder.Store(holder)+ })+ if err != nil {+ done <- err+ return+ }+ if got := locker.Holder(path); got != "task-2" {+ done <- errorsNew("holder after handover = " + got)+ return+ }+ rel()+ done <- nil+ }()++ // give the goroutine time to enter the wait+ deadline := time.Now().Add(time.Second)+ for time.Now().Before(deadline) && waitCalls.Load() == 0 {+ time.Sleep(5 * time.Millisecond)+ }+ if waitCalls.Load() != 1 {+ t.Fatalf("onWait calls = %d, want 1", waitCalls.Load())+ }+ if got := sawHolder.Load(); got != "task-1" {+ t.Errorf("onWait holder = %v, want task-1", got)+ }++ rel1()+ select {+ case err := <-done:+ if err != nil {+ t.Fatalf("waiter result: %v", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("waiter never woke")+ }+ if got := locker.Holder(path); got != "" {+ t.Errorf("holder after release = %q, want empty", got)+ }+}++func TestLocalPathLockerCtxCancel(t *testing.T) {+ locker := NewLocalPathLocker()+ const path = "/some/path"++ rel1, err := locker.Acquire(context.Background(), path, "task-1", nil)+ if err != nil {+ t.Fatalf("acquire 1: %v", err)+ }+ defer rel1()++ ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)+ defer cancel()++ _, err = locker.Acquire(ctx, path, "task-2", nil)+ if err == nil {+ t.Fatalf("expected ctx error, got nil")+ }+ if !errors.Is(err, context.DeadlineExceeded) {+ t.Fatalf("err = %v, want DeadlineExceeded", err)+ }+}++func TestLocalPathLockerDistinctPathsParallel(t *testing.T) {+ locker := NewLocalPathLocker()++ rel1, err := locker.Acquire(context.Background(), "/a", "task-1", nil)+ if err != nil {+ t.Fatalf("acquire 1: %v", err)+ }+ defer rel1()++ // Different path must not block.+ done := make(chan struct{})+ var wg sync.WaitGroup+ wg.Add(1)+ go func() {+ defer wg.Done()+ rel2, err := locker.Acquire(context.Background(), "/b", "task-2", nil)+ if err != nil {+ t.Errorf("acquire 2: %v", err)+ return+ }+ rel2()+ close(done)+ }()+ select {+ case <-done:+ case <-time.After(time.Second):+ t.Fatal("acquire on distinct path blocked")+ }+ wg.Wait()+}++// errorsNew is a tiny helper so the goroutine above can return a typed error+// without importing errors / fmt at the call site.+func errorsNew(msg string) error { return &waiterError{msg: msg} }++type waiterError struct{ msg string }++func (e *waiterError) Error() string { return e.msg }++// TestAcquireLocalDirectoryLock_CancelDuringWait covers the gap between+// dispatch and StartTask: while the path mutex is contended, the main+// per-task cancellation watcher hasn't started yet. If the issue is+// cancelled (or the task row is reassigned / deleted) during the wait,+// the daemon must notice promptly and bail — otherwise the slot stays+// pinned by a phantom waiter for the full lifetime of the holder.+func TestAcquireLocalDirectoryLock_CancelDuringWait(t *testing.T) {+ t.Parallel()++ dir := t.TempDir() // valid, writable, non-blacklisted+ // Pre-claim must use the same key the production path computes, which+ // is the symlink-resolved realpath. On macOS, /tmp/... resolves to+ // /private/tmp/..., so a literal preclaim with `dir` would miss the+ // production key and the new acquire would win on the fast path.+ realDir, err := filepath.EvalSymlinks(dir)+ if err != nil {+ t.Fatalf("evalsymlinks: %v", err)+ }++ // Server-side state for the fake. Mark the task cancelled only after+ // we've seen the daemon call wait-local-directory, so the test can+ // assert the watcher reacted to the post-park cancel rather than+ // reading stale state on the very first poll.+ var (+ parked atomic.Bool+ waitCall atomic.Int32+ )+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ switch {+ case strings.HasSuffix(r.URL.Path, "/wait-local-directory"):+ waitCall.Add(1)+ parked.Store(true)+ w.WriteHeader(http.StatusOK)+ case strings.HasSuffix(r.URL.Path, "/status"):+ w.Header().Set("Content-Type", "application/json")+ if parked.Load() {+ _, _ = w.Write([]byte(`{"status":"cancelled"}`))+ } else {+ _, _ = w.Write([]byte(`{"status":"running"}`))+ }+ default:+ // We don't expect /fail in the cancel path — assert that+ // by failing loud if it gets called.+ t.Errorf("unexpected daemon call: %s %s", r.Method, r.URL.Path)+ w.WriteHeader(http.StatusOK)+ }+ }))+ t.Cleanup(srv.Close)++ const daemonID = "d-test"+ const heldByTaskID = "task-holder"+ const newTaskID = "task-waiter"++ locker := NewLocalPathLocker()+ // Pre-claim the lock so the new task has to wait. Use the resolved+ // realpath as the key to match findLocalDirectoryAssignment.+ release, err := locker.Acquire(context.Background(), realDir, heldByTaskID, nil)+ if err != nil {+ t.Fatalf("preclaim acquire: %v", err)+ }+ t.Cleanup(release)++ d := &Daemon{+ client: NewClient(srv.URL),+ logger: slog.Default(),+ localPathLocks: locker,+ cancelPollInterval: 10 * time.Millisecond,+ cfg: Config{DaemonID: daemonID},+ }++ ref, err := json.Marshal(localDirectoryRef{LocalPath: dir, DaemonID: daemonID})+ if err != nil {+ t.Fatalf("marshal ref: %v", err)+ }+ task := Task{+ ID: newTaskID,+ ProjectResources: []ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: ref},+ },+ }++ type result struct {+ release func()+ abort bool+ }+ done := make(chan result, 1)+ go func() {+ rel, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), task, slog.Default())+ done <- result{release: rel, abort: abort}+ }()++ select {+ case got := <-done:+ if !got.abort {+ t.Fatal("expected abort=true after server-side cancel, got abort=false")+ }+ if got.release != nil {+ t.Fatal("expected nil release on cancel, got a non-nil callback")+ }+ case <-time.After(2 * time.Second):+ t.Fatal("acquireLocalDirectoryLockIfNeeded blocked past 2s — cancel was not observed during wait")+ }++ if got := waitCall.Load(); got != 1 {+ t.Errorf("wait-local-directory calls = %d, want 1", got)+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 6883ff1bcd..ccb1d3f657 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1617,6 +1617,45 @@ func (h *Handler) StartTask(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, taskToResponse(*task))}+// TaskWaitLocalDirectoryRequest is the body the daemon POSTs when it parks+// a freshly-dispatched task on a busy local_directory path.+type TaskWaitLocalDirectoryRequest struct {+ // Reason is a short hint surfaced by the UI alongside the status —+ // typically "<path>" or "<path> (holder: <task short id>)". Small+ // enough to fit on the issue card. Empty is accepted; the column is+ // nullable on the server.+ Reason string `json:"reason"`+}++// MarkTaskWaitingLocalDirectory transitions a dispatched task to+// waiting_local_directory. Called by the daemon when, after claiming a task+// whose project carries a local_directory resource, it discovers another+// in-flight task already holds the path's mutex.+func (h *Handler) MarkTaskWaitingLocalDirectory(w http.ResponseWriter, r *http.Request) {+ taskID := chi.URLParam(r, "taskId")++ if _, ok := h.requireDaemonTaskAccess(w, r, taskID); !ok {+ return+ }++ var req TaskWaitLocalDirectoryRequest+ if r.ContentLength != 0 {+ if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }+ }++ task, err := h.TaskService.MarkTaskWaitingLocalDirectory(r.Context(), parseUUID(taskID), req.Reason)+ if err != nil {+ slog.Warn("mark task waiting_local_directory failed", "task_id", taskID, "error", err)+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }++ writeJSON(w, http.StatusOK, taskToResponse(*task))+}+// ReportTaskProgress broadcasts a progress update.type TaskProgressRequest struct {Summary string `json:"summary"`diff --git a/server/internal/handler/project.go b/server/internal/handler/project.goindex 2522c4f88f..04611a8f2f 100644--- a/server/internal/handler/project.go+++ b/server/internal/handler/project.go@@ -223,8 +223,15 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {}// Pre-validate every resource payload before opening a transaction so an- // invalid ref produces a clean 400 with no DB work.+ // invalid ref produces a clean 400 with no DB work. For local_directory we+ // also enforce one row per daemon_id within the batch — the daemon-side+ // resolver picks the first match by daemon_id, so two rows on the same+ // daemon would silently route the agent into whichever sorts first.+ // The standalone POST/PUT paths run the same check via+ // findLocalDirectoryConflict; this loop just covers the bundled-create+ // surface, where there is no existing row to compare against yet.normalizedRefs := make([]json.RawMessage, len(req.Resources))+ localDirSeen := map[string]int{}for i, res := range req.Resources {res.ResourceType = strings.TrimSpace(res.ResourceType)if res.ResourceType == "" {@@ -237,6 +244,18 @@ func (h *Handler) CreateProject(w http.ResponseWriter, r *http.Request) {return}normalizedRefs[i] = ref+ if res.ResourceType == "local_directory" {+ var ld localDirectoryRef+ if err := json.Unmarshal(ref, &ld); err != nil {+ writeError(w, http.StatusBadRequest, "resources["+strconv.Itoa(i)+"]: "+err.Error())+ return+ }+ if prev, ok := localDirSeen[ld.DaemonID]; ok {+ writeError(w, http.StatusBadRequest, "resources["+strconv.Itoa(i)+"]: duplicate local_directory for daemon (already at index "+strconv.Itoa(prev)+"); each daemon may attach at most one local_directory per project")+ return+ }+ localDirSeen[ld.DaemonID] = i+ }}createParams := db.CreateProjectParams{diff --git a/server/internal/handler/project_resource.go b/server/internal/handler/project_resource.goindex a5b58583f5..54a4d9968c 100644--- a/server/internal/handler/project_resource.go+++ b/server/internal/handler/project_resource.go@@ -54,6 +54,15 @@ type CreateProjectResourceRequest struct {Position *int32 `json:"position"`}+// UpdateProjectResourceRequest is the body for PUT /api/projects/{id}/resources/{resourceId}.+// resource_type cannot change after creation — pick a new type by deleting and+// re-adding. Every field is optional; omitted fields keep their current value.+type UpdateProjectResourceRequest struct {+ ResourceRef json.RawMessage `json:"resource_ref"`+ Label *string `json:"label"`+ Position *int32 `json:"position"`+}+// validateAndNormalizeResourceRef checks the payload for a known resource_type.// New types are added here without schema migration; unknown types are rejected// at the API boundary so a typo can't slip through and produce a resource the@@ -65,14 +74,16 @@ func validateAndNormalizeResourceRef(resourceType string, ref json.RawMessage) (switch resourceType {case "github_repo":return validateGithubRepoRef(ref)+ case "local_directory":+ return validateLocalDirectoryRef(ref)default:return nil, fmt.Errorf("unknown resource_type %q", resourceType)}}type githubRepoRef struct {- URL string `json:"url"`- DefaultBranchHint string `json:"default_branch_hint,omitempty"`+ URL string `json:"url"`+ DefaultBranchHint string `json:"default_branch_hint,omitempty"`}func validateGithubRepoRef(ref json.RawMessage) (json.RawMessage, error) {@@ -95,6 +106,68 @@ func validateGithubRepoRef(ref json.RawMessage) (json.RawMessage, error) {return out, nil}+// localDirectoryRef is the JSONB shape stored for resource_type=local_directory.+// It pins a project to an existing directory on a specific user machine, so+// agent tasks run in-place rather than in an isolated git worktree. The+// daemon_id scopes the path to one daemon registration — the same string path+// on a different machine is a different resource. The optional label is a+// human-readable hint used by the UI; the row-level project_resource.label+// column remains the generic column for any resource type.+type localDirectoryRef struct {+ LocalPath string `json:"local_path"`+ DaemonID string `json:"daemon_id"`+ Label string `json:"label,omitempty"`+}++func validateLocalDirectoryRef(ref json.RawMessage) (json.RawMessage, error) {+ var payload localDirectoryRef+ if err := json.Unmarshal(ref, &payload); err != nil {+ return nil, fmt.Errorf("invalid local_directory payload: %w", err)+ }+ payload.LocalPath = strings.TrimSpace(payload.LocalPath)+ if payload.LocalPath == "" {+ return nil, errors.New("local_directory: local_path is required")+ }+ if !isAbsoluteLocalPath(payload.LocalPath) {+ return nil, errors.New("local_directory: local_path must be an absolute path")+ }+ payload.DaemonID = strings.TrimSpace(payload.DaemonID)+ if payload.DaemonID == "" {+ return nil, errors.New("local_directory: daemon_id is required")+ }+ payload.Label = strings.TrimSpace(payload.Label)+ out, err := json.Marshal(payload)+ if err != nil {+ return nil, err+ }+ return out, nil+}++// isAbsoluteLocalPath checks the path looks absolute on either POSIX or+// Windows daemons. The server can't know which OS the daemon runs on, so we+// accept the union: a leading "/" (POSIX), a UNC prefix "\\", or a drive+// letter like "C:\" or "C:/". The daemon still verifies existence at run+// time — this is a typo guard, not a filesystem check.+func isAbsoluteLocalPath(s string) bool {+ if s == "" {+ return false+ }+ if s[0] == '/' {+ return true+ }+ if strings.HasPrefix(s, `\\`) {+ return true+ }+ if len(s) >= 3 && isDriveLetter(s[0]) && s[1] == ':' && (s[2] == '\\' || s[2] == '/') {+ return true+ }+ return false+}++func isDriveLetter(b byte) bool {+ return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')+}+// isValidGitRepoURL accepts the three forms a user can paste from GitHub's// "Code" menu: https://, ssh:// (with explicit scheme), and the scp-like// shorthand `git@host:owner/repo.git`. The check is intentionally lax — we are@@ -203,6 +276,14 @@ func (h *Handler) CreateProjectResource(w http.ResponseWriter, r *http.Request)return}+ if conflict, err := h.findLocalDirectoryConflict(r.Context(), project.ID, req.ResourceType, normalizedRef, pgtype.UUID{}); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check existing resources")+ return+ } else if conflict {+ writeError(w, http.StatusConflict, "this daemon already has a local_directory attached to the project; remove it before adding another")+ return+ }+var label pgtype.Textif req.Label != nil && strings.TrimSpace(*req.Label) != "" {label = pgtype.Text{String: strings.TrimSpace(*req.Label), Valid: true}@@ -246,6 +327,164 @@ func (h *Handler) CreateProjectResource(w http.ResponseWriter, r *http.Request)writeJSON(w, http.StatusCreated, resp)}+// UpdateProjectResource edits an existing resource's ref/label/position.+// resource_type is immutable — re-pointing a resource at a different type is+// almost always a different conceptual entity, so the caller should delete and+// re-add instead. Omitted fields keep their current value, including the+// `label` JSON null vs. missing distinction (missing = keep, explicit "" =+// clear).+func (h *Handler) UpdateProjectResource(w http.ResponseWriter, r *http.Request) {+ project, ok := h.loadProjectForResource(w, r, chi.URLParam(r, "id"))+ if !ok {+ return+ }+ resourceUUID, ok := parseUUIDOrBadRequest(w, chi.URLParam(r, "resourceId"), "resource id")+ if !ok {+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }++ existing, err := h.Queries.GetProjectResourceInWorkspace(r.Context(), db.GetProjectResourceInWorkspaceParams{+ ID: resourceUUID, WorkspaceID: project.WorkspaceID,+ })+ if err != nil {+ writeError(w, http.StatusNotFound, "project resource not found")+ return+ }+ if uuidToString(existing.ProjectID) != uuidToString(project.ID) {+ writeError(w, http.StatusNotFound, "project resource not found")+ return+ }++ // Decode into a raw map first so we can tell "field omitted" from+ // "field present with zero value" — the label clear case in particular+ // relies on this distinction.+ var raw map[string]json.RawMessage+ if err := json.NewDecoder(r.Body).Decode(&raw); err != nil {+ writeError(w, http.StatusBadRequest, "invalid request body")+ return+ }++ nextRef := json.RawMessage(existing.ResourceRef)+ if rawRef, ok := raw["resource_ref"]; ok {+ normalized, err := validateAndNormalizeResourceRef(existing.ResourceType, rawRef)+ if err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }+ nextRef = normalized+ }++ if conflict, err := h.findLocalDirectoryConflict(r.Context(), project.ID, existing.ResourceType, nextRef, existing.ID); err != nil {+ writeError(w, http.StatusInternalServerError, "failed to check existing resources")+ return+ } else if conflict {+ writeError(w, http.StatusConflict, "another local_directory on this daemon is already attached to the project")+ return+ }++ nextLabel := existing.Label+ if rawLabel, ok := raw["label"]; ok {+ var labelStr *string+ if err := json.Unmarshal(rawLabel, &labelStr); err != nil {+ writeError(w, http.StatusBadRequest, "label must be a string or null")+ return+ }+ if labelStr == nil || strings.TrimSpace(*labelStr) == "" {+ nextLabel = pgtype.Text{}+ } else {+ nextLabel = pgtype.Text{String: strings.TrimSpace(*labelStr), Valid: true}+ }+ }++ nextPosition := existing.Position+ if rawPos, ok := raw["position"]; ok {+ var pos *int32+ if err := json.Unmarshal(rawPos, &pos); err != nil {+ writeError(w, http.StatusBadRequest, "position must be an integer")+ return+ }+ if pos != nil {+ nextPosition = *pos+ }+ }++ updated, err := h.Queries.UpdateProjectResource(r.Context(), db.UpdateProjectResourceParams{+ ID: existing.ID,+ ResourceRef: nextRef,+ Label: nextLabel,+ Position: nextPosition,+ })+ if err != nil {+ if isUniqueViolation(err) {+ writeError(w, http.StatusConflict, "this resource is already attached to the project")+ return+ }+ writeError(w, http.StatusInternalServerError, "failed to update project resource")+ return+ }++ resp := projectResourceToResponse(updated)+ h.publish(+ protocol.EventProjectResourceUpdated,+ uuidToString(project.WorkspaceID),+ "member",+ userID,+ map[string]any{"resource": resp, "project_id": uuidToString(project.ID)},+ )+ writeJSON(w, http.StatusOK, resp)+}++// findLocalDirectoryConflict enforces "at most one local_directory resource+// per (project, daemon)". The daemon picks the first matching daemon_id row+// out of a task's resources (findLocalDirectoryAssignment), so letting a+// project carry two rows for the same daemon would mean the agent silently+// writes into whichever happens to come back first — a safety hazard for a+// feature that operates directly on the user's real working directory.+//+// The DB-level UNIQUE(project_id, resource_type, resource_ref) constraint+// alone is not enough here: it only fires on full ref-JSON equality, so a+// different local_path or even a typoed label on the same daemon would slip+// through. We do the daemon-scoped check here in application code instead.+//+// `excludeID` lets the update path ignore the row being edited.+func (h *Handler) findLocalDirectoryConflict(ctx context.Context, projectID pgtype.UUID, resourceType string, normalizedRef json.RawMessage, excludeID pgtype.UUID) (bool, error) {+ if resourceType != "local_directory" {+ return false, nil+ }+ var incoming localDirectoryRef+ if err := json.Unmarshal(normalizedRef, &incoming); err != nil {+ return false, err+ }+ rows, err := h.Queries.ListProjectResources(ctx, projectID)+ if err != nil {+ return false, err+ }+ for _, row := range rows {+ if row.ResourceType != "local_directory" {+ continue+ }+ if excludeID.Valid && uuidToString(row.ID) == uuidToString(excludeID) {+ continue+ }+ var existing localDirectoryRef+ if err := json.Unmarshal(row.ResourceRef, &existing); err != nil {+ continue+ }+ // Daemon-scoped uniqueness: one local_directory per daemon per+ // project. Different daemons can each carry one row (one per+ // user device); the daemon-side resolver routes each daemon to+ // its own assignment by daemon_id.+ if existing.DaemonID == incoming.DaemonID {+ return true, nil+ }+ }+ return false, nil+}+// DeleteProjectResource removes a resource from a project.func (h *Handler) DeleteProjectResource(w http.ResponseWriter, r *http.Request) {project, ok := h.loadProjectForResource(w, r, chi.URLParam(r, "id"))diff --git a/server/internal/handler/project_resource_test.go b/server/internal/handler/project_resource_test.goindex bcb06d2b2e..68bd5b1d92 100644--- a/server/internal/handler/project_resource_test.go+++ b/server/internal/handler/project_resource_test.go@@ -215,9 +215,9 @@ func TestIsValidGitRepoURL(t *testing.T) {"ftp://example.com/repo", // unsupported scheme"file:///tmp/repo", // unsupported scheme"some random text with spaces",- "github.com:org/repo@branch", // '@' after ':' belongs to the path, not user- "foo:bar@baz", // '@' after ':' with no scheme- ":foo/bar", // leading ':' with no host+ "github.com:org/repo@branch", // '@' after ':' belongs to the path, not user+ "foo:bar@baz", // '@' after ':' with no scheme+ ":foo/bar", // leading ':' with no host}for _, s := range good {if !isValidGitRepoURL(s) {@@ -231,6 +231,227 @@ func TestIsValidGitRepoURL(t *testing.T) {}}+// TestProjectResourceLocalDirectoryLifecycle covers the full CRUD path for the+// local_directory resource type added in MUL-2662. Unlike github_repo, the+// ref schema requires local_path + daemon_id and forbids any path that isn't+// absolute. Two project-scoped resources pointing at the same daemon_id /+// local_path on different projects must be allowed — Bohan explicitly chose+// not to add a UNIQUE(daemon_id, local_path) constraint.+func TestProjectResourceLocalDirectoryLifecycle(t *testing.T) {+ createProject := func(title string) ProjectResponse {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": title,+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProject(%s): %d %s", title, w.Code, w.Body.String())+ }+ var p ProjectResponse+ if err := json.NewDecoder(w.Body).Decode(&p); err != nil {+ t.Fatalf("decode CreateProject: %v", err)+ }+ return p+ }+ deleteProject := func(id string) {+ r := newRequest("DELETE", "/api/projects/"+id, nil)+ r = withURLParam(r, "id", id)+ testHandler.DeleteProject(httptest.NewRecorder(), r)+ }++ projectA := createProject("Local directory project A")+ defer deleteProject(projectA.ID)+ projectB := createProject("Local directory project B")+ defer deleteProject(projectB.ID)++ const (+ daemonID = "daemon-aaaa-bbbb-cccc"+ localPath = "/Users/foo/work/my-game"+ )++ // Happy path: attach local_directory resource with label.+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects/"+projectA.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": daemonID,+ "label": "Game Repo",+ },+ })+ req = withURLParam(req, "id", projectA.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProjectResource: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var created ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {+ t.Fatalf("decode CreateProjectResource: %v", err)+ }+ if created.ResourceType != "local_directory" {+ t.Errorf("ResourceType = %q, want local_directory", created.ResourceType)+ }+ var ref struct {+ LocalPath string `json:"local_path"`+ DaemonID string `json:"daemon_id"`+ Label string `json:"label"`+ }+ if err := json.Unmarshal(created.ResourceRef, &ref); err != nil {+ t.Fatalf("decode resource_ref: %v", err)+ }+ if ref.LocalPath != localPath || ref.DaemonID != daemonID || ref.Label != "Game Repo" {+ t.Errorf("ref = %+v, want {%q, %q, Game Repo}", ref, localPath, daemonID)+ }++ // Listing must include the new resource.+ w = httptest.NewRecorder()+ req = newRequest("GET", "/api/projects/"+projectA.ID+"/resources", nil)+ req = withURLParam(req, "id", projectA.ID)+ testHandler.ListProjectResources(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ListProjectResources: %d %s", w.Code, w.Body.String())+ }+ var listResp struct {+ Resources []ProjectResourceResponse `json:"resources"`+ Total int `json:"total"`+ }+ if err := json.NewDecoder(w.Body).Decode(&listResp); err != nil {+ t.Fatalf("decode list: %v", err)+ }+ if listResp.Total != 1 || listResp.Resources[0].ID != created.ID {+ t.Fatalf("list mismatch: %+v", listResp)+ }++ // Same (daemon_id, local_path) on a different project must succeed —+ // the design explicitly allows the same directory to back multiple+ // projects, contrast with github_repo's per-project UNIQUE check.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+projectB.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": daemonID,+ },+ })+ req = withURLParam(req, "id", projectB.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("same path on project B: expected 201, got %d: %s", w.Code, w.Body.String())+ }++ // Duplicate attach on the same project must still conflict — the+ // UNIQUE(project_id, resource_type, resource_ref) row constraint+ // remains in effect.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+projectA.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": daemonID,+ "label": "Game Repo",+ },+ })+ req = withURLParam(req, "id", projectA.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusConflict {+ t.Errorf("duplicate on same project: expected 409, got %d: %s", w.Code, w.Body.String())+ }++ // Delete the resource on project A.+ w = httptest.NewRecorder()+ req = newRequest("DELETE", "/api/projects/"+projectA.ID+"/resources/"+created.ID, nil)+ req = withURLParams(req, "id", projectA.ID, "resourceId", created.ID)+ testHandler.DeleteProjectResource(w, req)+ if w.Code != http.StatusNoContent {+ t.Fatalf("DeleteProjectResource: expected 204, got %d: %s", w.Code, w.Body.String())+ }+}++// TestProjectResourceLocalDirectoryValidation pins the schema rejection+// surface for local_directory: missing path, missing daemon, relative paths,+// and malformed JSON must all return 400. These are the only client-visible+// errors agents will hit, so freezing them as tests prevents accidental+// loosening when someone touches the validator.+func TestProjectResourceLocalDirectoryValidation(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Local directory validation",+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProject: %d %s", w.Code, w.Body.String())+ }+ var project ProjectResponse+ if err := json.NewDecoder(w.Body).Decode(&project); err != nil {+ t.Fatalf("decode CreateProject: %v", err)+ }+ defer func() {+ r := newRequest("DELETE", "/api/projects/"+project.ID, nil)+ r = withURLParam(r, "id", project.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), r)+ }()++ cases := []struct {+ name string+ ref any+ }{+ {"missing local_path", map[string]any{"daemon_id": "d1"}},+ {"blank local_path", map[string]any{"local_path": " ", "daemon_id": "d1"}},+ {"relative local_path", map[string]any{"local_path": "work/my-game", "daemon_id": "d1"}},+ {"home-shorthand path", map[string]any{"local_path": "~/work/my-game", "daemon_id": "d1"}},+ {"missing daemon_id", map[string]any{"local_path": "/Users/foo/work"}},+ {"blank daemon_id", map[string]any{"local_path": "/Users/foo/work", "daemon_id": ""}},+ {"wrong type in payload", map[string]any{"local_path": 42, "daemon_id": "d1"}},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": tc.ref,+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusBadRequest {+ t.Errorf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ })+ }+}++func TestIsAbsoluteLocalPath(t *testing.T) {+ good := []string{+ "/Users/foo/work",+ "/",+ "/a",+ `C:\Users\foo`,+ `C:/Users/foo`,+ `d:\code\repo`,+ `\\server\share\path`,+ }+ bad := []string{+ "",+ "work/my-game",+ "./relative",+ "../relative",+ "~/work",+ "C:relative",+ "C:",+ `\foo`,+ "file:///tmp",+ }+ for _, s := range good {+ if !isAbsoluteLocalPath(s) {+ t.Errorf("isAbsoluteLocalPath(%q) = false, want true", s)+ }+ }+ for _, s := range bad {+ if isAbsoluteLocalPath(s) {+ t.Errorf("isAbsoluteLocalPath(%q) = true, want false", s)+ }+ }+}+func TestCreateProjectAttachesResources(t *testing.T) {w := httptest.NewRecorder()req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{@@ -438,3 +659,409 @@ func TestCreateProjectRollsBackOnInvalidResource(t *testing.T) {}}+// TestProjectResourceUpdateLifecycle covers the PUT endpoint added in MUL-2662:+// editing label / position / resource_ref independently must succeed, and a+// missing resource_type swap is enforced implicitly because the request body+// has no resource_type field.+func TestProjectResourceUpdateLifecycle(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Update lifecycle project",+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProject: %d %s", w.Code, w.Body.String())+ }+ var project ProjectResponse+ if err := json.NewDecoder(w.Body).Decode(&project); err != nil {+ t.Fatalf("decode CreateProject: %v", err)+ }+ defer func() {+ r := newRequest("DELETE", "/api/projects/"+project.ID, nil)+ r = withURLParam(r, "id", project.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), r)+ }()++ // Seed one local_directory resource we will mutate.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/a",+ "daemon_id": "d1",+ "label": "A",+ },+ "label": "outer",+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProjectResource: %d %s", w.Code, w.Body.String())+ }+ var created ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&created); err != nil {+ t.Fatalf("decode CreateProjectResource: %v", err)+ }++ // Update only the label; ref/position/type must stay untouched.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "label": "renamed",+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateProjectResource label-only: %d %s", w.Code, w.Body.String())+ }+ var updated ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {+ t.Fatalf("decode UpdateProjectResource: %v", err)+ }+ if updated.Label == nil || *updated.Label != "renamed" {+ t.Errorf("after label edit: label = %v, want renamed", updated.Label)+ }+ var ref localDirectoryRef+ if err := json.Unmarshal(updated.ResourceRef, &ref); err != nil {+ t.Fatalf("decode resource_ref: %v", err)+ }+ if ref.LocalPath != "/Users/foo/work/a" || ref.DaemonID != "d1" || ref.Label != "A" {+ t.Errorf("label-only update leaked into resource_ref: %+v", ref)+ }++ // Update the ref payload (move to a new daemon path) and bump position.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/b",+ "daemon_id": "d2",+ "label": "B",+ },+ "position": 5,+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateProjectResource ref+position: %d %s", w.Code, w.Body.String())+ }+ if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {+ t.Fatalf("decode UpdateProjectResource: %v", err)+ }+ if err := json.Unmarshal(updated.ResourceRef, &ref); err != nil {+ t.Fatalf("decode resource_ref: %v", err)+ }+ if ref.LocalPath != "/Users/foo/work/b" || ref.DaemonID != "d2" || ref.Label != "B" {+ t.Errorf("ref-update mismatch: %+v", ref)+ }+ if updated.Position != 5 {+ t.Errorf("position = %d, want 5", updated.Position)+ }+ if updated.Label == nil || *updated.Label != "renamed" {+ t.Errorf("label should survive ref edit, got %v", updated.Label)+ }++ // Explicit null clears the outer label.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "label": nil,+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("UpdateProjectResource label=null: %d %s", w.Code, w.Body.String())+ }+ if err := json.NewDecoder(w.Body).Decode(&updated); err != nil {+ t.Fatalf("decode UpdateProjectResource: %v", err)+ }+ if updated.Label != nil {+ t.Errorf("label should be cleared, got %v", *updated.Label)+ }++ // Bad ref payload must reject with 400 (relative path).+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+created.ID, map[string]any{+ "resource_ref": map[string]any{"local_path": "relative/path", "daemon_id": "d3"},+ })+ req = withURLParams(req, "id", project.ID, "resourceId", created.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusBadRequest {+ t.Errorf("relative path: expected 400, got %d: %s", w.Code, w.Body.String())+ }++ // Unknown resource id must 404.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/00000000-0000-0000-0000-000000000000", map[string]any{+ "label": "ghost",+ })+ req = withURLParams(req, "id", project.ID, "resourceId", "00000000-0000-0000-0000-000000000000")+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusNotFound {+ t.Errorf("missing resource: expected 404, got %d: %s", w.Code, w.Body.String())+ }+}++// TestProjectResourceLocalDirectoryDaemonScopedConflict pins the project-level+// conflict check for local_directory: one row per daemon per project. The+// daemon-side resolver picks the first match by daemon_id, so silently+// allowing two rows on the same daemon — even at distinct paths — would let+// the agent write into whichever sorts first. The DB UNIQUE constraint only+// catches identical ref JSON; this check covers the broader invariant.+func TestProjectResourceLocalDirectoryDaemonScopedConflict(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Local dir daemon-scoped conflict",+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("CreateProject: %d %s", w.Code, w.Body.String())+ }+ var project ProjectResponse+ if err := json.NewDecoder(w.Body).Decode(&project); err != nil {+ t.Fatalf("decode CreateProject: %v", err)+ }+ defer func() {+ r := newRequest("DELETE", "/api/projects/"+project.ID, nil)+ r = withURLParam(r, "id", project.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), r)+ }()++ const (+ daemonID = "d-scoped"+ otherDaemon = "d-other"+ localPath = "/Users/foo/work/scoped"+ )++ // First attach succeeds.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": daemonID,+ "label": "first",+ },+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("first attach: %d %s", w.Code, w.Body.String())+ }+ var first ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&first); err != nil {+ t.Fatalf("decode first: %v", err)+ }++ // Same (daemon_id, local_path) with a different label must 409 — the+ // embedded label is human metadata, not a discriminator.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": daemonID,+ "label": "different label",+ },+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusConflict {+ t.Errorf("same daemon same path create: expected 409, got %d: %s", w.Code, w.Body.String())+ }++ // A second row on the same daemon at a DIFFERENT path must also 409 —+ // the daemon-scoped invariant rejects more than one local_directory+ // per (project, daemon), even if the paths differ.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/other",+ "daemon_id": daemonID,+ "label": "other path",+ },+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusConflict {+ t.Errorf("same daemon different path create: expected 409, got %d: %s", w.Code, w.Body.String())+ }++ // Adding the same path on a DIFFERENT daemon is allowed — each daemon+ // gets to register exactly one local_directory.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects/"+project.ID+"/resources", map[string]any{+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": otherDaemon,+ "label": "other-machine",+ },+ })+ req = withURLParam(req, "id", project.ID)+ testHandler.CreateProjectResource(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("other daemon attach: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var second ProjectResourceResponse+ if err := json.NewDecoder(w.Body).Decode(&second); err != nil {+ t.Fatalf("decode other-daemon row: %v", err)+ }++ // An UPDATE that drives the other-daemon row onto the first daemon must+ // also 409 — the first daemon already has a registration.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+second.ID, map[string]any{+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": daemonID,+ "label": "fresh",+ },+ })+ req = withURLParams(req, "id", project.ID, "resourceId", second.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusConflict {+ t.Errorf("update onto existing daemon: expected 409, got %d: %s", w.Code, w.Body.String())+ }++ // Editing the same row in place (different label, same target) must+ // succeed — the conflict check ignores the row being updated.+ w = httptest.NewRecorder()+ req = newRequest("PUT", "/api/projects/"+project.ID+"/resources/"+first.ID, map[string]any{+ "resource_ref": map[string]any{+ "local_path": localPath,+ "daemon_id": daemonID,+ "label": "renamed inline",+ },+ })+ req = withURLParams(req, "id", project.ID, "resourceId", first.ID)+ testHandler.UpdateProjectResource(w, req)+ if w.Code != http.StatusOK {+ t.Errorf("in-place rename: expected 200, got %d: %s", w.Code, w.Body.String())+ }+}++// TestCreateProjectBundledLocalDirectoryDaemonConflict pins the second leg of+// the daemon-scoped invariant: a single POST /api/projects that bundles two+// local_directory resources on the same daemon — same path, same daemon+// with different labels, or different paths on the same daemon — must+// reject with 400 before any DB work.+func TestCreateProjectBundledLocalDirectoryDaemonConflict(t *testing.T) {+ w := httptest.NewRecorder()+ req := newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Bundled label shadow",+ "resources": []map[string]any{+ {+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/dup",+ "daemon_id": "d-bundle",+ "label": "first",+ },+ },+ {+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/dup",+ "daemon_id": "d-bundle",+ "label": "second label",+ },+ },+ },+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("bundled label shadow: expected 400, got %d: %s", w.Code, w.Body.String())+ }++ // Confirm the rollback: no project with the title should exist.+ w = httptest.NewRecorder()+ req = newRequest("GET", "/api/projects?workspace_id="+testWorkspaceID, nil)+ testHandler.ListProjects(w, req)+ if w.Code != http.StatusOK {+ t.Fatalf("ListProjects: %d %s", w.Code, w.Body.String())+ }+ var list struct {+ Projects []ProjectResponse `json:"projects"`+ }+ if err := json.NewDecoder(w.Body).Decode(&list); err != nil {+ t.Fatalf("decode list: %v", err)+ }+ for _, p := range list.Projects {+ if p.Title == "Bundled label shadow" {+ t.Errorf("expected no project to survive bundled-create rejection, but found %s", p.ID)+ }+ }++ // Two distinct paths on the same daemon must ALSO 400 — the invariant+ // is "one local_directory per (project, daemon)", not "one per (project,+ // daemon, path)".+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Bundled distinct paths same daemon",+ "resources": []map[string]any{+ {+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/a",+ "daemon_id": "d-bundle",+ "label": "A",+ },+ },+ {+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/b",+ "daemon_id": "d-bundle",+ "label": "B",+ },+ },+ },+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("distinct-paths same daemon bundle: expected 400, got %d: %s", w.Code, w.Body.String())+ }++ // A bundle with one row per daemon is allowed — each daemon owns its+ // own local_directory.+ w = httptest.NewRecorder()+ req = newRequest("POST", "/api/projects?workspace_id="+testWorkspaceID, map[string]any{+ "title": "Bundled per-daemon rows",+ "resources": []map[string]any{+ {+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/a",+ "daemon_id": "d-bundle-1",+ "label": "A",+ },+ },+ {+ "resource_type": "local_directory",+ "resource_ref": map[string]any{+ "local_path": "/Users/foo/work/b",+ "daemon_id": "d-bundle-2",+ "label": "B",+ },+ },+ },+ })+ testHandler.CreateProject(w, req)+ if w.Code != http.StatusCreated {+ t.Fatalf("per-daemon bundle: expected 201, got %d: %s", w.Code, w.Body.String())+ }+ var resp struct {+ ID string `json:"id"`+ Resources []ProjectResourceResponse `json:"resources"`+ }+ if err := json.NewDecoder(w.Body).Decode(&resp); err != nil {+ t.Fatalf("decode: %v", err)+ }+ defer func() {+ r := newRequest("DELETE", "/api/projects/"+resp.ID, nil)+ r = withURLParam(r, "id", resp.ID)+ testHandler.DeleteProject(httptest.NewRecorder(), r)+ }()+ if len(resp.Resources) != 2 {+ t.Errorf("per-daemon bundle: expected 2 resources, got %d", len(resp.Resources))+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex f1417f5946..5031b7b286 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -960,15 +960,40 @@ func (s *TaskService) StartTask(ctx context.Context, taskID pgtype.UUID) (*db.Agslog.Info("task started", "task_id", util.UUIDToString(task.ID), "issue_id", util.UUIDToString(task.IssueID))s.captureTaskStarted(ctx, task)// Tell every connected workspace WS client that this task transitioned- // dispatched → running. Without this, the workspace-wide- // `agentTaskSnapshot` query only refreshes on the 30s staleTime, so any- // UI that distinguishes "queued" from "running" (e.g. the issue-card- // agent activity indicator) lags by up to half a minute on the- // transition users care about most.+ // (dispatched | waiting_local_directory) → running. Without this, the+ // workspace-wide `agentTaskSnapshot` query only refreshes on the 30s+ // staleTime, so any UI that distinguishes "queued" from "running" (e.g.+ // the issue-card agent activity indicator) lags by up to half a minute+ // on the transition users care about most.s.broadcastTaskEvent(ctx, protocol.EventTaskRunning, task)return &task, nil}+// MarkTaskWaitingLocalDirectory parks a dispatched task in the+// waiting_local_directory state while the daemon waits for another in-flight+// task to release the project_resource path lock. reason carries a short+// human-readable hint (typically the contested path) that the UI surfaces+// next to the status. Returns the updated row so the daemon can confirm the+// transition and so the broadcast carries the up-to-date snapshot.+func (s *TaskService) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID pgtype.UUID, reason string) (*db.AgentTaskQueue, error) {+ reason = strings.TrimSpace(reason)+ task, err := s.Queries.MarkAgentTaskWaitingLocalDirectory(ctx, db.MarkAgentTaskWaitingLocalDirectoryParams{+ ID: taskID,+ WaitReason: pgtype.Text{String: reason, Valid: reason != ""},+ })+ if err != nil {+ return nil, fmt.Errorf("mark task waiting_local_directory: %w", err)+ }++ slog.Info("task waiting_local_directory",+ "task_id", util.UUIDToString(task.ID),+ "issue_id", util.UUIDToString(task.IssueID),+ "reason", reason,+ )+ s.broadcastTaskEvent(ctx, protocol.EventTaskWaitingLocalDirectory, task)+ return &task, nil+}+// CompleteTask marks a task as completed.// Issue status is NOT changed here — the agent manages it via the CLI.//diff --git a/server/migrations/109_agent_task_waiting_local_directory.down.sql b/server/migrations/109_agent_task_waiting_local_directory.down.sqlnew file mode 100644index 0000000000..4cbe7bbcb5--- /dev/null+++ b/server/migrations/109_agent_task_waiting_local_directory.down.sql@@ -0,0 +1,12 @@+-- Revert: drop the waiting_local_directory status and wait_reason column.+-- Any rows currently sitting in waiting_local_directory are first moved back+-- to dispatched so the restored CHECK constraint accepts them.++UPDATE agent_task_queue SET status = 'dispatched', wait_reason = NULL+WHERE status = 'waiting_local_directory';++ALTER TABLE agent_task_queue DROP COLUMN IF EXISTS wait_reason;++ALTER TABLE agent_task_queue DROP CONSTRAINT IF EXISTS agent_task_queue_status_check;+ALTER TABLE agent_task_queue ADD CONSTRAINT agent_task_queue_status_check+ CHECK (status IN ('queued', 'dispatched', 'running', 'completed', 'failed', 'cancelled'));diff --git a/server/migrations/109_agent_task_waiting_local_directory.up.sql b/server/migrations/109_agent_task_waiting_local_directory.up.sqlnew file mode 100644index 0000000000..17b1b5ccc2--- /dev/null+++ b/server/migrations/109_agent_task_waiting_local_directory.up.sql@@ -0,0 +1,17 @@+-- Adds the `waiting_local_directory` task status used by the daemon when a+-- task targets a project_resource of type `local_directory` whose path is+-- already held by another in-flight task. The daemon claims the row+-- (dispatched), discovers the path is busy, transitions to+-- waiting_local_directory, and only flips to running once it has the path+-- lock. This is the daemon → server protocol surface for the UI to render+-- "等待本地目录释放" instead of letting the row sit silently in dispatched.+--+-- wait_reason carries a short human-readable hint (e.g. the path being+-- waited on) that the UI can display alongside the status. It is set when+-- the row enters waiting_local_directory and cleared when it leaves.++ALTER TABLE agent_task_queue DROP CONSTRAINT IF EXISTS agent_task_queue_status_check;+ALTER TABLE agent_task_queue ADD CONSTRAINT agent_task_queue_status_check+ CHECK (status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'completed', 'failed', 'cancelled'));++ALTER TABLE agent_task_queue ADD COLUMN IF NOT EXISTS wait_reason TEXT;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 586c316e6a..09385aae93 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -177,8 +177,8 @@ func (q *Queries) ArchiveAgentsByRuntime(ctx context.Context, arg ArchiveAgentsBconst cancelAgentTask = `-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {@@ -210,6 +210,7 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -217,8 +218,8 @@ func (q *Queries) CancelAgentTask(ctx context.Context, id pgtype.UUID) (AgentTasconst cancelAgentTasksByAgent = `-- name: CancelAgentTasksByAgent :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`// Bulk-cancel every active (queued/dispatched/running) task for an agent.@@ -261,6 +262,7 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UU&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -275,8 +277,8 @@ func (q *Queries) CancelAgentTasksByAgent(ctx context.Context, agentID pgtype.UUconst cancelAgentTasksByChatSession = `-- name: CancelAgentTasksByChatSession :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`// Cancels active tasks belonging to a chat session. Called from@@ -319,6 +321,7 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSession&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -333,8 +336,8 @@ func (q *Queries) CancelAgentTasksByChatSession(ctx context.Context, chatSessionconst cancelAgentTasksByIssue = `-- name: CancelAgentTasksByIssue :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`// Cancels every active task on the issue and returns the affected rows so the@@ -377,6 +380,7 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UU&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -391,8 +395,8 @@ func (q *Queries) CancelAgentTasksByIssue(ctx context.Context, issueID pgtype.UUconst cancelAgentTasksByIssueAndAgent = `-- name: CancelAgentTasksByIssueAndAgent :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type CancelAgentTasksByIssueAndAgentParams struct {@@ -439,6 +443,7 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Cance&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -453,8 +458,8 @@ func (q *Queries) CancelAgentTasksByIssueAndAgent(ctx context.Context, arg Canceconst cancelAgentTasksByTriggerComment = `-- name: CancelAgentTasksByTriggerComment :manyUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`// Cancels active tasks whose trigger is the given comment. Called when a@@ -497,6 +502,7 @@ func (q *Queries) CancelAgentTasksByTriggerComment(ctx context.Context, triggerC&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -517,7 +523,7 @@ WHERE id = (AND NOT EXISTS (SELECT 1 FROM agent_task_queue activeWHERE active.agent_id = atq.agent_id- AND active.status IN ('dispatched', 'running')+ AND active.status IN ('dispatched', 'running', 'waiting_local_directory')AND ((atq.issue_id IS NOT NULL AND active.issue_id = atq.issue_id)OR (atq.chat_session_id IS NOT NULL AND active.chat_session_id = atq.chat_session_id)@@ -535,7 +541,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`// Claims the next queued task for an agent, enforcing per-(issue, agent) serialization:@@ -576,6 +582,7 @@ func (q *Queries) ClaimAgentTask(ctx context.Context, agentID pgtype.UUID) (Agen&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -659,7 +666,7 @@ const completeAgentTask = `-- name: CompleteAgentTask :oneUPDATE agent_task_queueSET status = 'completed', completed_at = now(), result = $2, session_id = $3, work_dir = $4WHERE id = $1 AND status = 'running'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type CompleteAgentTaskParams struct {@@ -703,13 +710,14 @@ func (q *Queries) CompleteAgentTask(ctx context.Context, arg CompleteAgentTaskPa&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}const countRunningTasks = `-- name: CountRunningTasks :oneSELECT count(*) FROM agent_task_queue-WHERE agent_id = $1 AND status IN ('dispatched', 'running')+WHERE agent_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')`func (q *Queries) CountRunningTasks(ctx context.Context, agentID pgtype.UUID) (int64, error) {@@ -805,7 +813,7 @@ VALUES (COALESCE($7::boolean, FALSE),COALESCE($8::boolean, FALSE))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type CreateAgentTaskParams struct {@@ -857,6 +865,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParams&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -864,7 +873,7 @@ func (q *Queries) CreateAgentTask(ctx context.Context, arg CreateAgentTaskParamsconst createQuickCreateTask = `-- name: CreateQuickCreateTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context)VALUES ($1, $2, NULL, 'queued', $3, $4)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type CreateQuickCreateTaskParams struct {@@ -911,6 +920,7 @@ func (q *Queries) CreateQuickCreateTask(ctx context.Context, arg CreateQuickCrea&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -932,7 +942,7 @@ SELECTp.is_leader_taskFROM agent_task_queue pWHERE p.id = $1-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`// Clones a parent task into a fresh queued attempt. Carries forward the@@ -974,6 +984,7 @@ func (q *Queries) CreateRetryTask(ctx context.Context, id pgtype.UUID) (AgentTas&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -996,7 +1007,7 @@ FROM victims vWHERE t.id = v.idAND t.status = 'queued'AND t.created_at < now() - make_interval(secs => $1::double precision)-RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task+RETURNING t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason`type ExpireStaleQueuedTasksParams struct {@@ -1062,6 +1073,7 @@ func (q *Queries) ExpireStaleQueuedTasks(ctx context.Context, arg ExpireStaleQue&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -1081,8 +1093,8 @@ SET status = 'failed',failure_reason = COALESCE($3, 'agent_error'),session_id = COALESCE($4, session_id),work_dir = COALESCE($5, work_dir)-WHERE id = $1 AND status IN ('dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type FailAgentTaskParams struct {@@ -1137,6 +1149,7 @@ func (q *Queries) FailAgentTask(ctx context.Context, arg FailAgentTaskParams) (A&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -1147,7 +1160,7 @@ SET status = 'failed', completed_at = now(), error = 'task timed out',failure_reason = 'timeout'WHERE (status = 'dispatched' AND dispatched_at < now() - make_interval(secs => $1::double precision))OR (status = 'running' AND started_at < now() - make_interval(secs => $2::double precision))-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type FailStaleTasksParams struct {@@ -1158,6 +1171,11 @@ type FailStaleTasksParams struct {// Fails tasks stuck in dispatched/running beyond the given thresholds.// Handles cases where the daemon is alive but the task is orphaned// (e.g. agent process hung, daemon failed to report completion).+// waiting_local_directory rows are intentionally excluded: the daemon owns+// the wait (with its own ctx-driven timeout) and a legitimate queue ahead+// of this task can exceed the dispatch / running timeouts without being+// "stuck". If the daemon dies, RecoverOrphanedTasksForRuntime reclaims+// those rows at restart.func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams) ([]AgentTaskQueue, error) {rows, err := q.db.Query(ctx, failStaleTasks, arg.DispatchTimeoutSecs, arg.RunningTimeoutSecs)if err != nil {@@ -1193,6 +1211,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -1280,7 +1299,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa}const getAgentTask = `-- name: GetAgentTask :one-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason FROM agent_task_queueWHERE id = $1`@@ -1313,6 +1332,7 @@ func (q *Queries) GetAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQu&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -1511,10 +1531,11 @@ func (q *Queries) GetWorkspaceAgentRunCounts(ctx context.Context, workspaceID pgconst hasActiveTaskForIssue = `-- name: HasActiveTaskForIssue :oneSELECT count(*) > 0 AS has_active FROM agent_task_queue-WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')`-// Returns true if there is any queued, dispatched, or running task for the issue.+// Returns true if there is any queued, dispatched, waiting_local_directory,+// or running task for the issue.func (q *Queries) HasActiveTaskForIssue(ctx context.Context, issueID pgtype.UUID) (bool, error) {row := q.db.QueryRow(ctx, hasActiveTaskForIssue, issueID)var has_active bool@@ -1692,8 +1713,8 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim}const listActiveTasksByIssue = `-- name: ListActiveTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task FROM agent_task_queue-WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason FROM agent_task_queue+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESC`@@ -1737,6 +1758,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -1749,7 +1771,7 @@ func (q *Queries) ListActiveTasksByIssue(ctx context.Context, issueID pgtype.UUI}const listAgentTasks = `-- name: ListAgentTasks :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason FROM agent_task_queueWHERE agent_id = $1ORDER BY created_at DESC`@@ -1789,6 +1811,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]Ag&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -1899,7 +1922,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([}const listPendingTasksByRuntime = `-- name: ListPendingTasksByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason FROM agent_task_queueWHERE runtime_id = $1 AND status IN ('queued', 'dispatched')ORDER BY priority DESC, created_at ASC`@@ -1939,6 +1962,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -1951,7 +1975,7 @@ func (q *Queries) ListPendingTasksByRuntime(ctx context.Context, runtimeID pgtyp}const listQueuedClaimCandidatesByRuntime = `-- name: ListQueuedClaimCandidatesByRuntime :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason FROM agent_task_queueWHERE runtime_id = $1 AND status = 'queued'ORDER BY priority DESC, created_at ASC`@@ -1999,6 +2023,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -2011,7 +2036,7 @@ func (q *Queries) ListQueuedClaimCandidatesByRuntime(ctx context.Context, runtim}const listTasksByIssue = `-- name: ListTasksByIssue :many-SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task FROM agent_task_queue+SELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason FROM agent_task_queueWHERE issue_id = $1ORDER BY created_at DESC`@@ -2051,6 +2076,7 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -2063,15 +2089,15 @@ func (q *Queries) ListTasksByIssue(ctx context.Context, issueID pgtype.UUID) ([]}const listWorkspaceAgentTaskSnapshot = `-- name: ListWorkspaceAgentTaskSnapshot :many-SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task FROM agent_task_queue atq+SELECT atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reason FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1- AND atq.status IN ('queued', 'dispatched', 'running')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')UNION ALL-SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task FROM (- SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task+SELECT t.id, t.agent_id, t.issue_id, t.status, t.priority, t.dispatched_at, t.started_at, t.completed_at, t.result, t.error, t.created_at, t.context, t.runtime_id, t.session_id, t.work_dir, t.trigger_comment_id, t.chat_session_id, t.autopilot_run_id, t.attempt, t.max_attempts, t.parent_task_id, t.failure_reason, t.trigger_summary, t.force_fresh_session, t.is_leader_task, t.wait_reason FROM (+ SELECT DISTINCT ON (atq.agent_id) atq.id, atq.agent_id, atq.issue_id, atq.status, atq.priority, atq.dispatched_at, atq.started_at, atq.completed_at, atq.result, atq.error, atq.created_at, atq.context, atq.runtime_id, atq.session_id, atq.work_dir, atq.trigger_comment_id, atq.chat_session_id, atq.autopilot_run_id, atq.attempt, atq.max_attempts, atq.parent_task_id, atq.failure_reason, atq.trigger_summary, atq.force_fresh_session, atq.is_leader_task, atq.wait_reasonFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1@@ -2133,6 +2159,7 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceI&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -2144,6 +2171,61 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceIreturn items, nil}+const markAgentTaskWaitingLocalDirectory = `-- name: MarkAgentTaskWaitingLocalDirectory :one+UPDATE agent_task_queue+SET status = 'waiting_local_directory', wait_reason = $2+WHERE id = $1 AND status = 'dispatched'+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason+`++type MarkAgentTaskWaitingLocalDirectoryParams struct {+ ID pgtype.UUID `json:"id"`+ WaitReason pgtype.Text `json:"wait_reason"`+}++// Transitions a freshly-dispatched task into 'waiting_local_directory' while+// the daemon waits for another in-flight task to release the path lock on a+// project_resource of type local_directory. wait_reason carries a short+// human-readable hint (typically the contested path) that the UI surfaces+// alongside the status.+//+// The CHECK only allows the transition from 'dispatched' so a daemon can't+// mark an already-running or terminal task as waiting; the StartAgentTask+// mutation handles the reverse transition once the lock is acquired.+func (q *Queries) MarkAgentTaskWaitingLocalDirectory(ctx context.Context, arg MarkAgentTaskWaitingLocalDirectoryParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, markAgentTaskWaitingLocalDirectory, arg.ID, arg.WaitReason)+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ )+ return i, err+}+const reclaimStaleDispatchedTaskForRuntime = `-- name: ReclaimStaleDispatchedTaskForRuntime :oneUPDATE agent_task_queueSET dispatched_at = now()@@ -2157,7 +2239,7 @@ WHERE id = (LIMIT 1FOR UPDATE SKIP LOCKED)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type ReclaimStaleDispatchedTaskForRuntimeParams struct {@@ -2199,6 +2281,7 @@ func (q *Queries) ReclaimStaleDispatchedTaskForRuntime(ctx context.Context, arg&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -2208,15 +2291,18 @@ UPDATE agent_task_queueSET status = 'failed',completed_at = now(),error = 'daemon restarted while task was in flight',- failure_reason = 'runtime_recovery'-WHERE runtime_id = $1 AND status IN ('dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+ failure_reason = 'runtime_recovery',+ wait_reason = NULL+WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`-// Called by the daemon at startup. Atomically fails any dispatched/running-// task that the prior incarnation of this runtime owned but did not-// finalize. Returns the failed rows so callers can hand them to the-// auto-retry path.+// Called by the daemon at startup. Atomically fails any dispatched/running/+// waiting_local_directory task that the prior incarnation of this runtime+// owned but did not finalize. Returns the failed rows so callers can hand+// them to the auto-retry path. waiting_local_directory rows are included+// because the daemon holding the path lock is the same process that just+// died — without us, the row would sit waiting forever.func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID pgtype.UUID) ([]AgentTaskQueue, error) {rows, err := q.db.Query(ctx, recoverOrphanedTasksForRuntime, runtimeID)if err != nil {@@ -2252,6 +2338,7 @@ func (q *Queries) RecoverOrphanedTasksForRuntime(ctx context.Context, runtimeID&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -2267,7 +2354,7 @@ const refreshAgentStatusFromTasks = `-- name: RefreshAgentStatusFromTasks :oneUPDATE agent AS aSET status = CASE WHEN EXISTS (SELECT 1 FROM agent_task_queue q- WHERE q.agent_id = a.id AND q.status IN ('dispatched', 'running')+ WHERE q.agent_id = a.id AND q.status IN ('dispatched', 'running', 'waiting_local_directory')) THEN 'working' ELSE 'idle' END,updated_at = now()WHERE a.id = $1@@ -2342,11 +2429,17 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erroconst startAgentTask = `-- name: StartAgentTask :oneUPDATE agent_task_queue-SET status = 'running', started_at = now()-WHERE id = $1 AND status = 'dispatched'-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+SET status = 'running', started_at = now(), wait_reason = NULL+WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`+// Transitions a task to running. Accepts either 'dispatched' (the normal+// claim → run flow) or 'waiting_local_directory' (the daemon held the row in+// a wait state while another task owned the local_directory path lock; once+// the lock was acquired the daemon flips here). wait_reason is cleared on+// the transition so a future read can't conflate "currently waiting" with+// "previously waited".func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {row := q.db.QueryRow(ctx, startAgentTask, id)var i AgentTaskQueue@@ -2376,6 +2469,7 @@ func (q *Queries) StartAgentTask(ctx context.Context, id pgtype.UUID) (AgentTask&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -2571,7 +2665,8 @@ type UpdateAgentTaskSessionParams struct {// Pins the resume pointer mid-flight so a daemon crash leaves a usable// session_id/work_dir on the task row. No-op if the task is no longer-// in dispatched/running.+// in dispatched/running. waiting_local_directory tasks have no session yet+// so this query intentionally skips them.func (q *Queries) UpdateAgentTaskSession(ctx context.Context, arg UpdateAgentTaskSessionParams) error {_, err := q.db.Exec(ctx, updateAgentTaskSession, arg.ID, arg.SessionID, arg.WorkDir)return errdiff --git a/server/pkg/db/generated/autopilot.sql.go b/server/pkg/db/generated/autopilot.sql.goindex 68261eaeb0..ca301b00e8 100644--- a/server/pkg/db/generated/autopilot.sql.go+++ b/server/pkg/db/generated/autopilot.sql.go@@ -222,7 +222,7 @@ const createAutopilotTask = `-- name: CreateAutopilotTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, autopilot_run_id, trigger_summary)VALUES ($1, $2, NULL, 'queued', $3, $4, $5)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type CreateAutopilotTaskParams struct {@@ -271,6 +271,7 @@ func (q *Queries) CreateAutopilotTask(ctx context.Context, arg CreateAutopilotTa&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 4bbeb4ee5a..d6cfe7c368 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -90,7 +90,7 @@ func (q *Queries) CreateChatSession(ctx context.Context, arg CreateChatSessionPaconst createChatTask = `-- name: CreateChatTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, chat_session_id)VALUES ($1, $2, NULL, 'queued', $3, $4)-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type CreateChatTaskParams struct {@@ -134,6 +134,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,)return i, err}@@ -274,7 +275,7 @@ func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgtyconst getPendingChatTask = `-- name: GetPendingChatTask :oneSELECT id, status, created_at FROM agent_task_queue-WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESCLIMIT 1`@@ -467,7 +468,7 @@ FROM agent_task_queue atqJOIN chat_session cs ON cs.id = atq.chat_session_idWHERE cs.workspace_id = $1AND cs.creator_id = $2- AND atq.status IN ('queued', 'dispatched', 'running')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY atq.created_at DESC`diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 73e9423652..a37b26ae75 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -96,6 +96,7 @@ type AgentTaskQueue struct {TriggerSummary pgtype.Text `json:"trigger_summary"`ForceFreshSession bool `json:"force_fresh_session"`IsLeaderTask bool `json:"is_leader_task"`+ WaitReason pgtype.Text `json:"wait_reason"`}type Attachment struct {diff --git a/server/pkg/db/generated/project_resource.sql.go b/server/pkg/db/generated/project_resource.sql.goindex 9982b54b75..05c52d3927 100644--- a/server/pkg/db/generated/project_resource.sql.go+++ b/server/pkg/db/generated/project_resource.sql.go@@ -226,3 +226,41 @@ func (q *Queries) ListProjectResourcesForProjects(ctx context.Context, projectId}return items, nil}++const updateProjectResource = `-- name: UpdateProjectResource :one+UPDATE project_resource+SET resource_ref = $2,+ label = $3,+ position = $4+WHERE id = $1+RETURNING id, project_id, workspace_id, resource_type, resource_ref, label, position, created_at, created_by+`++type UpdateProjectResourceParams struct {+ ID pgtype.UUID `json:"id"`+ ResourceRef []byte `json:"resource_ref"`+ Label pgtype.Text `json:"label"`+ Position int32 `json:"position"`+}++func (q *Queries) UpdateProjectResource(ctx context.Context, arg UpdateProjectResourceParams) (ProjectResource, error) {+ row := q.db.QueryRow(ctx, updateProjectResource,+ arg.ID,+ arg.ResourceRef,+ arg.Label,+ arg.Position,+ )+ var i ProjectResource+ err := row.Scan(+ &i.ID,+ &i.ProjectID,+ &i.WorkspaceID,+ &i.ResourceType,+ &i.ResourceRef,+ &i.Label,+ &i.Position,+ &i.CreatedAt,+ &i.CreatedBy,+ )+ return i, err+}diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 1aad412992..97e78f9231 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -15,8 +15,8 @@ const cancelAgentTasksByRuntimeOrAgent = `-- name: CancelAgentTasksByRuntimeOrAgUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE (runtime_id = ANY($1::uuid[]) OR agent_id = ANY($2::uuid[]))- AND status IN ('queued', 'dispatched', 'running')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`type CancelAgentTasksByRuntimeOrAgentParams struct {@@ -73,6 +73,7 @@ func (q *Queries) CancelAgentTasksByRuntimeOrAgent(ctx context.Context, arg Canc&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}@@ -152,16 +153,18 @@ func (q *Queries) DeleteStaleOfflineRuntimes(ctx context.Context, staleSeconds fconst failTasksForOfflineRuntimes = `-- name: FailTasksForOfflineRuntimes :manyUPDATE agent_task_queueSET status = 'failed', completed_at = now(), error = 'runtime went offline',- failure_reason = 'runtime_offline'-WHERE status IN ('dispatched', 'running')+ failure_reason = 'runtime_offline',+ wait_reason = NULL+WHERE status IN ('dispatched', 'running', 'waiting_local_directory')AND runtime_id IN (SELECT id FROM agent_runtime WHERE status = 'offline')-RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason`-// Marks dispatched/running tasks as failed when their runtime is offline.-// This cleans up orphaned tasks after a daemon crash or network partition.+// Marks dispatched/running/waiting_local_directory tasks as failed when+// their runtime is offline. This cleans up orphaned tasks after a daemon+// crash or network partition.func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQueue, error) {rows, err := q.db.Query(ctx, failTasksForOfflineRuntimes)if err != nil {@@ -197,6 +200,7 @@ func (q *Queries) FailTasksForOfflineRuntimes(ctx context.Context) ([]AgentTaskQ&i.TriggerSummary,&i.ForceFreshSession,&i.IsLeaderTask,+ &i.WaitReason,); err != nil {return nil, err}diff --git a/server/pkg/db/generated/squad.sql.go b/server/pkg/db/generated/squad.sql.goindex 27711b8bb5..ecb4f0bd70 100644--- a/server/pkg/db/generated/squad.sql.go+++ b/server/pkg/db/generated/squad.sql.go@@ -386,7 +386,7 @@ LEFT JOIN agent_runtime arLEFT JOIN agent_task_queue atqON sm.member_type = 'agent'AND atq.agent_id = sm.member_id- AND atq.status IN ('dispatched', 'running')+ AND atq.status IN ('dispatched', 'running', 'waiting_local_directory')LEFT JOIN issue iON i.id = atq.issue_idWHERE sm.squad_id = $1diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 21401e3c82..07649b11ba 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -201,7 +201,7 @@ RETURNING *;-- status="working" with no self-correction.UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: CancelAgentTasksByIssueAndAgent :many@@ -211,7 +211,7 @@ RETURNING *;-- still-running @-mention agent on the same issue.UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running')+WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: CancelAgentTasksByAgent :many@@ -222,7 +222,7 @@ RETURNING *;-- behave consistently.UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE agent_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: CancelAgentTasksByTriggerComment :many@@ -233,7 +233,7 @@ RETURNING *;-- and we'd lose the ability to find the affected tasks.UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE trigger_comment_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: CancelAgentTasksByChatSession :many@@ -244,7 +244,7 @@ RETURNING *;-- could no longer reach those tasks.UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: GetAgentTask :one@@ -269,7 +269,7 @@ WHERE id = (AND NOT EXISTS (SELECT 1 FROM agent_task_queue activeWHERE active.agent_id = atq.agent_id- AND active.status IN ('dispatched', 'running')+ AND active.status IN ('dispatched', 'running', 'waiting_local_directory')AND ((atq.issue_id IS NOT NULL AND active.issue_id = atq.issue_id)OR (atq.chat_session_id IS NOT NULL AND active.chat_session_id = atq.chat_session_id)@@ -310,8 +310,29 @@ WHERE id = (RETURNING *;-- name: StartAgentTask :one+-- Transitions a task to running. Accepts either 'dispatched' (the normal+-- claim → run flow) or 'waiting_local_directory' (the daemon held the row in+-- a wait state while another task owned the local_directory path lock; once+-- the lock was acquired the daemon flips here). wait_reason is cleared on+-- the transition so a future read can't conflate "currently waiting" with+-- "previously waited".UPDATE agent_task_queue-SET status = 'running', started_at = now()+SET status = 'running', started_at = now(), wait_reason = NULL+WHERE id = $1 AND status IN ('dispatched', 'waiting_local_directory')+RETURNING *;++-- name: MarkAgentTaskWaitingLocalDirectory :one+-- Transitions a freshly-dispatched task into 'waiting_local_directory' while+-- the daemon waits for another in-flight task to release the path lock on a+-- project_resource of type local_directory. wait_reason carries a short+-- human-readable hint (typically the contested path) that the UI surfaces+-- alongside the status.+--+-- The CHECK only allows the transition from 'dispatched' so a daemon can't+-- mark an already-running or terminal task as waiting; the StartAgentTask+-- mutation handles the reverse transition once the lock is acquired.+UPDATE agent_task_queue+SET status = 'waiting_local_directory', wait_reason = $2WHERE id = $1 AND status = 'dispatched'RETURNING *;@@ -385,35 +406,44 @@ SET status = 'failed',failure_reason = COALESCE(sqlc.narg('failure_reason'), 'agent_error'),session_id = COALESCE(sqlc.narg('session_id'), session_id),work_dir = COALESCE(sqlc.narg('work_dir'), work_dir)-WHERE id = $1 AND status IN ('dispatched', 'running')+WHERE id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: UpdateAgentTaskSession :exec-- Pins the resume pointer mid-flight so a daemon crash leaves a usable-- session_id/work_dir on the task row. No-op if the task is no longer--- in dispatched/running.+-- in dispatched/running. waiting_local_directory tasks have no session yet+-- so this query intentionally skips them.UPDATE agent_task_queueSET session_id = COALESCE(sqlc.narg('session_id'), session_id),work_dir = COALESCE(sqlc.narg('work_dir'), work_dir)WHERE id = $1 AND status IN ('dispatched', 'running');-- name: RecoverOrphanedTasksForRuntime :many--- Called by the daemon at startup. Atomically fails any dispatched/running--- task that the prior incarnation of this runtime owned but did not--- finalize. Returns the failed rows so callers can hand them to the--- auto-retry path.+-- Called by the daemon at startup. Atomically fails any dispatched/running/+-- waiting_local_directory task that the prior incarnation of this runtime+-- owned but did not finalize. Returns the failed rows so callers can hand+-- them to the auto-retry path. waiting_local_directory rows are included+-- because the daemon holding the path lock is the same process that just+-- died — without us, the row would sit waiting forever.UPDATE agent_task_queueSET status = 'failed',completed_at = now(),error = 'daemon restarted while task was in flight',- failure_reason = 'runtime_recovery'-WHERE runtime_id = $1 AND status IN ('dispatched', 'running')+ failure_reason = 'runtime_recovery',+ wait_reason = NULL+WHERE runtime_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: FailStaleTasks :many-- Fails tasks stuck in dispatched/running beyond the given thresholds.-- Handles cases where the daemon is alive but the task is orphaned-- (e.g. agent process hung, daemon failed to report completion).+-- waiting_local_directory rows are intentionally excluded: the daemon owns+-- the wait (with its own ctx-driven timeout) and a legitimate queue ahead+-- of this task can exceed the dispatch / running timeouts without being+-- "stuck". If the daemon dies, RecoverOrphanedTasksForRuntime reclaims+-- those rows at restart.UPDATE agent_task_queueSET status = 'failed', completed_at = now(), error = 'task timed out',failure_reason = 'timeout'@@ -466,17 +496,18 @@ RETURNING t.*;-- name: CancelAgentTask :oneUPDATE agent_task_queueSET status = 'cancelled', completed_at = now()-WHERE id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: CountRunningTasks :oneSELECT count(*) FROM agent_task_queue-WHERE agent_id = $1 AND status IN ('dispatched', 'running');+WHERE agent_id = $1 AND status IN ('dispatched', 'running', 'waiting_local_directory');-- name: HasActiveTaskForIssue :one--- Returns true if there is any queued, dispatched, or running task for the issue.+-- Returns true if there is any queued, dispatched, waiting_local_directory,+-- or running task for the issue.SELECT count(*) > 0 AS has_active FROM agent_task_queue-WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running');+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory');-- name: HasPendingTaskForIssue :one-- Returns true if there is a queued or dispatched (but not yet running) task for the issue.@@ -529,7 +560,7 @@ ORDER BY priority DESC, created_at ASC;-- busy on a prior task, and a silent UI during that window looks like the-- platform never received the trigger.SELECT * FROM agent_task_queue-WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE issue_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESC;-- name: GetWorkspaceAgentRunCounts :many@@ -594,7 +625,7 @@ ORDER BY atq.agent_id, bucket;SELECT atq.* FROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1- AND atq.status IN ('queued', 'dispatched', 'running')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')UNION ALL@@ -621,7 +652,7 @@ RETURNING *;UPDATE agent AS aSET status = CASE WHEN EXISTS (SELECT 1 FROM agent_task_queue q- WHERE q.agent_id = a.id AND q.status IN ('dispatched', 'running')+ WHERE q.agent_id = a.id AND q.status IN ('dispatched', 'running', 'waiting_local_directory')) THEN 'working' ELSE 'idle' END,updated_at = now()WHERE a.id = $1diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 3db5d1b6c2..b9604e5ce3 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -121,7 +121,7 @@ LIMIT 1;-- elapsed = now - task.created_at), so the pill survives refresh / reopen-- without "resetting to 0s".SELECT id, status, created_at FROM agent_task_queue-WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running')+WHERE chat_session_id = $1 AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY created_at DESCLIMIT 1;@@ -134,7 +134,7 @@ FROM agent_task_queue atqJOIN chat_session cs ON cs.id = atq.chat_session_idWHERE cs.workspace_id = $1AND cs.creator_id = $2- AND atq.status IN ('queued', 'dispatched', 'running')+ AND atq.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')ORDER BY atq.created_at DESC;-- name: MarkChatSessionRead :execdiff --git a/server/pkg/db/queries/project_resource.sql b/server/pkg/db/queries/project_resource.sqlindex 741548e067..088b44171b 100644--- a/server/pkg/db/queries/project_resource.sql+++ b/server/pkg/db/queries/project_resource.sql@@ -23,6 +23,14 @@ INSERT INTO project_resource ($1, $2, $3, $4, $5, $6, $7) RETURNING *;+-- name: UpdateProjectResource :one+UPDATE project_resource+SET resource_ref = $2,+ label = $3,+ position = $4+WHERE id = $1+RETURNING *;+-- name: DeleteProjectResource :execDELETE FROM project_resource WHERE id = $1;diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex 9054badd1c..c0007699ab 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -142,12 +142,14 @@ WHERE status = 'online'RETURNING id, workspace_id, owner_id, daemon_id, provider;-- name: FailTasksForOfflineRuntimes :many--- Marks dispatched/running tasks as failed when their runtime is offline.--- This cleans up orphaned tasks after a daemon crash or network partition.+-- Marks dispatched/running/waiting_local_directory tasks as failed when+-- their runtime is offline. This cleans up orphaned tasks after a daemon+-- crash or network partition.UPDATE agent_task_queueSET status = 'failed', completed_at = now(), error = 'runtime went offline',- failure_reason = 'runtime_offline'-WHERE status IN ('dispatched', 'running')+ failure_reason = 'runtime_offline',+ wait_reason = NULL+WHERE status IN ('dispatched', 'running', 'waiting_local_directory')AND runtime_id IN (SELECT id FROM agent_runtime WHERE status = 'offline')@@ -188,7 +190,7 @@ RETURNING id, workspace_id, owner_id, daemon_id, provider;UPDATE agent_task_queueSET status = 'cancelled', completed_at = now()WHERE (runtime_id = ANY(@runtime_ids::uuid[]) OR agent_id = ANY(@agent_ids::uuid[]))- AND status IN ('queued', 'dispatched', 'running')+ AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')RETURNING *;-- name: DeleteAgentRuntime :execdiff --git a/server/pkg/db/queries/squad.sql b/server/pkg/db/queries/squad.sqlindex cc740f4970..edc7aa36ac 100644--- a/server/pkg/db/queries/squad.sql+++ b/server/pkg/db/queries/squad.sql@@ -144,7 +144,7 @@ LEFT JOIN agent_runtime arLEFT JOIN agent_task_queue atqON sm.member_type = 'agent'AND atq.agent_id = sm.member_id- AND atq.status IN ('dispatched', 'running')+ AND atq.status IN ('dispatched', 'running', 'waiting_local_directory')LEFT JOIN issue iON i.id = atq.issue_idWHERE sm.squad_id = $1diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex dd736ba68b..63c64e2278 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -30,14 +30,15 @@ const (// subscribes by `task:` prefix and invalidates the workspace task// snapshot, so the granularity here is "what does the user want to see// change" — not "every internal status flip".- EventTaskQueued = "task:queued" // ∅ → queued (enqueue / retry create)- EventTaskDispatch = "task:dispatch" // queued → dispatched (daemon claim)- EventTaskRunning = "task:running" // dispatched → running (daemon started)- EventTaskProgress = "task:progress"- EventTaskCompleted = "task:completed" // running → completed- EventTaskFailed = "task:failed" // running → failed- EventTaskMessage = "task:message"- EventTaskCancelled = "task:cancelled" // * → cancelled+ EventTaskQueued = "task:queued" // ∅ → queued (enqueue / retry create)+ EventTaskDispatch = "task:dispatch" // queued → dispatched (daemon claim)+ EventTaskRunning = "task:running" // dispatched → running (daemon started)+ EventTaskWaitingLocalDirectory = "task:waiting_local_directory" // dispatched → waiting_local_directory (daemon parked on a busy local_directory path)+ EventTaskProgress = "task:progress"+ EventTaskCompleted = "task:completed" // running → completed+ EventTaskFailed = "task:failed" // running → failed+ EventTaskMessage = "task:message"+ EventTaskCancelled = "task:cancelled" // * → cancelled// Inbox eventsEventInboxNew = "inbox:new"@@ -79,6 +80,7 @@ const (EventProjectUpdated = "project:updated"EventProjectDeleted = "project:deleted"EventProjectResourceCreated = "project_resource:created"+ EventProjectResourceUpdated = "project_resource:updated"EventProjectResourceDeleted = "project_resource:deleted"// Label events