Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6504 fix(daemon): stop chat tasks holding the local_directory mutex they never write to (#7378)
Bohan Jiangbae3a324fcd0
diff --git a/packages/core/chat/pending.test.ts b/packages/core/chat/pending.test.tsindex f2e5362c3b..574b181a29 100644--- a/packages/core/chat/pending.test.ts+++ b/packages/core/chat/pending.test.ts@@ -291,3 +291,57 @@ describe("pending chat queue", () => {expect(result.queued_tasks?.map((item) => item.task_id)).toEqual(["next"]);});});++describe("promotePendingChatTask wait_reason", () => {+ const waiting = "waiting_local_directory";++ it("keeps the reason a hold arrives with", () => {+ const promoted = promotePendingChatTask(+ { task_id: "t1", status: "dispatched" },+ "t1",+ waiting,+ undefined,+ "NuvioTV (held by task a1b2c3d4)",+ );+ expect(promoted.status).toBe(waiting);+ expect(promoted.wait_reason).toBe("NuvioTV (held by task a1b2c3d4)");+ });++ it("carries the cached reason across repeat events for the same hold", () => {+ // The daemon stamps wait_reason once; a later event for the same parked+ // task may arrive without it, and the pill must not blank mid-wait.+ const promoted = promotePendingChatTask(+ { task_id: "t1", status: waiting, wait_reason: "NuvioTV" },+ "t1",+ waiting,+ );+ expect(promoted.wait_reason).toBe("NuvioTV");+ });++ it("drops the reason the moment the task stops waiting", () => {+ // The server never clears the column, so a task that has been running for+ // ten minutes would otherwise still claim to be held by another task.+ const promoted = promotePendingChatTask(+ { task_id: "t1", status: waiting, wait_reason: "NuvioTV" },+ "t1",+ "running",+ );+ expect(promoted.status).toBe("running");+ expect(promoted.wait_reason).toBeUndefined();+ });++ it("does not inherit a reason when a queued follow-up is promoted", () => {+ const promoted = promotePendingChatTask(+ {+ task_id: "t1",+ status: waiting,+ wait_reason: "NuvioTV",+ queued_tasks: [{ task_id: "t2", status: "queued", created_at: "2026-07-01T00:00:00Z" }],+ },+ "t2",+ "running",+ );+ expect(promoted.task_id).toBe("t2");+ expect(promoted.wait_reason).toBeUndefined();+ });+});diff --git a/packages/core/chat/pending.ts b/packages/core/chat/pending.tsindex caba45f5a1..7a499e92dc 100644--- a/packages/core/chat/pending.ts+++ b/packages/core/chat/pending.ts@@ -86,17 +86,33 @@ export function enqueuePendingChatTask(};}+// A hold explanation outlives the hold: the daemon writes wait_reason once on+// the way in and never clears it, so the only thing keeping "held by task+// abc12345" off a task that has since started running is this gate. Any status+// other than the waiting one drops the text, whether it arrived on this event+// or was already in the cache.+function resolveWaitReason(+ status: string,+ incoming: string | undefined,+ existing: string | undefined,+): string | undefined {+ if (status !== "waiting_local_directory") return undefined;+ return incoming ?? existing;+}+export function promotePendingChatTask(current: ChatPendingTask | undefined,taskID: string,status: string,createdAt?: string,+ waitReason?: string,): ChatPendingTask {const queue = current?.queued_tasks ?? [];if (current?.task_id === taskID) {return {...current,status,+ wait_reason: resolveWaitReason(status, waitReason, current.wait_reason),queued_tasks: queue.filter((task) => task.task_id !== taskID),};}@@ -110,6 +126,7 @@ export function promotePendingChatTask(...promoted,supports_queue: current.supports_queue,status,+ wait_reason: resolveWaitReason(status, waitReason, undefined),created_at: promoted.created_at || createdAt || "",queued_tasks: uniqueQueue([...(previousHead?.status === "queued" ? [previousHead] : []),diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 8bdbfc8fe7..dd0fa8dacf 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -1565,6 +1565,8 @@ export function useRealtimeSync(old,payload.task_id,"waiting_local_directory",+ undefined,+ payload.wait_reason,),);invalidateChatMessageQueries(qc, payload.chat_session_id);diff --git a/packages/core/types/chat.ts b/packages/core/types/chat.tsindex d5ce5f9cd6..f49ef7e78f 100644--- a/packages/core/types/chat.ts+++ b/packages/core/types/chat.ts@@ -282,6 +282,14 @@ export interface ChatPendingTask {task_id?: string;status?: string;created_at?: string;+ /**+ * Why a `waiting_local_directory` task is parked: the directory it needs and,+ * when known, the short id of the task holding it. Set only while that status+ * is current — see promotePendingChatTask, which clears it on every other+ * transition so a stale hold can never be read as a live one. Absent on+ * servers predating the field, which renders as the bare waiting label.+ */+ wait_reason?: string;/** Explicit capability gate; absent on servers predating follow-up queues. */supports_queue?: boolean;/**diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 29e4456cb2..88ae17792c 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -322,9 +322,12 @@ export interface TaskRunningPayload {// 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.+// daemon is already executing in the same local_directory. `wait_reason` names+// the directory and, when known, the short id of the task holding it; the+// StatusPill renders it so a parked task explains itself instead of just+// spinning. It is a display name, never an absolute path — the daemon strips+// that at the source (localDirectoryAssignment.DisplayName), because this text+// reaches every client on the session and lands in screenshots.export interface TaskWaitingLocalDirectoryPayload {task_id: string;agent_id: string;diff --git a/packages/views/chat/components/task-status-pill.test.ts b/packages/views/chat/components/task-status-pill.test.tsindex 92cfe2bde3..c6db6311e5 100644--- a/packages/views/chat/components/task-status-pill.test.ts+++ b/packages/views/chat/components/task-status-pill.test.ts@@ -37,6 +37,7 @@ describe("pickStageKeys", () => {// 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({+ needsWaitReason: true,stageKey: "waiting_local_directory",static: true,});@@ -47,13 +48,34 @@ describe("pickStageKeys", () => {// status is the more specific signal — surface it.expect(pickStageKeys("waiting_local_directory", [], "unstable"),- ).toEqual({ stageKey: "waiting_local_directory", static: true });+ ).toEqual({+ stageKey: "waiting_local_directory",+ static: true,+ needsWaitReason: true,+ });expect(pickStageKeys("waiting_local_directory", [], "offline"),- ).toEqual({ stageKey: "waiting_local_directory", static: true });+ ).toEqual({+ stageKey: "waiting_local_directory",+ static: true,+ needsWaitReason: true,+ });});it("returns thinking for running with no messages", () => {expect(pickStageKeys("running", [], "online")).toEqual({ stageKey: "thinking" });});});++describe("pickStageKeys wait reason", () => {+ it("flags the hold status as wanting a reason", () => {+ // The flag is what lets the renderer choose the explaining label; every+ // other stage leaves it unset so no other status can pick up stale text.+ expect(+ pickStageKeys("waiting_local_directory", [], "online").needsWaitReason,+ ).toBe(true);+ for (const status of ["queued", "dispatched", "running", "deferred"]) {+ expect(pickStageKeys(status, [], "online").needsWaitReason).toBeUndefined();+ }+ });+});diff --git a/packages/views/chat/components/task-status-pill.tsx b/packages/views/chat/components/task-status-pill.tsxindex da74b5bd51..fe32a9a625 100644--- a/packages/views/chat/components/task-status-pill.tsx+++ b/packages/views/chat/components/task-status-pill.tsx@@ -62,7 +62,12 @@ export function pickStageKeys(status: string | undefined,taskMessages: readonly TaskMessagePayload[],availability: AgentAvailability | undefined,-): { stageKey: StageKey; toolKey?: ToolKey; static?: boolean } {+): {+ stageKey: StageKey;+ toolKey?: ToolKey;+ static?: boolean;+ needsWaitReason?: boolean;+} {// A deferred chat task is an older turn waiting for its retry backoff, not// active model work. Keep this ahead of availability hints so the specific// retry state never degrades to a misleading queued/thinking label.@@ -85,7 +90,11 @@ export function pickStageKeys(// 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 };+ return {+ stageKey: "waiting_local_directory",+ static: true,+ needsWaitReason: true,+ };}if (status === "queued") return { stageKey: "queued" };if (status === "dispatched") return { stageKey: "starting_up" };@@ -127,15 +136,29 @@ function useResolveStage(): (status: string | undefined,taskMessages: readonly TaskMessagePayload[],availability: AgentAvailability | undefined,+ waitReason?: string,) => Stage {const { t } = useT("chat");- return (status, taskMessages, availability) => {+ return (status, taskMessages, availability, waitReason) => {const decision = pickStageKeys(status, taskMessages, availability);if (decision.toolKey) {return {label: t(($) => $.status_pill.tools[decision.toolKey!]),};}+ // A parked task that names what it is parked on turns an unexplained wait+ // into an actionable one: the user can see it is a sibling task, not a+ // hung agent, and decide whether cancelling is worth it. Older servers send+ // no reason, so the bare label has to stay reachable.+ const reason = waitReason?.trim();+ if (decision.needsWaitReason && reason) {+ return {+ label: t(($) => $.status_pill.stages.waiting_local_directory_reason, {+ reason,+ }),+ static: decision.static,+ };+ }return {label: t(($) => $.status_pill.stages[decision.stageKey]),static: decision.static,@@ -174,7 +197,15 @@ export function TaskStatusPill({// when the server has since moved that same task into retry backoff.const status = effectiveTaskStatus(pendingTask.status, taskMessages);const elapsedSecs = Math.max(0, Math.floor((now - anchor) / 1000));- const stage = resolveStage(status, taskMessages, availability);+ // Read the reason only when the effective status is still the waiting one:+ // streamed messages can promote a cached waiting task to "running" locally+ // before the next server payload clears the stored text.+ const stage = resolveStage(+ status,+ taskMessages,+ availability,+ status === "waiting_local_directory" ? pendingTask.wait_reason : undefined,+ );return (<divdiff --git a/packages/views/locales/en/chat.json b/packages/views/locales/en/chat.jsonindex c34f259f87..45c1c8a1ae 100644--- a/packages/views/locales/en/chat.json+++ b/packages/views/locales/en/chat.json@@ -195,6 +195,7 @@"retrying": "Retrying","queued": "Queued","waiting_local_directory": "Waiting for local directory",+ "waiting_local_directory_reason": "Waiting for {{reason}}","starting_up": "Starting up","thinking": "Thinking","typing": "Typing"diff --git a/packages/views/locales/ja/chat.json b/packages/views/locales/ja/chat.jsonindex e0978fe906..63b061c64e 100644--- a/packages/views/locales/ja/chat.json+++ b/packages/views/locales/ja/chat.json@@ -191,6 +191,7 @@"retrying": "再試行中","queued": "待機中","waiting_local_directory": "ローカルディレクトリを待機中",+ "waiting_local_directory_reason": "{{reason}} を待機中","starting_up": "起動中","thinking": "考え中","typing": "入力中"diff --git a/packages/views/locales/ko/chat.json b/packages/views/locales/ko/chat.jsonindex 161f6ca772..d6a9de73f8 100644--- a/packages/views/locales/ko/chat.json+++ b/packages/views/locales/ko/chat.json@@ -191,6 +191,7 @@"retrying": "재시도 중","queued": "대기 중","waiting_local_directory": "로컬 디렉터리 대기 중",+ "waiting_local_directory_reason": "{{reason}} 대기 중","starting_up": "시작 중","thinking": "생각 중","typing": "입력 중"diff --git a/packages/views/locales/zh-Hans/chat.json b/packages/views/locales/zh-Hans/chat.jsonindex e3ff6441e4..398cfcc789 100644--- a/packages/views/locales/zh-Hans/chat.json+++ b/packages/views/locales/zh-Hans/chat.json@@ -191,6 +191,7 @@"retrying": "重试中","queued": "排队中","waiting_local_directory": "等待本地目录释放",+ "waiting_local_directory_reason": "等待 {{reason}}","starting_up": "启动中","thinking": "思考中","typing": "输入中"diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex fc05ce29c2..580270c3c5 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -5334,6 +5334,18 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tasreturn nil, false}+ // A conversation is not a second writer. Everything above still applied —+ // the mode was checked, the path was validated, and the assignment stands,+ // so this task keeps the user's directory as its working directory. Only+ // the queueing is skipped, which is what stops a chat turn from sitting+ // behind a 20-minute build with nothing to contribute to it (issue #7344).+ // See localDirectoryLockExempt for why the mutex does not owe this task a+ // slot.+ if localDirectoryLockExempt(task) {+ taskLog.Info("local_directory: chat task, skipping path mutex")+ return nil, false+ }+// 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 the lock is acquired. If the user@@ -5371,8 +5383,17 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas// server status update below fails.d.resourceWaitTasks.Add(1)waitCounted = true- reason := fmt.Sprintf("local_directory %s", assignment.AbsPath)+ // Rendered to the user, so it names the directory rather than its path+ // (see localDirectoryAssignment.DisplayName). The absolute path stays in+ // the daemon's own logs, which is where an operator debugging a wedged+ // lock looks for it.+ reason := assignment.DisplayName()if holder != "" {+ // Known rough edge: this clause is English and the client renders it+ // inside a localized "Waiting for {reason}" label, so a zh/ja/ko user+ // sees mixed script. Fixing it properly means sending the directory+ // and the holder as separate fields and localizing the join on the+ // client — worth doing if this hint grows, not for one parenthetical.reason = fmt.Sprintf("%s (held by task %s)", reason, shortID(holder))}taskLog.Info("local_directory: waiting on path mutex", "holder", shortID(holder))@@ -6991,7 +7012,15 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iif err != nil {d.logger.Warn("execenv: inject runtime config failed (non-fatal)", "error", err)}- prompt := BuildPrompt(task, provider)+ // An exempt turn runs in the user's directory without having queued for it,+ // so a sibling coding task may be writing to the same tree right now. That+ // is the one thing it cannot work out from its own context — tell it.+ // Worktree mode is excluded: there the tree is this task's private checkout.+ var promptOptions []PromptOption+ if localAssignment != nil && !localAssignment.UsesWorktree() && localDirectoryLockExempt(task) {+ promptOptions = append(promptOptions, WithSharedLocalDirectory())+ }+ prompt := BuildPrompt(task, provider, promptOptions...)// Pass task-scoped auth credentials and context so the spawned agent CLI// can call the Multica API and the local daemon (e.g. `multica repo checkout`).@@ -7358,7 +7387,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot iexecOpts.SystemPrompt = runtimeBrief}}- freshPrompt := BuildPrompt(task, provider)+ freshPrompt := BuildPrompt(task, provider, promptOptions...)retryResult, retryTools, retryErr := d.executeAndDrain(ctx, backend, freshPrompt, execOpts, taskLog, task.ID, env.CodexHome, &msgSeq)if retryErr != nil {diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 8c2affff87..155b2a2095 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -924,13 +924,13 @@ func TestSessionContinuityNoticeMatchesSurface(t *testing.T) {}// The notice only renders when the resume actually failed.- if blocks := perTurnContextBlocks(Task{IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"}); strings.Contains(blocks, "Session Continuity Notice") {+ if blocks := perTurnContextBlocks(Task{IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890"}, promptOpts{}); strings.Contains(blocks, "Session Continuity Notice") {t.Errorf("continuity notice leaked into a run that resumed fine:\n%s", blocks)}lost := perTurnContextBlocks(Task{IssueID: "a1b2c3d4-e5f6-7890-abcd-ef1234567890",PriorSessionResumeUnavailable: true,- })+ }, promptOpts{})if !strings.Contains(lost, "Session Continuity Notice") {t.Errorf("continuity notice missing when the resume was unavailable:\n%s", lost)}diff --git a/server/internal/daemon/local_directory.go b/server/internal/daemon/local_directory.goindex 78989191b9..5880c14856 100644--- a/server/internal/daemon/local_directory.go+++ b/server/internal/daemon/local_directory.go@@ -59,6 +59,26 @@ func (a *localDirectoryAssignment) UsesWorktree() bool {return a != nil && strings.TrimSpace(a.Ref.ExecutionMode) == localDirectoryModeWorktree}+// DisplayName is the human-facing name for this directory, safe to render in+// UI. It is deliberately NOT the absolute path: the wait reason built from it+// is stored server-side and pushed to every client on the session, and a chip+// in a chat transcript ends up in screen shares and screenshots. Absolute+// paths carry the account name, which is why handler.relativeWorkDir exists+// for the sibling work_dir chip; this is the same contract for the same reason.+//+// The resource's own label wins when the user set one — that is the name they+// chose for this directory. Otherwise the basename, which is what distinguishes+// sibling checkouts ("NuvioTV" vs "multica") without naming their parent.+func (a *localDirectoryAssignment) DisplayName() string {+ if a == nil {+ return ""+ }+ if label := strings.TrimSpace(a.Ref.Label); label != "" {+ return label+ }+ return filepath.Base(a.AbsPath)+}+// ValidateExecutionMode rejects a mode this daemon does not implement.//// Falling back to in_place would be the wrong direction, even though it is the@@ -88,6 +108,16 @@ func (a *localDirectoryAssignment) ValidateExecutionMode() error {// should execute inside. Squad-leader tasks are coordinators: they may create// child issues or comments, but should not bind to the user's repo worktree or// hold the path mutex while downstream workers are ready to write.+//+// This answers WHERE a task runs, and only that. Its result also drives the+// agent's working directory (daemon.runTask plumbs AbsPath into+// execenv.PrepareParams.LocalWorkDir) and the GC-meta stamp that exempts a+// user-owned path from env-root cleanup. Whether the task additionally takes+// the per-path mutex is a SEPARATE question, answered by+// localDirectoryLockExempt — collapsing the two is what made a read-only chat+// turn queue behind a 20-minute build (issue #7344), and answering "no+// assignment" there to free the lock would have silently moved chat out of the+// user's directory as well.func localDirectoryAssignmentForTask(task Task, daemonID string) (*localDirectoryAssignment, error) {if task.IsLeaderTask {return nil, nil@@ -95,6 +125,33 @@ func localDirectoryAssignmentForTask(task Task, daemonID string) (*localDirectorreturn findLocalDirectoryAssignment(task.ProjectResources, daemonID)}+// localDirectoryLockExempt reports whether a task may run inside an in_place+// local_directory WITHOUT serialising on the per-path mutex. It is asked only+// after an assignment has been resolved and validated, so an exempt task still+// runs in the user's directory — it just doesn't queue for it.+//+// What the mutex actually protects: two long coding runs interleaving two sets+// of edits into one working tree. It was never a general write barrier and+// cannot become one — the user's own editor, their terminal, and any external+// script write to that same tree unsynchronised, and always have. So the+// question a task must answer to earn the lock is not "could it ever write?"+// (everything could) but "is it a second heavyweight writer?".+//+// A chat turn is not. It is a conversation that reads the tree to answer+// questions and at most saves a file the way the user's own Cmd+S does — the+// risk class the lock already declines to cover. Serialising it bought nothing+// and muted the squad leader for the length of every build (issue #7344).+//+// Keyed on ChatSessionID because that is the daemon's only chat discriminator+// (see Task.ChatSessionID). IsLeaderTask cannot serve here even though the+// comment above it describes chat's semantics exactly: the server never writes+// that column on the chat-task insert path (service.EnqueueChatTask →+// db.CreateChatTaskParams has no such field), so it is false on every chat+// turn ever dispatched.+func localDirectoryLockExempt(task Task) bool {+ return task.ChatSessionID != ""+}+// 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 regulardiff --git a/server/internal/daemon/local_directory_test.go b/server/internal/daemon/local_directory_test.goindex 5815d59bf7..323f32f93b 100644--- a/server/internal/daemon/local_directory_test.go+++ b/server/internal/daemon/local_directory_test.go@@ -965,3 +965,249 @@ func TestValidateExecutionModeAcceptsKnownModes(t *testing.T) {t.Errorf("nil assignment should validate, got %v", err)}}++// TestLocalDirectoryLockExempt pins the discriminator itself. IsLeaderTask is+// listed explicitly because it is the flag the original carve-out keyed on, and+// the whole defect in issue #7344 was that it is false on every chat task the+// server has ever inserted.+func TestLocalDirectoryLockExempt(t *testing.T) {+ t.Parallel()++ cases := []struct {+ name string+ task Task+ want bool+ }{+ {"chat task", Task{ChatSessionID: "sess-1"}, true},+ {"chat task dispatched in the leader role", Task{ChatSessionID: "sess-1", IsLeaderTask: true}, true},+ {"issue task", Task{IssueID: "issue-1"}, false},+ {"issue task in the leader role", Task{IssueID: "issue-1", IsLeaderTask: true}, false},+ {"autopilot task", Task{AutopilotRunID: "run-1"}, false},+ }+ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ if got := localDirectoryLockExempt(tc.task); got != tc.want {+ t.Fatalf("localDirectoryLockExempt = %v, want %v", got, tc.want)+ }+ })+ }+}++// TestChatTaskSkipsPathMutexButKeepsAssignment is the regression test for issue+// #7344 and for the trap in the obvious one-line fix for it.+//+// Two properties, and BOTH have to hold. A chat turn must not queue on the path+// mutex — that is the reported bug. But it must still resolve an assignment,+// because that same value is what puts the agent in the user's directory and+// what stamps the GC meta; freeing the lock by returning no assignment would+// have moved chat out of the repo it was asked about.+func TestChatTaskSkipsPathMutexButKeepsAssignment(t *testing.T) {+ t.Parallel()++ const daemonID = "d-mine"+ tmp := t.TempDir()+ raw, err := json.Marshal(localDirectoryRef{LocalPath: tmp, DaemonID: daemonID})+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ resources := []ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: raw},+ }++ worker := Task{ID: "worker-task", IssueID: "issue-1", ProjectResources: resources}+ chat := Task{ID: "chat-task", ChatSessionID: "sess-1", ProjectResources: resources}++ // Property 1: the chat task still binds to the user's directory.+ chatAssignment, err := localDirectoryAssignmentForTask(chat, daemonID)+ if err != nil {+ t.Fatalf("chat assignment: %v", err)+ }+ if chatAssignment == nil {+ t.Fatal("chat assignment is nil: the chat turn would run outside the user's directory")+ }+ if chatAssignment.AbsPath != tmp {+ t.Fatalf("chat assignment path = %q, want %q", chatAssignment.AbsPath, tmp)+ }+ if chatAssignment.UsesWorktree() {+ t.Fatal("chat assignment reports worktree mode for an in_place resource")+ }++ // The exempt path never calls the server, but a REGRESSION would: it would+ // park and post waiting_local_directory. Wiring a real client is what makes+ // that regression fail with the message below instead of a nil-client panic.+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ cfg: Config{DaemonID: daemonID},+ client: NewClient(srv.URL),+ localPathLocks: NewLocalPathLocker(),+ logger: slog.Default(),+ cancelPollInterval: time.Hour,+ }++ // The coding task takes the lock and keeps it for the rest of the test —+ // this is the 20-minute build the chat turn used to queue behind.+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), worker, slog.Default())+ if abort {+ t.Fatal("worker lock acquisition aborted")+ }+ if release == nil {+ t.Fatal("worker lock acquisition returned nil release")+ }+ defer release()+ if got := d.localPathLocks.Holder(chatAssignment.RealPath); got != worker.ID {+ t.Fatalf("holder = %q, want %q", got, worker.ID)+ }++ // Property 2: the chat task walks straight past the held lock. Run it off+ // the test goroutine so a regression reports as a failure here instead of+ // hanging until the package-wide test timeout.+ type acquireResult struct {+ release func()+ abort bool+ }+ done := make(chan acquireResult, 1)+ go func() {+ chatRelease, chatAbort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), chat, slog.Default())+ done <- acquireResult{release: chatRelease, abort: chatAbort}+ }()++ select {+ case got := <-done:+ if got.abort {+ t.Fatal("chat lock acquisition aborted")+ }+ if got.release != nil {+ t.Fatal("chat lock acquisition returned a release callback: it took the mutex")+ }+ case <-time.After(10 * time.Second):+ t.Fatal("chat task blocked on the path mutex held by a coding task (issue #7344)")+ }++ // And it left the holder alone on the way past.+ if got := d.localPathLocks.Holder(chatAssignment.RealPath); got != worker.ID {+ t.Fatalf("holder after chat skip = %q, want %q", got, worker.ID)+ }+}++// TestChatTaskOnWorktreeResourceKeepsAssignment guards the interaction between+// the two exemptions: worktree mode is checked first, so a chat task on a+// worktree resource must still come back with an assignment (its worktree is+// built from it) rather than falling through to the chat carve-out's nil.+func TestChatTaskOnWorktreeResourceKeepsAssignment(t *testing.T) {+ t.Parallel()++ const daemonID = "d-mine"+ tmp := t.TempDir()+ raw, err := json.Marshal(localDirectoryRef{+ LocalPath: tmp,+ DaemonID: daemonID,+ ExecutionMode: localDirectoryModeWorktree,+ })+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ chat := Task{+ ID: "chat-task",+ ChatSessionID: "sess-1",+ ProjectResources: []ProjectResourceData{{ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: raw}},+ }++ assignment, err := localDirectoryAssignmentForTask(chat, daemonID)+ if err != nil {+ t.Fatalf("chat assignment: %v", err)+ }+ if assignment == nil {+ t.Fatal("chat assignment on a worktree resource is nil")+ }+ if !assignment.UsesWorktree() {+ t.Fatal("assignment lost worktree mode")+ }++ d := &Daemon{+ cfg: Config{DaemonID: daemonID},+ localPathLocks: NewLocalPathLocker(),+ logger: slog.Default(),+ }+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), chat, slog.Default())+ if abort {+ t.Fatal("chat lock acquisition aborted")+ }+ if release != nil {+ t.Fatal("worktree chat task took the path mutex")+ }+ if got := d.localPathLocks.Holder(assignment.RealPath); got != "" {+ t.Fatalf("holder = %q, want empty", got)+ }+}++// TestIssueTasksStillSerialiseOnPathMutex is the negative control: the+// exemption must not have widened into "nobody locks any more". Two issue tasks+// on one in_place directory still take turns.+func TestIssueTasksStillSerialiseOnPathMutex(t *testing.T) {+ t.Parallel()++ const daemonID = "d-mine"+ tmp := t.TempDir()+ raw, err := json.Marshal(localDirectoryRef{LocalPath: tmp, DaemonID: daemonID})+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ resources := []ProjectResourceData{+ {ID: "r1", ResourceType: localDirectoryResourceType, ResourceRef: raw},+ }+ first := Task{ID: "issue-task-1", IssueID: "issue-1", ProjectResources: resources}+ second := Task{ID: "issue-task-2", IssueID: "issue-2", ProjectResources: resources}++ // Parking calls back to the server to flip the row into+ // waiting_local_directory, so this daemon — unlike the exempt-path ones+ // above, which never reach contention — needs a real client.+ var waitCalls atomic.Int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {+ if strings.HasSuffix(req.URL.Path, "/wait-local-directory") {+ waitCalls.Add(1)+ }+ w.WriteHeader(http.StatusOK)+ }))+ t.Cleanup(srv.Close)++ d := &Daemon{+ cfg: Config{DaemonID: daemonID},+ client: NewClient(srv.URL),+ localPathLocks: NewLocalPathLocker(),+ logger: slog.Default(),+ cancelPollInterval: time.Hour, // never poll; the test drives cancellation itself+ }+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), first, slog.Default())+ if abort || release == nil {+ t.Fatalf("first issue task failed to take the lock (abort=%v)", abort)+ }++ // The second task must park rather than barge in. Cancelling the context is+ // how we observe "it was waiting" without needing the first task to finish.+ ctx, cancel := context.WithCancel(context.Background())+ blocked := make(chan struct{})+ go func() {+ defer close(blocked)+ secondRelease, _ := d.acquireLocalDirectoryLockIfNeeded(ctx, second, slog.Default())+ if secondRelease != nil {+ secondRelease()+ }+ }()++ select {+ case <-blocked:+ t.Fatal("second issue task did not wait for the path mutex")+ case <-time.After(200 * time.Millisecond):+ // Still parked, which is the point.+ }+ cancel()+ <-blocked+ if waitCalls.Load() == 0 {+ t.Error("waiting task never reported waiting_local_directory to the server")+ }+ release()+}diff --git a/server/internal/daemon/prompt.go b/server/internal/daemon/prompt.goindex 01f1656c66..ec619ac983 100644--- a/server/internal/daemon/prompt.go+++ b/server/internal/daemon/prompt.go@@ -60,9 +60,10 @@ func backendResumeContinuityNotice(task Task) string {// changing them costs only this turn's own tokens (MUL-5377).//// Returns "" when none of the blocks apply.-func perTurnContextBlocks(task Task) string {+func perTurnContextBlocks(task Task, opts promptOpts) string {var b strings.Builderb.WriteString(buildActiveSiblingRunsBlock(task.IssueID, task.ActiveSiblingRuns))+ b.WriteString(buildSharedLocalDirectoryBlock(opts.sharedLocalDirectory))if task.PriorSessionResumeUnavailable {b.WriteString(sessionContinuityNoticeFor(task))}@@ -71,6 +72,43 @@ func perTurnContextBlocks(task Task) string {return b.String()}+// promptOpts carries per-run facts the claimed Task does not: things only the+// daemon's own execution context can answer. Kept behind PromptOption so the+// common BuildPrompt(task, provider) call sites stay unchanged.+type promptOpts struct {+ sharedLocalDirectory bool+}++// PromptOption tunes per-turn prompt copy with run-scoped context.+type PromptOption func(*promptOpts)++// WithSharedLocalDirectory marks a turn that runs inside the user's own+// directory WITHOUT holding its path mutex — today, a chat turn on an in_place+// local_directory resource (see localDirectoryLockExempt). Such a turn may+// overlap a coding task writing to the same tree, and unlike every other task+// it got there by design rather than by winning the lock, so it is the one that+// has to be told (issue #7344).+func WithSharedLocalDirectory() PromptOption {+ return func(o *promptOpts) { o.sharedLocalDirectory = true }+}++// buildSharedLocalDirectoryBlock warns an unlocked turn that its working+// directory is shared live. Deliberately guidance and not a prohibition: the+// mutex never covered the user's own editor either, so refusing writes here+// would buy a restriction the surrounding system does not actually enforce.+// What the turn cannot infer on its own is that a sibling task may be mid-edit+// in the same tree — so state that, and let it size its writes accordingly.+func buildSharedLocalDirectoryBlock(shared bool) string {+ if !shared {+ return ""+ }+ var b strings.Builder+ b.WriteString("## Shared working directory\n\n")+ b.WriteString("Your working directory is the user's own checkout, and another task on this machine may be editing it while you run. This turn deliberately neither holds nor waits for the directory lock — that is what keeps a conversation from queueing behind a long build.\n\n")+ b.WriteString("Read freely. Treat writing the way the user treats saving a file in their own editor: reasonable for a small change they just asked for, wrong for a broad refactor, a dependency install, or a build that rewrites many files. Work that size belongs in an issue task, which is serialised against the other writers. If you do write, say so in your reply — a sibling task may be looking at the same file.\n\n")+ return b.String()+}+func buildActiveSiblingRunsBlock(currentIssueID string, runs []ActiveSiblingRunData) string {// Sibling issue work is useful context only for another issue task. Chat,// autopilot, and quick-create tasks have no current target issue whose claim@@ -112,12 +150,16 @@ func buildActiveSiblingRunsBlock(currentIssueID string, runs []ActiveSiblingRunD// is provider-agnostic AND host-agnostic now (every OS → write a UTF-8 file,// post with `--content-file`) because the shell-layer corruption it guards// against is not specific to any one provider or host (MUL-2904, #4182).-func BuildPrompt(task Task, provider string) string {+func BuildPrompt(task Task, provider string, options ...PromptOption) string {+ var opts promptOpts+ for _, apply := range options {+ apply(&opts)+ }body := buildPromptBody(task, provider)// Run-scoped context is appended, never prepended: everything ahead of it// is stable across runs of a resumed session, and appending keeps it after// the cached prefix (MUL-5377).- if blocks := perTurnContextBlocks(task); blocks != "" {+ if blocks := perTurnContextBlocks(task, opts); blocks != "" {if !strings.HasSuffix(body, "\n\n") {body += "\n"}diff --git a/server/internal/daemon/prompt_test.go b/server/internal/daemon/prompt_test.goindex bcad1521d6..2738bc82d8 100644--- a/server/internal/daemon/prompt_test.go+++ b/server/internal/daemon/prompt_test.go@@ -1728,3 +1728,47 @@ func TestChatChannelDeliversFilesDefaultsOffAcrossVersions(t *testing.T) {t.Error("a server that reported file delivery did not produce the upload guidance")}}++// TestSharedLocalDirectoryBlock covers the notice a lock-exempt turn gets. It+// is opt-in per run rather than derived from the Task, because whether the+// directory is shared depends on the daemon's own resolution of the resource —+// something the claimed Task does not carry.+func TestSharedLocalDirectoryBlock(t *testing.T) {+ t.Parallel()++ chat := Task{ChatSessionID: "sess-1", ChatMessage: "how does the parser work?"}++ t.Run("absent by default", func(t *testing.T) {+ out := BuildPrompt(chat, "claude")+ if strings.Contains(out, "Shared working directory") {+ t.Fatalf("notice leaked into a run with no local_directory:\n%s", out)+ }+ })++ t.Run("present when the turn runs unlocked in a shared directory", func(t *testing.T) {+ out := BuildPrompt(chat, "claude", WithSharedLocalDirectory())+ if !strings.Contains(out, "Shared working directory") {+ t.Fatalf("notice missing:\n%s", out)+ }+ // The non-inferable fact is the concurrent writer. Without it the block+ // is just style advice.+ if !strings.Contains(out, "another task on this machine may be editing it") {+ t.Fatalf("notice does not state that a sibling task may be writing:\n%s", out)+ }+ // It must stay guidance: turning it into a prohibition would promise an+ // isolation the daemon does not enforce for the user's own editor either.+ if strings.Contains(out, "Do NOT write") || strings.Contains(out, "must not write") {+ t.Fatalf("notice hardened into a prohibition the system does not enforce:\n%s", out)+ }+ })++ t.Run("appended after the cacheable prefix", func(t *testing.T) {+ // Run-scoped blocks go at the end so a resumed session's cached prefix+ // is unchanged by them (MUL-5377).+ out := BuildPrompt(chat, "claude", WithSharedLocalDirectory())+ body := buildChatPrompt(chat)+ if !strings.HasPrefix(out, body) {+ t.Fatalf("notice was not appended after the chat body:\n%s", out)+ }+ })+}diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex fa81a1f1aa..db82d84d29 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -1225,13 +1225,31 @@ func (h *Handler) ListChatMessagesPage(w http.ResponseWriter, r *http.Request) {// optimistic seeds don't have a real task created_at and the timer needs to// survive refresh / reopen.type PendingChatTaskResponse struct {- TaskID string `json:"task_id,omitempty"`- Status string `json:"status,omitempty"`- CreatedAt string `json:"created_at,omitempty"`+ TaskID string `json:"task_id,omitempty"`+ Status string `json:"status,omitempty"`+ CreatedAt string `json:"created_at,omitempty"`+ // WaitReason explains a waiting_local_directory hold: which directory the+ // task is parked on and, when known, the short id of the task holding it.+ // Emitted only for that status — on any other one the column still carries+ // the last hold's text, which would read as a live explanation for a task+ // that is running fine. Absent on older servers, which the client renders+ // as today's bare "Waiting for local directory".+ WaitReason string `json:"wait_reason,omitempty"`SupportsQueue bool `json:"supports_queue"`QueuedTasks []QueuedChatTaskResponse `json:"queued_tasks,omitempty"`}+// waitReasonForStatus gates the stored hold text on the status it describes.+// wait_reason is never cleared when a task resumes — the daemon writes it once+// on the way into the hold — so returning it unconditionally would attach "held+// by task abc12345" to a task that has been running for ten minutes.+func waitReasonForStatus(status string, reason pgtype.Text) string {+ if status != "waiting_local_directory" || !reason.Valid {+ return ""+ }+ return strings.TrimSpace(reason.String)+}+type QueuedChatTaskResponse struct {TaskID string `json:"task_id"`Status string `json:"status"`@@ -1606,6 +1624,7 @@ func (h *Handler) GetPendingChatTask(w http.ResponseWriter, r *http.Request) {TaskID: uuidToString(head.ID),Status: head.Status,CreatedAt: timestampToString(head.CreatedAt),+ WaitReason: waitReasonForStatus(head.Status, head.WaitReason),SupportsQueue: true,QueuedTasks: queued,})diff --git a/server/internal/handler/chat_wait_reason_test.go b/server/internal/handler/chat_wait_reason_test.gonew file mode 100644index 0000000000..a36d655079--- /dev/null+++ b/server/internal/handler/chat_wait_reason_test.go@@ -0,0 +1,44 @@+package handler++import (+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+)++// TestWaitReasonForStatus pins the gate that keeps a finished hold from being+// reported as a live one. wait_reason is written once, on the way into+// waiting_local_directory, and never cleared — so the status is the only thing+// that says whether the text still describes the present.+func TestWaitReasonForStatus(t *testing.T) {+ t.Parallel()++ held := pgtype.Text{String: "NuvioTV (held by task a1b2c3d4)", Valid: true}++ t.Run("returned while the task is parked", func(t *testing.T) {+ if got := waitReasonForStatus("waiting_local_directory", held); got != "NuvioTV (held by task a1b2c3d4)" {+ t.Fatalf("wait reason = %q, want the stored text", got)+ }+ })++ t.Run("suppressed once the task moves on", func(t *testing.T) {+ for _, status := range []string{"running", "dispatched", "queued", "deferred"} {+ if got := waitReasonForStatus(status, held); got != "" {+ t.Errorf("status %q leaked a stale hold reason: %q", status, got)+ }+ }+ })++ t.Run("absent reason is empty, not NULL text", func(t *testing.T) {+ if got := waitReasonForStatus("waiting_local_directory", pgtype.Text{}); got != "" {+ t.Fatalf("wait reason = %q, want empty for a NULL column", got)+ }+ })++ t.Run("whitespace-only reason reads as absent", func(t *testing.T) {+ blank := pgtype.Text{String: " ", Valid: true}+ if got := waitReasonForStatus("waiting_local_directory", blank); got != "" {+ t.Fatalf("wait reason = %q, want empty", got)+ }+ })+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 84248742f9..24391e5d6e 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -3658,7 +3658,7 @@ func (s *TaskService) ExtendTaskPrepareLease(ctx context.Context, taskID, runtim// 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)+ reason = sanitizeWaitReason(reason)task, err := s.Queries.MarkAgentTaskWaitingLocalDirectory(ctx, db.MarkAgentTaskWaitingLocalDirectoryParams{ID: taskID,WaitReason: pgtype.Text{String: reason, Valid: reason != ""},@@ -3678,10 +3678,73 @@ func (s *TaskService) MarkTaskWaitingLocalDirectory(ctx context.Context, taskID// reconcile immediately when it parks instead of leaving that persisted// status stale until a terminal transition.s.ReconcileAgentStatus(ctx, task.AgentID)- s.broadcastTaskEvent(ctx, protocol.EventTaskWaitingLocalDirectory, task)+ // Carry the reason on the event, not just in the row. Without it the client+ // learns WHY a task parked only on the follow-up refetch, so the pill spends+ // that round-trip saying nothing useful — which is the gap this hint exists+ // to close. Already sanitized above, so the socket cannot carry a path the+ // REST payload would have withheld.+ extra := map[string]any{}+ if reason != "" {+ extra["wait_reason"] = reason+ }+ s.broadcastTaskEvent(ctx, protocol.EventTaskWaitingLocalDirectory, task, extra)return &task, nil}+// legacyLocalDirectoryWaitPrefix is how daemons before the display-name change+// opened a wait reason: the literal word, a space, then the absolute path.+const legacyLocalDirectoryWaitPrefix = "local_directory "++// sanitizeWaitReason drops a wait reason that carries an absolute filesystem+// path, then trims what remains.+//+// Version skew makes this load-bearing rather than defensive. Current daemons+// send a display name (localDirectoryAssignment.DisplayName) precisely because+// this text reaches every client on the session and lands in screenshots. An+// OLDER daemon paired with this server still sends `local_directory /Users/+// <name>/repo (held by task abc12345)`, and since clients now render the field+// instead of ignoring it, passing that through would put the user's home path+// — and account name — on screen. The leak would be introduced BY surfacing+// the field, so the guard belongs with it.+//+// Dropping the whole string rather than editing it: clients already handle an+// absent reason (older servers never sent one) by showing the plain waiting+// label, which is exactly the pre-change behaviour and is never wrong.+//+// Remove once no supported daemon emits the legacy format.+func sanitizeWaitReason(reason string) string {+ reason = strings.TrimSpace(reason)+ rest, ok := strings.CutPrefix(reason, legacyLocalDirectoryWaitPrefix)+ if ok && startsWithAbsolutePath(rest) {+ return ""+ }+ return reason+}++// startsWithAbsolutePath reports whether s opens with an absolute path on any+// platform the daemon runs on: POSIX (/…), Windows drive (C:\… or C:/…), or a+// UNC share (\\host\share). Checked against the daemon's own output, so the+// question is only "did an old daemon put a path here", not general parsing.+//+// It deliberately does NOT match the holder clause a current daemon appends —+// `local_directory (held by task abc12345)` is what this server produces when+// a directory is genuinely NAMED "local_directory", and that name is the user's+// own label, not a path.+func startsWithAbsolutePath(s string) bool {+ if s == "" {+ return false+ }+ if s[0] == '/' || strings.HasPrefix(s, `\\`) {+ return true+ }+ // Drive-letter form: a single ASCII letter, a colon, then a separator.+ if len(s) >= 3 && s[1] == ':' && (s[2] == '\\' || s[2] == '/') {+ c := s[0]+ return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')+ }+ return false+}+// CompleteTask marks a task as completed.// Issue status is NOT changed here — the agent manages it via the CLI.//diff --git a/server/internal/service/wait_reason_test.go b/server/internal/service/wait_reason_test.gonew file mode 100644index 0000000000..8d86fdf012--- /dev/null+++ b/server/internal/service/wait_reason_test.go@@ -0,0 +1,61 @@+package service++import "testing"++// TestSanitizeWaitReason covers the version-skew guard on the hold hint.+//+// The leak this prevents is one that surfacing the field CREATED: before the+// StatusPill read wait_reason, an old daemon's absolute path sat unread in a+// column. A new server paired with an old daemon would now render it, so the+// legacy format has to die at the write boundary — the one place both the REST+// payload and the websocket event read through.+func TestSanitizeWaitReason(t *testing.T) {+ t.Parallel()++ t.Run("drops the legacy absolute-path format", func(t *testing.T) {+ cases := []string{+ "local_directory /Users/foxace/repos/NuvioTV",+ "local_directory /Users/foxace/repos/NuvioTV (held by task a1b2c3d4)",+ "local_directory /home/foxace/src/app (held by task a1b2c3d4)",+ `local_directory C:\Users\foxace\repos\NuvioTV`,+ `local_directory c:/Users/foxace/repos/NuvioTV (held by task a1b2c3d4)`,+ `local_directory \\fileserver\share\repo`,+ " local_directory /Users/foxace/repos/NuvioTV ",+ }+ for _, reason := range cases {+ if got := sanitizeWaitReason(reason); got != "" {+ t.Errorf("sanitizeWaitReason(%q) = %q, want empty — a path reached the client", reason, got)+ }+ }+ })++ t.Run("keeps the display-name format current daemons send", func(t *testing.T) {+ cases := map[string]string{+ "NuvioTV": "NuvioTV",+ "NuvioTV (held by task a1b2c3d4)": "NuvioTV (held by task a1b2c3d4)",+ " NuvioTV (held by task a1b2c3d4) ": "NuvioTV (held by task a1b2c3d4)",+ "my repo with spaces": "my repo with spaces",+ "team/service-api": "team/service-api",+ "": "",+ }+ for reason, want := range cases {+ if got := sanitizeWaitReason(reason); got != want {+ t.Errorf("sanitizeWaitReason(%q) = %q, want %q", reason, got, want)+ }+ }+ })++ t.Run("keeps a directory genuinely named local_directory", func(t *testing.T) {+ // Current daemons send label-or-basename, so this is what a directory+ // actually called "local_directory" produces. The guard must key on the+ // path that follows the legacy prefix, not on the word alone.+ for _, reason := range []string{+ "local_directory",+ "local_directory (held by task a1b2c3d4)",+ } {+ if got := sanitizeWaitReason(reason); got != reason {+ t.Errorf("sanitizeWaitReason(%q) = %q, want it kept", reason, got)+ }+ }+ })+}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 32d19badfe..7d6a57a079 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -2016,6 +2016,11 @@ SELECTtask.id,task.status,task.created_at,+ -- Only meaningful while status is waiting_local_directory: the daemon+ -- stamps which directory this task is parked on and who holds it, so the+ -- StatusPill can say why it is not moving. Stale on any other status; the+ -- renderer reads it only for the waiting one.+ task.wait_reason,message.id AS message_id,COALESCE(message.content, '')::text AS contentFROM agent_task_queue AS task@@ -2042,11 +2047,12 @@ ORDER BY`type ListPendingChatTasksForSessionRow struct {- ID pgtype.UUID `json:"id"`- Status string `json:"status"`- CreatedAt pgtype.Timestamptz `json:"created_at"`- MessageID pgtype.UUID `json:"message_id"`- Content string `json:"content"`+ ID pgtype.UUID `json:"id"`+ Status string `json:"status"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ WaitReason pgtype.Text `json:"wait_reason"`+ MessageID pgtype.UUID `json:"message_id"`+ Content string `json:"content"`}// Returns a claimed task first, then a deferred retry, followed by prioritized@@ -2070,6 +2076,7 @@ func (q *Queries) ListPendingChatTasksForSession(ctx context.Context, chatSessio&i.ID,&i.Status,&i.CreatedAt,+ &i.WaitReason,&i.MessageID,&i.Content,); err != nil {diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex e0ff9cb066..ebc078aeaa 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -1147,6 +1147,11 @@ SELECTtask.id,task.status,task.created_at,+ -- Only meaningful while status is waiting_local_directory: the daemon+ -- stamps which directory this task is parked on and who holds it, so the+ -- StatusPill can say why it is not moving. Stale on any other status; the+ -- renderer reads it only for the waiting one.+ task.wait_reason,message.id AS message_id,COALESCE(message.content, '')::text AS contentFROM agent_task_queue AS task