Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(daemon): release execution capacity while Direct tasks wait for a directory (#10846)

Danila Katalshov84c626cda95a
diff --git a/apps/docs/content/docs/daemon-runtimes.fr.mdx b/apps/docs/content/docs/daemon-runtimes.fr.mdx
index f27ffbb3a4..ef8f51b155 100644
--- a/apps/docs/content/docs/daemon-runtimes.fr.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.fr.mdx
@@ -103,6 +103,8 @@ Les états détaillés et les règles de relance figurent dans [Exécutions](/ta
Par défaut, un daemon traite au maximum 20 exécutions simultanées, et chaque agent au maximum 6. Le parallélisme effectif correspond à la plus petite de ces deux valeurs.
+Les exécutions qui attendent un répertoire local en mode Direct n'occupent pas de slot d'exécution du daemon. Elles en reprennent un avant de démarrer et restent comptées comme du travail détenu par le daemon pour la sécurité de l'arrêt et des mises à jour.
+
Une fois une limite atteinte, les nouvelles exécutions restent en file d'attente. Le parallélisme d'un agent se règle dans ses paramètres, le plafond global de la machine avec `MULTICA_DAEMON_MAX_CONCURRENT_TASKS`. Les exécutions en parallèle se disputent en même temps la capacité de la machine, le quota du compte de l'outil et le même répertoire de travail.
La consommation de tokens, les coûts et les échecs des exécutions sont regroupés par espace de travail sur la page [Statistiques](/analytics) ; `multica runtime usage <runtime-id>` affiche la consommation de tokens d'un seul runtime.
diff --git a/apps/docs/content/docs/daemon-runtimes.ja.mdx b/apps/docs/content/docs/daemon-runtimes.ja.mdx
index f0b20df4e4..cdc793ceeb 100644
--- a/apps/docs/content/docs/daemon-runtimes.ja.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ja.mdx
@@ -103,6 +103,8 @@ multica daemon autostart disable
1 つのデーモンはデフォルトで最大 20 件の実行を同時に処理します。各エージェントはデフォルトで最大 6 件です。実効的な同時実行数は両者の小さい方になります。
+直接モードのローカルディレクトリを待つ実行は、デーモンの実行スロットを消費しません。開始前にスロットを再取得します。待機中もデーモンが所有する処理として数えられ、終了や更新の安全確認の対象になります。
+
上限に達すると、新しい実行はキューで待ち続けます。個々のエージェントの同時実行数はエージェント設定で、マシン全体の上限は `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` で調整できます。並列実行は、マシンの性能、ツールアカウントのクォータ、同じ作業ディレクトリを同時に取り合います。
実行で使われたトークン、費用、失敗はワークスペースごとに[分析](/analytics)ページにまとまっています。1 つのランタイムのトークン使用量は `multica runtime usage <runtime-id>` でも確認できます。
diff --git a/apps/docs/content/docs/daemon-runtimes.ko.mdx b/apps/docs/content/docs/daemon-runtimes.ko.mdx
index 88c26913d9..f66e7720b4 100644
--- a/apps/docs/content/docs/daemon-runtimes.ko.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.ko.mdx
@@ -103,6 +103,8 @@ multica daemon autostart disable
데몬 한 대는 기본적으로 실행을 최대 20개까지 동시에 처리하며, 에이전트 한 명은 기본적으로 최대 6개까지 처리합니다. 실제 동시 실행 수에는 둘 중 더 작은 값이 적용됩니다.
+직접 모드의 로컬 디렉터리를 기다리는 실행은 데몬 실행 슬롯을 차지하지 않습니다. 시작 전에 슬롯을 다시 확보하며, 대기 중에도 종료와 업데이트의 안전 확인에서는 데몬이 소유한 작업으로 계산됩니다.
+
상한에 도달하면 새 실행은 계속 큐에서 기다립니다. 에이전트 설정에서 개별 에이전트의 동시 실행 수를 조정할 수 있고 `MULTICA_DAEMON_MAX_CONCURRENT_TASKS`로 컴퓨터 전체 상한을 조정할 수도 있습니다. 병렬 실행은 컴퓨터 성능, 도구 계정 사용량, 같은 작업 디렉터리를 동시에 사용합니다.
실행에 쓰인 토큰, 비용, 실패는 워크스페이스별로 [분석](/analytics) 페이지에 모여 있습니다. 런타임 하나의 토큰 사용량은 `multica runtime usage <runtime-id>`로도 볼 수 있습니다.
diff --git a/apps/docs/content/docs/daemon-runtimes.mdx b/apps/docs/content/docs/daemon-runtimes.mdx
index bd4404a63f..427bc4dee4 100644
--- a/apps/docs/content/docs/daemon-runtimes.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.mdx
@@ -103,6 +103,8 @@ Detailed states and retry rules are in [Runs](/tasks).
One daemon executes at most 20 runs at a time by default; each agent at most 6. Effective concurrency is the smaller of the two.
+Runs waiting for a Direct local directory do not use a daemon execution slot. They reacquire a slot before starting and still count as owned work for shutdown and update safety.
+
Once a limit is reached, new runs keep queueing. Adjust a single agent's concurrency in the agent settings, and the machine-wide cap with `MULTICA_DAEMON_MAX_CONCURRENT_TASKS`. Parallel runs compete for machine capacity, tool account quota, and the same working directory all at once.
Token usage, cost, and failures across runs are summarized per workspace on the [Analytics](/analytics) page; `multica runtime usage <runtime-id>` shows token usage for a single runtime.
diff --git a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
index 4efcbae4de..4e4bd52384 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh-Hant.mdx
@@ -104,6 +104,8 @@ multica daemon autostart disable
一臺守護程序預設最多同時執行 20 次執行;每個 AI 代理預設最多同時執行 6 次。實際併發取兩者中的較小值。
+等待直接修改模式本地目錄的執行不佔用守護程序執行槽位。開始前會重新取得槽位;等待期間仍由守護程序持有,關閉和更新時的安全檢查仍會計入這些執行。
+
達到上限後,新執行繼續排隊。單個 AI 代理的併發數在 AI 代理設定中調整,整臺電腦的上限用 `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` 調整。並行執行會同時佔用機器效能、工具帳號額度和同一工作目錄。
執行消耗的 token、費用和失敗情況在[統計](/analytics)頁按工作區彙總;單條執行時的 token 用量也可以用 `multica runtime usage <runtime-id>` 檢視。
diff --git a/apps/docs/content/docs/daemon-runtimes.zh.mdx b/apps/docs/content/docs/daemon-runtimes.zh.mdx
index 9c60652d69..948624668c 100644
--- a/apps/docs/content/docs/daemon-runtimes.zh.mdx
+++ b/apps/docs/content/docs/daemon-runtimes.zh.mdx
@@ -104,6 +104,8 @@ multica daemon autostart disable
一台守护进程默认最多同时执行 20 次运行;每个智能体默认最多同时执行 6 次。实际并发取两者中的较小值。
+等待直接修改模式本地目录的运行不占用守护进程执行槽位。开始前会重新获取槽位;等待期间仍由守护进程持有,关闭和更新时的安全检查仍会计入这些运行。
+
达到上限后,新运行继续排队。单个智能体的并发数在智能体设置中调整,整台电脑的上限用 `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` 调整。并行执行会同时占用机器性能、工具账号额度和同一工作目录。
运行消耗的 token、费用和失败情况在[统计](/analytics)页按工作区汇总;单条运行时的 token 用量也可以用 `multica runtime usage <runtime-id>` 查看。
diff --git a/apps/docs/content/docs/project-resources.fr.mdx b/apps/docs/content/docs/project-resources.fr.mdx
index 97d22b4579..60778d8656 100644
--- a/apps/docs/content/docs/project-resources.fr.mdx
+++ b/apps/docs/content/docs/project-resources.fr.mdx
@@ -92,7 +92,7 @@ Un répertoire local dispose de deux modes d'exécution, définis par ressource
L'agent travaille directement dans votre répertoire, et les exécutions ont lieu une à la fois. Lorsque deux exécutions utilisent le même répertoire réel, la seconde passe en `waiting_local_directory` et reprend une fois que la première a libéré le répertoire. Deux chemins qui mènent au même répertoire via des liens symboliques différents sont sérialisés de la même manière.
-L'attente ne modifie pas le répertoire. Une exécution en attente peut être annulée ; sinon, elle attend que le répertoire devienne disponible.
+L'attente ne modifie pas le répertoire et n'occupe pas de slot d'exécution du daemon. Une exécution en attente peut être annulée ; sinon, elle reprend le démarrage lorsque le répertoire et la capacité d'exécution sont disponibles.
Un simple répertoire non git ne peut utiliser que ce mode : le mode worktree est réservé aux dépôts git.
diff --git a/apps/docs/content/docs/project-resources.ja.mdx b/apps/docs/content/docs/project-resources.ja.mdx
index c10e32b795..7c646eec8f 100644
--- a/apps/docs/content/docs/project-resources.ja.mdx
+++ b/apps/docs/content/docs/project-resources.ja.mdx
@@ -94,7 +94,7 @@ Desktop のローカルデーモンがオンラインであることを確認し
エージェントはあなたのディレクトリで直接作業し、実行は一度に 1 つずつ進みます。2 つの実行が同じ実体のディレクトリを使う場合、後から来た実行は `waiting_local_directory` に入り、先の実行がディレクトリを解放してから続行します。異なるシンボリックリンク経由で同じディレクトリに到達する 2 つのパスも、同じように直列化されます。
-待機中にディレクトリが変更されることはありません。待機中の実行はキャンセルできます。キャンセルしなければ、ディレクトリが使えるようになるまで待ち続けます。
+待機中はディレクトリを変更せず、デーモンの実行スロットも消費しません。待機中の実行はキャンセルできます。キャンセルしなければ、ディレクトリと実行容量の両方が利用可能になってから起動を再開します。
git 管理外の通常のディレクトリはこのモードしか使えません。ワークツリーモードは git リポジトリ専用です。
diff --git a/apps/docs/content/docs/project-resources.ko.mdx b/apps/docs/content/docs/project-resources.ko.mdx
index 9f2b9cb64b..74aeb9455d 100644
--- a/apps/docs/content/docs/project-resources.ko.mdx
+++ b/apps/docs/content/docs/project-resources.ko.mdx
@@ -92,7 +92,7 @@ Desktop의 로컬 데몬이 온라인인지 확인합니다.
에이전트가 사용자의 디렉터리에서 직접 작업하며, 실행은 한 번에 하나씩 진행됩니다. 두 실행이 같은 실제 디렉터리를 사용하면 나중에 도착한 실행이 `waiting_local_directory` 상태로 들어가 앞선 실행이 디렉터리를 해제할 때까지 기다립니다. 서로 다른 심볼릭 링크 경로가 같은 디렉터리를 가리켜도 직렬로 실행됩니다.
-기다리는 동안 디렉터리는 변경되지 않습니다. 대기 중인 실행은 취소할 수 있으며 취소하지 않으면 디렉터리를 사용할 수 있을 때까지 계속 기다립니다.
+기다리는 동안 디렉터리를 변경하지 않으며 데몬 실행 슬롯도 차지하지 않습니다. 대기 중인 실행은 취소할 수 있습니다. 취소하지 않으면 디렉터리와 실행 용량을 모두 사용할 수 있을 때 시작 과정을 재개합니다.
git으로 관리되지 않는 일반 디렉터리는 이 모드만 사용할 수 있습니다. 워크트리 모드는 git 저장소 전용입니다.
diff --git a/apps/docs/content/docs/project-resources.mdx b/apps/docs/content/docs/project-resources.mdx
index 0757b678c6..dcb67e2ae8 100644
--- a/apps/docs/content/docs/project-resources.mdx
+++ b/apps/docs/content/docs/project-resources.mdx
@@ -92,7 +92,7 @@ A local directory has two execution modes, set per resource with `execution_mode
The agent works directly in your directory, and runs execute one at a time. When two runs use the same real directory, the later one enters `waiting_local_directory` and continues after the earlier one releases the directory. Two paths that reach the same directory through different symlinks serialize the same way.
-Waiting does not modify the directory. A waiting run can be cancelled; otherwise it waits until the directory becomes available.
+Waiting does not modify the directory or consume a daemon execution slot. A waiting run can be cancelled; otherwise it resumes startup once both the directory and execution capacity are available.
A plain non-git directory can only use this mode: worktree mode covers git repositories.
diff --git a/apps/docs/content/docs/project-resources.zh-Hant.mdx b/apps/docs/content/docs/project-resources.zh-Hant.mdx
index dcae27e7ce..d650ab111a 100644
--- a/apps/docs/content/docs/project-resources.zh-Hant.mdx
+++ b/apps/docs/content/docs/project-resources.zh-Hant.mdx
@@ -93,7 +93,7 @@ import { LocalDirModeDemo } from "@/components/demos/local-dir-mode-demo";
AI 代理直接在你的目錄裡工作,同一時間只進行一次執行。兩次執行使用同一個真實目錄時,後到的執行進入 `waiting_local_directory`,等前一次釋放目錄後繼續。兩個路徑經不同符號連結指向同一目錄時,同樣序列。
-等待不會修改目錄。等待中的執行可以取消,否則會一直等到目錄可用。
+等待不會修改目錄,也不佔用守護程序執行槽位。等待中的執行可以取消,否則會在目錄和執行容量都可用後繼續啟動。
普通的非 git 目錄只能用這種模式:worktree 模式只面向 git 倉庫。
diff --git a/apps/docs/content/docs/project-resources.zh.mdx b/apps/docs/content/docs/project-resources.zh.mdx
index 85bdf81f02..57a68f7844 100644
--- a/apps/docs/content/docs/project-resources.zh.mdx
+++ b/apps/docs/content/docs/project-resources.zh.mdx
@@ -93,7 +93,7 @@ import { LocalDirModeDemo } from "@/components/demos/local-dir-mode-demo";
智能体直接在你的目录里工作,同一时间只进行一次运行。两次运行使用同一个真实目录时,后到的运行进入 `waiting_local_directory`,等前一次释放目录后继续。两个路径经不同符号链接指向同一目录时,同样串行。
-等待不会修改目录。等待中的运行可以取消,否则会一直等到目录可用。
+等待不会修改目录,也不占用守护进程执行槽位。等待中的运行可以取消,否则会在目录和执行容量都可用后继续启动。
普通的非 git 目录只能用这种模式:worktree 模式只面向 git 仓库。
diff --git a/apps/docs/content/docs/tasks.fr.mdx b/apps/docs/content/docs/tasks.fr.mdx
index 845659510f..96eae098a5 100644
--- a/apps/docs/content/docs/tasks.fr.mdx
+++ b/apps/docs/content/docs/tasks.fr.mdx
@@ -42,7 +42,7 @@ Une exécution passe généralement par ces états :
| `deferred` | Programmée pour plus tard ; entre dans la file d'attente à l'heure prévue |
| `queued` | En attente de prise en charge par un runtime |
| `dispatched` | Un runtime l'a prise en charge et démarre l'outil de codage IA |
-| `waiting_local_directory` | Le répertoire local cible est occupé par une autre exécution ; attente de la libération du verrou du répertoire |
+| `waiting_local_directory` | En attente du répertoire local cible ou d'un slot d'exécution du daemon avant le démarrage |
| `running` | L'outil de codage IA est en cours d'exécution |
| `completed` | L'exécution s'est terminée normalement |
| `failed` | L'exécution a rencontré une erreur ou a été interrompue |
@@ -167,7 +167,7 @@ Les valeurs ci-dessous sont celles de la configuration par défaut du serveur.
| `deferred` | Programmée pour plus tard | Passe à `queued` à l'heure prévue, puis les règles ci-dessous s'appliquent |
| `queued` | En attente de prise en charge par un runtime | Attend tant que son runtime continue d'envoyer des signaux de vie, et dans tous les cas au moins un délai de grâce de reconnexion après la mise en file d'attente ; n'échoue que lorsque les deux fenêtres sont écoulées, et n'est pas relancée automatiquement |
| `dispatched` | Prise en charge ; l'outil démarre | Considérée comme en échec après plus de **5 minutes** dans cet état |
-| `waiting_local_directory` | En attente de la libération du verrou du répertoire local | Pas de délai propre ; reprend le processus de démarrage une fois le répertoire libéré |
+| `waiting_local_directory` | En attente du répertoire local et de la capacité d'exécution | Pas de délai propre ; reprend le démarrage lorsque le répertoire et un slot d'exécution du daemon sont disponibles |
| `running` | L'outil de codage IA est en cours d'exécution | Pas de durée maximale fixe ; la vivacité suit le signal de vie du runtime — un toutes les 15 secondes ; un runtime qui perd son signal de vie est marqué hors ligne au plus tard en 3 minutes environ. Ses exécutions n'échouent qu'une fois le signal de vie absent au-delà du délai de grâce de reconnexion (`MULTICA_RUNTIME_RECONNECT_GRACE`, 3 heures par défaut) ; un redémarrage du daemon les récupère directement |
La relance automatique ne couvre que les défaillances transitoires ci-dessous, et ne s'applique qu'aux exécutions rattachées à une tâche ou à une discussion (hors mode **Exécution seule** des automatisations) :
diff --git a/apps/docs/content/docs/tasks.ja.mdx b/apps/docs/content/docs/tasks.ja.mdx
index 53720e0605..b342e06134 100644
--- a/apps/docs/content/docs/tasks.ja.mdx
+++ b/apps/docs/content/docs/tasks.ja.mdx
@@ -42,7 +42,7 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";
| `deferred` | 後で発火するようスケジュール済み。指定時刻になるとキューに入る |
| `queued` | ランタイムによる取得を待っている |
| `dispatched` | ランタイムが取得し、AI コーディングツールを起動中 |
-| `waiting_local_directory` | 対象のローカルディレクトリを別の実行が使用中で、ディレクトリロックの解放を待っている |
+| `waiting_local_directory` | 起動前に対象のローカルディレクトリまたはデーモンの実行スロットを待っている |
| `running` | AI コーディングツールが実行中 |
| `completed` | この実行は正常に終了した |
| `failed` | 実行がエラーになったか中断された |
@@ -167,7 +167,7 @@ multica issue rerun-task <run-id>
| `deferred` | 後で発火するようスケジュール済み | 予定時刻になると `queued` に入り、以降は下のルールに従う |
| `queued` | ランタイムによる取得待ち | ランタイムがハートビートを送り続けている限り待機し、さらにどの場合でもキュー投入から最低 1 回分の再接続猶予は確保される。両方の期間が過ぎたときにのみ失敗し、自動リトライはされない |
| `dispatched` | ランタイムが取得し、ツールを起動中 | **5 分**を超えてこの状態に留まると失敗として扱われる |
-| `waiting_local_directory` | ローカルディレクトリロックの解放待ち | 独自のタイムアウトはなし。ディレクトリが解放されると起動フローに戻る |
+| `waiting_local_directory` | ローカルディレクトリと実行容量の待機 | 独自のタイムアウトはなし。ディレクトリとデーモンの実行スロットが利用可能になると起動を再開する |
| `running` | AI コーディングツールが実行中 | 固定の時間上限はなし。生存はランタイムのハートビート(15 秒ごと)で判定し、ハートビートを失ったランタイムは遅くとも約 3 分でオフラインと判定される。その上の実行が失敗するのは、ハートビートの途絶が再接続猶予(`MULTICA_RUNTIME_RECONNECT_GRACE`、デフォルト 3 時間)を超えたとき。デーモンが再起動した場合は、これらの実行を直接回収する |
自動リトライは以下の一時的な障害のみを対象とし、タスクまたはチャットに紐づく実行にのみ適用されます(オートパイロットの**実行のみ**モードを除く):
diff --git a/apps/docs/content/docs/tasks.ko.mdx b/apps/docs/content/docs/tasks.ko.mdx
index eff40da7c9..6a20048e9e 100644
--- a/apps/docs/content/docs/tasks.ko.mdx
+++ b/apps/docs/content/docs/tasks.ko.mdx
@@ -42,7 +42,7 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";
| `deferred` | 나중에 트리거되도록 예약되었으며 지정 시간이 되면 큐에 들어갑니다. |
| `queued` | 런타임이 가져가기를 기다립니다. |
| `dispatched` | 런타임이 가져갔고 AI 코딩 도구를 시작하고 있습니다. |
-| `waiting_local_directory` | 대상 로컬 디렉터리를 다른 실행이 사용 중이어서 디렉터리 잠금 해제를 기다립니다. |
+| `waiting_local_directory` | 시작 전에 대상 로컬 디렉터리 또는 데몬 실행 슬롯을 기다립니다. |
| `running` | AI 코딩 도구가 실행 중입니다. |
| `completed` | 이번 실행이 정상적으로 끝났습니다. |
| `failed` | 실행 중 오류가 발생했거나 중단되었습니다. |
@@ -167,7 +167,7 @@ multica issue rerun-task <run-id>
| `deferred` | 나중에 트리거되도록 예약됨 | 예정 시간이 되면 `queued`로 들어가고 이후 아래 규칙에 따라 시간을 계산합니다. |
| `queued` | 런타임이 가져가기를 기다림 | 런타임이 하트비트를 보내는 동안에는 계속 기다리고, 어떤 경우에도 큐에 들어간 뒤 최소 한 번의 재연결 유예는 확보합니다. 두 기간이 모두 지난 뒤에만 실패하며 자동 재시도하지 않습니다. |
| `dispatched` | 런타임이 가져갔고 도구를 시작 중 | **5분** 넘게 머물면 실패로 처리합니다. |
-| `waiting_local_directory` | 로컬 디렉터리 잠금 해제를 기다림 | 별도 timeout이 없으며 디렉터리가 해제되면 시작 과정으로 돌아갑니다. |
+| `waiting_local_directory` | 로컬 디렉터리와 실행 용량을 기다림 | 별도 timeout이 없으며 디렉터리와 데몬 실행 슬롯을 사용할 수 있을 때 시작 과정을 재개합니다. |
| `running` | AI 코딩 도구 실행 중 | 고정 시간 상한이 없습니다. 런타임 하트비트로 생존을 판단하며 15초마다 하트비트를 보냅니다. 하트비트를 잃은 런타임은 늦어도 약 3분 뒤 오프라인으로 판단됩니다. 그 위의 실행은 하트비트가 재연결 유예(`MULTICA_RUNTIME_RECONNECT_GRACE`, 기본 3시간)를 넘겨 끊긴 뒤에야 실패하며, 데몬이 재시작되면 바로 회수됩니다. |
자동 재시도는 아래의 일시적 장애만 포함하며 태스크 또는 대화에 연결된 실행에만 적용됩니다. 오토파일럿의 **실행만** 모드는 제외됩니다.
diff --git a/apps/docs/content/docs/tasks.mdx b/apps/docs/content/docs/tasks.mdx
index 562c170b3f..71bff3615a 100644
--- a/apps/docs/content/docs/tasks.mdx
+++ b/apps/docs/content/docs/tasks.mdx
@@ -42,7 +42,7 @@ A run typically moves through these states:
| `deferred` | Scheduled to fire later; enters the queue at the appointed time |
| `queued` | Waiting for a runtime to claim it |
| `dispatched` | A runtime has claimed it and is starting the AI coding tool |
-| `waiting_local_directory` | The target local directory is held by another run; waiting for the directory lock to release |
+| `waiting_local_directory` | Waiting for the target local directory or a daemon execution slot before startup |
| `running` | The AI coding tool is executing |
| `completed` | The run finished normally |
| `failed` | The run errored or was interrupted |
@@ -167,7 +167,7 @@ The numbers below are the server's defaults.
| `deferred` | Scheduled to fire later | Enters `queued` at the scheduled time, then the rules below apply |
| `queued` | Waiting for a runtime to claim it | Waits as long as its runtime keeps heartbeating, and in every case for at least one reconnect grace after being queued; fails only when both windows have passed, and is not retried automatically |
| `dispatched` | Claimed; the tool is starting | Treated as failed after more than **5 minutes** in this state |
-| `waiting_local_directory` | Waiting for the local directory lock to release | No timeout of its own; returns to the startup flow once the directory is released |
+| `waiting_local_directory` | Waiting for the local directory and execution capacity | No timeout of its own; resumes startup once the directory and a daemon execution slot are available |
| `running` | The AI coding tool is executing | No fixed duration cap; liveness follows the runtime heartbeat — one every 15 seconds; a runtime that loses its heartbeat is marked offline within about 3 minutes at the latest. Its runs fail only once the heartbeat has been missing longer than the reconnect grace (`MULTICA_RUNTIME_RECONNECT_GRACE`, 3 hours by default); a daemon restart reclaims them directly |
Automatic retry covers only the transient faults below, and only applies to runs attached to an issue or a chat (excluding the Autopilot **run only** mode):
diff --git a/apps/docs/content/docs/tasks.zh-Hant.mdx b/apps/docs/content/docs/tasks.zh-Hant.mdx
index e81676077b..f60b4a0392 100644
--- a/apps/docs/content/docs/tasks.zh-Hant.mdx
+++ b/apps/docs/content/docs/tasks.zh-Hant.mdx
@@ -42,7 +42,7 @@ AI 代理每開始一次工作,Multica 就建立一條**執行記錄**,寫
| `deferred` | 已安排稍後觸發,到達指定時間後進入佇列 |
| `queued` | 正在等待執行時領取 |
| `dispatched` | 執行時已經領取,正在啟動 AI 程式設計工具 |
-| `waiting_local_directory` | 目標本地目錄正被另一條執行佔用,等待目錄鎖釋放 |
+| `waiting_local_directory` | 啟動前等待目標本地目錄或守護程序執行槽位 |
| `running` | AI 程式設計工具正在執行 |
| `completed` | 這次執行已正常結束 |
| `failed` | 執行出錯或中斷 |
@@ -167,7 +167,7 @@ multica issue rerun-task <run-id>
| `deferred` | 已安排稍後觸發 | 到達預定時間後進入 `queued`,再按下面的規則計時 |
| `queued` | 等待執行時領取 | 只要執行時還在心跳就一直等待,並且無論如何都會在入隊後至少保留一個重連寬限期;兩個視窗都過去才會失敗,且不會自動重試 |
| `dispatched` | 執行時已領取,正在啟動工具 | 停留超過 **5 分鐘**按失敗處理 |
-| `waiting_local_directory` | 等待本地目錄鎖釋放 | 沒有獨立超時;目錄釋放後回到啟動流程 |
+| `waiting_local_directory` | 等待本地目錄和執行容量 | 沒有獨立超時;目錄和守護程序執行槽位可用後繼續啟動 |
| `running` | AI 程式設計工具正在執行 | 不設固定時長上限;以執行時心跳判定存活,心跳每 15 秒一次,失去心跳的執行時最遲約 3 分鐘被判為離線。其上的執行要等心跳缺席超過重連寬限期(`MULTICA_RUNTIME_RECONNECT_GRACE`,預設 3 小時)才失敗;守護程序重啟時,會直接回收這些執行 |
自動重試只覆蓋以下臨時故障,且僅適用於掛在任務或對話上的執行(自動化**僅執行**模式除外):
diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdx
index 803d6f1da1..0e2dc3cfbb 100644
--- a/apps/docs/content/docs/tasks.zh.mdx
+++ b/apps/docs/content/docs/tasks.zh.mdx
@@ -42,7 +42,7 @@ import { RunLifecycleDemo } from "@/components/demos/run-lifecycle-demo";
| `deferred` | 已安排稍后触发,到达指定时间后进入队列 |
| `queued` | 正在等待运行时领取 |
| `dispatched` | 运行时已经领取,正在启动 AI 编程工具 |
-| `waiting_local_directory` | 目标本地目录正被另一条执行占用,等待目录锁释放 |
+| `waiting_local_directory` | 启动前等待目标本地目录或守护进程执行槽位 |
| `running` | AI 编程工具正在执行 |
| `completed` | 这次执行已正常结束 |
| `failed` | 执行出错或中断 |
@@ -167,7 +167,7 @@ multica issue rerun-task <run-id>
| `deferred` | 已安排稍后触发 | 到达预定时间后进入 `queued`,再按下面的规则计时 |
| `queued` | 等待运行时领取 | 只要运行时还在心跳就一直等待,并且无论如何都会在入队后至少保留一个重连宽限期;两个窗口都过去才会失败,且不会自动重试 |
| `dispatched` | 运行时已领取,正在启动工具 | 停留超过 **5 分钟**按失败处理 |
-| `waiting_local_directory` | 等待本地目录锁释放 | 没有独立超时;目录释放后回到启动流程 |
+| `waiting_local_directory` | 等待本地目录和执行容量 | 没有独立超时;目录和守护进程执行槽位可用后继续启动 |
| `running` | AI 编程工具正在执行 | 不设固定时长上限;以运行时心跳判定存活,心跳每 15 秒一次,失去心跳的运行时最迟约 3 分钟被判为离线。其上的运行要等心跳缺席超过重连宽限期(`MULTICA_RUNTIME_RECONNECT_GRACE`,默认 3 小时)才失败;守护进程重启时,会直接回收这些运行 |
自动重试只覆盖以下临时故障,且仅适用于挂在任务或对话上的运行(自动化**仅运行**模式除外):
diff --git a/apps/docs/content/docs/troubleshooting.fr.mdx b/apps/docs/content/docs/troubleshooting.fr.mdx
index 8e4db74bea..eecc08fa25 100644
--- a/apps/docs/content/docs/troubleshooting.fr.mdx
+++ b/apps/docs/content/docs/troubleshooting.fr.mdx
@@ -139,11 +139,11 @@ Si la liste des runtimes ne contient pas un outil attendu, vérifiez d'abord que
</Tab>
<Tab value="waiting_local_directory">
-Ce statut (affiché « En attente du répertoire local ») signifie qu'une autre exécution en cours utilise le même répertoire local. Multica attend que le verrou du répertoire soit libéré, afin que deux agents ne modifient jamais les mêmes fichiers en même temps.
+Avant le démarrage, cette exécution attend son répertoire local ou un slot d'exécution libre du daemon. L'indication `held by task ...` désigne le détenteur observé au début de l'attente ; elle ne suit pas le propriétaire actuel.
-Cette attente n'existe qu'en mode `in_place` (« Direct ») du répertoire. Si le répertoire est un dépôt git, passer la ressource en `worktree` (« Parallèle ») supprime complètement la file d'attente : chaque exécution obtient son propre worktree et rend son travail sous forme de branche, si bien que rien n'attend quoi que ce soit. Consultez [Ressources de projet](/project-resources#comment-les-exécutions-partagent-le-répertoire).
+Les exécutions Direct (`in_place`) sérialisent les écritures dans le même répertoire. Les exécutions Parallèle (`worktree`) utilisent des copies distinctes, mais la préparation d'un instantané de la source peut encore attendre si ce chemin est partagé avec des exécutions Direct. Consultez [Ressources de projet](/project-resources#comment-les-exécutions-partagent-le-répertoire).
-Sinon, il suffit d'attendre la fin de l'exécution précédente. Si elle est bloquée, arrêtez-la depuis son journal d'exécution (**Annuler l'exécution**), ou choisissez un autre répertoire local pour l'agent actuel. Ce verrou d'exclusion mutuelle du répertoire réside dans la mémoire du daemon ; aucun fichier de verrou n'est écrit sur le disque. Si vous soupçonnez un état de verrou obsolète, `multica daemon restart` le libère ; il n'y a rien à supprimer manuellement.
+Vérifiez que le détenteur indiqué est toujours en cours d'exécution avant de l'arrêter. S'il est réellement bloqué, arrêtez-le depuis son journal d'exécution ou choisissez un autre répertoire local. Si le répertoire est libre mais que le daemon exécute d'autres travaux, attendez qu'un slot se libère. Le verrou du répertoire réside dans la mémoire du daemon ; aucun fichier de verrou n'est à supprimer. Utilisez `multica daemon restart` pour un verrou en mémoire dont l'état obsolète est confirmé.
</Tab>
</Tabs>
diff --git a/apps/docs/content/docs/troubleshooting.ja.mdx b/apps/docs/content/docs/troubleshooting.ja.mdx
index 2fa43150ef..2b36d70ece 100644
--- a/apps/docs/content/docs/troubleshooting.ja.mdx
+++ b/apps/docs/content/docs/troubleshooting.ja.mdx
@@ -139,11 +139,11 @@ multica issue runs <issue-id>
</Tab>
<Tab value="waiting_local_directory">
-これは、進行中の別の実行が同じローカルディレクトリを使っていることを意味します。2 つのエージェントが同じファイルを同時に変更しないよう、Multica はディレクトリロックの解放を待ちます。
+起動前に、対象のローカルディレクトリかデーモンの空き実行スロットを待っている状態です。`held by task ...` はディレクトリの待機開始時に確認した保持者を示します。現在の保持者を追跡する表示ではありません。
-この待機はディレクトリの `in_place`(「直接」)モードにのみ存在します。ディレクトリが git リポジトリであれば、リソースを `worktree`(「並行」)に切り替えるとキューそのものがなくなります。各実行が自分のワークツリーを受け取り、成果をブランチとして返すため、どの実行も待ちません。[プロジェクトリソース](/project-resources#実行がディレクトリを共有する方法)を参照してください。
+直接(`in_place`)モードでは、同じディレクトリへの書き込みを直列化します。並行(`worktree`)モードは別々の作業コピーを使いますが、同じソースパスを直接モードの実行と共有している場合、ソースのスナップショット作成時に待つことがあります。[プロジェクトリソース](/project-resources#実行がディレクトリを共有する方法)を参照してください。
-そうでなければ、通常は前の実行が終わるのを待つだけで十分です。前の実行が固まっている場合は、その実行ログから停止するか、現在のエージェントに別のローカルディレクトリを選んでください。このディレクトリの排他はデーモンがメモリ内で管理しており、ディスクにロックファイルは書き込まれません。ロック状態が異常だと疑われる場合は `multica daemon restart` で解放されます。手動で削除すべきファイルはありません。
+表示された保持者を停止する前に、その実行がまだ動いているか確認してください。実際に停止している場合は実行ログから停止するか、別のローカルディレクトリを選択してください。ディレクトリが空いていてもデーモンが他の処理を実行中なら、実行スロットが空くのを待ちます。ディレクトリの排他はデーモンのメモリ内で管理されるため、削除するロックファイルはありません。メモリ内のロック状態が古いと確認できた場合は `multica daemon restart` を使ってください。
</Tab>
</Tabs>
diff --git a/apps/docs/content/docs/troubleshooting.ko.mdx b/apps/docs/content/docs/troubleshooting.ko.mdx
index 748c5f1c8b..3e43d415b0 100644
--- a/apps/docs/content/docs/troubleshooting.ko.mdx
+++ b/apps/docs/content/docs/troubleshooting.ko.mdx
@@ -139,11 +139,11 @@ multica issue runs <issue-id>
</Tab>
<Tab value="waiting_local_directory">
-다른 진행 중인 실행이 같은 로컬 디렉터리를 사용하고 있다는 뜻입니다. Multica는 두 에이전트가 같은 파일을 동시에 수정하지 않도록 디렉터리 잠금이 해제되기를 기다립니다.
+시작 전에 대상 로컬 디렉터리 또는 데몬의 빈 실행 슬롯을 기다리는 상태입니다. `held by task ...` 힌트는 디렉터리 대기가 시작될 때 확인한 점유자를 나타내며 현재 점유 상태를 추적하지 않습니다.
-이 대기는 디렉터리의 `in_place`("직접") 모드에서만 발생합니다. 디렉터리가 git 저장소라면 리소스를 `worktree`("병렬")로 전환하면 대기열 자체가 사라집니다. 각 실행이 자기 워크트리를 받고 결과를 브랜치로 돌려주므로 어느 실행도 기다리지 않습니다. [프로젝트 리소스](/project-resources#실행이-디렉터리를-공유하는-방식)를 참고하세요.
+직접(`in_place`) 모드의 실행은 같은 디렉터리에 대한 쓰기를 직렬화합니다. 병렬(`worktree`) 모드는 별도 작업 복사본을 사용하지만, 직접 모드 실행과 같은 원본 경로를 공유하면 원본 스냅샷을 준비할 때 기다릴 수 있습니다. [프로젝트 리소스](/project-resources#실행이-디렉터리를-공유하는-방식)를 참고하세요.
-그렇지 않으면 일반적으로 앞선 실행이 끝날 때까지 기다리면 됩니다. 앞선 실행이 멈췄다면 해당 실행 로그에서 중지할 수 있고, 현재 에이전트에 다른 로컬 디렉터리를 선택할 수도 있습니다. 이 디렉터리 상호 배제는 데몬이 메모리에서 관리하며 디스크에 lock 파일을 쓰지 않습니다. 잠금 상태가 비정상이라고 의심되면 `multica daemon restart`를 실행해 해제하세요. 직접 삭제해야 할 파일은 없습니다.
+표시된 점유자를 중지하기 전에 해당 실행이 아직 진행 중인지 확인하세요. 실제로 멈췄다면 실행 로그에서 중지하거나 다른 로컬 디렉터리를 선택하세요. 디렉터리가 비어 있어도 데몬이 다른 작업을 실행 중이면 실행 슬롯이 빌 때까지 기다립니다. 디렉터리 잠금은 데몬 메모리에서 관리되므로 삭제할 잠금 파일은 없습니다. 메모리의 잠금 상태가 오래된 것으로 확인된 경우 `multica daemon restart`를 사용하세요.
</Tab>
</Tabs>
diff --git a/apps/docs/content/docs/troubleshooting.mdx b/apps/docs/content/docs/troubleshooting.mdx
index c45caaf2b1..012624e887 100644
--- a/apps/docs/content/docs/troubleshooting.mdx
+++ b/apps/docs/content/docs/troubleshooting.mdx
@@ -139,11 +139,11 @@ If the runtime list is missing an expected tool, first confirm the tool runs and
</Tab>
<Tab value="waiting_local_directory">
-This means another in-flight run is using the same local directory. Multica waits for the directory lock to be released so two agents never modify the same files at once.
+Before startup, this run is waiting for its local directory or a free daemon execution slot. The `held by task ...` hint identifies the holder seen when the directory wait began; it does not track current ownership.
-This wait only exists in the directory's `in_place` ("Direct") mode. If the directory is a git repository, switching the resource to `worktree` ("Parallel") removes the queue altogether: each run gets its own worktree and hands its work back as a branch, so nothing waits on anything. See [Project resources](/project-resources#how-runs-share-the-directory).
+Direct (`in_place`) runs serialize writes to the same directory. Parallel (`worktree`) runs use separate checkouts, but preparing a source snapshot can still wait when that source path is shared with Direct runs. See [Project resources](/project-resources#how-runs-share-the-directory).
-Otherwise you just wait for the earlier run to finish. If it is stuck, stop it from its execution log, or pick a different local directory for the current agent. This directory mutex lives in the daemon's memory — no lock file is written to disk. If you suspect stale lock state, `multica daemon restart` releases it; there is nothing to delete manually.
+Check whether the indicated holder is still running before stopping it. If it is genuinely stuck, stop it from its execution log or choose a different local directory. If the directory is free but the daemon is executing other work, wait for capacity. The directory mutex lives in daemon memory; there is no lock file to delete. Use `multica daemon restart` for a confirmed stale in-memory lock.
</Tab>
</Tabs>
diff --git a/apps/docs/content/docs/troubleshooting.zh-Hant.mdx b/apps/docs/content/docs/troubleshooting.zh-Hant.mdx
index 9dd29cb34f..8fe1a514c9 100644
--- a/apps/docs/content/docs/troubleshooting.zh-Hant.mdx
+++ b/apps/docs/content/docs/troubleshooting.zh-Hant.mdx
@@ -139,11 +139,11 @@ multica issue runs <issue-id>
</Tab>
<Tab value="waiting_local_directory">
-這表示另一條在途執行正在使用同一個本地目錄。Multica 會等待目錄鎖釋放,避免兩個 AI 代理同時修改同一份檔案。
+這條執行在啟動前等待本地目錄或空閒的守護程序執行槽位。`held by task ...` 提示記錄開始等待時佔用目錄的執行,不會即時更新。
-這種等待只存在於目錄的 `in_place`("原地")模式。如果這個目錄是 git 倉庫,把資源切到 `worktree`("並行")就沒有佇列了:每次執行拿到自己的 worktree,並以分支形式交回結果,誰都不用等誰。見[專案資源](/project-resources#執行如何共享這個目錄)。
+直接修改模式(`in_place`)會序列執行對同一目錄的寫入。並行模式(`worktree`)使用獨立的工作副本,但如果來源路徑與直接修改模式的執行共用,準備來源目錄快照時仍可能等待。見[專案資源](/project-resources#執行如何共享這個目錄)。
-否則通常只需等前一次執行結束。若前一次已經卡住,可以從它的執行日誌中停止,也可以為當前 AI 代理選擇其他本地目錄。這個目錄互斥由守護程序在記憶體中維護,不寫磁碟鎖檔案。懷疑鎖狀態異常時,執行 `multica daemon restart` 即可釋放,沒有需要手動刪除的檔案。
+停止提示中的執行前,先確認它是否仍在執行。如果確實卡住,可以從執行日誌中停止,或選擇其他本地目錄。如果目錄已空閒,但守護程序正在執行其他工作,則等待執行槽位釋放。目錄互斥由守護程序在記憶體中維護,沒有需要刪除的鎖檔案。確認記憶體中的鎖狀態異常後,可使用 `multica daemon restart`。
</Tab>
</Tabs>
diff --git a/apps/docs/content/docs/troubleshooting.zh.mdx b/apps/docs/content/docs/troubleshooting.zh.mdx
index c77fba0393..1369163c67 100644
--- a/apps/docs/content/docs/troubleshooting.zh.mdx
+++ b/apps/docs/content/docs/troubleshooting.zh.mdx
@@ -139,11 +139,11 @@ multica issue runs <issue-id>
</Tab>
<Tab value="waiting_local_directory">
-这表示另一条在途运行正在使用同一个本地目录。Multica 会等待目录锁释放,避免两个智能体同时修改同一份文件。
+这条运行在启动前等待本地目录或空闲的守护进程执行槽位。`held by task ...` 提示记录开始等待时占用目录的运行,不会实时更新。
-这种等待只存在于目录的 `in_place`("原地")模式。如果这个目录是 git 仓库,把资源切到 `worktree`("并行")就没有队列了:每次运行拿到自己的 worktree,并以分支形式交回结果,谁都不用等谁。见[项目资源](/project-resources#运行如何共享这个目录)。
+直接修改模式(`in_place`)会串行执行对同一目录的写入。并行模式(`worktree`)使用独立的工作副本,但如果源路径与直接修改模式的运行共用,准备源目录快照时仍可能等待。见[项目资源](/project-resources#运行如何共享这个目录)。
-否则通常只需等前一次运行结束。若前一次已经卡住,可以从它的执行日志中停止,也可以为当前智能体选择其他本地目录。这个目录互斥由守护进程在内存中维护,不写磁盘锁文件。怀疑锁状态异常时,运行 `multica daemon restart` 即可释放,没有需要手动删除的文件。
+停止提示中的运行前,先确认它是否仍在执行。如果确实卡住,可以从执行日志中停止,或选择其他本地目录。如果目录已空闲,但守护进程正在执行其他工作,则等待执行槽位释放。目录互斥由守护进程在内存中维护,没有需要删除的锁文件。确认内存中的锁状态异常后,可使用 `multica daemon restart`。
</Tab>
</Tabs>
diff --git a/server/internal/daemon/client_start_test.go b/server/internal/daemon/client_start_test.go
index af00c9ed0f..061524c7b4 100644
--- a/server/internal/daemon/client_start_test.go
+++ b/server/internal/daemon/client_start_test.go
@@ -126,7 +126,7 @@ func TestHandleTaskRejectedStartDoesNotFailNewOwner(t *testing.T) {
ran = true
return TaskResult{}, errStartClaimRejected
})
- d.handleTask(context.Background(), Task{ID: "stale-task", WorkspaceID: "workspace", RuntimeID: "rt-1", Agent: &AgentData{Name: "test-agent"}}, 0)
+ d.handleTask(context.Background(), Task{ID: "stale-task", WorkspaceID: "workspace", RuntimeID: "rt-1", Agent: &AgentData{Name: "test-agent"}}, newTestTaskSlot(0))
if !ran || callbacks.Load() != 0 {
t.Fatalf("ran=%t terminal callbacks=%d", ran, callbacks.Load())
}
diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.go
index a48f29e450..0989f967a7 100644
--- a/server/internal/daemon/daemon.go
+++ b/server/internal/daemon/daemon.go
@@ -5551,8 +5551,8 @@ func (d *Daemon) pollLoop(ctx context.Context, taskWakeups <-chan taskWakeup) er
// runBatchPoller is the single machine-level claim+dispatch loop. Each cycle it
// acquires whatever execution slots are free (slot-before-claim, so a claimed
-// task never sits server-side `dispatched` without local capacity to run it and
-// race the dispatch-timeout sweeper), asks the server for up to that many tasks
+// newly claimed task has startup capacity rather than waiting server-side as
+// `dispatched` and racing the timeout sweeper), asks for up to that many tasks
// across all of the daemon's runtimes in one call, and dispatches each returned
// task — routed to its runtime by handleTask — into a slot.
//
@@ -5667,16 +5667,9 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i
go func(t Task, slot int) {
defer taskWG.Done()
defer d.activeTasks.Add(-1)
- defer func() {
- // Release local capacity before waking the poller. The task's
- // terminal callback and local cleanup have both finished at this
- // point, so a successor that was previously blocked by agent
- // capacity or per-(issue, agent) serialization can be claimed
- // immediately instead of waiting for PollInterval.
- sem <- slot
- signalPollerWakeup(wakeup)
- }()
- d.handleTask(parentCtx, t, slot)
+ executionSlot := newTaskSlotLease(sem, slot, wakeup)
+ defer executionSlot.release()
+ d.handleTask(parentCtx, t, executionSlot)
}(t, slot)
dispatched++
}
@@ -6017,7 +6010,7 @@ func (d *Daemon) watchTaskCancellation(ctx context.Context, taskID string, pollI
return cancelled
}
-func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
+func (d *Daemon) handleTask(ctx context.Context, task Task, slot *taskSlotLease) {
d.mu.Lock()
rt, tracked := d.runtimeIndex[task.RuntimeID]
d.mu.Unlock()
@@ -6086,7 +6079,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
// fires only after execenv.Prepare/Reuse has put env.WorkDir on disk,
// so consumers that read status==running can resolve the workdir path
// without racing the daemon's os.MkdirAll.
- localRelease, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, taskLog)
+ localRelease, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, taskLog, slot)
if abort {
return
}
@@ -6139,7 +6132,7 @@ func (d *Daemon) handleTask(ctx context.Context, task Task, slot int) {
}
}()
- result, err := d.runner.run(runCtx, task, provider, slot, taskLog)
+ result, err := d.runner.run(runCtx, task, provider, slot.index, taskLog)
if errors.Is(err, errStartClaimRejected) {
// The row belongs to another claim (or is terminal). A task-id-only
// failure callback from this stale delivery could kill its new owner.
@@ -6439,10 +6432,11 @@ func withoutWorktreePreserved(err error) error {
// 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.
+// lock, returning execution capacity during the wait. Reacquire capacity
+// before returning the path release callback.
// 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) {
+func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Task, taskLog *slog.Logger, slot *taskSlotLease) (release func(), abort bool) {
if len(task.ProjectResources) == 0 || d.cfg.DaemonID == "" {
return nil, false
}
@@ -6546,11 +6540,15 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
}()
onWait := func(holder string) {
- // LocalPathLocker invokes onWait synchronously and at most once for an
- // Acquire call. Count the actual mutex wait even if the best-effort
- // server status update below fails.
+ // Retrying the path after capacity becomes available can contend again.
+ // Keep one wait lifecycle while returning the slot on every conflict.
+ if waitCounted {
+ slot.release()
+ return
+ }
d.resourceWaitTasks.Add(1)
waitCounted = true
+ slot.release()
// 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
@@ -6590,7 +6588,30 @@ func (d *Daemon) acquireLocalDirectoryLockIfNeeded(ctx context.Context, task Tas
}()
})
}
- release, err = d.localPathLocks.Acquire(waitCtx, assignment.RealPath, task.ID, onWait)
+ for {
+ release, err = d.localPathLocks.Acquire(waitCtx, assignment.RealPath, task.ID, onWait)
+ if err != nil {
+ break
+ }
+ acquired, acquireErr := slot.tryAcquire(waitCtx)
+ if acquireErr != nil {
+ release()
+ release = nil
+ err = acquireErr
+ break
+ }
+ if acquired {
+ break
+ }
+ // Worktree snapshot preparation takes the same path mutex while owning
+ // its execution slot. Never hold the path while blocking on capacity.
+ release()
+ release = nil
+ taskLog.Debug("local_directory: waiting for execution capacity")
+ if err = slot.acquire(waitCtx); err != nil {
+ break
+ }
+ }
if err != nil {
// If the wait was cut short because the server finalized the task
// (terminal state) or deleted the row, the row is already in a
diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.go
index ef67a2ef67..3db9a9eef6 100644
--- a/server/internal/daemon/daemon_test.go
+++ b/server/internal/daemon/daemon_test.go
@@ -5776,7 +5776,7 @@ func TestHandleTask_BareErrorReportsFailureWithCancelledParent(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
- d.handleTask(ctx, Task{ID: "task-bare-error", RuntimeID: "rt-1"}, 0)
+ d.handleTask(ctx, Task{ID: "task-bare-error", RuntimeID: "rt-1"}, newTestTaskSlot(0))
if got := failCalls.Load(); got != 1 {
t.Fatalf("fail callback calls = %d, want 1", got)
@@ -5818,7 +5818,7 @@ func TestHandleTask_UntrackedRuntimeFailsBackForRetry(t *testing.T) {
return TaskResult{}, nil
})
- d.handleTask(context.Background(), Task{ID: "task-gone-runtime", RuntimeID: "rt-demoted"}, 0)
+ d.handleTask(context.Background(), Task{ID: "task-gone-runtime", RuntimeID: "rt-demoted"}, newTestTaskSlot(0))
body, _ := failBody.Load().(map[string]any)
if body == nil {
@@ -5891,7 +5891,7 @@ func TestHandleTask_ReportsUsageBeforeCancel(t *testing.T) {
Agent: &AgentData{Name: "test-agent"},
}
- d.handleTask(context.Background(), task, 0)
+ d.handleTask(context.Background(), task, newTestTaskSlot(0))
mu.Lock()
order := make([]string, len(callOrder))
@@ -5994,7 +5994,7 @@ func TestHandleTask_ReportsUsageWhenCancelledByPoll(t *testing.T) {
Agent: &AgentData{Name: "test-agent"},
}
- d.handleTask(context.Background(), task, 0)
+ d.handleTask(context.Background(), task, newTestTaskSlot(0))
mu.Lock()
order := make([]string, len(callOrder))
@@ -6652,7 +6652,7 @@ func TestHandleTask_AcksCancelAfterPollCancelled(t *testing.T) {
Agent: &AgentData{Name: "test-agent"},
}
- d.handleTask(context.Background(), task, 0)
+ d.handleTask(context.Background(), task, newTestTaskSlot(0))
mu.Lock()
order := make([]string, len(callOrder))
@@ -6721,7 +6721,7 @@ func TestHandleTask_AcksCancelOnPostRunStatusCheck(t *testing.T) {
Agent: &AgentData{Name: "test-agent"},
}
- d.handleTask(context.Background(), task, 0)
+ d.handleTask(context.Background(), task, newTestTaskSlot(0))
if got := ackCalls.Load(); got != 1 {
t.Fatalf("cancel-ack calls = %d, want 1", got)
diff --git a/server/internal/daemon/local_directory_test.go b/server/internal/daemon/local_directory_test.go
index 8f319da8b4..91c73bde06 100644
--- a/server/internal/daemon/local_directory_test.go
+++ b/server/internal/daemon/local_directory_test.go
@@ -180,7 +180,7 @@ func TestAcquireLocalDirectoryLockSkipsSquadLeaderTasks(t *testing.T) {
if leaderAssignment != nil {
t.Fatalf("leader assignment = %+v, want nil", leaderAssignment)
}
- leaderRelease, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), leader, slog.Default())
+ leaderRelease, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), leader, slog.Default(), newTestTaskSlot(0))
if abort {
t.Fatal("leader lock acquisition aborted")
}
@@ -191,7 +191,7 @@ func TestAcquireLocalDirectoryLockSkipsSquadLeaderTasks(t *testing.T) {
t.Fatalf("holder after leader skip = %q, want empty", got)
}
- release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), worker, slog.Default())
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), worker, slog.Default(), newTestTaskSlot(0))
if abort {
t.Fatal("worker lock acquisition aborted")
}
@@ -203,7 +203,7 @@ func TestAcquireLocalDirectoryLockSkipsSquadLeaderTasks(t *testing.T) {
t.Fatalf("holder = %q, want %q", got, worker.ID)
}
- leaderRelease, abort = d.acquireLocalDirectoryLockIfNeeded(context.Background(), leader, slog.Default())
+ leaderRelease, abort = d.acquireLocalDirectoryLockIfNeeded(context.Background(), leader, slog.Default(), newTestTaskSlot(0))
if abort {
t.Fatal("leader lock acquisition aborted")
}
@@ -614,7 +614,7 @@ func TestAcquireLocalDirectoryLock_CancelDuringWait(t *testing.T) {
}
done := make(chan result, 1)
go func() {
- rel, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), task, slog.Default())
+ rel, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), task, slog.Default(), newTestTaskSlot(0))
done <- result{release: rel, abort: abort}
}()
@@ -701,7 +701,7 @@ func TestAcquireLocalDirectoryLock_ParentCancellationReportsWaitFailure(t *testi
}
done := make(chan result, 1)
go func() {
- rel, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, slog.Default())
+ rel, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, slog.Default(), newTestTaskSlot(0))
done <- result{release: rel, abort: abort}
}()
@@ -781,7 +781,7 @@ func TestAcquireLocalDirectoryLock_EarlyFailureReportsWithCancelledParent(t *tes
ctx, cancel := context.WithCancel(context.Background())
cancel()
- release, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, slog.Default())
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, task, slog.Default(), newTestTaskSlot(0))
if !abort {
t.Fatal("expected local_directory failure to abort task")
}
@@ -836,6 +836,7 @@ func TestAcquireLocalDirectoryLockSkipsWorktreeMode(t *testing.T) {
context.Background(),
Task{ID: taskID, ProjectResources: resources},
slog.Default(),
+ newTestTaskSlot(0),
)
if abort {
t.Fatalf("%s: acquisition aborted", taskID)
@@ -937,6 +938,7 @@ func TestAcquireLocalDirectoryLockRejectsUnknownExecutionMode(t *testing.T) {
context.Background(),
Task{ID: "t1", ProjectResources: resources},
slog.Default(),
+ newTestTaskSlot(0),
)
if !abort {
t.Error("abort = false; the task was allowed to run with an unsupported mode")
@@ -1053,7 +1055,7 @@ func TestChatTaskSkipsPathMutexButKeepsAssignment(t *testing.T) {
// 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())
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), worker, slog.Default(), newTestTaskSlot(0))
if abort {
t.Fatal("worker lock acquisition aborted")
}
@@ -1074,7 +1076,7 @@ func TestChatTaskSkipsPathMutexButKeepsAssignment(t *testing.T) {
}
done := make(chan acquireResult, 1)
go func() {
- chatRelease, chatAbort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), chat, slog.Default())
+ chatRelease, chatAbort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), chat, slog.Default(), newTestTaskSlot(0))
done <- acquireResult{release: chatRelease, abort: chatAbort}
}()
@@ -1135,7 +1137,7 @@ func TestChatTaskOnWorktreeResourceKeepsAssignment(t *testing.T) {
localPathLocks: NewLocalPathLocker(),
logger: slog.Default(),
}
- release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), chat, slog.Default())
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), chat, slog.Default(), newTestTaskSlot(0))
if abort {
t.Fatal("chat lock acquisition aborted")
}
@@ -1184,7 +1186,7 @@ func TestIssueTasksStillSerialiseOnPathMutex(t *testing.T) {
logger: slog.Default(),
cancelPollInterval: time.Hour, // never poll; the test drives cancellation itself
}
- release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), first, slog.Default())
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), first, slog.Default(), newTestTaskSlot(0))
if abort || release == nil {
t.Fatalf("first issue task failed to take the lock (abort=%v)", abort)
}
@@ -1195,7 +1197,7 @@ func TestIssueTasksStillSerialiseOnPathMutex(t *testing.T) {
blocked := make(chan struct{})
go func() {
defer close(blocked)
- secondRelease, _ := d.acquireLocalDirectoryLockIfNeeded(ctx, second, slog.Default())
+ secondRelease, _ := d.acquireLocalDirectoryLockIfNeeded(ctx, second, slog.Default(), newTestTaskSlot(0))
if secondRelease != nil {
secondRelease()
}
diff --git a/server/internal/daemon/opencode_clock_unix_test.go b/server/internal/daemon/opencode_clock_unix_test.go
index ae0142d9ed..3816cfadf1 100644
--- a/server/internal/daemon/opencode_clock_unix_test.go
+++ b/server/internal/daemon/opencode_clock_unix_test.go
@@ -88,7 +88,7 @@ exit 1
t.Fatalf("seed managed workdir: %+v, %v", prepared, err)
}
task.PriorWorkDir = prepared.WorkDir
- d.handleTask(context.Background(), task, 0)
+ d.handleTask(context.Background(), task, newTestTaskSlot(0))
select {
case report := <-reports:
if report["retired_session_id"] != "ses-old" {
diff --git a/server/internal/daemon/runtime_launch_windows_test.go b/server/internal/daemon/runtime_launch_windows_test.go
index a545553105..6a2d27a8a0 100644
--- a/server/internal/daemon/runtime_launch_windows_test.go
+++ b/server/internal/daemon/runtime_launch_windows_test.go
@@ -72,7 +72,7 @@ func TestHandleTaskReportsWindowsCodexProcessStartFailure(t *testing.T) {
ID: "agent-windows-launch-failure",
Name: "Windows launch failure agent",
},
- }, 0)
+ }, newTestTaskSlot(0))
body, _ := failBody.Load().(map[string]any)
if body == nil {
diff --git a/server/internal/daemon/shutdown_lock_wait_test.go b/server/internal/daemon/shutdown_lock_wait_test.go
index a0c6236ff0..c7e1d5fa51 100644
--- a/server/internal/daemon/shutdown_lock_wait_test.go
+++ b/server/internal/daemon/shutdown_lock_wait_test.go
@@ -114,7 +114,7 @@ func TestHandleTask_LocalDirectoryWaitCancellation(t *testing.T) {
}
task := Task{ID: "waiter", RuntimeID: "rt", ProjectResources: []ProjectResourceData{{ID: "resource", ResourceType: localDirectoryResourceType, ResourceRef: ref}}}
done := make(chan struct{})
- go func() { defer close(done); d.handleTask(parent, task, 0) }()
+ go func() { defer close(done); d.handleTask(parent, task, newTestTaskSlot(0)) }()
wait := func(ch <-chan struct{}, what string) {
t.Helper()
select {
diff --git a/server/internal/daemon/shutdown_provider_unix_test.go b/server/internal/daemon/shutdown_provider_unix_test.go
index dd22cf30d9..ee776fbd80 100644
--- a/server/internal/daemon/shutdown_provider_unix_test.go
+++ b/server/internal/daemon/shutdown_provider_unix_test.go
@@ -96,7 +96,7 @@ exit 1
d.setAgentVersion("opencode", "1.18.31")
task := Task{ID: "task-shutdown", WorkspaceID: "ws-shutdown", RuntimeID: "rt-shutdown", IssueID: "issue-shutdown", AgentID: "agent-shutdown", AuthToken: "mat_test_shutdown", Agent: &AgentData{ID: "agent-shutdown", Name: "shutdown fixture", CustomEnv: map[string]string{"SHUTDOWN_GATE": gate}}}
done := make(chan struct{})
- go func() { defer close(done); d.handleTask(ctx, task, 0) }()
+ go func() { defer close(done); d.handleTask(ctx, task, newTestTaskSlot(0)) }()
select {
case <-ready:
case <-time.After(10 * time.Second):
diff --git a/server/internal/daemon/shutdown_retry_test.go b/server/internal/daemon/shutdown_retry_test.go
index a80a705f9c..5b7bfa602b 100644
--- a/server/internal/daemon/shutdown_retry_test.go
+++ b/server/internal/daemon/shutdown_retry_test.go
@@ -72,7 +72,7 @@ func TestHandleTask_ShutdownDisposition(t *testing.T) {
Usage: []TaskUsageEntry{{Provider: "openai", Model: "test", InputTokens: 100, OutputTokens: 50}},
}, nil
})
- d.handleTask(ctx, Task{ID: "task", RuntimeID: "rt"}, 0)
+ d.handleTask(ctx, Task{ID: "task", RuntimeID: "rt"}, newTestTaskSlot(0))
mu.Lock()
defer mu.Unlock()
if !strings.HasSuffix(endpoint, tc.wantEndpoint) {
diff --git a/server/internal/daemon/task_log_correlation_test.go b/server/internal/daemon/task_log_correlation_test.go
index 03234c5ec8..bf2d02e26e 100644
--- a/server/internal/daemon/task_log_correlation_test.go
+++ b/server/internal/daemon/task_log_correlation_test.go
@@ -88,7 +88,7 @@ func TestHandleTask_LogsFullTaskIDSoConcurrentRunsStayDistinct(t *testing.T) {
RuntimeID: "rt-1",
IssueID: "issue-log-correlation",
Agent: &AgentData{Name: "test-agent"},
- }, 0)
+ }, newTestTaskSlot(0))
}
out := logs.String()
@@ -148,7 +148,7 @@ func TestHandleTask_LogsFullChatSessionID(t *testing.T) {
RuntimeID: "rt-1",
ChatSessionID: chatSessionID,
Agent: &AgentData{Name: "test-agent"},
- }, 0)
+ }, newTestTaskSlot(0))
out := logs.String()
if !strings.Contains(out, "chat_session="+chatSessionID) {
@@ -174,7 +174,7 @@ func TestHandleTask_UntrackedRuntimeLogsFullTaskID(t *testing.T) {
cancelPollInterval: time.Hour,
}
- d.handleTask(context.Background(), Task{ID: collidingTaskIDB, RuntimeID: "rt-demoted"}, 0)
+ d.handleTask(context.Background(), Task{ID: collidingTaskIDB, RuntimeID: "rt-demoted"}, newTestTaskSlot(0))
if out := logs.String(); !strings.Contains(out, "task="+collidingTaskIDB) {
t.Errorf("runtime-offline warning did not carry the full task id; logs:\n%s", out)
diff --git a/server/internal/daemon/task_output_observer_test.go b/server/internal/daemon/task_output_observer_test.go
index faa6b9a10c..e347ee9816 100644
--- a/server/internal/daemon/task_output_observer_test.go
+++ b/server/internal/daemon/task_output_observer_test.go
@@ -197,7 +197,7 @@ func TestHandleTask_CancelAckCarriesRetiredSession(t *testing.T) {
RuntimeID: "rt-1",
IssueID: "issue-retire-ack",
Agent: &AgentData{Name: "test-agent"},
- }, 0)
+ }, newTestTaskSlot(0))
mu.Lock()
defer mu.Unlock()
diff --git a/server/internal/daemon/task_phase_timing_test.go b/server/internal/daemon/task_phase_timing_test.go
index ad09080822..b68a28f8c0 100644
--- a/server/internal/daemon/task_phase_timing_test.go
+++ b/server/internal/daemon/task_phase_timing_test.go
@@ -144,7 +144,7 @@ func TestTaskPhaseRecorderHandleTaskMarksBoundaryPhases(t *testing.T) {
return TaskResult{Status: "completed"}, nil
})
- d.handleTask(context.Background(), Task{ID: "task-1", RuntimeID: "runtime-1"}, 0)
+ d.handleTask(context.Background(), Task{ID: "task-1", RuntimeID: "runtime-1"}, newTestTaskSlot(0))
want := []taskPhase{taskPhaseClaimed, taskPhaseFinished}
if got := capture.phasesSnapshot(); !slices.Equal(got, want) {
diff --git a/server/internal/daemon/task_slot.go b/server/internal/daemon/task_slot.go
new file mode 100644
index 0000000000..cf78df02f2
--- /dev/null
+++ b/server/internal/daemon/task_slot.go
@@ -0,0 +1,64 @@
+package daemon
+
+import "context"
+
+// taskSlotLease belongs to one task goroutine. A parked task keeps its task
+// ownership but returns execution capacity, then may resume on a different index.
+type taskSlotLease struct {
+ slots chan int
+ wakeup chan struct{}
+ index int
+ held bool
+}
+
+func newTaskSlotLease(slots chan int, index int, wakeup chan struct{}) *taskSlotLease {
+ return &taskSlotLease{slots: slots, wakeup: wakeup, index: index, held: true}
+}
+
+func (s *taskSlotLease) release() {
+ if !s.held {
+ return
+ }
+ s.held = false
+ s.slots <- s.index
+ signalPollerWakeup(s.wakeup)
+}
+
+func (s *taskSlotLease) acquire(ctx context.Context) error {
+ if acquired, err := s.tryAcquire(ctx); acquired || err != nil {
+ return err
+ }
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ case index := <-s.slots:
+ return s.adopt(ctx, index)
+ }
+}
+
+func (s *taskSlotLease) tryAcquire(ctx context.Context) (bool, error) {
+ if err := ctx.Err(); err != nil {
+ return false, err
+ }
+ if s.held {
+ return true, nil
+ }
+ select {
+ case index := <-s.slots:
+ err := s.adopt(ctx, index)
+ return err == nil, err
+ default:
+ return false, nil
+ }
+}
+
+func (s *taskSlotLease) adopt(ctx context.Context, index int) error {
+ s.index = index
+ s.held = true
+ // A ready token can win a select at the same time as cancellation.
+ if err := ctx.Err(); err != nil {
+ s.release()
+ return err
+ }
+ return nil
+}
diff --git a/server/internal/daemon/task_slot_test.go b/server/internal/daemon/task_slot_test.go
new file mode 100644
index 0000000000..aa5aa0587f
--- /dev/null
+++ b/server/internal/daemon/task_slot_test.go
@@ -0,0 +1,145 @@
+package daemon
+
+import (
+ "context"
+ "errors"
+ "testing"
+ "time"
+)
+
+func newTestTaskSlot(index int) *taskSlotLease {
+ return newTaskSlotLease(make(chan int, 1), index, nil)
+}
+
+func TestTaskSlotLeaseReleaseIsIdempotent(t *testing.T) {
+ t.Parallel()
+ slots := newTaskSlotSemaphore(1)
+ wakeup := make(chan struct{}, 1)
+ lease := newTaskSlotLease(slots, <-slots, wakeup)
+ lease.release()
+ if got := len(slots); got != 1 {
+ t.Fatalf("free slots = %d, want 1", got)
+ }
+ select {
+ case <-wakeup:
+ default:
+ t.Fatal("returning capacity did not wake the poller")
+ }
+ if got := <-slots; got != 0 {
+ t.Fatalf("returned index = %d, want 0", got)
+ }
+ lease.release()
+ if got := len(slots); got != 0 {
+ t.Fatalf("second release duplicated the occupied slot: %d available", got)
+ }
+}
+
+func TestTaskSlotLeaseReacquiresCurrentIndex(t *testing.T) {
+ t.Parallel()
+ slots := newTaskSlotSemaphore(2)
+ lease := newTaskSlotLease(slots, <-slots, nil)
+ spare := <-slots
+ lease.release()
+ other := <-slots
+ slots <- spare
+ if err := lease.acquire(context.Background()); err != nil {
+ t.Fatal(err)
+ }
+ if lease.index != spare || lease.index == other {
+ t.Fatalf("reacquired index = %d, want free %d while %d is occupied", lease.index, spare, other)
+ }
+ if err := lease.acquire(context.Background()); err != nil {
+ t.Fatalf("already held slot: %v", err)
+ }
+ lease.release()
+ slots <- other
+ seen := map[int]bool{}
+ for range 2 {
+ index := <-slots
+ if seen[index] {
+ t.Fatalf("returned duplicate slot %d", index)
+ }
+ seen[index] = true
+ }
+}
+
+func TestTaskSlotLeaseCancelledAcquireConservesCapacity(t *testing.T) {
+ t.Parallel()
+ for _, ready := range []bool{false, true} {
+ t.Run(map[bool]string{false: "occupied", true: "available"}[ready], func(t *testing.T) {
+ slots := newTaskSlotSemaphore(1)
+ lease := newTaskSlotLease(slots, <-slots, nil)
+ lease.release()
+ if !ready {
+ <-slots
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if err := lease.acquire(ctx); !errors.Is(err, context.Canceled) {
+ t.Fatalf("cancelled acquisition = %v", err)
+ }
+ lease.release()
+ want := 0
+ if ready {
+ want = 1
+ }
+ if got := len(slots); got != want {
+ t.Fatalf("free slots after cancellation = %d, want %d", got, want)
+ }
+ })
+ }
+}
+
+func TestTaskSlotLeaseAcquireObservesCancellationWhileBlocked(t *testing.T) {
+ t.Parallel()
+ slots := newTaskSlotSemaphore(1)
+ lease := newTaskSlotLease(slots, <-slots, nil)
+ lease.release()
+ other := <-slots
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ done := make(chan error, 1)
+ go func() { done <- lease.acquire(ctx) }()
+ cancel()
+ select {
+ case err := <-done:
+ if !errors.Is(err, context.Canceled) {
+ t.Fatalf("acquisition = %v", err)
+ }
+ case <-time.After(time.Second):
+ t.Fatal("slot acquisition ignored cancellation")
+ }
+ lease.release()
+ slots <- other
+ if got := len(slots); got != 1 {
+ t.Fatalf("free slots = %d, want 1", got)
+ }
+}
+
+func TestTaskSlotLeaseTryAcquireDoesNotWait(t *testing.T) {
+ t.Parallel()
+ slots := newTaskSlotSemaphore(1)
+ lease := newTaskSlotLease(slots, <-slots, nil)
+ lease.release()
+ other := <-slots
+ ctx, cancel := context.WithTimeout(context.Background(), time.Second)
+ defer cancel()
+ if acquired, err := lease.tryAcquire(ctx); acquired || err != nil {
+ t.Fatalf("occupied slot: acquired=%v error=%v", acquired, err)
+ }
+ slots <- other
+ if acquired, err := lease.tryAcquire(ctx); !acquired || err != nil {
+ t.Fatalf("available slot: acquired=%v error=%v", acquired, err)
+ }
+ if acquired, err := lease.tryAcquire(ctx); !acquired || err != nil {
+ t.Fatalf("already held slot: acquired=%v error=%v", acquired, err)
+ }
+ lease.release()
+ cancel()
+ if acquired, err := lease.tryAcquire(ctx); acquired || !errors.Is(err, context.Canceled) {
+ t.Fatalf("cancelled admission: acquired=%v error=%v", acquired, err)
+ }
+ if len(slots) != 1 {
+ t.Fatal("cancelled nonblocking admission consumed capacity")
+ }
+}
diff --git a/server/internal/daemon/task_slot_wait_test.go b/server/internal/daemon/task_slot_wait_test.go
new file mode 100644
index 0000000000..3f2a9117fe
--- /dev/null
+++ b/server/internal/daemon/task_slot_wait_test.go
@@ -0,0 +1,459 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "path/filepath"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+type executionCapacityWaitWriter struct {
+ signal chan struct{}
+ once sync.Once
+}
+
+func (w *executionCapacityWaitWriter) Write(p []byte) (int, error) {
+ if strings.Contains(string(p), "local_directory: waiting for execution capacity") {
+ w.once.Do(func() { close(w.signal) })
+ }
+ return len(p), nil
+}
+
+func TestRunBatchPollerDirectoryWaitReleasesExecutionCapacity(t *testing.T) {
+ t.Parallel()
+
+ dir := t.TempDir()
+ realDir, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ref, err := json.Marshal(localDirectoryRef{LocalPath: dir, DaemonID: "daemon"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ resource := ProjectResourceData{ID: "resource", ResourceType: localDirectoryResourceType, ResourceRef: ref}
+ holder := Task{ID: "holder", RuntimeID: "local", IssueID: "holder-issue", AgentID: "holder-agent", Agent: &AgentData{Name: "holder"}, ProjectResources: []ProjectResourceData{resource}}
+ waiter := Task{ID: "waiter", RuntimeID: "local", IssueID: "waiter-issue", AgentID: "waiter-agent", Agent: &AgentData{Name: "waiter"}, ProjectResources: []ProjectResourceData{resource}}
+ unrelated := Task{ID: "unrelated", RuntimeID: "other", IssueID: "other-issue", AgentID: "other-agent", Agent: &AgentData{Name: "other"}}
+
+ holderStarted := make(chan struct{})
+ waiting := make(chan struct{})
+ unrelatedStarted := make(chan struct{})
+ waiterStarted := make(chan struct{})
+ finishHolder := make(chan struct{})
+ finishUnrelated := make(chan struct{})
+ var finishHolderOnce, finishUnrelatedOnce, waitingOnce sync.Once
+ var claims atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/api/daemon/tasks/claim"):
+ var tasks []Task
+ switch claims.Add(1) {
+ case 1:
+ tasks = []Task{holder}
+ case 2:
+ select {
+ case <-holderStarted:
+ tasks = []Task{waiter}
+ case <-r.Context().Done():
+ return
+ }
+ case 3:
+ tasks = []Task{unrelated}
+ }
+ _ = json.NewEncoder(w).Encode(map[string]any{"tasks": tasks})
+ case strings.HasSuffix(r.URL.Path, "/tasks/waiter/wait-local-directory"):
+ waitingOnce.Do(func() { close(waiting) })
+ _, _ = w.Write([]byte("{}"))
+ default:
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": "dispatched"})
+ }
+ }))
+ t.Cleanup(srv.Close)
+
+ d := New(Config{ServerBaseURL: srv.URL, DaemonID: "daemon", WorkspacesRoot: t.TempDir(), PollInterval: 10 * time.Millisecond, MaxConcurrentTasks: 2}, slog.New(slog.NewTextHandler(noopWriter{}, nil)))
+ d.workspaces["workspace"] = &workspaceState{workspaceID: "workspace", runtimeIDs: []string{"local", "other"}}
+ d.runtimeIndex["local"] = Runtime{ID: "local", Provider: "codex"}
+ d.runtimeIndex["other"] = Runtime{ID: "other", Provider: "claude"}
+ d.cancelPollInterval = time.Hour
+ d.taskSlotWait = 20 * time.Millisecond
+
+ var mu sync.Mutex
+ inUse := map[int]string{}
+ usedSlots := map[string]int{}
+ peak := 0
+ d.runner = taskRunnerFunc(func(ctx context.Context, task Task, _ string, slot int, _ *slog.Logger) (TaskResult, error) {
+ mu.Lock()
+ if owner, used := inUse[slot]; used {
+ t.Errorf("task %s reused slot %d while %s was running", task.ID, slot, owner)
+ }
+ inUse[slot] = task.ID
+ usedSlots[task.ID] = slot
+ if len(inUse) > peak {
+ peak = len(inUse)
+ }
+ mu.Unlock()
+ defer func() {
+ mu.Lock()
+ delete(inUse, slot)
+ mu.Unlock()
+ }()
+ var finish <-chan struct{}
+ switch task.ID {
+ case "holder":
+ close(holderStarted)
+ finish = finishHolder
+ case "unrelated":
+ close(unrelatedStarted)
+ finish = finishUnrelated
+ case "waiter":
+ close(waiterStarted)
+ return TaskResult{Status: "completed"}, nil
+ }
+ select {
+ case <-finish:
+ return TaskResult{Status: "completed"}, nil
+ case <-ctx.Done():
+ return TaskResult{Status: "cancelled"}, ctx.Err()
+ }
+ })
+
+ ctx, cancel := context.WithCancel(context.Background())
+ var taskWG sync.WaitGroup
+ sem := newTaskSlotSemaphore(2)
+ pollDone := make(chan struct{})
+ go func() {
+ defer close(pollDone)
+ d.runBatchPoller(ctx, ctx, sem, make(chan struct{}, 1), &taskWG)
+ }()
+ t.Cleanup(func() {
+ cancel()
+ finishHolderOnce.Do(func() { close(finishHolder) })
+ finishUnrelatedOnce.Do(func() { close(finishUnrelated) })
+ <-pollDone
+ taskWG.Wait()
+ })
+ select {
+ case <-waiting:
+ case <-time.After(3 * time.Second):
+ t.Fatal("second task never parked on the holder's directory")
+ }
+ select {
+ case <-unrelatedStarted:
+ case <-time.After(3 * time.Second):
+ t.Fatal("parked directory waiter pinned execution capacity for an unrelated runtime")
+ }
+ if got := d.activeTasks.Load(); got != 3 {
+ t.Fatalf("owned tasks = %d, want holder, waiter and unrelated task", got)
+ }
+ if got := d.resourceWaitTasks.Load(); got != 1 {
+ t.Fatalf("resource waiters = %d, want 1", got)
+ }
+ if got := d.localPathLocks.Holder(realDir); got != "holder" {
+ t.Fatalf("directory holder = %q, want holder", got)
+ }
+ finishHolderOnce.Do(func() { close(finishHolder) })
+ select {
+ case <-waiterStarted:
+ case <-time.After(3 * time.Second):
+ t.Fatal("waiter did not resume after the holder released its directory and slot")
+ }
+ mu.Lock()
+ defer mu.Unlock()
+ if peak > 2 {
+ t.Errorf("peak running tasks = %d, want at most 2", peak)
+ }
+ if usedSlots["waiter"] == usedSlots["unrelated"] {
+ t.Errorf("resumed waiter reused unrelated task's occupied slot: %v", usedSlots)
+ }
+}
+
+func TestDirectoryWaitCancellationWhileReacquiringSlot(t *testing.T) {
+ t.Parallel()
+ for _, mode := range []string{"server cancellation", "daemon shutdown"} {
+ t.Run(mode, func(t *testing.T) {
+ dir := t.TempDir()
+ realDir, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ref, err := json.Marshal(localDirectoryRef{LocalPath: dir, DaemonID: "daemon"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ waiting := make(chan struct{})
+ waitingCapacity := make(chan struct{})
+ var waitingOnce sync.Once
+ var serverCancelled atomic.Bool
+ var prepareLeases atomic.Int64
+ failReasons := make(chan string, 2)
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ switch {
+ case strings.HasSuffix(r.URL.Path, "/prepare-lease"):
+ prepareLeases.Add(1)
+ case strings.HasSuffix(r.URL.Path, "/wait-local-directory"):
+ waitingOnce.Do(func() { close(waiting) })
+ case strings.HasSuffix(r.URL.Path, "/fail"):
+ var body struct {
+ FailureReason string `json:"failure_reason"`
+ }
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Errorf("decode failure: %v", err)
+ }
+ failReasons <- body.FailureReason
+ }
+ status := "dispatched"
+ if serverCancelled.Load() {
+ status = "cancelled"
+ }
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": status})
+ }))
+ t.Cleanup(srv.Close)
+ d := New(Config{ServerBaseURL: srv.URL, DaemonID: "daemon"}, slog.New(slog.NewTextHandler(&executionCapacityWaitWriter{signal: waitingCapacity}, &slog.HandlerOptions{Level: slog.LevelDebug})))
+ d.cancelPollInterval = 10 * time.Millisecond
+ d.prepareLeaseRefresh = 5 * time.Millisecond
+ releaseHolder, err := d.localPathLocks.Acquire(context.Background(), realDir, "holder", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(releaseHolder)
+ slots := newTaskSlotSemaphore(1)
+ lease := newTaskSlotLease(slots, <-slots, nil)
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+ type result struct {
+ release func()
+ abort bool
+ }
+ done := make(chan result, 1)
+ finished := make(chan struct{})
+ go func() {
+ defer close(finished)
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, Task{ID: "waiter", RuntimeID: "runtime", ProjectResources: []ProjectResourceData{{ID: "resource", ResourceType: localDirectoryResourceType, ResourceRef: ref}}}, d.logger, lease)
+ done <- result{release: release, abort: abort}
+ }()
+ t.Cleanup(func() {
+ cancel()
+ releaseHolder()
+ select {
+ case <-finished:
+ case <-time.After(3 * time.Second):
+ t.Error("directory waiter did not stop during cleanup")
+ }
+ })
+ select {
+ case <-waiting:
+ case <-time.After(3 * time.Second):
+ t.Fatal("task did not enter the directory wait")
+ }
+ var occupied int
+ select {
+ case occupied = <-slots:
+ case <-time.After(3 * time.Second):
+ t.Fatal("directory wait did not release its execution slot")
+ }
+ releaseHolder()
+ select {
+ case <-waitingCapacity:
+ case <-time.After(3 * time.Second):
+ t.Fatal("waiter did not reach execution-capacity admission")
+ }
+ if holder := d.localPathLocks.Holder(realDir); holder != "" {
+ t.Fatalf("waiter kept directory %q while waiting for execution capacity", holder)
+ }
+ previousLeases := prepareLeases.Load()
+ leaseDeadline := time.After(3 * time.Second)
+ for prepareLeases.Load() <= previousLeases {
+ select {
+ case <-leaseDeadline:
+ t.Fatal("prepare lease stopped while the task waited for execution capacity")
+ case <-time.After(time.Millisecond):
+ }
+ }
+ if mode == "server cancellation" {
+ serverCancelled.Store(true)
+ } else {
+ cancel()
+ }
+ select {
+ case got := <-done:
+ if !got.abort || got.release != nil {
+ if got.release != nil {
+ got.release()
+ }
+ t.Fatalf("cancelled slot reacquisition returned abort=%v release=%v", got.abort, got.release != nil)
+ }
+ case <-time.After(3 * time.Second):
+ t.Fatal("slot reacquisition ignored cancellation")
+ }
+ if holder := d.localPathLocks.Holder(realDir); holder != "" {
+ t.Errorf("cancelled waiter kept the directory: %q", holder)
+ }
+ if n := d.resourceWaitTasks.Load(); n != 0 {
+ t.Errorf("resource wait count = %d after cancellation", n)
+ }
+ lease.release()
+ if len(slots) != 0 {
+ t.Fatal("cancelled waiter returned another task's execution slot")
+ }
+ slots <- occupied
+ if mode == "server cancellation" {
+ if len(failReasons) != 0 {
+ t.Fatal("server-cancelled task received another failure report")
+ }
+ } else {
+ select {
+ case reason := <-failReasons:
+ if reason != "runtime_recovery" {
+ t.Errorf("shutdown failure reason = %q, want runtime_recovery", reason)
+ }
+ default:
+ t.Fatal("daemon shutdown did not report the owned waiter for recovery")
+ }
+ }
+ })
+ }
+}
+
+func TestDirectoryFastPathsRetainExecutionSlot(t *testing.T) {
+ t.Parallel()
+ for _, mode := range []string{"direct", "worktree", "chat", "no directory"} {
+ t.Run(mode, func(t *testing.T) {
+ dir := t.TempDir()
+ ref := localDirectoryRef{LocalPath: dir, DaemonID: "daemon"}
+ if mode == "worktree" {
+ ref.ExecutionMode = "worktree"
+ }
+ raw, err := json.Marshal(ref)
+ if err != nil {
+ t.Fatal(err)
+ }
+ task := Task{ID: "task", ProjectResources: []ProjectResourceData{{ID: "resource", ResourceType: localDirectoryResourceType, ResourceRef: raw}}}
+ if mode == "chat" {
+ task.ChatSessionID = "chat"
+ }
+ if mode == "no directory" {
+ task.ProjectResources = nil
+ }
+ d := &Daemon{cfg: Config{DaemonID: "daemon"}, localPathLocks: NewLocalPathLocker(), logger: slog.New(slog.NewTextHandler(noopWriter{}, nil))}
+ slots := newTaskSlotSemaphore(1)
+ lease := newTaskSlotLease(slots, <-slots, nil)
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(context.Background(), task, d.logger, lease)
+ if release != nil {
+ defer release()
+ }
+ if abort {
+ t.Fatal("uncontended task aborted")
+ }
+ if len(slots) != 0 || lease.index != 0 {
+ t.Fatal("uncontended or exempt task returned its execution slot")
+ }
+ if (release != nil) != (mode == "direct") {
+ t.Fatalf("path lock held=%v for %s", release != nil, mode)
+ }
+ lease.release()
+ if len(slots) != 1 {
+ t.Fatal("task did not return its slot on completion")
+ }
+ })
+ }
+}
+
+func TestDirectDirectoryWaitDoesNotBlockWorktreeSnapshot(t *testing.T) {
+ t.Parallel()
+ dir := t.TempDir()
+ realDir, err := filepath.EvalSymlinks(dir)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ref, err := json.Marshal(localDirectoryRef{LocalPath: dir, DaemonID: "daemon"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ waiting := make(chan struct{})
+ waitingCapacity := make(chan struct{})
+ var waitingOnce sync.Once
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ if strings.HasSuffix(r.URL.Path, "/wait-local-directory") {
+ waitingOnce.Do(func() { close(waiting) })
+ }
+ _ = json.NewEncoder(w).Encode(map[string]string{"status": "dispatched"})
+ }))
+ t.Cleanup(srv.Close)
+ d := New(Config{ServerBaseURL: srv.URL, DaemonID: "daemon"}, slog.New(slog.NewTextHandler(&executionCapacityWaitWriter{signal: waitingCapacity}, &slog.HandlerOptions{Level: slog.LevelDebug})))
+ d.cancelPollInterval = time.Hour
+ releaseInitial, err := d.localPathLocks.Acquire(context.Background(), realDir, "initial", nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
+ slots := newTaskSlotSemaphore(1)
+ lease := newTaskSlotLease(slots, <-slots, nil)
+ directDone := make(chan bool, 1)
+ var wg sync.WaitGroup
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ release, abort := d.acquireLocalDirectoryLockIfNeeded(ctx, Task{ID: "direct", ProjectResources: []ProjectResourceData{{ID: "resource", ResourceType: localDirectoryResourceType, ResourceRef: ref}}}, d.logger, lease)
+ if release != nil {
+ release()
+ }
+ lease.release()
+ directDone <- abort
+ }()
+ t.Cleanup(func() {
+ cancel()
+ releaseInitial()
+ wg.Wait()
+ })
+ select {
+ case <-waiting:
+ case <-ctx.Done():
+ t.Fatal("Direct task did not park behind the initial directory holder")
+ }
+ var snapshotSlot int
+ select {
+ case snapshotSlot = <-slots:
+ case <-ctx.Done():
+ t.Fatal("Direct waiter did not return its execution capacity")
+ }
+ snapshotDone := make(chan error, 1)
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ defer func() { slots <- snapshotSlot }()
+ select {
+ case <-waitingCapacity:
+ case <-ctx.Done():
+ snapshotDone <- ctx.Err()
+ return
+ }
+ // Worktree preparation already owns its execution slot when it takes
+ // this same mutex to snapshot a source also used in Direct mode.
+ release, err := d.localPathLocks.Acquire(ctx, realDir, "snapshot", nil)
+ if release != nil {
+ release()
+ }
+ snapshotDone <- err
+ }()
+ releaseInitial()
+ if err := <-snapshotDone; err != nil || ctx.Err() != nil {
+ t.Fatalf("worktree snapshot could not progress while Direct waited for its slot: %v", err)
+ }
+ if abort := <-directDone; abort || ctx.Err() != nil {
+ t.Fatal("Direct task did not reacquire its directory and capacity after the snapshot")
+ }
+ if got := len(slots); got != 1 {
+ t.Fatalf("free slots after mixed-mode preparation = %d, want 1", got)
+ }
+}
diff --git a/server/internal/daemon/workdir_race_test.go b/server/internal/daemon/workdir_race_test.go
index 43a0a3efa6..3909d8dc39 100644
--- a/server/internal/daemon/workdir_race_test.go
+++ b/server/internal/daemon/workdir_race_test.go
@@ -72,7 +72,7 @@ func TestHandleTask_DoesNotCallStartTaskItself(t *testing.T) {
Agent: &AgentData{Name: "test-agent"},
}
- d.handleTask(context.Background(), task, 0)
+ d.handleTask(context.Background(), task, newTestTaskSlot(0))
if !runnerCalled.Load() {
t.Fatal("fake runner was never invoked — handleTask aborted before runner.run, can't assert ordering")
@@ -863,7 +863,7 @@ func TestHandleTask_KeepsEnvRootActiveAcrossCompletion(t *testing.T) {
Agent: &AgentData{Name: "test-agent"},
}
- d.handleTask(context.Background(), task, 0)
+ d.handleTask(context.Background(), task, newTestTaskSlot(0))
if !completeCalled.Load() {
t.Fatal("/complete was never hit — handleTask did not reach reportTaskResult")