Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7008: Relax healthy WebSocket claim polling to 3 minutes (#7983)
Multica Evecc09c3c12a1d
diff --git a/.env.example b/.env.exampleindex 84269a52f1..0192ee92f7 100644--- a/.env.example+++ b/.env.example@@ -165,6 +165,8 @@ MULTICA_WORKSPACE_ID=MULTICA_DAEMON_ID=MULTICA_DAEMON_DEVICE_NAME=MULTICA_DAEMON_POLL_INTERVAL=30s+# Independent healthy-WebSocket safety poll upper bound; does not replace the ordinary poll interval.+MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL=3mMULTICA_DAEMON_HEARTBEAT_INTERVAL=15sMULTICA_CODEX_PATH=codexMULTICA_CODEX_MODEL=diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex b73ebe3352..fcf0ecf79a 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -247,6 +247,7 @@ Daemon behavior is configured via flags or environment variables:| Setting | Flag | Env Variable | Default ||---------|------|--------------|---------|| Poll interval | `--poll-interval` | `MULTICA_DAEMON_POLL_INTERVAL` | `30s` (catch-up fallback; WebSocket wake signals deliver work sooner) |+| Healthy WebSocket claim poll upper bound | `--ws-claim-poll-interval` | `MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL` | `3m` (configured independently of `--poll-interval`; downward jitter makes the normal interval `2m30s`–`2m45s`, while old servers and uncertain claims retain the ordinary poll interval) || Heartbeat interval | `--heartbeat-interval` | `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` || Agent timeout | `--agent-timeout` | `MULTICA_AGENT_TIMEOUT` | `0` (no cap; bounded by the watchdogs) || Agent idle watchdog | — | `MULTICA_AGENT_IDLE_WATCHDOG` | `2h` (`0` disables the whole watchdog suite) |diff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex 9173776fee..4e6258760b 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -210,6 +210,7 @@ These are configured on each user's machine, not on the server:| `MULTICA_SERVER_URL` | `ws://localhost:8080/ws` | WebSocket URL for daemon → server connection || `MULTICA_APP_URL` | `http://localhost:3000` | Frontend URL for CLI login flow || `MULTICA_DAEMON_POLL_INTERVAL` | `30s` | Catch-up poll for tasks; WebSocket wake signals normally deliver work sooner |+| `MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL` | `3m` | Upper bound for healthy WebSocket claim safety polls, configured independently of `MULTICA_DAEMON_POLL_INTERVAL`; downward jitter keeps normal polls at `2m30s`–`2m45s`, while old servers and uncertain claims retain the ordinary poll interval || `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` | Heartbeat frequency |Agent-specific overrides:diff --git a/apps/docs/content/docs/environment-variables.ja.mdx b/apps/docs/content/docs/environment-variables.ja.mdxindex 69f6ff7819..5b58805939 100644--- a/apps/docs/content/docs/environment-variables.ja.mdx+++ b/apps/docs/content/docs/environment-variables.ja.mdx@@ -228,6 +228,7 @@ API key と base URL の両方が空の場合、このレイヤーは無効に| `MULTICA_DAEMON_DEVICE_NAME` | ホスト名 | ランタイム一覧に表示されるデバイス名 || `MULTICA_AGENT_RUNTIME_NAME` | `Local Agent` | ランタイムの表示名 || `MULTICA_DAEMON_POLL_INTERVAL` | `30s` | ウェイクイベントがないときの実行ポーリング間隔 |+| `MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL` | `3m` | 正常な WebSocket での claim 安全ポーリング上限。`MULTICA_DAEMON_POLL_INTERVAL` とは独立して設定され、下方向のジッターにより既定値は実際には `2m30s`–`2m45s` となり、旧 Server または結果が不確実な claim では通常のポーリング間隔を維持します || `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` | ハートビート間隔 || `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | デーモン 1 つあたりの同時実行上限 || `MULTICA_AGENT_TIMEOUT` | `0` | 1 回の実行の絶対時間上限。`0` は上限なし |@@ -276,6 +277,7 @@ multica config show| `workspaces_root` | `~` 配下のプロファイル別パス | 実行用作業ディレクトリのルート || `max_concurrent_tasks` | `20` | 同時実行上限。`0` または空は未設定を意味します || `poll_interval` | `30s` | 実行のポーリング間隔 |+| `ws_claim_poll_interval` | `3m` | 正常な WebSocket での claim 安全ポーリング上限。`poll_interval` とは独立して設定され、Daemon は下方向のジッターを適用します || `heartbeat_interval` | `15s` | ハートビート間隔 || `agent_timeout` | 無制限 | 1 回の実行の絶対時間上限 || `codex_semantic_inactivity_timeout` | 派生値 | Codex のセマンティック静穏しきい値。未設定なら idle と tool の watchdog 予算のうち大きい方を採用し、tool 予算が `0` の場合は idle 予算に回帰します。Codex 自身の `10m` が残るのは watchdog 一式を無効化したときだけです |diff --git a/apps/docs/content/docs/environment-variables.ko.mdx b/apps/docs/content/docs/environment-variables.ko.mdxindex e8d70052c4..487e7bcb4b 100644--- a/apps/docs/content/docs/environment-variables.ko.mdx+++ b/apps/docs/content/docs/environment-variables.ko.mdx@@ -228,6 +228,7 @@ API key와 base URL이 모두 비어 있으면 이 레이어가 꺼지고 업스| `MULTICA_DAEMON_DEVICE_NAME` | host 이름 | 런타임 목록의 기기 이름 || `MULTICA_AGENT_RUNTIME_NAME` | `Local Agent` | 런타임 표시 이름 || `MULTICA_DAEMON_POLL_INTERVAL` | `30s` | wakeup 이벤트가 없을 때 실행 polling 간격 |+| `MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL` | `3m` | 정상 WebSocket에서 claim 안전 polling의 상한. `MULTICA_DAEMON_POLL_INTERVAL`과 독립적으로 설정되며, 하향 jitter를 적용한 기본 실제 간격은 `2m30s`–`2m45s`이고 구형 Server 또는 결과가 불확실한 claim은 일반 polling 간격을 유지합니다 || `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` | heartbeat 간격 || `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | 데몬 하나의 동시 실행 상한 || `MULTICA_AGENT_TIMEOUT` | `0` | 단일 실행의 절대 시간 제한. `0`은 제한 없음 |@@ -276,6 +277,7 @@ multica config show| `workspaces_root` | `~` 아래 profile별 경로 | 실행용 작업 디렉터리의 루트 || `max_concurrent_tasks` | `20` | 동시 실행 상한. `0` 또는 빈 값은 설정되지 않음을 의미 || `poll_interval` | `30s` | 실행 polling 간격 |+| `ws_claim_poll_interval` | `3m` | 정상 WebSocket에서 claim 안전 polling의 상한. `poll_interval`과 독립적으로 설정되며 Daemon은 하향 jitter를 적용합니다 || `heartbeat_interval` | `15s` | heartbeat 간격 || `agent_timeout` | 제한 없음 | 단일 실행의 절대 시간 제한 || `codex_semantic_inactivity_timeout` | 파생 | Codex 의미 활동 없음 기준값. 설정하지 않으면 idle과 tool watchdog 예산 중 큰 값을 따르고, tool 예산이 `0`이면 idle 예산으로 되돌아갑니다. Codex 자체의 `10m`은 watchdog 전체를 비활성화했을 때만 유지됩니다 |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 8886f2b81e..950411591e 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -228,6 +228,7 @@ The variables below are read on the computer that runs your agents, not in the A| `MULTICA_DAEMON_DEVICE_NAME` | hostname | Device name shown in the runtime list || `MULTICA_AGENT_RUNTIME_NAME` | `Local Agent` | Runtime display name || `MULTICA_DAEMON_POLL_INTERVAL` | `30s` | Run polling interval when no wake event arrives |+| `MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL` | `3m` | Upper bound for healthy WebSocket claim safety polls, configured independently of `MULTICA_DAEMON_POLL_INTERVAL`; downward jitter makes the normal default `2m30s`–`2m45s`, while old servers and uncertain claims retain the ordinary poll interval || `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` | Heartbeat interval || `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | Concurrent run ceiling per daemon || `MULTICA_AGENT_TIMEOUT` | `0` | Absolute time limit per run; `0` means no limit |@@ -276,6 +277,7 @@ Supported keys:| `workspaces_root` | profile-aware path under `~` | Root directory for run working directories || `max_concurrent_tasks` | `20` | Concurrent run ceiling; `0` or empty means unset || `poll_interval` | `30s` | Run polling interval |+| `ws_claim_poll_interval` | `3m` | Upper bound for healthy WebSocket claim safety polls, independent of `poll_interval`; the daemon applies downward-only jitter || `heartbeat_interval` | `15s` | Heartbeat interval || `agent_timeout` | unlimited | Absolute time limit per run || `codex_semantic_inactivity_timeout` | derived | Codex semantic-silence threshold. With nothing set it takes the larger of the idle and tool watchdog budgets; a tool budget of `0` falls back to the idle budget, and only when the whole watchdog suite is disabled does Codex keep its own `10m` |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex b0c54f4184..7bbf52f623 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -228,6 +228,7 @@ API key 与 base URL 都为空时,这一层关闭,不会发出任何上游| `MULTICA_DAEMON_DEVICE_NAME` | 主机名 | 运行时列表中的设备名 || `MULTICA_AGENT_RUNTIME_NAME` | `Local Agent` | 运行时显示名 || `MULTICA_DAEMON_POLL_INTERVAL` | `30s` | 没有唤醒事件时的运行轮询间隔 |+| `MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL` | `3m` | 健康 WebSocket 下 claim 安全轮询的上限,与 `MULTICA_DAEMON_POLL_INTERVAL` 独立配置;向下抖动后默认实际为 `2m30s`–`2m45s`,旧 Server 或结果不确定的 claim 仍使用普通轮询间隔 || `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` | 心跳间隔 || `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | 单个守护进程的并发运行上限 || `MULTICA_AGENT_TIMEOUT` | `0` | 单次执行的绝对时限;`0` 表示不设置 |@@ -276,6 +277,7 @@ multica config show| `workspaces_root` | `~` 下按 profile 区分的路径 | 执行工作目录的根目录 || `max_concurrent_tasks` | `20` | 并发运行上限;`0` 或留空表示未设置 || `poll_interval` | `30s` | 运行轮询间隔 |+| `ws_claim_poll_interval` | `3m` | 健康 WebSocket 下 claim 安全轮询的上限,与 `poll_interval` 独立配置;Daemon 会应用向下抖动 || `heartbeat_interval` | `15s` | 心跳间隔 || `agent_timeout` | 不限制 | 单次执行的绝对时限 || `codex_semantic_inactivity_timeout` | 派生 | Codex 语义静默阈值。未设置时取 idle 与 tool watchdog 预算中较大的那个;tool 预算为 `0` 时回落到 idle 预算;只有整套 watchdog 关闭时才保留 Codex 自己的 `10m` |diff --git a/server/cmd/multica/cmd_config.go b/server/cmd/multica/cmd_config.goindex 7eaea4cb2f..6c52f1a67e 100644--- a/server/cmd/multica/cmd_config.go+++ b/server/cmd/multica/cmd_config.go@@ -37,6 +37,7 @@ var configSetSupportedKeys = []string{"workspaces_root","max_concurrent_tasks","poll_interval",+ "ws_claim_poll_interval","heartbeat_interval","agent_timeout","codex_semantic_inactivity_timeout",@@ -51,12 +52,12 @@ var configSetCmd = &cobra.Command{Short: "Set a CLI configuration value",Long: "Supported keys: " +"server_url, app_url, workspace_id, " +- "device_name, runtime_name, workspaces_root, max_concurrent_tasks, poll_interval, " ++ "device_name, runtime_name, workspaces_root, max_concurrent_tasks, poll_interval, ws_claim_poll_interval, " +"heartbeat_interval, agent_timeout, " +"codex_semantic_inactivity_timeout, codex_handshake_timeout, " +"disable_auto_update, auto_update_check_interval, disable_auto_reload.\n\n" +"The daemon keys (device_name, runtime_name, workspaces_root, max_concurrent_tasks, " +- "poll_interval, heartbeat_interval, agent_timeout, " ++ "poll_interval, ws_claim_poll_interval, heartbeat_interval, agent_timeout, " +"codex_semantic_inactivity_timeout, codex_handshake_timeout, " +"disable_auto_update, auto_update_check_interval, disable_auto_reload) mirror their " +"--flag / env counterparts and are read by `daemon start` when " +@@ -102,6 +103,7 @@ func runConfigShow(cmd *cobra.Command, _ []string) error {fmt.Fprintf(os.Stdout, "%-34s %s\n", "workspaces_root:", valueOrDefault(cfg.WorkspacesRoot, "(not set)"))fmt.Fprintf(os.Stdout, "%-34s %s\n", "max_concurrent_tasks:", intOrDefault(cfg.MaxConcurrentTasks, "(not set)"))fmt.Fprintf(os.Stdout, "%-34s %s\n", "poll_interval:", valueOrDefault(cfg.PollInterval, "(not set)"))+ fmt.Fprintf(os.Stdout, "%-34s %s\n", "ws_claim_poll_interval:", valueOrDefault(cfg.WSClaimPollInterval, "(not set)"))fmt.Fprintf(os.Stdout, "%-34s %s\n", "heartbeat_interval:", valueOrDefault(cfg.HeartbeatInterval, "(not set)"))fmt.Fprintf(os.Stdout, "%-34s %s\n", "agent_timeout:", agentTimeoutDisplay(cfg.AgentTimeout))fmt.Fprintf(os.Stdout, "%-34s %s\n", "codex_semantic_inactivity_timeout:", valueOrDefault(cfg.CodexSemanticInactivityTimeout, "(not set)"))@@ -205,6 +207,10 @@ func applyConfigSet(cfg *cli.CLIConfig, key, value string) error {return fmt.Errorf("poll_interval must be positive (got %s); use `config set poll_interval \"\"` to clear it", d)}cfg.PollInterval = value+ case "ws_claim_poll_interval":+ if err := assignPositiveDuration(&cfg.WSClaimPollInterval, key, value); err != nil {+ return err+ }case "heartbeat_interval":if err := assignPositiveDuration(&cfg.HeartbeatInterval, key, value); err != nil {return errdiff --git a/server/cmd/multica/cmd_config_test.go b/server/cmd/multica/cmd_config_test.goindex 5d17bad1e5..84ba1fb51d 100644--- a/server/cmd/multica/cmd_config_test.go+++ b/server/cmd/multica/cmd_config_test.go@@ -71,6 +71,7 @@ func TestRunConfigShowIncludesProfileAndDefaults(t *testing.T) {"workspaces_root:","max_concurrent_tasks:","poll_interval:",+ "ws_claim_poll_interval:","heartbeat_interval:","agent_timeout:","codex_semantic_inactivity_timeout:",@@ -207,6 +208,7 @@ func TestApplyConfigSetSupportsDaemonKeys(t *testing.T) {{"workspaces_root", workspacesRoot},{"max_concurrent_tasks", "4"},{"poll_interval", "10s"},+ {"ws_claim_poll_interval", "3m"},{"heartbeat_interval", "5s"},{"codex_semantic_inactivity_timeout", "15m"},{"codex_handshake_timeout", "45s"},@@ -224,6 +226,7 @@ func TestApplyConfigSetSupportsDaemonKeys(t *testing.T) {cfg.WorkspacesRoot != workspacesRoot ||cfg.MaxConcurrentTasks != 4 ||cfg.PollInterval != "10s" ||+ cfg.WSClaimPollInterval != "3m" ||cfg.HeartbeatInterval != "5s" ||cfg.CodexSemanticInactivityTimeout != "15m" ||cfg.CodexHandshakeTimeout != "45s" ||@@ -262,6 +265,7 @@ func TestApplyConfigSetPositiveDurationRoundTripsToDaemonResolver(t *testing.T)key stringread func(cli.CLIConfig) string}{+ {"ws_claim_poll_interval", func(cfg cli.CLIConfig) string { return cfg.WSClaimPollInterval }},{"heartbeat_interval", func(cfg cli.CLIConfig) string { return cfg.HeartbeatInterval }},{"codex_semantic_inactivity_timeout", func(cfg cli.CLIConfig) string { return cfg.CodexSemanticInactivityTimeout }},{"codex_handshake_timeout", func(cfg cli.CLIConfig) string { return cfg.CodexHandshakeTimeout }},@@ -345,6 +349,8 @@ func TestApplyConfigSetRejectsBadValues(t *testing.T) {{"poll bad duration", "poll_interval", "10", "duration"},{"poll zero", "poll_interval", "0s", "positive"},{"poll negative", "poll_interval", "-5s", "positive"},+ {"ws claim poll bad duration", "ws_claim_poll_interval", "three", "duration"},+ {"ws claim poll zero", "ws_claim_poll_interval", "0s", "positive"},{"heartbeat bad duration", "heartbeat_interval", "abc", "duration"},{"heartbeat zero", "heartbeat_interval", "0s", "positive"},{"codex semantic zero", "codex_semantic_inactivity_timeout", "0s", "positive"},diff --git a/server/cmd/multica/cmd_daemon.go b/server/cmd/multica/cmd_daemon.goindex 2ff337a588..a889ac4176 100644--- a/server/cmd/multica/cmd_daemon.go+++ b/server/cmd/multica/cmd_daemon.go@@ -99,6 +99,7 @@ func init() {f.String("runtime-name", "", "Runtime display name (env: MULTICA_AGENT_RUNTIME_NAME)")f.String("workspaces-root", "", "Base directory for run workspaces (env: MULTICA_WORKSPACES_ROOT)")f.Duration("poll-interval", 0, "Run poll interval (env: MULTICA_DAEMON_POLL_INTERVAL)")+ f.Duration("ws-claim-poll-interval", 0, "Healthy WebSocket claim safety-poll upper bound (env: MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL)")f.Duration("heartbeat-interval", 0, "Heartbeat interval (env: MULTICA_DAEMON_HEARTBEAT_INTERVAL)")f.Duration("agent-timeout", 0, "Absolute per-run wall-clock cap; 0 = no cap, rely on the watchdogs (env: MULTICA_AGENT_TIMEOUT)")f.Duration("codex-semantic-inactivity-timeout", 0, "Codex semantic inactivity timeout (env: MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT)")@@ -121,6 +122,7 @@ func init() {rf.String("runtime-name", "", "Runtime display name (env: MULTICA_AGENT_RUNTIME_NAME)")rf.String("workspaces-root", "", "Base directory for run workspaces (env: MULTICA_WORKSPACES_ROOT)")rf.Duration("poll-interval", 0, "Run poll interval (env: MULTICA_DAEMON_POLL_INTERVAL)")+ rf.Duration("ws-claim-poll-interval", 0, "Healthy WebSocket claim safety-poll upper bound (env: MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL)")rf.Duration("heartbeat-interval", 0, "Heartbeat interval (env: MULTICA_DAEMON_HEARTBEAT_INTERVAL)")rf.Duration("agent-timeout", 0, "Absolute per-run wall-clock cap; 0 = no cap, rely on the watchdogs (env: MULTICA_AGENT_TIMEOUT)")rf.Duration("codex-semantic-inactivity-timeout", 0, "Codex semantic inactivity timeout (env: MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT)")@@ -869,6 +871,9 @@ func buildDaemonStartArgs(cmd *cobra.Command) []string {if d, _ := cmd.Flags().GetDuration("poll-interval"); d > 0 {args = append(args, "--poll-interval", d.String())}+ if d, _ := cmd.Flags().GetDuration("ws-claim-poll-interval"); d > 0 {+ args = append(args, "--ws-claim-poll-interval", d.String())+ }if d, _ := cmd.Flags().GetDuration("heartbeat-interval"); d > 0 {args = append(args, "--heartbeat-interval", d.String())}@@ -989,6 +994,14 @@ func runDaemonForeground(cmd *cobra.Command) error {if pollOverride > 0 {overrides.PollInterval = pollOverride}+ wsClaimPollFlag, _ := cmd.Flags().GetDuration("ws-claim-poll-interval")+ wsClaimPollOverride, err := resolveDaemonDurationOverride(wsClaimPollFlag, "MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL", fileCfg.WSClaimPollInterval)+ if err != nil {+ return err+ }+ if wsClaimPollOverride > 0 {+ overrides.WSClaimPollInterval = wsClaimPollOverride+ }heartbeatFlag, _ := cmd.Flags().GetDuration("heartbeat-interval")heartbeatOverride, err := resolveDaemonDurationOverride(heartbeatFlag, "MULTICA_DAEMON_HEARTBEAT_INTERVAL", fileCfg.HeartbeatInterval)if err != nil {diff --git a/server/cmd/multica/cmd_daemon_test.go b/server/cmd/multica/cmd_daemon_test.goindex 6ddd363edd..be016bc4bf 100644--- a/server/cmd/multica/cmd_daemon_test.go+++ b/server/cmd/multica/cmd_daemon_test.go@@ -105,6 +105,20 @@ func TestBuildDaemonStartArgsForwardsCodexHandshakeTimeout(t *testing.T) {}}+func TestBuildDaemonStartArgsForwardsWSClaimPollInterval(t *testing.T) {+ cmd := &cobra.Command{}+ cmd.Flags().Duration("ws-claim-poll-interval", 0, "")+ if err := cmd.Flags().Set("ws-claim-poll-interval", "3m"); err != nil {+ t.Fatalf("set flag: %v", err)+ }++ args := buildDaemonStartArgs(cmd)+ want := []string{"daemon", "start", "--foreground", "--ws-claim-poll-interval", (3 * time.Minute).String()}+ if strings.Join(args, " ") != strings.Join(want, " ") {+ t.Fatalf("buildDaemonStartArgs() = %q, want %q", args, want)+ }+}+func TestBuildDaemonStartArgsForwardsWorkspacesRoot(t *testing.T) {cmd := &cobra.Command{}cmd.Flags().String("workspaces-root", "", "")diff --git a/server/internal/cli/config.go b/server/internal/cli/config.goindex a972a9fa2a..edcd2b4e5d 100644--- a/server/internal/cli/config.go+++ b/server/internal/cli/config.go@@ -75,6 +75,13 @@ type CLIConfig struct {// MULTICA_DAEMON_POLL_INTERVAL env, this field, DefaultPollInterval.PollInterval string `json:"poll_interval,omitempty"`+ // WSClaimPollInterval is the upper bound for missed-event safety polls+ // while task claims use a healthy WebSocket. The daemon applies+ // downward-only jitter, and retains PollInterval for old servers and+ // uncertain claims. Resolution precedence: --ws-claim-poll-interval,+ // MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL, this field, 3m default.+ WSClaimPollInterval string `json:"ws_claim_poll_interval,omitempty"`+// HeartbeatInterval is how often the daemon sends heartbeat pings to// the server (Go duration string). Same persist-once motivation as// PollInterval. Empty ("") means "not set — use env / built-indiff --git a/server/internal/daemon/client.go b/server/internal/daemon/client.goindex ec30957a5d..3c82c389df 100644--- a/server/internal/daemon/client.go+++ b/server/internal/daemon/client.go@@ -178,16 +178,29 @@ func (c *Client) setIdentityHeaders(req *http.Request) {if c.os != "" {req.Header.Set("X-Client-OS", c.os)}- req.Header.Set("X-Client-Capabilities", daemonClientCapabilities())+ req.Header.Set("X-Client-Capabilities", daemonHTTPClientCapabilities())}// daemonClientCapabilities is the X-Client-Capabilities value the daemon-// advertises on BOTH the HTTP control-plane requests and the WS handshake, so a-// claim built over WS gets the same capability gating (skill refs,-// coalesced-comments) as the HTTP path. rpc-v1 advertises WS request/response-// support (MUL-4257).+// advertises on the WS handshake. A claim built over WS gets the common+// capability gating plus WS-only scheduling metadata. rpc-v1 advertises WS+// request/response support (MUL-4257).func daemonClientCapabilities() string {- return strings.Join([]string{+ return strings.Join(append(daemonCommonCapabilities(),+ protocol.DaemonCapabilityClaimPollHintsV1,+ ), ",")+}++// daemonHTTPClientCapabilities omits claim-poll-hints-v1 because HTTP fallback+// responses cannot drive the healthy-WS scheduler. Advertising it there would+// make the server run the deferred-task hint query only for the daemon to ignore+// the result.+func daemonHTTPClientCapabilities() string {+ return strings.Join(daemonCommonCapabilities(), ",")+}++func daemonCommonCapabilities() []string {+ return []string{protocol.DaemonCapabilitySkillBundlesV1,protocol.DaemonCapabilityCoalescedCommentsV1,protocol.DaemonCapabilityExecutionManifestV1,@@ -196,7 +209,7 @@ func daemonClientCapabilities() string {protocol.DaemonCapabilityLocalWorktreeV1,protocol.DaemonCapabilitySourceContextQuickCreateV1,protocol.DaemonCapabilityRPCV1,- }, ",")+ }}// SetToken sets the auth token for authenticated requests.@@ -255,6 +268,17 @@ func (c *Client) ResolveRemoteMCPCredential(ctx context.Context, daemonToken, ta// comfortably above p99 claim latency so recovery stays the exception.const batchClaimRequestTimeout = 5 * time.Second+// claimTasksResult carries optional scheduling metadata understood only by+// daemons advertising claim-poll-hints-v1. A zero-value result is deliberately+// conservative: it makes the poller retain PollInterval, which protects new+// daemons talking to old servers and claims whose WS outcome was uncertain.+type claimTasksResult struct {+ Tasks []*Task `json:"tasks"`+ ClaimPollHintSupported bool `json:"claim_poll_hint_supported,omitempty"`+ NextDeferredTaskAfterMillis int64 `json:"next_deferred_task_after_ms,omitempty"`+ ClaimedOverWS bool `json:"-"`+}+// ClaimTasks is the machine-level (MUL-4257) batch counterpart of ClaimTask:// it asks the server, in a single request, to claim up to maxTasks tasks across// every runtime the daemon hosts. daemonID scopes the request to this machine —@@ -266,19 +290,22 @@ const batchClaimRequestTimeout = 5 * time.Second// one slow claim cannot stall the whole batch; the deadline propagates to the// server and cancels the in-flight query there too.func (c *Client) ClaimTasks(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) ([]*Task, error) {+ result, err := c.claimTasksWithHints(ctx, daemonID, runtimeIDs, maxTasks)+ return result.Tasks, err+}++func (c *Client) claimTasksWithHints(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) (claimTasksResult, error) {reqCtx, cancel := context.WithTimeout(ctx, batchClaimRequestTimeout)defer cancel()- var resp struct {- Tasks []*Task `json:"tasks"`- }+ var resp claimTasksResultif err := c.postJSON(reqCtx, "/api/daemon/tasks/claim", map[string]any{"daemon_id": daemonID,"runtime_ids": runtimeIDs,"max_tasks": maxTasks,}, &resp); err != nil {- return nil, err+ return claimTasksResult{}, err}- return resp.Tasks, nil+ return resp, nil}// isBatchClaimUnsupported reports whether err is a 404 from the batch claimdiff --git a/server/internal/daemon/client_batch_claim_test.go b/server/internal/daemon/client_batch_claim_test.goindex a76cdc852d..adb04684e9 100644--- a/server/internal/daemon/client_batch_claim_test.go+++ b/server/internal/daemon/client_batch_claim_test.go@@ -6,7 +6,10 @@ import ("io""net/http""net/http/httptest"+ "strings""testing"++ "github.com/multica-ai/multica/server/pkg/protocol")// TestClient_ClaimTasks_PostsRuntimeSetAndParsesTasks verifies the machine-level@@ -15,6 +18,7 @@ import (// each task's runtime_id so the daemon can route it locally.func TestClient_ClaimTasks_PostsRuntimeSetAndParsesTasks(t *testing.T) {var gotPath string+ var gotCapabilities stringvar gotBody struct {DaemonID string `json:"daemon_id"`RuntimeIDs []string `json:"runtime_ids"`@@ -23,6 +27,7 @@ func TestClient_ClaimTasks_PostsRuntimeSetAndParsesTasks(t *testing.T) {srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {gotPath = r.URL.Path+ gotCapabilities = r.Header.Get("X-Client-Capabilities")body, _ := io.ReadAll(r.Body)_ = json.Unmarshal(body, &gotBody)w.Header().Set("Content-Type", "application/json")@@ -44,6 +49,9 @@ func TestClient_ClaimTasks_PostsRuntimeSetAndParsesTasks(t *testing.T) {if gotPath != "/api/daemon/tasks/claim" {t.Errorf("path = %q, want /api/daemon/tasks/claim", gotPath)}+ if strings.Contains(gotCapabilities, protocol.DaemonCapabilityClaimPollHintsV1) {+ t.Errorf("HTTP capabilities = %q, unexpectedly advertise WS-only %q", gotCapabilities, protocol.DaemonCapabilityClaimPollHintsV1)+ }if gotBody.DaemonID != "daemon-x" {t.Errorf("posted daemon_id = %q, want daemon-x", gotBody.DaemonID)}@@ -61,6 +69,24 @@ func TestClient_ClaimTasks_PostsRuntimeSetAndParsesTasks(t *testing.T) {}}+func TestClient_ClaimTasksWithHints_ParsesSchedulingMetadata(t *testing.T) {+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Content-Type", "application/json")+ w.Write([]byte(`{"tasks":[],"claim_poll_hint_supported":true,"next_deferred_task_after_ms":4750}`))+ }))+ defer srv.Close()++ c := NewClient(srv.URL)+ c.SetToken("tok")+ result, err := c.claimTasksWithHints(context.Background(), "daemon-x", []string{"rt-a"}, 1)+ if err != nil {+ t.Fatalf("claimTasksWithHints: %v", err)+ }+ if !result.ClaimPollHintSupported || result.NextDeferredTaskAfterMillis != 4750 {+ t.Fatalf("result = %+v, want supported hint after 4750ms", result)+ }+}+// TestClient_ClaimTasks_EmptyResult confirms an empty batch (idle daemon) is// returned as a nil/empty slice, not an error.func TestClient_ClaimTasks_EmptyResult(t *testing.T) {diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 1ca239c2de..833cf5da14 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -19,9 +19,13 @@ import ()const (- DefaultServerURL = "ws://localhost:8080/ws"- DefaultPollInterval = 30 * time.Second- DefaultHeartbeatInterval = 15 * time.Second+ DefaultServerURL = "ws://localhost:8080/ws"+ DefaultPollInterval = 30 * time.Second+ // DefaultWSClaimPollInterval is the upper bound for missed-event safety+ // polls while task availability and claims use a healthy WebSocket. The+ // poller applies downward-only jitter before each sleep.+ DefaultWSClaimPollInterval = 3 * time.Minute+ DefaultHeartbeatInterval = 15 * time.Second// DefaultAgentTimeout is the optional absolute wall-clock cap on a single// agent run. 0 = no cap: a run is bounded only by the inactivity watchdog// (DefaultAgentIdleWatchdog), so a session that keeps emitting events is@@ -125,6 +129,7 @@ type Config struct {AutoUpdateCheckInterval time.Duration // how often the auto-update loop polls for a new release (default: 6h)AutoReloadEnabled bool // restart when the multica binary on disk no longer matches the running version (default: true for CLI-launched daemons)PollInterval time.Duration+ WSClaimPollInterval time.Duration // upper bound for healthy WS batch-claim safety polls; actual sleeps use downward-only jitterHeartbeatInterval time.DurationAgentTimeout time.DurationCodexSemanticInactivityTimeout time.Duration@@ -157,10 +162,11 @@ type Config struct {// Overrides allows CLI flags to override environment variables and defaults.// Zero values are ignored and the env/default value is used instead.type Overrides struct {- ServerURL string- WorkspacesRoot string- PollInterval time.Duration- HeartbeatInterval time.Duration+ ServerURL string+ WorkspacesRoot string+ PollInterval time.Duration+ WSClaimPollInterval time.Duration+ HeartbeatInterval time.Duration// AgentTimeout is a pointer so an explicit `--agent-timeout 0` (no cap) is// distinguishable from "flag not passed". nil = use env/default.AgentTimeout *time.Duration@@ -289,6 +295,16 @@ func LoadConfig(overrides Overrides) (Config, error) {if overrides.PollInterval > 0 {pollInterval = overrides.PollInterval}+ wsClaimPollInterval, err := durationFromEnv("MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL", DefaultWSClaimPollInterval)+ if err != nil {+ return Config{}, err+ }+ if overrides.WSClaimPollInterval > 0 {+ wsClaimPollInterval = overrides.WSClaimPollInterval+ }+ if wsClaimPollInterval <= 0 {+ return Config{}, fmt.Errorf("MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL must be positive (got %s)", wsClaimPollInterval)+ }heartbeatInterval, err := durationFromEnv("MULTICA_DAEMON_HEARTBEAT_INTERVAL", DefaultHeartbeatInterval)if err != nil {@@ -612,6 +628,7 @@ func LoadConfig(overrides Overrides) (Config, error) {HealthPort: healthPort,MaxConcurrentTasks: maxConcurrentTasks,PollInterval: pollInterval,+ WSClaimPollInterval: wsClaimPollInterval,HeartbeatInterval: heartbeatInterval,AgentTimeout: agentTimeout,CodexSemanticInactivityTimeout: codexSemanticInactivityTimeout,diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.goindex c6bde47f27..19471e42c6 100644--- a/server/internal/daemon/config_test.go+++ b/server/internal/daemon/config_test.go@@ -142,6 +142,46 @@ func TestLoadConfig_CompletedTaskTTLDefaultsDisabledOnSelfHostAndReadsEnv(t *tes}}+func TestLoadConfig_WSClaimPollIntervalPrecedence(t *testing.T) {+ stageFakeAgent(t)+ t.Setenv("HOME", t.TempDir())+ t.Setenv("SHELL", filepath.Join(t.TempDir(), "missing-shell"))+ t.Setenv("MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL", "")+ base := Overrides{ServerURL: "http://localhost:0", WorkspacesRoot: t.TempDir()}++ cfg, err := LoadConfig(base)+ if err != nil {+ t.Fatalf("LoadConfig default: %v", err)+ }+ if cfg.WSClaimPollInterval != DefaultWSClaimPollInterval {+ t.Fatalf("default WSClaimPollInterval = %s, want %s", cfg.WSClaimPollInterval, DefaultWSClaimPollInterval)+ }++ t.Setenv("MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL", "75s")+ cfg, err = LoadConfig(base)+ if err != nil {+ t.Fatalf("LoadConfig env: %v", err)+ }+ if cfg.WSClaimPollInterval != 75*time.Second {+ t.Fatalf("env WSClaimPollInterval = %s, want 75s", cfg.WSClaimPollInterval)+ }++ base.WSClaimPollInterval = 2 * time.Minute+ cfg, err = LoadConfig(base)+ if err != nil {+ t.Fatalf("LoadConfig override: %v", err)+ }+ if cfg.WSClaimPollInterval != 2*time.Minute {+ t.Fatalf("override WSClaimPollInterval = %s, want 2m", cfg.WSClaimPollInterval)+ }++ base.WSClaimPollInterval = 0+ t.Setenv("MULTICA_DAEMON_WS_CLAIM_POLL_INTERVAL", "0s")+ if _, err := LoadConfig(base); err == nil || !strings.Contains(err.Error(), "must be positive") {+ t.Fatalf("LoadConfig zero WS claim poll error = %v, want positive-duration validation", err)+ }+}+func TestLoadConfig_CompletedTaskTTLDefaultsBoundedOnOfficialCloud(t *testing.T) {stageFakeAgent(t)t.Setenv("HOME", t.TempDir())diff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 21515618c1..9bc7409002 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -1981,6 +1981,7 @@ func (d *Daemon) Run(ctx context.Context) error {"workspaces_root", d.cfg.WorkspacesRoot,"health_port", d.cfg.HealthPort,"poll_interval", d.cfg.PollInterval,+ "ws_claim_poll_interval", d.cfg.WSClaimPollInterval,"heartbeat_interval", d.cfg.HeartbeatInterval,"agent_timeout", d.cfg.AgentTimeout,"idle_watchdog", d.cfg.AgentIdleWatchdog,@@ -5100,7 +5101,7 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan icontinue}- tasks, err := d.ClaimTasksWSFirst(pollerCtx, d.cfg.DaemonID, runtimeIDs, len(slots))+ claimResult, err := d.claimTasksWSFirst(pollerCtx, d.cfg.DaemonID, runtimeIDs, len(slots))if err != nil {d.exitClaim()releaseSlots(slots)@@ -5112,6 +5113,7 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i}continue}+ tasks := claimResult.Tasks// Dispatch each claimed task into a slot. activeTasks is incremented for// every dispatched task BEFORE exitClaim so the auto-update barrier never@@ -5159,16 +5161,56 @@ func (d *Daemon) runBatchPoller(pollerCtx, parentCtx context.Context, sem chan i}// If we filled every slot, more work may be queued — loop immediately.- // Otherwise wait for the next wakeup / poll interval.+ // Otherwise wait for the next wakeup / poll interval. A connection that+ // negotiated WS RPC receives task-available pushes, so this poll is only+ // a missed-event safety net and can run less often. Claim errors retain+ // the configured fallback cadence above.if dispatched > 0 && dispatched == len(slots) {continue}- if err := sleepWithContextOrWakeup(pollerCtx, d.cfg.PollInterval, wakeup); err != nil {+ if err := sleepWithContextOrWakeup(pollerCtx, d.taskClaimPollInterval(claimResult), wakeup); err != nil {return}}}+// taskClaimPollInterval returns the next missed-event safety poll. The longer+// cadence is only safe when this exact claim response came from a server that+// opted into scheduling hints; a missing hint covers old servers and uncertain+// WS claims, both of which retain the normal fallback cadence. Downward-only+// jitter keeps the default below the server's 3-minute empty-claim cache TTL+// while preventing an idle fleet from polling in lockstep.+func (d *Daemon) taskClaimPollInterval(result claimTasksResult) time.Duration {+ if !d.wsRPC.supportsRPCV1() || !result.ClaimedOverWS || !result.ClaimPollHintSupported {+ if d.cfg.PollInterval > 0 {+ return d.cfg.PollInterval+ }+ return DefaultPollInterval+ }+ upperBound := d.cfg.WSClaimPollInterval+ if upperBound <= 0 {+ upperBound = DefaultWSClaimPollInterval+ }+ interval := downwardJitterDuration(upperBound)+ if result.NextDeferredTaskAfterMillis > 0 {+ untilDeferred := time.Duration(result.NextDeferredTaskAfterMillis) * time.Millisecond+ if untilDeferred < interval {+ interval = untilDeferred+ }+ }+ return interval+}++func downwardJitterDuration(interval time.Duration) time.Duration {+ minReduction := interval / 12+ maxReduction := interval / 6+ if minReduction <= 0 || maxReduction <= minReduction {+ return interval+ }+ reduction := minReduction + time.Duration(rand.Int63n(int64(maxReduction-minReduction)+1))+ return interval - reduction+}+func signalPollerWakeup(wakeup chan<- struct{}) {select {case wakeup <- struct{}{}:diff --git a/server/internal/daemon/runtime_isolation_test.go b/server/internal/daemon/runtime_isolation_test.goindex a1fbfbbdec..794b4fe6c3 100644--- a/server/internal/daemon/runtime_isolation_test.go+++ b/server/internal/daemon/runtime_isolation_test.go@@ -203,6 +203,43 @@ func TestRunBatchPollerClaimsAcrossRuntimes(t *testing.T) {taskWG.Wait()}+func TestTaskClaimPollIntervalTracksWSRPCAvailability(t *testing.T) {+ t.Parallel()++ d := New(Config{PollInterval: 30 * time.Second, WSClaimPollInterval: 3 * time.Minute}, slog.Default())+ if got := d.taskClaimPollInterval(claimTasksResult{}); got != 30*time.Second {+ t.Fatalf("interval without websocket = %v, want 30s", got)+ }++ generation := d.wsRPC.attach(func([]byte) (*wsOutbound, error) { return nil, nil })+ if got := d.taskClaimPollInterval(claimTasksResult{}); got != 30*time.Second {+ t.Fatalf("interval before rpc-v1 negotiation = %v, want 30s", got)+ }++ d.wsRPC.markRPCV1Supported(generation)+ if got := d.taskClaimPollInterval(claimTasksResult{}); got != 30*time.Second {+ t.Fatalf("interval without a server hint = %v, want 30s", got)+ }+ if got := d.taskClaimPollInterval(claimTasksResult{ClaimPollHintSupported: true}); got != 30*time.Second {+ t.Fatalf("interval after HTTP fallback = %v, want 30s", got)+ }++ hinted := claimTasksResult{ClaimPollHintSupported: true, ClaimedOverWS: true}+ if got := d.taskClaimPollInterval(hinted); got < 150*time.Second || got > 165*time.Second {+ t.Fatalf("jittered interval with a hint = %v, want 2m30s..2m45s", got)+ }++ hinted.NextDeferredTaskAfterMillis = 4200+ if got := d.taskClaimPollInterval(hinted); got != 4200*time.Millisecond {+ t.Fatalf("interval with deferred task = %v, want 4.2s", got)+ }++ d.wsRPC.attach(nil)+ if got := d.taskClaimPollInterval(hinted); got != 30*time.Second {+ t.Fatalf("interval after websocket disconnect = %v, want 30s", got)+ }+}+// TestRunBatchPollerWakesAfterTaskExit guards the gap where a queued task is// temporarily unclaimable (for example, because the same agent/issue task is// still running), the batch claim returns empty, and the poller goes to sleepdiff --git a/server/internal/daemon/wakeup.go b/server/internal/daemon/wakeup.goindex d6b803d7ee..07d42aaabe 100644--- a/server/internal/daemon/wakeup.go+++ b/server/internal/daemon/wakeup.go@@ -115,8 +115,8 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strinif d.client.os != "" {headers.Set("X-Client-OS", d.client.os)}- // Advertise the same capabilities as the HTTP path so a claim built over- // this WS connection gets identical capability gating (MUL-4257).+ // WS claims use the common capabilities plus scheduling hints that only the+ // healthy-connection poller can consume.headers.Set("X-Client-Capabilities", daemonClientCapabilities())// A hand-built websocket.Dialer has Proxy == nil, which gorilla reads as@@ -232,6 +232,10 @@ func (d *Daemon) runTaskWakeupConnection(ctx context.Context, runtimeIDs []strin// frame will be dropped), and flip the send-closed flag under sendMu so// any in-flight guarded send finishes before we close writes.d.wsRPC.attach(nil)+ // A healthy WS connection lets the claim poller use a longer fallback+ // interval. Wake it as soon as the connection drops so it immediately+ // observes the detach and resumes the configured HTTP cadence.+ signalTaskWakeup(taskWakeups, "")sendMu.Lock()sendClosed = truesendMu.Unlock()diff --git a/server/internal/daemon/wakeup_test.go b/server/internal/daemon/wakeup_test.goindex 8def0ff688..52baf77d17 100644--- a/server/internal/daemon/wakeup_test.go+++ b/server/internal/daemon/wakeup_test.go@@ -63,6 +63,68 @@ func TestTaskWakeupURL(t *testing.T) {}}+func TestRunTaskWakeupConnectionSignalsDisconnect(t *testing.T) {+ upgrader := websocket.Upgrader{}+ connected := make(chan struct{})+ capabilities := make(chan string, 1)+ closeConnection := make(chan struct{})+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ capabilities <- r.Header.Get("X-Client-Capabilities")+ conn, err := upgrader.Upgrade(w, r, nil)+ if err != nil {+ return+ }+ close(connected)+ <-closeConnection+ conn.Close()+ }))+ defer srv.Close()+ defer func() {+ select {+ case <-closeConnection:+ default:+ close(closeConnection)+ }+ }()++ d := New(Config{+ ServerBaseURL: srv.URL,+ HeartbeatInterval: time.Hour,+ }, slog.Default())+ taskWakeups := make(chan taskWakeup, 2)+ errCh := make(chan error, 1)+ go func() {+ _, err := d.runTaskWakeupConnection(context.Background(), []string{"runtime-1"}, taskWakeups, make(chan struct{}))+ errCh <- err+ }()++ select {+ case <-connected:+ case <-time.After(time.Second):+ t.Fatal("websocket did not connect")+ }+ if got := <-capabilities; !strings.Contains(got, protocol.DaemonCapabilityClaimPollHintsV1) {+ t.Fatalf("WS capabilities = %q, missing %q", got, protocol.DaemonCapabilityClaimPollHintsV1)+ }+ select {+ case <-taskWakeups: // initial catch-up claim+ case <-time.After(time.Second):+ t.Fatal("connection did not signal initial wakeup")+ }++ close(closeConnection)+ select {+ case <-errCh:+ case <-time.After(time.Second):+ t.Fatal("connection did not stop after peer disconnect")+ }+ select {+ case <-taskWakeups:+ case <-time.After(time.Second):+ t.Fatal("disconnect did not wake the claim poller")+ }+}+// TestWSHeartbeatFreshnessSuppressesHTTP pins the WS-vs-HTTP coordination:// once a runtime acked over WS within the freshness window the HTTP// heartbeat loop must skip it to avoid duplicate DB writes.diff --git a/server/internal/daemon/wsrpc.go b/server/internal/daemon/wsrpc.goindex 4e9356a222..2458cddaab 100644--- a/server/internal/daemon/wsrpc.go+++ b/server/internal/daemon/wsrpc.go@@ -313,11 +313,17 @@ func (c *wsRPCClient) deliver(resp protocol.RPCResponsePayload) {// are identical to the HTTP endpoint so both transports are interchangeable.// Wired into the claim poller as part of the poller cutover.func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) ([]*Task, error) {+ result, err := d.claimTasksWSFirst(ctx, daemonID, runtimeIDs, maxTasks)+ return result.Tasks, err+}++func (d *Daemon) claimTasksWSFirst(ctx context.Context, daemonID string, runtimeIDs []string, maxTasks int) (claimTasksResult, error) {// Un-upgraded server without the batch route: a prior poll already learned// this (via a 404), so go straight to the legacy per-runtime claim and skip// the WS + batch attempts each cycle.if d.batchClaimUnsupported.Load() {- return d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ tasks, err := d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ return claimTasksResult{Tasks: tasks}, err}bypassWSOnce := falseif retryAfterNanos := d.wsClaimHTTPFallbackAfter.Load(); retryAfterNanos > 0 {@@ -326,7 +332,7 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtimeif now.Before(retryAfter) {d.logger.Debug("ws claim outcome uncertain; delaying http fallback until safety window elapses","retry_after", retryAfter.Sub(now).Round(time.Millisecond))- return nil, nil+ return claimTasksResult{}, nil}if d.wsClaimHTTPFallbackAfter.CompareAndSwap(retryAfterNanos, 0) {bypassWSOnce = true@@ -334,9 +340,7 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtime}}if !bypassWSOnce && d.wsRPC.supportsRPCV1() {- var resp struct {- Tasks []*Task `json:"tasks"`- }+ var resp claimTasksResult// batchClaimRequestTimeout is the server-side execution budget; the// daemon waits that plus the client's grace margin for the response._, err := d.wsRPC.CallIfRPCV1Supported(ctx, "tasks.claim", batchClaimRequestTimeout, map[string]any{@@ -345,7 +349,8 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtime"max_tasks": maxTasks,}, &resp)if err == nil {- return resp.Tasks, nil+ resp.ClaimedOverWS = true+ return resp, nil}if errors.Is(err, errWSRPCUncertain) {// The WS claim may have committed server-side; claiming the same@@ -360,13 +365,13 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtime}d.wsClaimHTTPFallbackAfter.Store(time.Now().Add(delay).UnixNano())d.logger.Debug("ws claim outcome uncertain after disconnect; delaying http fallback", "retry_after", delay)- return nil, nil+ return claimTasksResult{}, nil}d.logger.Debug("ws claim failed; falling back to http", "error", err)}- tasks, err := d.client.ClaimTasks(ctx, daemonID, runtimeIDs, maxTasks)+ result, err := d.client.claimTasksWithHints(ctx, daemonID, runtimeIDs, maxTasks)if err == nil {- return tasks, nil+ return result, nil}// Server has no batch route (404): freeze the old API contract by falling// back to the legacy per-runtime claim loop, and remember it so we don't@@ -374,7 +379,8 @@ func (d *Daemon) ClaimTasksWSFirst(ctx context.Context, daemonID string, runtimeif isBatchClaimUnsupported(err) {d.batchClaimUnsupported.Store(true)d.logger.Info("batch claim route unsupported by server; using legacy per-runtime claim")- return d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ tasks, legacyErr := d.client.claimTasksLegacy(ctx, runtimeIDs, maxTasks)+ return claimTasksResult{Tasks: tasks}, legacyErr}- return nil, err+ return claimTasksResult{}, err}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 1d3a8b3c14..25101a2126 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -37,6 +37,13 @@ import ("github.com/multica-ai/multica/server/pkg/taskfailure")+// claimPollHintMinDelay bounds a future mismatch between the hint query and+// deferred-task promotion to at most one follow-up claim per second. Under the+// shared eligibility fences an overdue task should normally be promoted by the+// current request, so this is a defense-in-depth floor rather than the steady+// state poll interval.+const claimPollHintMinDelay = time.Second+// ---------------------------------------------------------------------------// Daemon workspace ownership helpers// ---------------------------------------------------------------------------@@ -1823,7 +1830,37 @@ func (h *Handler) ClaimTasksByRuntime(w http.ResponseWriter, r *http.Request) {"runtimes", len(authorized), "requested_max", maxTasks, "claimed", len(out),"total_ms", time.Since(start).Milliseconds())}- writeMeasuredJSON(w, http.StatusOK, map[string]any{"tasks": out})+ response := map[string]any{"tasks": out}+ // Only opted-in daemons understand this additive response metadata. Query+ // after the claim so a future fire_at can shorten the long healthy-WS safety+ // poll; a task that crossed fire_at during this request yields a bounded+ // follow-up hint and is promoted on the next claim. If the lookup fails,+ // omit the support bit so the daemon conservatively retains its ordinary+ // PollInterval.+ if len(out) < maxTasks && requestHasClientCapability(r, protocol.DaemonCapabilityClaimPollHintsV1) {+ nextDeferred, nextErr := h.Queries.NextDeferredTaskFireAtForRuntimes(r.Context(), db.NextDeferredTaskFireAtForRuntimesParams{+ RuntimeIds: authorized,+ RuntimeStaleSecs: service.RuntimeClaimFreshnessSeconds,+ })+ if nextErr != nil {+ slog.Warn("batch claim: next deferred task lookup failed; retaining short client poll",+ "error", nextErr)+ } else {+ response["claim_poll_hint_supported"] = true+ if nextDeferred.Valid {+ response["next_deferred_task_after_ms"] = claimPollHintDelay(time.Now(), nextDeferred.Time).Milliseconds()+ }+ }+ }+ writeMeasuredJSON(w, http.StatusOK, response)+}++func claimPollHintDelay(now, fireAt time.Time) time.Duration {+ delay := fireAt.Sub(now)+ if delay < claimPollHintMinDelay {+ return claimPollHintMinDelay+ }+ return delay}// claimBuildFailure captures a pre-response failure fromdiff --git a/server/internal/handler/daemon_batch_claim_test.go b/server/internal/handler/daemon_batch_claim_test.goindex 8277f8d9a4..852ce3552b 100644--- a/server/internal/handler/daemon_batch_claim_test.go+++ b/server/internal/handler/daemon_batch_claim_test.go@@ -7,7 +7,13 @@ import ("net/http/httptest""strings""testing"+ "time"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/service"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol""github.com/multica-ai/multica/server/pkg/taskfailure")@@ -19,6 +25,8 @@ type batchClaimResponse struct {RuntimeID string `json:"runtime_id"`AuthToken string `json:"auth_token"`} `json:"tasks"`+ ClaimPollHintSupported bool `json:"claim_poll_hint_supported"`+ NextDeferredTaskAfterMillis int64 `json:"next_deferred_task_after_ms"`}func seedQueuedIssueTask(t *testing.T, ctx context.Context, agentID, runtimeID, issueID string) string {@@ -36,20 +44,133 @@ func seedQueuedIssueTask(t *testing.T, ctx context.Context, agentID, runtimeID,}func postBatchClaim(t *testing.T, workspaceID string, runtimeIDs []string, maxTasks int) *httptest.ResponseRecorder {+ return postBatchClaimWithCapabilities(t, workspaceID, runtimeIDs, maxTasks, "")+}++func postBatchClaimWithCapabilities(t *testing.T, workspaceID string, runtimeIDs []string, maxTasks int, capabilities string) *httptest.ResponseRecorder {t.Helper()w := httptest.NewRecorder()- req := newDaemonTokenRequest("POST", "/api/daemon/tasks/claim",- map[string]any{"daemon_id": batchClaimTestDaemonID, "runtime_ids": runtimeIDs, "max_tasks": maxTasks},- workspaceID, batchClaimTestDaemonID)+ req := batchClaimRequest(workspaceID, runtimeIDs, maxTasks, capabilities)testHandler.ClaimTasksByRuntime(w, req)return w}+func batchClaimRequest(workspaceID string, runtimeIDs []string, maxTasks int, capabilities string) *http.Request {+ req := newDaemonTokenRequest(http.MethodPost, "/api/daemon/tasks/claim",+ map[string]any{"daemon_id": batchClaimTestDaemonID, "runtime_ids": runtimeIDs, "max_tasks": maxTasks}, workspaceID, batchClaimTestDaemonID)+ if capabilities != "" {+ req.Header.Set("X-Client-Capabilities", capabilities)+ }+ return req+}+// batchClaimTestDaemonID is the daemon id used by both the mdt_ token context// and the request body in batch-claim handler tests, so the daemon_id// consistency check passes on the happy path.const batchClaimTestDaemonID = "batch-claim-review"+func TestClaimTasksByRuntime_ClaimPollHintSchedulesNextDeferredTask(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()+ runtimeID := createClaimReclaimRuntime(t, ctx, "Batch claim deferred hint")+ agentID, issueID := createClaimReclaimAgentAndIssue(t, ctx, runtimeID, "Batch claim deferred hint agent")+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "deferred",+ "fire_at": testutil.Raw("now() + interval '5 seconds'"),+ })++ hinted := testutil.Decode[batchClaimResponse](t, testHandler.ClaimTasksByRuntime,+ batchClaimRequest(testWorkspaceID, []string{runtimeID}, 1, protocol.DaemonCapabilityClaimPollHintsV1), http.StatusOK)+ if !hinted.ClaimPollHintSupported {+ t.Fatal("response did not confirm claim poll hint support")+ }+ if hinted.NextDeferredTaskAfterMillis <= 0 || hinted.NextDeferredTaskAfterMillis > 5000 {+ t.Fatalf("next deferred delay = %dms, want 1..5000ms", hinted.NextDeferredTaskAfterMillis)+ }++ legacy := testutil.Decode[batchClaimResponse](t, testHandler.ClaimTasksByRuntime,+ batchClaimRequest(testWorkspaceID, []string{runtimeID}, 1, ""), http.StatusOK)+ if legacy.ClaimPollHintSupported || legacy.NextDeferredTaskAfterMillis != 0 {+ t.Fatalf("legacy response unexpectedly exposed poll hints: %+v", legacy)+ }+}++func TestNextDeferredTaskFireAtForRuntimes_OmitsIneligibleOverdueTasks(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ tests := []struct {+ name string+ runtimeCols testutil.Cols+ occupied bool+ wantHint bool+ }{+ {name: "eligible", wantHint: true},+ {name: "occupied", occupied: true},+ {name: "runtime offline", runtimeCols: testutil.Cols{"status": "offline"}},+ {name: "runtime stale", runtimeCols: testutil.Cols{+ "last_seen_at": testutil.Raw("now() - interval '10 minutes'"),+ "updated_at": testutil.Raw("now() - interval '10 minutes'"),+ }},+ }++ for _, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "deferred hint "+tt.name, tt.runtimeCols)+ agentID := dbfx.Agent(t, "deferred hint "+tt.name, runtimeID)+ issueID := dbfx.Issue(t, "deferred hint "+tt.name)+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "deferred",+ "fire_at": testutil.Raw("now() - interval '1 second'"),+ })+ if tt.occupied {+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "queued",+ })+ }++ next, err := testHandler.Queries.NextDeferredTaskFireAtForRuntimes(t.Context(), db.NextDeferredTaskFireAtForRuntimesParams{+ RuntimeIds: []pgtype.UUID{parseUUID(runtimeID)},+ RuntimeStaleSecs: service.RuntimeClaimFreshnessSeconds,+ })+ if err != nil {+ t.Fatalf("NextDeferredTaskFireAtForRuntimes: %v", err)+ }+ if next.Valid != tt.wantHint {+ t.Fatalf("hint validity = %v, want %v", next.Valid, tt.wantHint)+ }+ })+ }+}++func TestClaimPollHintDelayHasOneSecondFloor(t *testing.T) {+ now := time.Unix(1_000, 0)+ for _, tt := range []struct {+ name string+ fireAt time.Time+ want time.Duration+ }{+ {name: "overdue", fireAt: now.Add(-time.Minute), want: time.Second},+ {name: "sub-second", fireAt: now.Add(100 * time.Millisecond), want: time.Second},+ {name: "future", fireAt: now.Add(5 * time.Second), want: 5 * time.Second},+ } {+ t.Run(tt.name, func(t *testing.T) {+ if got := claimPollHintDelay(now, tt.fireAt); got != tt.want {+ t.Fatalf("claimPollHintDelay() = %s, want %s", got, tt.want)+ }+ })+ }+}+// TestClaimTasksByRuntime_RoutesAcrossRuntimesAndMintsTokens covers the happy// path: one call claims across two runtimes on the same machine, returns one// task per runtime (per-agent dedup), and mints a task-scoped token for each.diff --git a/server/internal/metrics/business.go b/server/internal/metrics/business.goindex 193695cf21..2256e79c72 100644--- a/server/internal/metrics/business.go+++ b/server/internal/metrics/business.go@@ -35,16 +35,17 @@ type activeTaskLabels struct {}type BusinessMetrics struct {- taskEnqueued *prometheus.CounterVec- taskDispatched *prometheus.CounterVec- taskStarted *prometheus.CounterVec- taskTerminal *prometheus.CounterVec- taskFailed *prometheus.CounterVec- taskQueueWait *prometheus.HistogramVec- taskRunSeconds *prometheus.HistogramVec- taskTotalSeconds *prometheus.HistogramVec- taskInProgress *prometheus.GaugeVec- taskIterations *prometheus.HistogramVec+ taskEnqueued *prometheus.CounterVec+ taskDispatched *prometheus.CounterVec+ taskStarted *prometheus.CounterVec+ taskTerminal *prometheus.CounterVec+ taskFailed *prometheus.CounterVec+ taskQueueWait *prometheus.HistogramVec+ taskClaimableWait *prometheus.HistogramVec+ taskRunSeconds *prometheus.HistogramVec+ taskTotalSeconds *prometheus.HistogramVec+ taskInProgress *prometheus.GaugeVec+ taskIterations *prometheus.HistogramVecllmTokens *prometheus.CounterVecllmCostUSD *prometheus.CounterVec@@ -124,6 +125,13 @@ func NewBusinessMetrics() *BusinessMetrics {Help: "Time agent tasks spent queued before dispatch.",Buckets: taskDurationBuckets,}, metricLabels("multica_agent_task_queue_wait_seconds")),+ taskClaimableWait: prometheus.NewHistogramVec(prometheus.HistogramOpts{+ Namespace: "multica",+ Subsystem: "agent_task",+ Name: "claimable_wait_seconds",+ Help: "Time from an agent task's scheduled claimability (creation or fire_at) to dispatch.",+ Buckets: taskDurationBuckets,+ }, metricLabels("multica_agent_task_claimable_wait_seconds")),taskRunSeconds: prometheus.NewHistogramVec(prometheus.HistogramOpts{Namespace: "multica",Subsystem: "agent_task",@@ -302,6 +310,7 @@ func (m *BusinessMetrics) Collectors() []prometheus.Collector {m.taskTerminal,m.taskFailed,m.taskQueueWait,+ m.taskClaimableWait,m.taskRunSeconds,m.taskTotalSeconds,m.taskInProgress,@@ -465,7 +474,7 @@ func (m *BusinessMetrics) RecordTaskEnqueued(source, runtimeMode string) {m.taskEnqueued.WithLabelValues(NormalizeTaskSource(source), NormalizeRuntimeMode(runtimeMode)).Inc()}-func (m *BusinessMetrics) RecordTaskDispatched(taskID, source, runtimeMode string, queueWaitSeconds float64) {+func (m *BusinessMetrics) RecordTaskDispatched(taskID, source, runtimeMode string, queueWaitSeconds, claimableWaitSeconds float64) {if m == nil {return}@@ -475,6 +484,9 @@ func (m *BusinessMetrics) RecordTaskDispatched(taskID, source, runtimeMode strinif queueWaitSeconds >= 0 {m.taskQueueWait.WithLabelValues(source, runtimeMode).Observe(queueWaitSeconds)}+ if claimableWaitSeconds >= 0 {+ m.taskClaimableWait.WithLabelValues(source, runtimeMode).Observe(claimableWaitSeconds)+ }m.markTaskInProgress(taskID, source, runtimeMode)}diff --git a/server/internal/metrics/business_test.go b/server/internal/metrics/business_test.goindex 2246e8c0b3..569c2609ca 100644--- a/server/internal/metrics/business_test.go+++ b/server/internal/metrics/business_test.go@@ -18,7 +18,7 @@ func TestBusinessMetricsLifecycleCountersAndGauge(t *testing.T) {m.RecordTaskEnqueued("issue", "local")for i := 0; i < 100; i++ {- m.RecordTaskDispatched("task-"+strconv.Itoa(i), "issue", "local", 2.5)+ m.RecordTaskDispatched("task-"+strconv.Itoa(i), "issue", "local", 2.5, 0.5)}m.RecordTaskStarted("issue", "local", "codex")m.RecordTaskTerminal("task-0", "issue", "local", "completed", 10, 20, 1)@@ -44,6 +44,9 @@ func TestBusinessMetricsLifecycleCountersAndGauge(t *testing.T) {if got := testutil.CollectAndCount(m.taskQueueWait); got != 1 {t.Fatalf("queue wait series count = %d, want 1", got)}+ if got := testutil.CollectAndCount(m.taskClaimableWait); got != 1 {+ t.Fatalf("claimable wait series count = %d, want 1", got)+ }if got := testutil.CollectAndCount(m.taskRunSeconds); got != 1 {t.Fatalf("run seconds series count = %d, want 1", got)}@@ -126,7 +129,7 @@ func TestBusinessMetricsRegistryExposesAllFamilies(t *testing.T) {registry.MustRegister(m.Collectors()...)m.RecordTaskEnqueued("issue", "local")- m.RecordTaskDispatched("task-1", "issue", "local", 1)+ m.RecordTaskDispatched("task-1", "issue", "local", 1, 0.25)m.RecordTaskStarted("issue", "local", "codex")m.RecordTaskTerminal("task-1", "issue", "local", "completed", 2, 3, 1)m.RecordTaskFailed("issue", "local", taskfailure.ReasonTimeout.String())diff --git a/server/internal/metrics/labels.go b/server/internal/metrics/labels.goindex 00ed4762c4..cef590ebd6 100644--- a/server/internal/metrics/labels.go+++ b/server/internal/metrics/labels.go@@ -44,6 +44,7 @@ var businessMetricLabels = map[string][]string{"multica_agent_task_terminal_total": {labelSource, labelRuntimeMode, labelTerminalStatus},"multica_agent_task_failed_total": {labelSource, labelRuntimeMode, labelFailureReason},"multica_agent_task_queue_wait_seconds": {labelSource, labelRuntimeMode},+ "multica_agent_task_claimable_wait_seconds": {labelSource, labelRuntimeMode},"multica_agent_task_run_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},"multica_agent_task_total_seconds": {labelSource, labelRuntimeMode, labelTerminalStatus},"multica_agent_task_in_progress": {labelSource, labelRuntimeMode},diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 5d8eb35f51..06db5dd54e 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -482,6 +482,9 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Issif !opts.AssignedAgentRunFireAt.IsZero() {assignedTaskID = assignedTask.IDif assignedTaskID.Valid {+ // The deferred task became durable with the issue at commit. Refresh the+ // daemon's schedule only now so a wakeup can never race uncommitted data.+ s.TaskService.notifyRuntimeMayHaveWork(assignedTask.RuntimeID, "")if err := s.TaskService.hydrateDeferredChannelIssueTaskOverlay(ctx, assignedTask); err != nil {// Runtime overlays are best-effort on every enqueue path. The task is// already durable and safely deferred, so an optional integrationdiff --git a/server/internal/service/issue_channel_media_test.go b/server/internal/service/issue_channel_media_test.goindex 7060161318..62da445e04 100644--- a/server/internal/service/issue_channel_media_test.go+++ b/server/internal/service/issue_channel_media_test.go@@ -137,6 +137,7 @@ func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(tagentUUID := util.MustParseUUID(agentID)bus := events.New()+ wakeup := &stubWakeup{}createdOverlay := json.RawMessage(`{"mcpServers":{"creator":{"url":"https://creator.example"}}}`)taskService := &TaskService{Queries: q,@@ -144,6 +145,7 @@ func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(tBus: bus,Composio: &stubOverlayBuilder{resp: createdOverlay},FeatureFlags: composioMCPAppsTestFlags(true),+ Wakeup: wakeup,}var competingTaskID pgtype.UUIDvar competingErr error@@ -248,6 +250,9 @@ func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(tif !result.AssignedTaskID.Valid {t.Fatal("media-gated issue did not return its deferred task")}+ if len(wakeup.calls) != 1 || wakeup.calls[0].taskID != "" {+ t.Fatalf("post-commit schedule wakeups = %+v, want one wakeup without a ready task id", wakeup.calls)+ }if !isDuplicatePendingTaskErr(competingErr) {t.Fatalf("post-commit competing queued insert error = %v, want duplicate pending task", competingErr)}@@ -255,21 +260,24 @@ func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(tt.Fatalf("post-commit competing task unexpectedly won: %s", util.UUIDToString(competingTaskID))}- var taskID, triggerCommentID pgtype.UUID+ var taskID, triggerCommentID, runtimeID pgtype.UUIDvar taskCount intif err := pool.QueryRow(ctx, `- SELECT id, trigger_comment_id, count(*) OVER ()+ SELECT id, trigger_comment_id, runtime_id, count(*) OVER ()FROM agent_task_queueWHERE issue_id = $1 AND agent_id = $2AND status IN ('queued', 'dispatched', 'deferred')ORDER BY created_atLIMIT 1`, result.Issue.ID, agentUUID).- Scan(&taskID, &triggerCommentID, &taskCount); err != nil {+ Scan(&taskID, &triggerCommentID, &runtimeID, &taskCount); err != nil {t.Fatalf("load final pending task: %v", err)}if taskCount != 1 || taskID != result.AssignedTaskID || triggerCommentID != mergedCommentID {t.Fatalf("pending task = count %d id %v trigger %v, want one task %v with trigger %v", taskCount, taskID, triggerCommentID, result.AssignedTaskID, mergedCommentID)}+ if wakeup.calls[0].runtimeID != util.UUIDToString(runtimeID) {+ t.Fatalf("schedule wakeup runtime = %q, want %q", wakeup.calls[0].runtimeID, util.UUIDToString(runtimeID))+ }}func TestHydrateDeferredChannelIssueTaskOverlayDoesNotOverwriteMergedCommentPlan(t *testing.T) {diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 9342aae732..75eb2651e5 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -803,7 +803,7 @@ func (s *TaskService) OriginatorForIssueTask(ctx context.Context, issue db.Issuefunc (s *TaskService) captureTaskDispatched(ctx context.Context, task db.AgentTaskQueue) {if s.Metrics != nil {source, runtimeMode, _ := s.taskMetricsContext(ctx, task)- s.Metrics.RecordTaskDispatched(util.UUIDToString(task.ID), source, runtimeMode, taskQueueWaitSeconds(task))+ s.Metrics.RecordTaskDispatched(util.UUIDToString(task.ID), source, runtimeMode, taskQueueWaitSeconds(task), taskClaimableWaitSeconds(task))}}@@ -1046,6 +1046,16 @@ func taskQueueWaitSeconds(task db.AgentTaskQueue) float64 {return durationSeconds(task.CreatedAt, task.DispatchedAt)}+// taskClaimableWaitSeconds excludes an intentional deferred delay when fire_at+// is still available on the claimed row. Immediate tasks start at creation.+func taskClaimableWaitSeconds(task db.AgentTaskQueue) float64 {+ claimableAt := task.CreatedAt+ if task.FireAt.Valid && (!claimableAt.Valid || task.FireAt.Time.After(claimableAt.Time)) {+ claimableAt = task.FireAt+ }+ return durationSeconds(claimableAt, task.DispatchedAt)+}+func taskRunSeconds(task db.AgentTaskQueue) float64 {return durationSeconds(task.StartedAt, task.CompletedAt)}@@ -1103,7 +1113,14 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, t// crash-safe fallback; the channel router promotes the task as soon as the// detached attachment transaction settles.func (s *TaskService) EnqueueDeferredChannelIssueTask(ctx context.Context, issue db.Issue, fireAt time.Time) (db.AgentTaskQueue, error) {- return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true})+ task, err := s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true})+ if err != nil {+ return db.AgentTaskQueue{}, err+ }+ // The task is durable but not claimable yet. Wake once without a task ID so+ // the daemon refreshes its deferred schedule without treating it as ready.+ s.notifyRuntimeMayHaveWork(task.RuntimeID, "")+ return task, nil}// createDeferredChannelIssueTaskWithQueries inserts the inert media-gated task@@ -1519,6 +1536,9 @@ func (s *TaskService) EnqueueDeferredAssigneeFallback(ctx context.Context, issue"agent_id", util.UUIDToString(agentID),"fire_at", fireAt.UTC().Format(time.RFC3339),)+ // Refresh the daemon's durable deferred schedule after the insert commits.+ // An empty task ID means "claim to refresh state", not "this task is ready".+ s.notifyRuntimeMayHaveWork(task.RuntimeID, "")return task, nil}diff --git a/server/internal/service/task_channel_media_race_test.go b/server/internal/service/task_channel_media_race_test.goindex 3a13970b84..234fd169d0 100644--- a/server/internal/service/task_channel_media_race_test.go+++ b/server/internal/service/task_channel_media_race_test.go@@ -491,7 +491,8 @@ func TestDeferredChannelIssueTaskPromotesAfterMediaSettlement(t *testing.T) {bus := events.New()queued := 0bus.Subscribe(protocol.EventTaskQueued, func(events.Event) { queued++ })- svc := &TaskService{Queries: q, TxStarter: pool, Bus: bus}+ wakeup := &stubWakeup{}+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: bus, Wakeup: wakeup}deadline := time.Now().Add(time.Minute)task, err := svc.EnqueueDeferredChannelIssueTask(ctx, db.Issue{ID: issueID,@@ -508,6 +509,9 @@ func TestDeferredChannelIssueTaskPromotesAfterMediaSettlement(t *testing.T) {if task.Status != "deferred" || !task.FireAt.Valid {t.Fatalf("task = status %q fire_at %v, want deferred", task.Status, task.FireAt)}+ if len(wakeup.calls) != 1 || wakeup.calls[0].runtimeID != util.UUIDToString(task.RuntimeID) || wakeup.calls[0].taskID != "" {+ t.Fatalf("deferred schedule wakeups = %+v, want one runtime wakeup without a ready task id", wakeup.calls)+ }if queued != 0 {t.Fatalf("queued events before media settlement = %d, want 0", queued)}@@ -551,6 +555,9 @@ func TestDeferredChannelIssueTaskPromotesAfterMediaSettlement(t *testing.T) {if queued != 1 {t.Fatalf("queued events after promotion = %d, want 1", queued)}+ if len(wakeup.calls) != 2 || wakeup.calls[1].taskID != util.UUIDToString(task.ID) {+ t.Fatalf("promotion wakeups = %+v, want schedule refresh then ready task", wakeup.calls)+ }var status stringvar fireAt pgtype.Timestamptzif err := pool.QueryRow(ctx, `SELECT status, fire_at FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&status, &fireAt); err != nil {diff --git a/server/internal/service/task_notify_test.go b/server/internal/service/task_notify_test.goindex e05147a75d..642a8bb12b 100644--- a/server/internal/service/task_notify_test.go+++ b/server/internal/service/task_notify_test.go@@ -3,11 +3,70 @@ package serviceimport ("context""testing"+ "time"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/testutil""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")+func TestTaskClaimableWaitSecondsExcludesDeferredDelay(t *testing.T) {+ createdAt := time.Unix(1_000, 0)+ fireAt := createdAt.Add(10 * time.Minute)+ dispatchedAt := fireAt.Add(3 * time.Second)+ task := db.AgentTaskQueue{+ CreatedAt: pgtype.Timestamptz{Time: createdAt, Valid: true},+ FireAt: pgtype.Timestamptz{Time: fireAt, Valid: true},+ DispatchedAt: pgtype.Timestamptz{Time: dispatchedAt, Valid: true},+ }++ if got := taskClaimableWaitSeconds(task); got != 3 {+ t.Fatalf("taskClaimableWaitSeconds() = %v, want 3", got)+ }+ task.FireAt = pgtype.Timestamptz{}+ if got := taskClaimableWaitSeconds(task); got != 603 {+ t.Fatalf("immediate task claimable wait = %v, want 603", got)+ }+}++func TestEnqueueDeferredAssigneeFallbackRefreshesRuntimeSchedule(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, issueID := seedAttributionFixture(t, pool)+ fx := testutil.New(pool, workspaceID, userID)+ triggerCommentID := fx.Comment(t, issueID, "fallback trigger")+ agent, err := q.GetAgent(ctx, util.MustParseUUID(agentID))+ if err != nil {+ t.Fatalf("GetAgent: %v", err)+ }+ primaryTaskID := fx.Task(t, agentID, testutil.Cols{+ "runtime_id": util.UUIDToString(agent.RuntimeID),+ "issue_id": issueID,+ "status": "running",+ "trigger_comment_id": triggerCommentID,+ })+ issue, err := q.GetIssue(ctx, util.MustParseUUID(issueID))+ if err != nil {+ t.Fatalf("GetIssue: %v", err)+ }+ wakeup := &stubWakeup{}+ svc := &TaskService{Queries: q, TxStarter: pool, Wakeup: wakeup}++ task, err := svc.EnqueueDeferredAssigneeFallback(ctx, issue, util.MustParseUUID(agentID), pgtype.UUID{}, util.MustParseUUID(primaryTaskID), util.MustParseUUID(triggerCommentID), time.Now().Add(time.Minute))+ if err != nil {+ t.Fatalf("EnqueueDeferredAssigneeFallback: %v", err)+ }+ fx.Cleanup(t, `DELETE FROM agent_task_queue WHERE id = $1`, task.ID)+ if task.Status != "deferred" || len(wakeup.calls) != 1 {+ t.Fatalf("fallback task/status wakeups = %q/%+v, want deferred with one schedule refresh", task.Status, wakeup.calls)+ }+ if wakeup.calls[0].runtimeID != util.UUIDToString(task.RuntimeID) || wakeup.calls[0].taskID != "" {+ t.Fatalf("fallback schedule wakeup = %+v, want runtime %s without task id", wakeup.calls[0], util.UUIDToString(task.RuntimeID))+ }+}+// stubWakeup records every call so the test can assert that notify// reaches the daemon hub and carries the right runtime / task IDs.type stubWakeup struct {diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex b2f585fa19..9b5aedb0a8 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -7017,6 +7017,53 @@ func (q *Queries) MergeDelegatedFailureCommentIntoPendingTask(ctx context.Contexreturn i, err}+const nextDeferredTaskFireAtForRuntimes = `-- name: NextDeferredTaskFireAtForRuntimes :one+SELECT MIN(fire_at)::timestamptz+FROM agent_task_queue t+WHERE t.runtime_id = ANY($1::uuid[])+ AND t.status = 'deferred'+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = t.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => $2::double precision)+ )+ AND (+ t.fire_at > now()+ OR NOT EXISTS (+ SELECT 1 FROM agent_task_queue occupant+ WHERE occupant.issue_id = t.issue_id+ AND occupant.agent_id = t.agent_id+ AND occupant.id <> t.id+ AND (+ occupant.status IN ('queued', 'dispatched')+ OR (occupant.status = 'deferred' AND occupant.context->>'channel_issue_media_pending' = 'true')+ )+ )+ )+`++type NextDeferredTaskFireAtForRuntimesParams struct {+ RuntimeIds []pgtype.UUID `json:"runtime_ids"`+ RuntimeStaleSecs float64 `json:"runtime_stale_secs"`+}++// Returns the next future deferred task for a daemon's authorized runtime set,+// or an eligible task that crossed fire_at during this claim. Overdue tasks+// whose runtime is offline/stale or that are blocked by an existing issue+agent+// occupant are omitted so they cannot cause a tight poll loop. Keep both fences+// in sync with PromoteDueDeferredTasksForRuntimes: a task that cannot be+// promoted must not advertise an immediate follow-up claim. The response+// converts the timestamp to a relative delay, avoiding any dependency on+// daemon/server clock synchronization.+func (q *Queries) NextDeferredTaskFireAtForRuntimes(ctx context.Context, arg NextDeferredTaskFireAtForRuntimesParams) (pgtype.Timestamptz, error) {+ row := q.db.QueryRow(ctx, nextDeferredTaskFireAtForRuntimes, arg.RuntimeIds, arg.RuntimeStaleSecs)+ var column_1 pgtype.Timestamptz+ err := row.Scan(&column_1)+ return column_1, err+}+const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTask :oneUPDATE agent_task_queueSET status = 'queued', fire_at = NULLdiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 05c135412f..a13cedb95a 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -2318,6 +2318,40 @@ WHERE atq.runtime_id = ANY(@runtime_ids::uuid[]))ORDER BY atq.priority DESC, atq.created_at ASC;+-- name: NextDeferredTaskFireAtForRuntimes :one+-- Returns the next future deferred task for a daemon's authorized runtime set,+-- or an eligible task that crossed fire_at during this claim. Overdue tasks+-- whose runtime is offline/stale or that are blocked by an existing issue+agent+-- occupant are omitted so they cannot cause a tight poll loop. Keep both fences+-- in sync with PromoteDueDeferredTasksForRuntimes: a task that cannot be+-- promoted must not advertise an immediate follow-up claim. The response+-- converts the timestamp to a relative delay, avoiding any dependency on+-- daemon/server clock synchronization.+SELECT MIN(fire_at)::timestamptz+FROM agent_task_queue t+WHERE t.runtime_id = ANY(@runtime_ids::uuid[])+ AND t.status = 'deferred'+ AND EXISTS (+ SELECT 1 FROM agent_runtime r+ WHERE r.id = t.runtime_id+ AND r.status = 'online'+ AND COALESCE(r.last_seen_at, r.updated_at) >=+ now() - make_interval(secs => @runtime_stale_secs::double precision)+ )+ AND (+ t.fire_at > now()+ OR NOT EXISTS (+ SELECT 1 FROM agent_task_queue occupant+ WHERE occupant.issue_id = t.issue_id+ AND occupant.agent_id = t.agent_id+ AND occupant.id <> t.id+ AND (+ occupant.status IN ('queued', 'dispatched')+ OR (occupant.status = 'deferred' AND occupant.context->>'channel_issue_media_pending' = 'true')+ )+ )+ );+-- name: PromoteDueDeferredTasksForRuntimes :many-- Batch variant of PromoteDueDeferredTasksForRuntime (MUL-4257): promotes all-- due deferred tasks across the runtime set in one UPDATE. Carries the same twodiff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex 3c35ed4482..efeb977b2a 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -30,6 +30,11 @@ const (// Gated so only daemons+servers that both support it route claim over WS;// everyone else keeps using the HTTP claim endpoint.DaemonCapabilityRPCV1 = "rpc-v1"+ // DaemonCapabilityClaimPollHintsV1 advertises that the daemon understands+ // the batch-claim response's safety-poll metadata. The server only performs+ // the extra deferred-task lookup for clients that opt in, and an older+ // server's missing fields make a newer daemon retain its short fallback.+ DaemonCapabilityClaimPollHintsV1 = "claim-poll-hints-v1"// AppCapabilityChatDraftRestoreV1 is advertised (X-Client-Capabilities) by// app clients that understand the durable draft-restore recovery path: