Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(daemon): bound silent OpenCode streams (#5523)
Multica Eve5251a0958da6
diff --git a/CLI_AND_DAEMON.md b/CLI_AND_DAEMON.mdindex 3749abd579..6ac9e6dd45 100644--- a/CLI_AND_DAEMON.md+++ b/CLI_AND_DAEMON.md@@ -173,6 +173,7 @@ Daemon behavior is configured via flags or environment variables:| Heartbeat interval | `--heartbeat-interval` | `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` || Agent timeout | `--agent-timeout` | `MULTICA_AGENT_TIMEOUT` | `0` (no cap; bounded by the watchdogs) || Codex semantic inactivity timeout | `--codex-semantic-inactivity-timeout` | `MULTICA_CODEX_SEMANTIC_INACTIVITY_TIMEOUT` | `10m` |+| OpenCode idle watchdog | — | `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` (`0` falls back to the generic idle watchdog; cannot extend it) || Max concurrent tasks | `--max-concurrent-tasks` | `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` || Daemon ID | `--daemon-id` | `MULTICA_DAEMON_ID` | hostname || Device name | `--device-name` | `MULTICA_DAEMON_DEVICE_NAME` | hostname |diff --git a/apps/docs/content/docs/environment-variables.mdx b/apps/docs/content/docs/environment-variables.mdxindex 2ad1e02ab9..7b386e9a75 100644--- a/apps/docs/content/docs/environment-variables.mdx+++ b/apps/docs/content/docs/environment-variables.mdx@@ -181,6 +181,10 @@ The daemon runs on the user's local machine, and its config is read from local e| `MULTICA_DAEMON_HEARTBEAT_INTERVAL` | `15s` | Heartbeat interval || `MULTICA_DAEMON_POLL_INTERVAL` | `3s` | Task polling interval || `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | Max concurrent tasks |+| `MULTICA_AGENT_TIMEOUT` | `0` | Absolute wall-clock limit for one task. `0` leaves long active runs uncapped and relies on the inactivity watchdogs |+| `MULTICA_AGENT_IDLE_WATCHDOG` | `30m` | Global no-message watchdog for runs with no tool in flight. `0` disables the whole watchdog, including provider-specific overrides |+| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode-specific no-message window for missing first tokens or stalled streams. `0` falls back to `MULTICA_AGENT_IDLE_WATCHDOG`; larger values cannot extend that global bound |+| `MULTICA_AGENT_TOOL_WATCHDOG` | `2h` | Silence budget while a tool call is in flight. `0` disables the stuck-tool backstop || `MULTICA_<PROVIDER>_PATH` | matches the CLI name | Path to each AI coding tool's executable (for example `MULTICA_CLAUDE_PATH`) || `MULTICA_<PROVIDER>_MODEL` | empty | Default model for each AI coding tool || `MULTICA_<PROVIDER>_ARGS` | empty | Daemon-wide default CLI arguments for a backend, applied to every task before each agent's own `custom_args`. Supported for `MULTICA_CLAUDE_ARGS`, `MULTICA_CODEX_ARGS`, and `MULTICA_CODEBUDDY_ARGS` |diff --git a/apps/docs/content/docs/environment-variables.zh.mdx b/apps/docs/content/docs/environment-variables.zh.mdxindex 2bd5998d20..6484d0df5b 100644--- a/apps/docs/content/docs/environment-variables.zh.mdx+++ b/apps/docs/content/docs/environment-variables.zh.mdx@@ -182,7 +182,8 @@ API 返回的 `download_url` 在未配置 CloudFront 签名时会指向 `GET /ap| `MULTICA_DAEMON_POLL_INTERVAL` | `3s` | 任务轮询频率 || `MULTICA_DAEMON_MAX_CONCURRENT_TASKS` | `20` | 并发任务上限 || `MULTICA_AGENT_TIMEOUT` | `0` | 单次任务的绝对墙钟上限;`0` = 不设上限,任务只受看门狗约束(活跃任务不会因为跑得久被杀)。想要硬性成本/资源天花板时再设一个正值 |-| `MULTICA_AGENT_IDLE_WATCHDOG` | `30m` | 空闲看门狗:backend 持续静默(无消息、消息队列为空、且没有工具在途)这么久就 force-stop。`0` = 关闭整套看门狗 |+| `MULTICA_AGENT_IDLE_WATCHDOG` | `30m` | 空闲看门狗:backend 持续静默(无消息、消息队列为空、且没有工具在途)这么久就 force-stop。`0` = 关闭整套看门狗,包括 provider 专用阈值 |+| `MULTICA_OPENCODE_IDLE_WATCHDOG` | `10m` | OpenCode 首 token 未到或流式回复中断时的专用无消息阈值;`0` = 回退到 `MULTICA_AGENT_IDLE_WATCHDOG`,更大的值不能放宽全局阈值 || `MULTICA_AGENT_TOOL_WATCHDOG` | `2h` | 工具在途时的静默上限:某个工具调用发出后长时间无任何输出(疑似卡死的子进程)这么久就 force-stop。`0` = 关闭该兜底(在途工具永不被停)|| `MULTICA_<PROVIDER>_PATH` | 对应 CLI 名 | 各 AI 编程工具的可执行文件路径(如 `MULTICA_CLAUDE_PATH`)|| `MULTICA_<PROVIDER>_MODEL` | 空 | 各 AI 编程工具的默认模型 |diff --git a/apps/docs/content/docs/tasks.zh.mdx b/apps/docs/content/docs/tasks.zh.mdxindex b9b721f56e..bf684cb902 100644--- a/apps/docs/content/docs/tasks.zh.mdx+++ b/apps/docs/content/docs/tasks.zh.mdx@@ -42,7 +42,7 @@ Multica 服务器每 30 秒扫描一次,有两种超时会触发失败:两种超时的失败原因都是 `timeout`,**会自动重试**(下一节)。关联的运行时失联判定见 [守护进程与运行时 → 运行时什么时候被判定为离线](/daemon-runtimes#运行时什么时候被判定为离线)。-上面这层是**服务端的粗粒度兜底**——按任务启动时间算,不看任务是否还在活动。真正区分「卡死」和「正常的长任务」的是**本地守护进程**:它不再用固定墙钟时长砍任务(`MULTICA_AGENT_TIMEOUT` 默认 `0` = 不设上限),而是看活动——只要 agent 还在持续产出事件(消息、工具调用),守护进程就不会因为跑得久判它超时(服务端那条 2.5h 仍是外层上限)。只有真正静默卡死时才会被**空闲看门狗**(`MULTICA_AGENT_IDLE_WATCHDOG`,默认 30 分钟)终止;如果是某个工具调用发出后长时间无任何输出(疑似卡死的子进程),则由更大的**工具看门狗**预算(`MULTICA_AGENT_TOOL_WATCHDOG`,默认 2 小时)兜底。这类被看门狗终止的任务失败原因是 `idle_watchdog`,和墙钟 `timeout` 区分开。各参数见 [环境变量 → 守护进程的调节参数](/environment-variables#守护进程的调节参数)。+上面这层是**服务端的粗粒度兜底**——按任务启动时间算,不看任务是否还在活动。真正区分「卡死」和「正常的长任务」的是**本地守护进程**:它不再用固定墙钟时长砍任务(`MULTICA_AGENT_TIMEOUT` 默认 `0` = 不设上限),而是看活动——只要 agent 还在持续产出事件(消息、工具调用),守护进程就不会因为跑得久判它超时(服务端那条 2.5h 仍是外层上限)。只有真正静默卡死时才会被**空闲看门狗**(`MULTICA_AGENT_IDLE_WATCHDOG`,默认 30 分钟)终止;OpenCode 还会用更短的 `MULTICA_OPENCODE_IDLE_WATCHDOG`(默认 10 分钟)识别首 token 未到或流式回复中断。如果是某个工具调用发出后长时间无任何输出(疑似卡死的子进程),则由更大的**工具看门狗**预算(`MULTICA_AGENT_TOOL_WATCHDOG`,默认 2 小时)兜底。这类被看门狗终止的任务失败原因是 `idle_watchdog`,和墙钟 `timeout` 区分开。各参数见 [环境变量 → 守护进程的调节参数](/environment-variables#守护进程的调节参数)。## 哪些失败会自动重试,哪些不会diff --git a/server/internal/daemon/config.go b/server/internal/daemon/config.goindex 547a95ad2e..cc16834739 100644--- a/server/internal/daemon/config.go+++ b/server/internal/daemon/config.go@@ -29,6 +29,12 @@ const (DefaultAgentTimeout = 0DefaultCodexSemanticInactivityTimeout = 10 * time.MinuteDefaultCodexHandshakeTimeout = 30 * time.Second+ // DefaultOpenCodeIdleWatchdog shortens the no-message budget for OpenCode+ // runs while they are not executing a tool. OpenCode streams text and tool+ // events incrementally, so a completely silent interval here covers both a+ // missing first model token and a stalled response stream. The generic+ // AgentIdleWatchdog remains the global enable/disable switch.+ DefaultOpenCodeIdleWatchdog = 10 * time.Minute// DefaultAgentIdleWatchdog is the per-task safety net that force-stops a// run when the backend has emitted no message for this long AND its// message queue is empty. Backends like Claude Code can hang indefinitely@@ -104,6 +110,7 @@ type Config struct {AgentTimeout time.DurationCodexSemanticInactivityTimeout time.DurationCodexHandshakeTimeout time.Duration+ OpenCodeIdleWatchdog time.Duration // OpenCode-specific no-message window; 0 falls back to AgentIdleWatchdog and values above it cannot extend the global boundAgentIdleWatchdog time.Duration // force-stop a run when the backend goes silent this long with an empty queue (0 = disabled)AgentToolWatchdog time.Duration // force-stop a run when a single tool call stays in flight (silent) this long (0 = disabled); backstop for hung tools now that there is no wall-clock capClaudeArgs []string@@ -406,6 +413,15 @@ func LoadConfig(overrides Overrides) (Config, error) {if err != nil {return Config{}, err}+ // MULTICA_OPENCODE_IDLE_WATCHDOG narrows the no-message window for+ // OpenCode's streamed model responses. Zero removes the provider-specific+ // override and falls back to MULTICA_AGENT_IDLE_WATCHDOG; positive values+ // cannot extend the global bound, and the global zero still disables the+ // whole mechanism.+ openCodeIdleWatchdog, err := durationFromEnv("MULTICA_OPENCODE_IDLE_WATCHDOG", DefaultOpenCodeIdleWatchdog)+ if err != nil {+ return Config{}, err+ }// MULTICA_AGENT_TOOL_WATCHDOG=0 disables the in-flight-tool backstop; any// positive duration overrides DefaultAgentToolWatchdog.@@ -567,6 +583,7 @@ func LoadConfig(overrides Overrides) (Config, error) {AgentTimeout: agentTimeout,CodexSemanticInactivityTimeout: codexSemanticInactivityTimeout,CodexHandshakeTimeout: codexHandshakeTimeout,+ OpenCodeIdleWatchdog: openCodeIdleWatchdog,AgentIdleWatchdog: agentIdleWatchdog,AgentToolWatchdog: agentToolWatchdog,ClaudeArgs: claudeArgs,diff --git a/server/internal/daemon/config_test.go b/server/internal/daemon/config_test.goindex bfc67579b5..fd2202f262 100644--- a/server/internal/daemon/config_test.go+++ b/server/internal/daemon/config_test.go@@ -432,6 +432,48 @@ func TestLoadConfig_CodexHandshakeTimeout(t *testing.T) {}}+func TestLoadConfig_OpenCodeIdleWatchdog(t *testing.T) {+ stageFakeAgent(t)+ t.Setenv("MULTICA_OPENCODE_IDLE_WATCHDOG", "")++ cfg, err := LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with default: %v", err)+ }+ if cfg.OpenCodeIdleWatchdog != DefaultOpenCodeIdleWatchdog {+ t.Fatalf("OpenCodeIdleWatchdog = %s, want default %s", cfg.OpenCodeIdleWatchdog, DefaultOpenCodeIdleWatchdog)+ }++ t.Setenv("MULTICA_OPENCODE_IDLE_WATCHDOG", "7m")+ cfg, err = LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with env: %v", err)+ }+ if cfg.OpenCodeIdleWatchdog != 7*time.Minute {+ t.Fatalf("OpenCodeIdleWatchdog = %s, want 7m from env", cfg.OpenCodeIdleWatchdog)+ }++ // Zero disables the OpenCode-specific override while leaving the generic+ // AgentIdleWatchdog as the fallback for OpenCode runs.+ t.Setenv("MULTICA_OPENCODE_IDLE_WATCHDOG", "0")+ cfg, err = LoadConfig(Overrides{+ ServerURL: "http://localhost:8080",+ WorkspacesRoot: t.TempDir(),+ })+ if err != nil {+ t.Fatalf("LoadConfig with zero env: %v", err)+ }+ if cfg.OpenCodeIdleWatchdog != 0 {+ t.Fatalf("OpenCodeIdleWatchdog = %s, want zero from env", cfg.OpenCodeIdleWatchdog)+ }+}+// TestLoadConfig_AutoUpdateDefault_CloudOn confirms the symmetric case: a// daemon pointed at Multica's hosted cloud keeps the historical opt-in// auto-update default. We pass the WSS form of the URL to also exercise thatdiff --git a/server/internal/daemon/daemon.go b/server/internal/daemon/daemon.goindex 842021a1c0..f038f47361 100644--- a/server/internal/daemon/daemon.go+++ b/server/internal/daemon/daemon.go@@ -945,6 +945,7 @@ func (d *Daemon) Run(ctx context.Context) error {"heartbeat_interval", d.cfg.HeartbeatInterval,"agent_timeout", d.cfg.AgentTimeout,"idle_watchdog", d.cfg.AgentIdleWatchdog,+ "opencode_idle_watchdog", d.cfg.OpenCodeIdleWatchdog,"max_concurrent_tasks", d.cfg.MaxConcurrentTasks,"gc_enabled", d.cfg.GCEnabled,"auto_update", d.cfg.AutoUpdateEnabled,@@ -4259,12 +4260,17 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot ithinkingLevel = ""}}+ var idleWatchdogTimeout time.Duration+ if provider == "opencode" {+ idleWatchdogTimeout = d.cfg.OpenCodeIdleWatchdog+ }execOpts := agent.ExecOptions{Cwd: env.WorkDir,Model: model,ThreadName: deriveTaskThreadName(task),Timeout: d.cfg.AgentTimeout,SemanticInactivityTimeout: d.cfg.CodexSemanticInactivityTimeout,+ IdleWatchdogTimeout: idleWatchdogTimeout,HandshakeTimeout: d.cfg.CodexHandshakeTimeout,ResumeSessionID: task.PriorSessionID,// Post-gate intent: PriorSessionID here already reflects the pre-flight@@ -4314,6 +4320,7 @@ func (d *Daemon) runTask(ctx context.Context, task Task, provider string, slot i"inline_system_prompt", execOpts.SystemPrompt != "","resume_session", execOpts.ResumeSessionID != "","timeout", execOpts.Timeout,+ "idle_watchdog", execOpts.IdleWatchdogTimeout,)// Shared across the resume-retry below so the retry's transcript rows@@ -4579,9 +4586,15 @@ func (d *Daemon) executeAndDrain(ctx context.Context, backend agent.Backend, pro// idleWatchdogThreshold records (as nanos) which silence budget actually// tripped the watchdog — the idle window or the larger in-flight-tool// window — so the failure message reports the real duration.- var idleWatchdogThreshold atomic.Int64- idleWatchdogThreshold.Store(int64(d.cfg.AgentIdleWatchdog))idleWindow := d.cfg.AgentIdleWatchdog+ // A provider may opt into a shorter per-run no-message budget. The global+ // zero remains authoritative so MULTICA_AGENT_IDLE_WATCHDOG=0 still disables+ // the entire watchdog suite. Tool calls continue to use AgentToolWatchdog.+ if idleWindow > 0 && opts.IdleWatchdogTimeout > 0 && opts.IdleWatchdogTimeout < idleWindow {+ idleWindow = opts.IdleWatchdogTimeout+ }+ var idleWatchdogThreshold atomic.Int64+ idleWatchdogThreshold.Store(int64(idleWindow))if idleWindow > 0 {go d.runIdleWatchdog(agentCtx, idleWindow, d.cfg.AgentToolWatchdog, &lastActivityAt, &inFlightTools, &idleWatchdogFired, &idleWatchdogThreshold, agentCancel, session.Messages, taskLog, taskID)}diff --git a/server/internal/daemon/daemon_test.go b/server/internal/daemon/daemon_test.goindex 7c66009298..6cd0e81a06 100644--- a/server/internal/daemon/daemon_test.go+++ b/server/internal/daemon/daemon_test.go@@ -1772,6 +1772,94 @@ func TestExecuteAndDrain_IdleWatchdog_FiresWhenNoMessageEverArrives(t *testing.T}}+func TestExecuteAndDrain_IdleWatchdog_UsesPerRunOverride(t *testing.T) {+ t.Parallel()++ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 500 * time.Millisecond++ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)++ start := time.Now()+ result, _, err := d.executeAndDrain(+ ctx,+ idleWatchdogBackend{emitOne: true},+ "p",+ agent.ExecOptions{IdleWatchdogTimeout: 50 * time.Millisecond},+ slog.Default(),+ "t-idle-override",+ new(atomic.Int32),+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.Status != "idle_watchdog" {+ t.Fatalf("expected status=idle_watchdog, got %q (err=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "50ms") {+ t.Fatalf("expected error to report the per-run threshold, got %q", result.Error)+ }+ if elapsed := time.Since(start); elapsed > 250*time.Millisecond {+ t.Fatalf("per-run watchdog override did not fire promptly: %s", elapsed)+ }+}++func TestExecuteAndDrain_IdleWatchdog_GlobalDisableWinsOverPerRunOverride(t *testing.T) {+ t.Parallel()++ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 0++ ctx, cancel := context.WithCancel(context.Background())+ time.AfterFunc(100*time.Millisecond, cancel)++ result, _, err := d.executeAndDrain(+ ctx,+ idleWatchdogBackend{emitOne: true},+ "p",+ agent.ExecOptions{IdleWatchdogTimeout: 20 * time.Millisecond},+ slog.Default(),+ "t-idle-global-off",+ new(atomic.Int32),+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.Status != "cancelled" {+ t.Fatalf("global watchdog disable must win; got status=%q (err=%q)", result.Status, result.Error)+ }+}++func TestExecuteAndDrain_IdleWatchdog_PerRunOverrideCannotExtendGlobalWindow(t *testing.T) {+ t.Parallel()++ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 50 * time.Millisecond++ ctx, cancel := context.WithCancel(context.Background())+ t.Cleanup(cancel)++ result, _, err := d.executeAndDrain(+ ctx,+ idleWatchdogBackend{emitOne: true},+ "p",+ agent.ExecOptions{IdleWatchdogTimeout: 500 * time.Millisecond},+ slog.Default(),+ "t-idle-global-bound",+ new(atomic.Int32),+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.Status != "idle_watchdog" {+ t.Fatalf("expected status=idle_watchdog, got %q (err=%q)", result.Status, result.Error)+ }+ if !strings.Contains(result.Error, "50ms") {+ t.Fatalf("provider override must not extend the global threshold, got %q", result.Error)+ }+}+func TestExecuteAndDrain_IdleWatchdog_DisabledWhenZero(t *testing.T) {t.Parallel()@@ -1896,6 +1984,30 @@ func TestExecuteAndDrain_IdleWatchdog_DoesNotFireDuringInFlightToolCall(t *testi}}+func TestExecuteAndDrain_IdleWatchdog_PerRunOverrideStillUsesToolWindow(t *testing.T) {+ t.Parallel()++ d := newTestDaemon(t)+ d.cfg.AgentIdleWatchdog = 500 * time.Millisecond+ d.cfg.AgentToolWatchdog = 500 * time.Millisecond++ result, _, err := d.executeAndDrain(+ context.Background(),+ longToolCallBackend{toolSilence: 200 * time.Millisecond},+ "p",+ agent.ExecOptions{IdleWatchdogTimeout: 50 * time.Millisecond},+ slog.Default(),+ "t-long-tool-override",+ new(atomic.Int32),+ )+ if err != nil {+ t.Fatalf("unexpected error: %v", err)+ }+ if result.Status != "completed" {+ t.Fatalf("per-run idle override must not replace the tool window; got status=%q (err=%q)", result.Status, result.Error)+ }+}+// stuckInFlightToolBackend models a hung tool: it emits a tool_use and then// goes silent forever — the matching tool_result never arrives, so inFlightTools// stays at 1 (e.g. a child process that never returns). With no wall-clock capdiff --git a/server/pkg/agent/agent.go b/server/pkg/agent/agent.goindex e92fb18dd3..e6bac24c71 100644--- a/server/pkg/agent/agent.go+++ b/server/pkg/agent/agent.go@@ -32,6 +32,12 @@ type ExecOptions struct {MaxTurns intTimeout time.DurationSemanticInactivityTimeout time.Duration+ // IdleWatchdogTimeout optionally narrows the daemon's generic no-message+ // watchdog for this execution. Zero keeps the daemon-wide window, and a+ // value above that window cannot extend the global safety bound. The+ // daemon-wide zero still disables the watchdog entirely, and an in-flight+ // tool continues to use the separate tool watchdog budget.+ IdleWatchdogTimeout time.Duration// HandshakeTimeout bounds startup RPCs for providers with a long-lived// protocol transport. It is currently consumed by Codex app-server;// zero uses the provider default rather than disabling the bound.