A local-first multi-agent app development platform, built on PenguinHarness
fix(server,core,web): Telegram poller conflicts, a missing Workspace misreported as a missing shell, and duplicate inbound messages (#484)
Yaowei Zheng7a86043a5fc0
diff --git a/changelog/unreleased/2026-08-27-messaging-inbound-dedupe.md b/changelog/unreleased/2026-08-27-messaging-inbound-dedupe.mdnew file mode 100644index 00000000..fa594c5f--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-inbound-dedupe.md@@ -0,0 +1,18 @@+# A redelivered chat message starts one Task, not two++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[中文版](2026-08-27-messaging-inbound-dedupe.zh.md)++A message a channel handed the bridge twice queued two Tasks and ran both, appearing twice in the chat and twice in the Web App. The bridge now drops a message its binding has already processed.++## Details++- Deduplication is per binding and keyed on the channel's own message identity — Feishu's `message_id`, Telegram's `chatId:message_id`. Never on the text: the same question asked twice is two messages and still runs twice.+- A duplicate is a complete no-op, ahead of the chat record and the text-only reply as well as the Task start, so a replayed sticker no longer answers with the notice twice.+- The memory is bounded on both axes — the last 64 message ids per binding, within a ten-minute window — and belongs to the binding rather than to one connection, so re-saving an enabled binding (which restarts its connector) does not replay what it already processed. It is dropped when the binding or its Session is removed.+- The memory is in-process: a server restart forgets, so a redelivery that survives a restart still duplicates.+- Both surfaces showed one duplicate because a queued follow-up's input is published to the Session channel. The same user-visible symptom is addressed from the other end by [the Telegram poller-conflict fix](2026-08-27-telegram-conflict-recovery.md), which removes a common source of redelivery.diff --git a/changelog/unreleased/2026-08-27-messaging-inbound-dedupe.zh.md b/changelog/unreleased/2026-08-27-messaging-inbound-dedupe.zh.mdnew file mode 100644index 00000000..a0c3b788--- /dev/null+++ b/changelog/unreleased/2026-08-27-messaging-inbound-dedupe.zh.md@@ -0,0 +1,18 @@+# 被重复投递的聊天消息只启动一个 Task++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[English](2026-08-27-messaging-inbound-dedupe.md)++被渠道投递两次的消息会排入两个 Task 并都执行,于是在聊天中出现两次,在 Web App 中也出现两次。桥接层现在会丢弃该绑定已经处理过的消息。++## 细节++- 去重按绑定进行,键取渠道自身的消息标识——飞书的 `message_id`、Telegram 的 `chatId:message_id`。绝不按文本去重:同一个问题问两遍是两条消息,仍然会执行两次。+- 重复消息是彻底的空操作,不仅不启动 Task,也在记录会话与「仅支持文本」回复之前就返回,因此被重播的表情消息不会再回两次提示。+- 记忆在两个维度上都有上界——每个绑定保留最近 64 个消息 id,时间窗口十分钟——且归属于绑定而非某一条连接,因此重新保存一个已启用的绑定(会重启其连接器)不会重播已处理过的消息。绑定或其会话被移除时该记忆一并丢弃。+- 该记忆只存在于进程内:服务端重启即遗忘,因此跨重启仍然到达的重复投递依然会重复执行。+- 两个界面都出现重复,是因为排队的后续输入会发布到会话通道。同一个用户可见症状的另一端由 [Telegram 轮询冲突修复](2026-08-27-telegram-conflict-recovery.zh.md)处理,它消除了重复投递的一个常见来源。diff --git a/changelog/unreleased/2026-08-27-missing-workspace-error.md b/changelog/unreleased/2026-08-27-missing-workspace-error.mdnew file mode 100644index 00000000..bfce5296--- /dev/null+++ b/changelog/unreleased/2026-08-27-missing-workspace-error.md@@ -0,0 +1,16 @@+# A command whose working directory is gone says so, instead of blaming the shell++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `core`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[中文版](2026-08-27-missing-workspace-error.zh.md)++`exec_command` answered `[spawn error: spawn bash ENOENT]` when the Session's Workspace directory had disappeared. The working directory is now checked before the spawn, so the failure names the directory.++## Details++- Node reports an unusable `cwd` as `spawn <command> ENOENT` — the error carries the command's name, not the directory's, so a deleted or moved Workspace was indistinguishable from a missing shell.+- `CommandSessionManager.spawn` now rejects a working directory that is missing or is not a directory, before starting the child. The message names the path and what to do about it, and the same check covers an `exec_command` `workdir` argument that does not resolve.+- The directory is not auto-created, matching `Agent.createSession` and the server's Workspace guard: a Workspace is never conjured, so a typo cannot silently start working in the wrong place.diff --git a/changelog/unreleased/2026-08-27-missing-workspace-error.zh.md b/changelog/unreleased/2026-08-27-missing-workspace-error.zh.mdnew file mode 100644index 00000000..1780ab15--- /dev/null+++ b/changelog/unreleased/2026-08-27-missing-workspace-error.zh.md@@ -0,0 +1,16 @@+# 工作目录消失时命令会直说,而不再归咎于 Shell++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `core`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[English](2026-08-27-missing-workspace-error.md)++当会话的 Workspace 目录已经消失时,`exec_command` 回答的是 `[spawn error: spawn bash ENOENT]`。现在会在 spawn 之前检查工作目录,失败信息直接点名该目录。++## 细节++- Node 把无法使用的 `cwd` 报告为 `spawn <command> ENOENT`——错误里带的是命令名而非目录名,因此被删除或移动的 Workspace 与缺失的 Shell 无从区分。+- `CommandSessionManager.spawn` 现在会在启动子进程前拒绝不存在或不是目录的工作目录。信息会点名该路径以及应当如何处理,`exec_command` 的 `workdir` 参数解析不到时同样适用。+- 该目录不会被自动创建,与 `Agent.createSession` 和服务端的 Workspace 校验保持一致:Workspace 从不凭空生成,一个笔误因此不会悄悄地在错误的位置开始工作。diff --git a/changelog/unreleased/2026-08-27-posix-shell-fallback.md b/changelog/unreleased/2026-08-27-posix-shell-fallback.mdnew file mode 100644index 00000000..0a8c73d7--- /dev/null+++ b/changelog/unreleased/2026-08-27-posix-shell-fallback.md@@ -0,0 +1,16 @@+# The agent shell no longer assumes bash exists on macOS and Linux++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `core`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[中文版](2026-08-27-posix-shell-fallback.zh.md)++The shell resolver gained on POSIX the fallback chain the Windows branch already had. Without it, a machine whose `PATH` has no `bash` failed every command before it ran.++## Details++- The POSIX branch resolved to a bare `bash` unconditionally, with no existence check and no alternative. A desktop app launched from a GUI inherits the desktop session's `PATH` rather than a login shell's, and a trimmed session `PATH` — or a distribution that does not install bash — left every command failing before it ran, on every surface of the app.+- Resolution order on POSIX is now: `PENGUIN_SHELL`, then `bash` on `PATH` (still spawned as the bare name, so the child resolves it against its own `PATH`), then `/bin/bash`, `/usr/bin/bash`, `/usr/local/bin/bash` and `/opt/homebrew/bin/bash`, then `$SHELL` when it names a POSIX shell that exists, then `sh`. `$SHELL` carries the login shell of the account the server runs as, so a service account's `/usr/sbin/nologin` or `/bin/false` is skipped rather than handed `-lc`. The probe is a `PATH` directory walk rather than a subprocess: a handful of `stat` calls once per process, no shell spawned to find a shell.+- A shell resolved through the non-bash steps is reported to the model under its own name — `zsh`, `sh` — through the system prompt's `{{SHELL}}` placeholder, because that is the syntax it has to write.diff --git a/changelog/unreleased/2026-08-27-posix-shell-fallback.zh.md b/changelog/unreleased/2026-08-27-posix-shell-fallback.zh.mdnew file mode 100644index 00000000..1fb0c2be--- /dev/null+++ b/changelog/unreleased/2026-08-27-posix-shell-fallback.zh.md@@ -0,0 +1,16 @@+# 智能体 Shell 不再假定 macOS 与 Linux 上一定有 bash++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `core`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[English](2026-08-27-posix-shell-fallback.md)++Shell 解析器在 POSIX 上补齐了 Windows 分支早已具备的回退链。没有它时,`PATH` 中没有 `bash` 的机器上每条命令都会在真正执行前失败。++## 细节++- POSIX 分支无条件解析为裸 `bash`,既不检查其是否存在,也没有替代方案。从图形界面启动的桌面应用继承的是桌面会话的 `PATH` 而非登录 Shell 的 `PATH`,一个被裁剪过的会话 `PATH`——或一个不安装 bash 的发行版——会让每条命令在真正执行前就失败,且应用的每个入口都是如此。+- POSIX 上的解析顺序现在是:`PENGUIN_SHELL`,然后是 `PATH` 中的 `bash`(仍以裸名启动,由子进程按自己的 `PATH` 解析),然后依次是 `/bin/bash`、`/usr/bin/bash`、`/usr/local/bin/bash` 与 `/opt/homebrew/bin/bash`,然后是指向一个已存在的 POSIX Shell 的 `$SHELL`,最后是 `sh`。`$SHELL` 记的是服务运行所用账户的登录 Shell,服务账户上常常是 `/usr/sbin/nologin` 或 `/bin/false`,这类值直接跳过,不会被塞进 `-lc`。探测走的是 `PATH` 目录遍历而非子进程:每个进程一次、若干次 `stat`,不为找 Shell 再启一个 Shell。+- 通过非 bash 步骤解析出的 Shell 会经系统提示词的 `{{SHELL}}` 占位符以自身名称告知模型——`zsh`、`sh`——因为那才是它需要书写的语法。diff --git a/changelog/unreleased/2026-08-27-telegram-conflict-recovery.md b/changelog/unreleased/2026-08-27-telegram-conflict-recovery.mdnew file mode 100644index 00000000..f0d4c527--- /dev/null+++ b/changelog/unreleased/2026-08-27-telegram-conflict-recovery.md@@ -0,0 +1,19 @@+# Telegram connections survive a poller conflict, and say what went wrong++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`, `web`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[中文版](2026-08-27-telegram-conflict-recovery.zh.md)++A Telegram binding that hit Telegram's one-poller-per-token rule parked at "connection error" and never delivered another message. The poll loop now treats a `getUpdates` failure as the outage it is, names a webhook that is blocking the poll, and the panel shows the whole failure message instead of its first few words.++## Details++- Recovery from a poll outage is gated on a `getUpdates` succeeding, not on the `getMe` probe in front of it. `getMe` never conflicts, so it used to clear the failure counter on every cycle: the exponential backoff never left its first step, the connector re-polled once a second indefinitely, `onError` fired on every retry, and the connection status flapped between `connected` and `error` faster than the panel polls it. One outage now reports once and backs off up to the 60-second ceiling, as documented.+- A recovery poll runs with a zero-second timeout, so the end of an outage is observed immediately rather than after the next 30-second long-poll window.+- A `getWebhookInfo` probe runs once per connection, before the first poll. A webhook and `getUpdates` are mutually exclusive on the Bot API, so a bot pointed at a webhook before it was bound could never be polled, and the 409 that resulted said only that one was set. The probe reports the registered URL — which is the whole of what has to be gone and found — and stops there. It does not clear the webhook: that registration belongs to whatever service the user pointed it at, and removing it here would take that service off the air with nothing to trace it to. Removing it there needs no re-enable: the probe repeats on each retry, and the connection comes back on its own.+- The Bot API's two actionable 409s are rewritten to lead with the action — "another program is already polling this bot …" and "a webhook is set on this bot, which blocks polling …" — instead of Telegram's wording, which buries it at the end of the sentence.+- The connection status line gives a failure its own row under the toggle, clamped to two lines with the full text on hover, rather than a truncated share of the row carrying the switch, the label and the status word. A Telegram binding's troubleshooting fold gained an entry naming the one-program-per-token rule.+- A poller conflict is one way the same inbound message reaches the bridge twice; the other end of that symptom is [inbound deduplication](2026-08-27-messaging-inbound-dedupe.md).diff --git a/changelog/unreleased/2026-08-27-telegram-conflict-recovery.zh.md b/changelog/unreleased/2026-08-27-telegram-conflict-recovery.zh.mdnew file mode 100644index 00000000..8224ff80--- /dev/null+++ b/changelog/unreleased/2026-08-27-telegram-conflict-recovery.zh.md@@ -0,0 +1,19 @@+# Telegram 连接能从轮询冲突中恢复,并说清失败原因++- **Date:** 2026-08-27+- **Type:** fix+- **Scope:** `server`, `web`+- **PR:** [#484](https://github.com/Prism-Shadow/penguin-harness/pull/484)++[English](2026-08-27-telegram-conflict-recovery.md)++撞上 Telegram「一个 Token 只允许一个轮询者」规则的 Telegram 绑定会停在「连接错误」,此后再也收不到消息。轮询循环现在把 `getUpdates` 失败当作真正的中断处理,会指名挡住轮询的那个 webhook,面板也完整显示失败信息,而不再只剩开头几个字。++## 细节++- 中断后的恢复以一次成功的 `getUpdates` 为准,而不是它前面的 `getMe` 探测。`getMe` 从不发生冲突,因此原先每一轮都会清零失败计数:指数退避停留在第一档,连接器无限期地每秒重试一次,每次重试都触发一次 `onError`,连接状态在 `connected` 与 `error` 之间翻转的速度快过面板的轮询。现在一次中断只上报一次,并按文档退避到 60 秒上限。+- 恢复用的轮询以 0 秒超时发出,中断结束会被立即观察到,而不必等下一个 30 秒长轮询窗口。+- 每条连接在首次轮询前执行一次 `getWebhookInfo` 探测。Bot API 中 webhook 与 `getUpdates` 互斥,因此绑定之前被指向过 webhook 的机器人此前永远无法轮询,而当时的 409 只说得出「设了一个」。探测把注册的 URL 报出来——那正是用户需要去找的东西——然后就到此为止。它不会清除该 webhook:那条注册属于用户指向的另一个服务,在这里把它删掉会让那个服务无声下线,且无从追溯。在那一侧移除后也无需重新启用:探测在每次重试时重做,连接会自行恢复。+- Bot API 中两种可操作的 409 被改写为以行动开头——「another program is already polling this bot …」与「a webhook is set on this bot, which blocks polling …」——不再沿用把要点放在句尾的 Telegram 原文。+- 连接状态行把失败信息移到开关下方独立一行,限高两行、悬停显示全文,不再与开关、标签、状态词挤在同一行里被截断。Telegram 绑定的常见问题折叠区新增一条,说明一个 Token 同一时刻只能被一个程序使用。+- 轮询冲突是同一条入站消息两次到达桥接层的原因之一;该症状的另一端见[入站去重](2026-08-27-messaging-inbound-dedupe.zh.md)。diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.tsindex 26b1d425..b4e0a4cd 100644--- a/packages/core/src/environment/tools/command/session-manager.ts+++ b/packages/core/src/environment/tools/command/session-manager.ts@@ -9,6 +9,7 @@* injection + hardening).* Docs: /docs/tools § "Background session caps".*/+import { statSync } from "node:fs";import { ManagedSession } from "./session.js";import { BackgroundRegistry } from "../background/index.js";import type { ProxyEnvPolicy } from "../../../interfaces/index.js";@@ -156,6 +157,36 @@ function hostEnvForChild(policy: ProxyEnvPolicy | null): NodeJS.ProcessEnv {return env;}+/**+ * Rejects a working directory that cannot be spawned into, before the spawn.+ *+ * Node reports a missing or unusable `cwd` as `spawn <shell> ENOENT` — the error names the+ * COMMAND, not the directory, so a Workspace that has been deleted or moved reads exactly+ * like a missing shell and sends the reader hunting for a `bash` that was there all along.+ * The directory is therefore checked here, where the real reason can still be named.+ *+ * Never auto-created: Agent.createSession and the server's Workspace guard both refuse to+ * create a Workspace so a typo cannot silently start working in the wrong place, and a+ * directory that disappeared under a live Session is a fact to report rather than paper over.+ *+ * A check before a spawn cannot close the gap between them: a directory removed in that+ * window still produces the old ENOENT. That is the rare case, and the only alternative is+ * re-reading Node's error after the fact, which is the string this exists to stop trusting.+ */+function assertUsableCwd(cwd: string): void {+ let stat;+ try {+ stat = statSync(cwd);+ } catch {+ throw new Error(+ `working directory does not exist: ${cwd}. That is the Session's Workspace unless a workdir was given — restore the directory, or run the command somewhere that exists.`,+ );+ }+ if (!stat.isDirectory()) {+ throw new Error(`working directory is not a directory: ${cwd}.`);+ }+}+export class CommandSessionManager {private readonly registry = new BackgroundRegistry<ManagedSession>({idPrefix: "proc",@@ -195,6 +226,7 @@ export class CommandSessionManager {if (this.registry.isDisposed) {throw new Error("command session manager disposed");}+ assertUsableCwd(opts.cwd);return new ManagedSession({cmd: opts.cmd,cwd: opts.cwd,diff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.tsindex 8b693759..6ac92a86 100644--- a/packages/core/src/environment/tools/command/session.ts+++ b/packages/core/src/environment/tools/command/session.ts@@ -1,12 +1,12 @@/*** ManagedSession — runtime state and collection logic for a single command session.*- * Spawns the process with `bash -lc <cmd>` (on Windows, the shell picked by `sessionShell()`- * — see shell.ts), with stdout/stderr going through plain pipes (no- * native dependency, clean output; an interactive program that detects no TTY falls back to- * non-interactive mode, which parses more cleanly for the Agent anyway). `detached` makes the- * child process the process-group leader, so both Ctrl-C and killing the whole group rely on- * **process-group signals** (sending a signal to `-pid` also reaches background child processes).+ * Spawns the process with the shell `sessionShell()` picked — `bash -lc <cmd>` wherever a bash+ * exists, its fallback chain otherwise (see shell.ts) — with stdout/stderr going through plain+ * pipes (no native dependency, clean output; an interactive program that detects no TTY falls+ * back to non-interactive mode, which parses more cleanly for the Agent anyway). `detached`+ * makes the child process the process-group leader, so both Ctrl-C and killing the whole group+ * rely on **process-group signals** (a signal to `-pid` also reaches background child processes).* Windows has neither process groups nor real signals: every "signal" degrades to a hard* TerminateProcess, and tree-wide cleanup goes through `taskkill /t` instead (see signalGroup).*diff --git a/packages/core/src/environment/tools/command/shell.ts b/packages/core/src/environment/tools/command/shell.tsindex 82bdd44d..a4a2ea59 100644--- a/packages/core/src/environment/tools/command/shell.ts+++ b/packages/core/src/environment/tools/command/shell.ts@@ -1,12 +1,18 @@/*** Shell selection for command sessions.*- * POSIX behavior is unchanged: commands run via `bash -lc <cmd>`. On Windows there is no- * bash by default, so the resolver picks the best available shell once per process:+ * Commands run via `bash -lc <cmd>` wherever a bash exists. Neither platform guarantees one+ * — Windows has none by default, and a POSIX box can be launched with a PATH that has none —+ * so the resolver picks the best available shell once per process:** 1. `PENGUIN_SHELL` (explicit executable name or path) always wins, on every platform;* the argument shape is inferred from its basename (see below).- * 2. Otherwise, non-Windows uses `bash -lc` (today's behavior, bit for bit).+ * 2. Otherwise, non-Windows uses `bash -lc` — but only after confirming a `bash` exists.+ * A GUI-launched app inherits the desktop session's PATH, not a login shell's, and a+ * trimmed session PATH (or a distribution that simply does not install bash) leaves+ * `spawn("bash")` dying with ENOENT before the command runs at all. So: `bash` on+ * PATH, then the usual absolute locations, then `$SHELL` when it is some other POSIX+ * shell, then `sh`. The probe is a PATH walk, not a subprocess.* 3. On Windows, probe PATH for `bash` (a full Git for Windows install — best compatibility* with the skill/prompt ecosystem, which is written for a POSIX shell). A `bash` that* resolves into the Windows system directory is ignored: that is the WSL launcher, which@@ -71,6 +77,39 @@ function shellBasename(command: string): string {.toLowerCase();}+/**+ * Absolute POSIX locations to try when no `bash` is on PATH. A GUI launch can inherit a+ * PATH that omits the directory bash actually lives in, while the binary is right there.+ */+const POSIX_BASH_PATHS = [+ "/bin/bash",+ "/usr/bin/bash",+ "/usr/local/bin/bash",+ "/opt/homebrew/bin/bash",+];++/** POSIX shells worth falling back to, in the order they are tried, once bash is ruled out. */+const POSIX_FALLBACK_SHELLS = ["sh", "/bin/sh", "/usr/bin/sh"];++/**+ * Basenames `$SHELL` is allowed to name. It carries the login shell of whatever account the+ * server runs as, and on a service account that field is routinely `/usr/sbin/nologin` or+ * `/bin/false` — both exist, neither runs a command, and `-lc` would turn every command into+ * a silent non-zero exit. Membership here means "accepts `-lc <cmd>`"; anything else falls+ * through to `sh`, which does.+ */+const POSIX_LOGIN_SHELLS = new Set([+ "bash",+ "zsh",+ "fish",+ "ksh",+ "ksh93",+ "mksh",+ "dash",+ "ash",+ "sh",+]);+/** Argument prefix for a shell, chosen by its basename (PowerShell-style vs cmd vs POSIX-style). */function argsForShell(name: string): string[] {if (name === "pwsh" || name === "powershell") return ["-NoLogo", "-NoProfile", "-Command"];@@ -78,6 +117,53 @@ function argsForShell(name: string): string[] {return ["-lc"];}+/**+ * Is `name` reachable as a bare command on this PATH? A plain directory walk — the POSIX+ * branch resolves at every process start and must not pay for a subprocess to do it.+ */+function onPath(name: string, env: NodeJS.ProcessEnv, exists: (p: string) => boolean): boolean {+ const raw = env.PATH ?? "";+ for (const dir of raw.split(path.posix.delimiter)) {+ // An empty entry means the working directory. Skipped deliberately: the Workspace is+ // model-writable, and picking a shell out of it would be an execution primitive.+ if (dir === "") continue;+ if (exists(path.posix.join(dir, name))) return true;+ }+ return false;+}++/**+ * The POSIX shell, in preference order. `bash` stays first and stays a *bare* name when+ * PATH has it, so the overwhelmingly common case is byte-identical to what shipped+ * before: the Skill and prompt ecosystem is written for bash, and the child resolves the+ * name against its own PATH. Everything after it exists so a box without bash degrades to+ * a working shell instead of an ENOENT on every single command.+ */+function resolvePosixShell(+ env: NodeJS.ProcessEnv,+ exists: (filePath: string) => boolean,+): ShellInvocation {+ if (onPath("bash", env, exists)) return { command: "bash", args: ["-lc"], name: "bash" };+ for (const candidate of POSIX_BASH_PATHS) {+ if (exists(candidate)) return { command: candidate, args: ["-lc"], name: "bash" };+ }+ // The user's own login shell, when it is one of the shells POSIX_LOGIN_SHELLS names (zsh,+ // fish, ksh …). It is named honestly to the model: `-lc` is what every one of them speaks,+ // but the syntax the model should write is that shell's, not bash's.+ const login = env.SHELL?.trim();+ if (login !== undefined && login.startsWith("/") && exists(login)) {+ const name = shellBasename(login);+ if (POSIX_LOGIN_SHELLS.has(name)) return { command: login, args: argsForShell(name), name };+ }+ for (const candidate of POSIX_FALLBACK_SHELLS) {+ if (candidate.startsWith("/") ? exists(candidate) : onPath(candidate, env, exists)) {+ return { command: candidate, args: ["-lc"], name: "sh" };+ }+ }+ // Nothing answered. Keep the historical invocation so the failure is the familiar one.+ return { command: "bash", args: ["-lc"], name: "bash" };+}+/** Default PATH probe: `where` lists every match line by line, in PATH order (win32 only). */function defaultWhichAll(cmd: string): string[] {try {@@ -110,12 +196,12 @@ export function resolveShell(opts: ResolveShellOptions = {}): ShellInvocation {return { command: explicit, args: argsForShell(name), name };}+ const exists = opts.exists ?? existsSync;if (platform !== "win32") {- return { command: "bash", args: ["-lc"], name: "bash" };+ return resolvePosixShell(env, exists);}const whichAll = opts.whichAll ?? defaultWhichAll;- const exists = opts.exists ?? existsSync;const systemRoot = opts.systemRoot ?? env.SystemRoot ?? "C:\\Windows";// The WSL launcher lives in <SystemRoot>\System32 (or Sysnative under WOW64); a Git for// Windows bash lives under the Git install dir. Only the first PATH match counts — thatdiff --git a/packages/core/test/exec-session.test.ts b/packages/core/test/exec-session.test.tsindex 65b79b20..4f17284f 100644--- a/packages/core/test/exec-session.test.ts+++ b/packages/core/test/exec-session.test.ts@@ -2,7 +2,7 @@* Behavior tests for long-running command sessions (exec_command yield + input_command).*/import { afterEach, beforeEach, describe, expect, it } from "vitest";-import { mkdtemp, rm } from "node:fs/promises";+import { mkdtemp, rm, writeFile } from "node:fs/promises";import { tmpdir } from "node:os";import path from "node:path";import { Environment, ManagedSession } from "../src/environment/index.js";@@ -676,3 +676,47 @@ describe("controlEnv injects the host's harness-control variables into commands"}});});++describe("exec_command — a working directory that is not there", () => {+ // Node reports an unusable `cwd` as `spawn <shell> ENOENT`: the error names the COMMAND,+ // so a Workspace deleted under a live Session reads exactly like a missing shell. These+ // pin the honest message — the one difference between "install bash" and "your Workspace+ // is gone" for whoever reads the reply.++ it("names the missing Workspace instead of blaming the shell", async () => {+ // The Session is live and its Environment already built; the directory goes away+ // underneath it, which is all it takes — the Workspace is validated when a Session+ // loads and never again.+ await rm(tmp, { recursive: true, force: true });+ const res = await runTool(env, "exec_command", { cmd: "echo test" });+ expect(res.output).toContain("working directory does not exist");+ expect(res.output).toContain(tmp);+ expect(res.output).not.toContain("ENOENT");+ expect(res.output).not.toContain("spawn bash");+ expect(res.stopReason).toBe("fatal");+ });++ it("names a workdir argument that does not resolve, rather than the shell", async () => {+ const res = await runTool(env, "exec_command", {+ cmd: "echo test",+ workdir: "no/such/subdir",+ });+ expect(res.output).toContain("working directory does not exist");+ expect(res.output).toContain(path.join(tmp, "no/such/subdir"));+ expect(res.output).not.toContain("spawn bash");+ });++ it("names a workdir that is a file, not a directory", async () => {+ const file = path.join(tmp, "notadir.txt");+ await writeFile(file, "x");+ const res = await runTool(env, "exec_command", { cmd: "echo test", workdir: "notadir.txt" });+ expect(res.output).toContain("is not a directory");+ expect(res.output).toContain(file);+ });++ it("still runs normally when the Workspace is there", async () => {+ const res = await runTool(env, "exec_command", { cmd: "echo test" });+ expect(res.output).toContain("test");+ expect(res.stopReason).toBe("completed");+ });+});diff --git a/packages/core/test/shell-resolver.test.ts b/packages/core/test/shell-resolver.test.tsindex b45cdcdd..7d96e27f 100644--- a/packages/core/test/shell-resolver.test.ts+++ b/packages/core/test/shell-resolver.test.ts@@ -1,8 +1,13 @@/*** Unit tests for the command-session shell resolver (pure function; platform, env and the- * PATH probe are injected — no real shells are spawned here).+ * existence/PATH probes are injected) plus one real spawn proving the POSIX fallback+ * chain resolves to something that actually runs a command.*/import { describe, expect, it } from "vitest";+import { spawnSync } from "node:child_process";+import { mkdtempSync, mkdirSync, symlinkSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";import { resolveShell } from "../src/environment/tools/command/shell.js";const POWERSHELL_ARGS = ["-NoLogo", "-NoProfile", "-Command"];@@ -12,25 +17,150 @@ function which(table: Record<string, string[]>): (cmd: string) => string[] {return (cmd) => table[cmd] ?? [];}+/** An exists stub answering true for exactly the listed absolute paths. */+function has(...paths: string[]): (filePath: string) => boolean {+ const set = new Set(paths);+ return (filePath) => set.has(filePath);+}+describe("resolveShell — POSIX", () => {it("uses bash -lc on linux without probing (today's behavior, unchanged)", () => {let probed = false;const shell = resolveShell({platform: "linux",- env: {},+ env: { PATH: "/usr/local/bin:/usr/bin:/bin" },+ exists: has("/usr/bin/bash"),whichAll: () => {probed = true;return [];},});+ // A bare name, not the resolved path: the child resolves it against its own PATH.expect(shell).toEqual({ command: "bash", args: ["-lc"], name: "bash" });+ // The POSIX branch must never cost a subprocess — it walks PATH itself.expect(probed).toBe(false);});it("uses bash -lc on darwin", () => {- const shell = resolveShell({ platform: "darwin", env: {} });+ const shell = resolveShell({+ platform: "darwin",+ env: { PATH: "/usr/bin:/bin" },+ exists: has("/bin/bash"),+ });+ expect(shell).toEqual({ command: "bash", args: ["-lc"], name: "bash" });+ });++ // A GUI-launched desktop app inherits the session's PATH, not a login shell's. When+ // that PATH omits bash, spawn("bash") dies with ENOENT before the command runs — every+ // exec_command on that machine, from every surface. The chain below is what stops it.+ it("falls back to an absolute bash when PATH omits it (the GUI-launch PATH)", () => {+ const shell = resolveShell({+ platform: "linux",+ env: { PATH: "/usr/games:/snap/bin" },+ exists: has("/bin/bash", "/bin/sh"),+ });+ expect(shell).toEqual({ command: "/bin/bash", args: ["-lc"], name: "bash" });+ });++ it("finds a Homebrew bash on a macOS PATH that has none", () => {+ const shell = resolveShell({+ platform: "darwin",+ env: { PATH: "/usr/sbin:/sbin" },+ exists: has("/opt/homebrew/bin/bash"),+ });+ expect(shell).toEqual({ command: "/opt/homebrew/bin/bash", args: ["-lc"], name: "bash" });+ });++ it("uses the user's own login shell when no bash exists anywhere", () => {+ const shell = resolveShell({+ platform: "linux",+ env: { PATH: "/usr/bin:/bin", SHELL: "/usr/bin/zsh" },+ exists: has("/usr/bin/zsh", "/bin/sh"),+ });+ // Named honestly: the model is told zsh, because that is the syntax it must write.+ expect(shell).toEqual({ command: "/usr/bin/zsh", args: ["-lc"], name: "zsh" });+ });++ it("skips a $SHELL that is not a shell at all", () => {+ // A service account's login shell field is routinely /usr/sbin/nologin or /bin/false.+ // Both exist; neither runs a command, and `-lc` would make every command exit silently.+ for (const login of ["/usr/sbin/nologin", "/bin/false"]) {+ const shell = resolveShell({+ platform: "linux",+ env: { PATH: "/usr/games", SHELL: login },+ exists: has(login, "/bin/sh"),+ });+ expect(shell).toEqual({ command: "/bin/sh", args: ["-lc"], name: "sh" });+ }+ });++ it("falls back to sh when there is neither a bash nor a usable $SHELL", () => {+ const shell = resolveShell({+ platform: "linux",+ env: { PATH: "/usr/games" },+ exists: has("/bin/sh"),+ });+ expect(shell).toEqual({ command: "/bin/sh", args: ["-lc"], name: "sh" });+ });++ it("prefers an sh on PATH over the absolute one", () => {+ const shell = resolveShell({+ platform: "linux",+ env: { PATH: "/busybox/bin" },+ exists: has("/busybox/bin/sh", "/bin/sh"),+ });+ expect(shell).toEqual({ command: "sh", args: ["-lc"], name: "sh" });+ });++ it("keeps the historical bash invocation when nothing at all resolves", () => {+ const shell = resolveShell({+ platform: "linux",+ env: { PATH: "/nowhere" },+ exists: () => false,+ });expect(shell).toEqual({ command: "bash", args: ["-lc"], name: "bash" });});++ it("PENGUIN_SHELL still wins over the whole POSIX chain", () => {+ const shell = resolveShell({+ platform: "linux",+ env: { PENGUIN_SHELL: "/usr/bin/fish", PATH: "/bin" },+ exists: has("/bin/bash"),+ });+ expect(shell).toEqual({ command: "/usr/bin/fish", args: ["-lc"], name: "fish" });+ });+});++describe("resolveShell — POSIX, real spawn", () => {+ /** A PATH directory carrying a POSIX sh and a few coreutils, but deliberately no bash. */+ function bashlessBin(): string {+ const bin = path.join(mkdtempSync(path.join(tmpdir(), "penguin-nobash-")), "bin");+ mkdirSync(bin);+ for (const tool of ["sh", "env", "cat", "echo", "printf"]) {+ try {+ symlinkSync(`/bin/${tool}`, path.join(bin, tool));+ } catch {+ // A tool this box does not have; the shell itself is what matters.+ }+ }+ return bin;+ }++ it.skipIf(process.platform === "win32")(+ "resolves to a shell that really runs a command when PATH has no bash",+ () => {+ const bin = bashlessBin();+ const shell = resolveShell({ platform: process.platform, env: { PATH: bin } });+ const res = spawnSync(shell.command, [...shell.args, "echo test"], {+ env: { PATH: bin },+ encoding: "utf8",+ });+ // Before the fallback chain this was spawn("bash") against a bashless PATH:+ // res.error was `spawn bash ENOENT` and the command never ran.+ expect(res.error).toBeUndefined();+ expect(res.stdout).toContain("test");+ },+ );});describe("resolveShell — win32 probing", () => {@@ -106,7 +236,11 @@ describe("resolveShell — PENGUIN_SHELL override", () => {});it("ignores a blank PENGUIN_SHELL", () => {- const shell = resolveShell({ platform: "linux", env: { PENGUIN_SHELL: " " } });+ const shell = resolveShell({+ platform: "linux",+ env: { PENGUIN_SHELL: " ", PATH: "/usr/bin:/bin" },+ exists: has("/bin/bash"),+ });expect(shell).toEqual({ command: "bash", args: ["-lc"], name: "bash" });});});diff --git a/packages/server/src/runtime/messaging/bridge.ts b/packages/server/src/runtime/messaging/bridge.tsindex 43673862..501192f4 100644--- a/packages/server/src/runtime/messaging/bridge.ts+++ b/packages/server/src/runtime/messaging/bridge.ts@@ -11,7 +11,9 @@* re-saving an enabled binding restarts its connector with the new credentials, so the* stored config and the live connection never diverge).*- * Inbound (channel → Session): every inbound message first records its chat as the+ * Inbound (channel → Session): a message the binding has already processed is dropped+ * first (see MESSAGING_INBOUND_DEDUPE_*) — channels redeliver, and nothing downstream of+ * here is idempotent. Then every inbound message records its chat as the* binding's reply target; a text message then starts a Task on the bound Session as an* ordinary user input — exactly as if typed into the web composer, no marker block and no* special sender (the model deliberately does not learn where the message came from) —@@ -70,6 +72,49 @@ export const MESSAGING_APPROVAL_NOTICE =export const MESSAGING_TEST_MESSAGE ="PenguinHarness test message: this Session's messaging binding works. 测试消息:该会话的消息绑定工作正常。";+/**+ * How many recently processed inbound message ids one binding remembers, and for how long.+ *+ * A redelivery arrives seconds after the original — a Feishu long connection replaying+ * across a reconnect, or any connector resuming a stream whose acknowledgement never+ * landed — so a short window over the last few messages catches every realistic one. The+ * bound is the point: an unbounded set on a server that runs for months is a leak.+ */+const MESSAGING_INBOUND_DEDUPE_SIZE = 64;+const MESSAGING_INBOUND_DEDUPE_WINDOW_MS = 10 * 60_000;++/**+ * The ids one binding has already processed, bounded by both count and age.+ *+ * Identity is the channel's own message id (Feishu's `message_id`, Telegram's+ * `chatId:message_id`), never the text: a user genuinely does send "status?" twice, and+ * swallowing the second one is a worse failure than the duplicate it would prevent.+ *+ * A `Map` iterates in insertion order, which is the ring: the oldest key is the first one+ * `keys()` yields, so eviction is a `delete` of that.+ */+class RecentInboundIds {+ private readonly seen = new Map<string, number>();++ /** True when this id was already processed inside the window; records it otherwise. */+ check(messageId: string, now: number): boolean {+ const firstSeen = this.seen.get(messageId);+ if (firstSeen !== undefined && now - firstSeen <= MESSAGING_INBOUND_DEDUPE_WINDOW_MS) {+ return true;+ }+ // An id past the window is treated as new and re-dated, so a message id a channel+ // reuses after long enough is not silently dropped forever.+ this.seen.delete(messageId);+ this.seen.set(messageId, now);+ while (this.seen.size > MESSAGING_INBOUND_DEDUPE_SIZE) {+ const oldest = this.seen.keys().next();+ if (oldest.done === true) break;+ this.seen.delete(oldest.value);+ }+ return false;+ }+}+/*** Splits an outbound reply into channel-sized chunks, preferring newline boundaries so a* split lands between paragraphs rather than mid-sentence when it can.@@ -90,6 +135,11 @@ export function chunkMessagingText(text: string, max = MESSAGING_TEXT_CHUNK_CHARreturn out;}+/** Dedupe scope: one binding, i.e. a Session's config for one channel. */+function inboundKey(sessionId: string, channel: string): string {+ return `${sessionId}:${channel}`;+}+/** Minimal dependency on SessionManager (eases test doubles; mirrors ScheduleTaskRunner). */export interface MessagingTaskRunner {statusOf(sessionId: string): string;@@ -150,6 +200,16 @@ interface BridgeEntry {export class MessagingBridge {private readonly entries = new Map<string, BridgeEntry>();+ /**+ * Processed inbound ids per BINDING (`sessionId:channel`), deliberately not per+ * connection: re-saving an enabled binding restarts its connector, and a message+ * already turned into a Task must not run again because the connector is new. In memory+ * only — a server restart forgets, so a redelivery that survives a restart still+ * duplicates. Accepted: a channel replays within seconds of its own reconnect, and+ * persisting this would put a write on every inbound message to close a window the+ * restart itself has almost always already closed.+ */+ private readonly recentInbound = new Map<string, RecentInboundIds>();private readonly connectors: ReadonlyMap<string, MessagingChannelConnector>;private readonly now: () => number;private readonly log: (line: string) => void;@@ -199,12 +259,16 @@ export class MessagingBridge {/** Route DELETE: disconnect (when this channel holds the connection) and drop the row. No-op when unbound. */unbind(sessionId: string, channel: string): void {if (this.entries.get(sessionId)?.channel === channel) this.disconnect(sessionId);+ this.recentInbound.delete(inboundKey(sessionId, channel));this.deps.repo.delete(sessionId, channel);}/** Session-delete cascade: disconnect and drop every channel's config. */unbindSession(sessionId: string): void {this.disconnect(sessionId);+ for (const key of [...this.recentInbound.keys()]) {+ if (key.startsWith(`${sessionId}:`)) this.recentInbound.delete(key);+ }this.deps.repo.deleteSession(sessionId);}@@ -347,8 +411,33 @@ export class MessagingBridge {// —— Inbound ——————————————————————————————————————————————————————————————+ /**+ * Has this binding already processed this message? A duplicate is a complete no-op —+ * ahead of the chat record and the text-only reply, not just the Task start, because a+ * replayed sticker would otherwise answer with the notice twice.+ *+ * Nothing downstream is idempotent: `startTask` with `queueIfBusy` appends to the+ * follow-up queue unconditionally, and a queued input is published to the Session+ * channel, so one redelivery becomes two runs in the chat AND two messages in the Web+ * App. A connector that mints no id opts out rather than having every message after the+ * first read as a duplicate.+ */+ private isRedelivery(entry: BridgeEntry, msg: MessagingInboundMessage): boolean {+ if (msg.messageId === "") return false;+ const key = inboundKey(entry.sessionId, entry.channel);+ let recent = this.recentInbound.get(key);+ if (recent === undefined) {+ recent = new RecentInboundIds();+ this.recentInbound.set(key, recent);+ }+ if (!recent.check(msg.messageId, this.now())) return false;+ this.log(`[messaging] ${entry.channel} redelivered message ${msg.messageId}, ignored`);+ return true;+ }+private async onInbound(entry: BridgeEntry, msg: MessagingInboundMessage): Promise<void> {if (this.entries.get(entry.sessionId) !== entry) return; // stale connection+ if (this.isRedelivery(entry, msg)) return;try {const isDirect = msg.chatKind === "direct";// The chat becomes the reply target BEFORE any processing: even a rejected messagediff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.tsindex bea0eb5e..238b490e 100644--- a/packages/server/src/runtime/messaging/connector.ts+++ b/packages/server/src/runtime/messaging/connector.ts@@ -24,7 +24,11 @@ export interface MessagingInboundMessage {* Channel-scoped id of the inbound message itself (the group reply target). Opaque to* the bridge: the connector both mints it here and consumes it in `replyText`, so a* channel whose native message ids are not globally unique encodes whatever context a- * reply needs (Telegram packs `chatId:messageId`).+ * reply needs (Telegram packs `chatId:messageId`). It is also the bridge's inbound+ * dedupe key, so it must identify the MESSAGE and not the delivery: a channel that+ * redelivers one message must mint the same id both times. `""` opts the channel out of+ * deduplication entirely — the honest answer for a connector with no message identity,+ * and better than every message after the first reading as a duplicate.*/messageId: string;/**diff --git a/packages/server/src/runtime/messaging/telegram-api.ts b/packages/server/src/runtime/messaging/telegram-api.tsindex d55df3c0..ed2eadf2 100644--- a/packages/server/src/runtime/messaging/telegram-api.ts+++ b/packages/server/src/runtime/messaging/telegram-api.ts@@ -1,7 +1,7 @@/**- * The Telegram Bot API seam: the three methods the Telegram connector uses (`getMe`,- * `sendMessage`, `getUpdates`), behind an injectable transport so unit tests substitute a- * fake and never open real network. Telegram needs no SDK — the Bot API is plain HTTPS+ * The Telegram Bot API seam: the four methods the Telegram connector uses (`getMe`,+ * `getWebhookInfo`, `sendMessage`, `getUpdates`), behind an injectable transport so unit+ * tests substitute a fake and never open real network. Telegram needs no SDK — the Bot API is plain HTTPS* POSTs against https://api.telegram.org — so the production transport is a thin fetch* wrapper.*@@ -41,6 +41,14 @@ export interface TelegramMessage {};}+/**+ * The slice of `getWebhookInfo`'s result the connector consumes. `url` is the empty string+ * when no webhook is registered — that is the Bot API's own encoding, not a normalization.+ */+export interface TelegramWebhookInfo {+ url: string;+}+/** One `getUpdates` entry. Only `message` updates are processed; the rest are skipped. */export interface TelegramUpdate {update_id: number;@@ -51,6 +59,15 @@ export interface TelegramUpdate {export interface TelegramBotClient {/** Credential probe: resolves the bot's own account (the test endpoint surfaces its username). */getMe(): Promise<TelegramBotUser>;+ /**+ * Reports the webhook registered on the bot, if any. A webhook and `getUpdates` are+ * mutually exclusive on the Bot API, so a bot pointed at one cannot be polled at all+ * until it is removed — and removing it is the user's call, not this app's: the+ * registration belongs to whatever service they pointed it at, and clearing it here+ * would silently take that service off the air. Read-only on purpose; the connector+ * reports the URL and leaves the bot alone.+ */+ getWebhookInfo(): Promise<TelegramWebhookInfo>;/** Sends a text message into a chat; `replyToMessageId` threads it under an inbound message. */sendMessage(args: { chatId: string; text: string; replyToMessageId?: number }): Promise<void>;/**@@ -86,6 +103,23 @@ interface TelegramEnvelope<T> {error_code?: number;}+/**+ * The two 409s a Bot API caller can actually act on, rewritten to lead with the action.+ * Telegram's own wording buries it — "Conflict: terminated by other getUpdates request;+ * make sure that only one bot instance is running" reads as an internal detail until the+ * end of the sentence, and a status line has room for a few words, not a paragraph. Any+ * other description passes through untouched.+ */+function conflictText(description: string): string | null {+ if (/terminated by other getUpdates/i.test(description)) {+ return "another program is already polling this bot — one bot token can serve only one PenguinHarness server at a time";+ }+ if (/webhook is active/i.test(description)) {+ return "a webhook is set on this bot, which blocks polling — remove it and the connection recovers on its own";+ }+ return null;+}+/*** Readable failure text out of fetch's throw shapes. The request URL embeds the bot* token, so nothing here may echo the URL — only the cause's own message (connect/DNS@@ -125,7 +159,11 @@ export function createTelegramTransport(): TelegramTransport {}const body = (await res.json().catch(() => null)) as TelegramEnvelope<T> | null;if (body === null || body.ok !== true) {- const detail = body?.description ?? `HTTP ${res.status}`;+ const described = body?.description;+ const detail =+ (described !== undefined ? conflictText(described) : null) ??+ described ??+ `HTTP ${res.status}`;const code = body?.error_code !== undefined ? ` (code ${body.error_code})` : "";throw new Error(`${method} failed: ${detail}${code}`);}@@ -141,6 +179,7 @@ export function createTelegramTransport(): TelegramTransport {return {getMe: () => call<TelegramBotUser>("getMe", {}),+ getWebhookInfo: () => call<TelegramWebhookInfo>("getWebhookInfo", {}),async sendMessage({ chatId, text, replyToMessageId }): Promise<void> {await call("sendMessage", {chat_id: wireChatId(chatId),diff --git a/packages/server/src/runtime/messaging/telegram-connector.ts b/packages/server/src/runtime/messaging/telegram-connector.tsindex 3bbc3493..50a1f7c5 100644--- a/packages/server/src/runtime/messaging/telegram-connector.ts+++ b/packages/server/src/runtime/messaging/telegram-connector.ts@@ -7,15 +7,31 @@* public webhook URL, so the connector pulls, which keeps local deployments working* exactly like the Feishu long connection does.*- * The poll loop's lifecycle: one `getMe` probe (a bad token surfaces immediately as the- * connection error instead of an eternally failing poll), then a one-time backlog drain- * (`offset: -1` confirms everything sent while no connection existed — a disabled binding- * must not replay its dark period as a task flood, matching Feishu, where missed events- * are simply gone), then long polls advancing `offset` past each processed update.- * Failures back off exponentially and report once per outage; recovery re-probes and- * fires `onReady` again, so the bridge's status tracks the outage. A save-while-enabled- * restart can briefly race Telegram's one-poller-per-token rule (409 until the server- * notices the old poll is gone) — that resolves through the same retry path.+ * The poll loop's lifecycle: a `getMe` probe (a bad token surfaces immediately as the+ * connection error instead of an eternally failing poll — it runs again ahead of every+ * recovery attempt, so a token revoked mid-outage stops reading as a stale conflict), a+ * `getWebhookInfo` probe (a webhook and `getUpdates` are mutually exclusive on the Bot API,+ * so a bot pointed at one cannot be polled until the webhook goes — the probe names it and+ * stops there, because removing it is the user's call: see below), then a one-time backlog+ * drain (`offset: -1` confirms everything sent while no connection existed+ * — a disabled binding must not replay its dark period as a task flood, matching Feishu,+ * where missed events are simply gone), then long polls advancing `offset` past each update.+ * Failures back off exponentially and report once per outage; recovery fires `onReady`+ * again, so the bridge's status tracks the outage.+ *+ * Readiness is proven by a `getUpdates`, NEVER by `getMe`. Telegram's one-poller-per-token+ * rule shows up only on `getUpdates`, as a 409 — a second server (or any other program)+ * holding the same token. `getMe` answers happily throughout, so a+ * recovery gated on `getMe` alone would clear the outage counter on every cycle: the+ * backoff would never leave its first step and every single failure would report again.+ * The recovery poll therefore runs with `timeoutSec: 0` — it must come back now, not park+ * for the long-poll window — and only its success clears `failures` and fires `onReady`.+ *+ * Nothing here writes to the bot. A registered webhook is reported, never deleted: it points+ * at whatever service the user set it on, and clearing it to make polling work here would+ * take that service off the air with no notice and no way to trace it back. So the probe+ * repeats on every recovery attempt rather than latching — the outage ends the moment the+ * user removes the webhook, and the connection then comes back on its own.*/import type {MessagingChannelConnector,@@ -172,8 +188,10 @@ export class TelegramConnector implements MessagingChannelConnector {signal: AbortSignal,isClosed: () => boolean,): Promise<void> {- /** Probe + drain done and onReady fired for the current up-streak. */+ /** A `getUpdates` has succeeded since the last failure, and onReady fired for that up-streak. */let ready = false;+ /** A webhook probe has come back clean; a bot with none never has to be asked twice. */+ let webhookChecked = false;/** The backlog drain runs once per connection, never again after an outage: messages sent during a mere blip still deliver. */let drained = false;let failures = 0;@@ -183,6 +201,19 @@ export class TelegramConnector implements MessagingChannelConnector {if (!ready) {await bot.getMe();if (isClosed()) return;+ if (!webhookChecked) {+ const { url } = await bot.getWebhookInfo();+ if (isClosed()) return;+ if (url !== "") {+ // Named, not cleared. `getUpdates` would 409 on the next line anyway, but its+ // description cannot say which webhook — and that is the whole of what the+ // user has to go and find. The flag stays unset so the next attempt re-probes.+ throw new Error(+ `a webhook is registered on this bot at ${url}, which blocks polling — remove it there and the connection recovers on its own`,+ );+ }+ webhookChecked = true;+ }if (!drained) {const backlog = await bot.getUpdates({ offset: -1, timeoutSec: 0, signal });if (isClosed()) return;@@ -190,18 +221,21 @@ export class TelegramConnector implements MessagingChannelConnector {if (newest !== undefined) offset = newest.update_id + 1;drained = true;}- ready = true;- failures = 0;- handlers.onReady?.();- continue;}const updates = await bot.getUpdates({...(offset !== undefined ? { offset } : {}),- timeoutSec: POLL_TIMEOUT_SEC,+ // Recovery polls must answer immediately — the outage is only over once a+ // `getUpdates` comes back, and parking for the long-poll window would hide that+ // for another 30s. Steady state parks as usual.+ timeoutSec: ready ? POLL_TIMEOUT_SEC : 0,signal,});if (isClosed()) return;failures = 0;+ if (!ready) {+ ready = true;+ handlers.onReady?.();+ }for (const update of updates) {offset = update.update_id + 1;const msg = normalizeUpdate(update);@@ -211,7 +245,10 @@ export class TelegramConnector implements MessagingChannelConnector {if (isClosed()) return;failures += 1;// One report per outage: the first failure flips the bridge to `error` and lands- // one error record; the retries stay quiet until recovery re-fires onReady.+ // one error record; the retries stay quiet until recovery re-fires onReady. The+ // counter survives the recovery attempt above precisely so a failure that only+ // ever hits `getUpdates` — a 409 conflict — still walks the backoff up to its+ // ceiling instead of re-polling every second forever.if (failures === 1) handlers.onError?.(err);ready = false;await sleep(this.retryDelayMs(failures), signal);diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.tsindex 37af19f7..785f2676 100644--- a/packages/server/test/messaging-telegram.test.ts+++ b/packages/server/test/messaging-telegram.test.ts@@ -6,7 +6,9 @@* reads, and the connector's long-poll loop through a fake Bot API transport — offset* advancement, the connect-time backlog drain, inbound routing as plain user input,* per-message mirroring with one reply thread per run in groups, 4096-safe chunking,- * non-text notices, and poll-failure status flips. No test opens real network.+ * non-text notices, poll-failure status flips, and the conflict path a second poller+ * produces (the 409 backoff, the connect-time webhook clear, and the actionable text the+ * transport maps a 409 to). No test opens real network.*/import { afterEach, beforeEach, describe, expect, it } from "vitest";import { assistantText } from "@prismshadow/penguin-core";@@ -27,9 +29,12 @@ import type {TelegramBotClient,TelegramBotUser,TelegramCredentials,+ TelegramTransport,TelegramUpdate,+ TelegramWebhookInfo,} from "../src/runtime/messaging/telegram-api.js";-import { telegramBotIdOf } from "../src/runtime/messaging/telegram-connector.js";+import { createTelegramTransport } from "../src/runtime/messaging/telegram-api.js";+import { TelegramConnector, telegramBotIdOf } from "../src/runtime/messaging/telegram-connector.js";import type {FeishuApiClient,FeishuCredentials,@@ -67,6 +72,13 @@ class FakeBotClient implements TelegramBotClient {private readonly t: FakeTelegramTransport,) {}+ webhookInfoCalls = 0;++ async getWebhookInfo(): Promise<TelegramWebhookInfo> {+ this.webhookInfoCalls++;+ return { url: this.t.webhookUrl };+ }+async getMe(): Promise<TelegramBotUser> {this.getMeCalls++;if (this.t.failGetMe !== null) throw new Error(this.t.failGetMe);@@ -147,6 +159,8 @@ class FakeTelegramTransport {failSend: string | null = null;/** Fails this many upcoming getUpdates calls. */failPolls = 0;+ /** The webhook registered on the bot; the empty string means none, as the Bot API encodes it. */+ webhookUrl = "";private nextUpdateId = 100;createClient(creds: TelegramCredentials): FakeBotClient {@@ -697,6 +711,40 @@ describe("telegram binding routes and connector loop", () => {expect(fake.lastClient().sawAbort).toBe(true);});+ it("the same Telegram message delivered under two update ids starts one Task", async () => {+ // What two pollers on one token do: each carries its own offset, so the same chat+ // message reaches the bridge twice wrapped in different updates. The dedupe key is+ // Telegram's own `chatId:message_id`, which is identical across both.+ await bindEnabled(SID);+ fake.push(privateText("deploy the build", 11));+ await waitFor(() => runs.length === 1);+ fake.push(privateText("deploy the build", 11));+ await settle(80);+ expect(runs).toHaveLength(1);+ // A different message with the same text is a different message.+ fake.push(privateText("deploy the build", 12));+ await waitFor(() => runs.length === 2);+ expect(runs.map((r) => r[0]!.text)).toEqual(["deploy the build", "deploy the build"]);+ });++ it("two syncs racing leave exactly one live poller (a second one would 409 the first)", async () => {+ await api.put(BASE(SID), { botToken: TOKEN });+ t.deps.messagingRepo.setEnabled(SID, "telegram", true);+ // The state toggle and a credential save both call sync(); nothing serialises them.+ // Telegram allows one getUpdates per token, so a leftover poller does not merely waste+ // a socket — it takes the live one's polls away with a 409.+ await Promise.all([t.deps.messaging.sync(SID), t.deps.messaging.sync(SID)]);+ await waitFor(() => t.deps.messaging.statusOf(SID, "telegram").state === "connected");+ await waitFor(() => fake.clients.filter((c) => c.parked).length === 1);+ expect(fake.clients.length).toBeGreaterThan(1);+ expect(fake.clients.filter((c) => c.parked)).toHaveLength(1);+ // And an inbound message starts one Task, not one per surviving poller.+ fake.push(privateText("hello once", 7));+ await waitFor(() => runs.length === 1);+ await settle(40);+ expect(runs).toHaveLength(1);+ });+it("the session list marks a telegram-ENABLED row with messagingChannel telegram", async () => {await bindEnabled(SID);const res = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);@@ -706,3 +754,300 @@ describe("telegram binding routes and connector loop", () => {expect(body.sessions.find((s) => s.sessionId === SID)?.messagingChannel).toBe("telegram");});});++// ---------------------------------------------------------------------------+// The conflict path: what a second poller on the same bot token does to the loop.+// Driven against the connector directly (no app, no HTTP) so a whole outage runs in+// milliseconds and the backoff the loop *would* sleep is observable.+// ---------------------------------------------------------------------------++/** Telegram's 409, verbatim, as the Bot API sends it when a second getUpdates takes over. */+const CONFLICT_DESCRIPTION =+ "Conflict: terminated by other getUpdates request; make sure that only one bot instance is running";++/** A bot client whose getMe always answers and whose getUpdates can be made to conflict. */+class ConflictBotClient implements TelegramBotClient {+ getMeCalls = 0;+ webhookInfoCalls = 0;+ pollCalls = 0;+ /** getUpdates rejects with the 409 while this is true. */+ conflict = false;+ /** Rejects the parked long poll (what Telegram does to the loser of the conflict). */+ private parkedReject: ((err: Error) => void) | null = null;++ constructor(+ readonly creds: TelegramCredentials,+ private readonly t: ConflictTransport,+ ) {}++ async getMe(): Promise<TelegramBotUser> {+ this.getMeCalls++;+ return { id: 7000000001, first_name: "Penguin Test", username: "penguin_test_bot" };+ }+ async getWebhookInfo(): Promise<TelegramWebhookInfo> {+ this.webhookInfoCalls++;+ return { url: this.t.webhookUrl };+ }+ async sendMessage(): Promise<void> {}+ getUpdates(args: {+ offset?: number;+ timeoutSec: number;+ signal: AbortSignal;+ }): Promise<TelegramUpdate[]> {+ this.pollCalls++;+ if (this.conflict)+ return Promise.reject(new Error(`getUpdates failed: ${CONFLICT_DESCRIPTION}`));+ if (args.timeoutSec === 0) return Promise.resolve([]);+ return new Promise((_resolve, reject) => {+ this.parkedReject = reject;+ args.signal.addEventListener("abort", () => reject(new Error("aborted")), { once: true });+ });+ }+ /** A second poller takes over: every poll from here on conflicts, parked one included. */+ startConflicting(): void {+ this.conflict = true;+ this.parkedReject?.(new Error(`getUpdates failed: ${CONFLICT_DESCRIPTION}`));+ }+}++class ConflictTransport implements TelegramTransport {+ readonly clients: ConflictBotClient[] = [];+ /** The webhook registered on the bot; the empty string means none, as the Bot API encodes it. */+ webhookUrl = "";+ createClient(creds: TelegramCredentials): ConflictBotClient {+ const client = new ConflictBotClient(creds, this);+ this.clients.push(client);+ return client;+ }+}++const settle = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));++describe("telegram poll loop under a persistent 409", () => {+ /**+ * Builds a connector whose backoff is instant but which records the delay the shipped+ * exponential curve would have slept, so a test can assert the curve without waiting on it.+ */+ function conflictConnector(): {+ connector: TelegramConnector;+ transport: ConflictTransport;+ backoff: number[];+ } {+ const transport = new ConflictTransport();+ const backoff: number[] = [];+ const connector = new TelegramConnector(transport, {+ retryDelayMs: (failures) => {+ backoff.push(Math.min(1000 * 2 ** (failures - 1), 60_000));+ return 1;+ },+ });+ return { connector, transport, backoff };+ }++ it("reports once and walks the backoff up, instead of re-polling every second forever", async () => {+ const { connector, transport, backoff } = conflictConnector();+ let errors = 0;+ let readies = 0;+ const conn = await connector.connect(+ { botToken: TOKEN },+ {+ onMessage: async () => {},+ onReady: () => {+ readies++;+ },+ onError: () => {+ errors++;+ },+ },+ );+ const bot = transport.clients[0]!;+ await waitFor(() => readies === 1);+ // A second program takes the token over. getMe keeps answering throughout — it is not+ // the call that conflicts — so nothing but a real getUpdates may end the outage.+ bot.startConflicting();+ await settle(150);+ conn.close();+ // One outage, one report, one error record. Before the fix this fired on every cycle.+ expect(errors).toBe(1);+ expect(readies).toBe(1);+ // The curve climbs to its ceiling. Before the fix the getMe-gated recovery reset the+ // counter every cycle, so this was [1000] and the loop hammered getUpdates at 1 Hz.+ expect(backoff.length).toBeGreaterThan(3);+ expect(backoff[0]).toBe(1000);+ expect(backoff.at(-1)).toBeGreaterThan(1000);+ expect(Math.max(...backoff)).toBeLessThanOrEqual(60_000);+ });++ it("recovers as soon as getUpdates stops conflicting, and fires onReady again", async () => {+ const { connector, transport } = conflictConnector();+ const inbound: string[] = [];+ let errors = 0;+ let readies = 0;+ const conn = await connector.connect(+ { botToken: TOKEN },+ {+ onMessage: async (msg) => {+ inbound.push(msg.text ?? "");+ },+ onReady: () => {+ readies++;+ },+ onError: () => {+ errors++;+ },+ },+ );+ const bot = transport.clients[0]!;+ await waitFor(() => readies === 1);+ bot.startConflicting();+ await waitFor(() => errors === 1);+ bot.conflict = false;+ await waitFor(() => readies === 2);+ expect(errors).toBe(1);+ conn.close();+ expect(inbound).toEqual([]);+ });++ it("probes for a webhook once per connection, before the first poll", async () => {+ const { connector, transport } = conflictConnector();+ let readies = 0;+ const conn = await connector.connect(+ { botToken: TOKEN },+ {+ onMessage: async () => {},+ onReady: () => {+ readies++;+ },+ onError: () => {},+ },+ );+ const bot = transport.clients[0]!;+ await waitFor(() => readies === 1);+ expect(bot.webhookInfoCalls).toBe(1);+ // A bot that answered "no webhook" is not asked again by a conflict-and-recover cycle.+ bot.startConflicting();+ await settle(30);+ bot.conflict = false;+ await waitFor(() => readies === 2);+ expect(bot.webhookInfoCalls).toBe(1);+ conn.close();+ });++ it("names the registered webhook and leaves the bot alone, then recovers once it is gone", async () => {+ const { connector, transport } = conflictConnector();+ const errors: string[] = [];+ let readies = 0;+ // The bot is pointed at a webhook before this connection is made.+ transport.webhookUrl = "https://hooks.example.test/telegram/abc123";+ const conn = await connector.connect(+ { botToken: TOKEN },+ {+ onMessage: async () => {},+ onReady: () => {+ readies++;+ },+ onError: (err) => {+ errors.push(err instanceof Error ? err.message : String(err));+ },+ },+ );+ await waitFor(() => errors.length === 1);+ // The URL is the whole point: "a webhook is set" does not say which one to go remove.+ expect(errors[0]).toContain("https://hooks.example.test/telegram/abc123");+ expect(errors[0]).toContain("recovers on its own");+ // Nothing was written to the bot, and the loop never got as far as polling.+ expect(transport.clients[0]!.pollCalls).toBe(0);+ expect(readies).toBe(0);++ // The user removes it elsewhere. No re-enable: the next probe passes and polling starts.+ transport.webhookUrl = "";+ await waitFor(() => readies === 1);+ expect(errors).toHaveLength(1);+ conn.close();+ });++ it("close() ends the poll: a closed connection issues no further calls", async () => {+ const { connector, transport } = conflictConnector();+ let readies = 0;+ const conn = await connector.connect(+ { botToken: TOKEN },+ {+ onMessage: async () => {},+ onReady: () => {+ readies++;+ },+ onError: () => {},+ },+ );+ const bot = transport.clients[0]!;+ await waitFor(() => readies === 1);+ conn.close();+ await settle(30);+ const pollsAtClose = bot.pollCalls;+ await settle(60);+ expect(bot.pollCalls).toBe(pollsAtClose);+ });+});++describe("telegram transport error mapping", () => {+ /** Runs one transport call against a stubbed fetch and returns the error it throws. */+ async function callWithBody(+ body: unknown,+ run: (bot: TelegramBotClient) => Promise<unknown>,+ ): Promise<string> {+ const original = globalThis.fetch;+ globalThis.fetch = (async () =>+ new Response(JSON.stringify(body), {+ status: 409,+ headers: { "content-type": "application/json" },+ })) as typeof fetch;+ try {+ const bot = createTelegramTransport().createClient({ botToken: TOKEN });+ await run(bot);+ return "";+ } catch (err) {+ return err instanceof Error ? err.message : String(err);+ } finally {+ globalThis.fetch = original;+ }+ }++ it("leads a getUpdates conflict with the action, not with Telegram's wording", async () => {+ const message = await callWithBody(+ { ok: false, error_code: 409, description: CONFLICT_DESCRIPTION },+ (bot) => bot.getUpdates({ timeoutSec: 0, signal: new AbortController().signal }),+ );+ // The first words survive the status line's truncation, and they name what to do.+ expect(message).toContain("another program is already polling this bot");+ expect(message).toContain("(code 409)");+ expect(message).not.toContain("Conflict: terminated");+ });++ it("names a leftover webhook as the reason polling is blocked", async () => {+ const message = await callWithBody(+ {+ ok: false,+ error_code: 409,+ description: "Conflict: can't use getUpdates method while webhook is active",+ },+ (bot) => bot.getUpdates({ timeoutSec: 0, signal: new AbortController().signal }),+ );+ expect(message).toContain("a webhook is set on this bot");+ });++ it("passes any other Bot API description through unchanged", async () => {+ const message = await callWithBody(+ { ok: false, error_code: 401, description: "Unauthorized" },+ (bot) => bot.getMe(),+ );+ expect(message).toBe("getMe failed: Unauthorized (code 401)");+ });++ it("never echoes the bot token, which the request URL embeds", async () => {+ const message = await callWithBody(+ { ok: false, error_code: 409, description: CONFLICT_DESCRIPTION },+ (bot) => bot.getUpdates({ timeoutSec: 0, signal: new AbortController().signal }),+ );+ expect(message).not.toContain(TOKEN);+ });+});diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.tsindex fdc666b0..6ce999ba 100644--- a/packages/server/test/messaging.test.ts+++ b/packages/server/test/messaging.test.ts@@ -696,4 +696,109 @@ describe("messaging binding routes and bridge", () => {t.deps.messaging.stop();expect(fake.connections[0]!.closed).toBe(true);});++ // —— Inbound deduplication ————————————————————————————————————————————————+ // A channel can hand the bridge the same message twice: a Feishu long connection+ // replays across a reconnect, and any connector that resumes an unconfirmed stream can+ // do the same. Nothing about `queueIfBusy` is idempotent, so both copies used to queue+ // and both used to run — reaching the chat AND the Web App, since a follow-up's input+ // is published to the Session channel.++ it("a redelivered message starts one Task, not two", async () => {+ await bindEnabled(SID);+ const replay = {+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_replayed",+ messageType: "text",+ content: JSON.stringify({ text: "deploy the build" }),+ };+ await fake.lastConnection().fire(replay);+ await waitFor(() => runs.length === 1);+ // The channel replays the identical event — same message id, same text.+ await fake.lastConnection().fire(replay);+ await settle(80);+ expect(runs).toHaveLength(1);+ expect(runs[0]![0]!.text).toBe("deploy the build");+ });++ it("does not swallow a genuine repeat: the same text sent twice runs twice", async () => {+ await bindEnabled(SID);+ const send = (messageId: string) =>+ fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId,+ messageType: "text",+ content: JSON.stringify({ text: "status?" }),+ });+ // Identity is the channel's message id, never the text — a user really does ask the+ // same question twice, and swallowing that is worse than the duplicate it prevents.+ await send("om_first");+ await waitFor(() => runs.length === 1);+ await send("om_second");+ await waitFor(() => runs.length === 2);+ expect(runs.map((r) => r[0]!.text)).toEqual(["status?", "status?"]);+ });++ it("dedupes a replayed non-text message too, so the text-only notice is sent once", async () => {+ await bindEnabled(SID);+ const sticker = {+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_sticker",+ messageType: "sticker",+ content: JSON.stringify({}),+ };+ await fake.lastConnection().fire(sticker);+ await waitFor(() => fake.allSends().length === 1);+ await fake.lastConnection().fire(sticker);+ await settle(80);+ expect(fake.allSends().filter((x) => x.text === MESSAGING_TEXT_ONLY_NOTICE)).toHaveLength(1);+ });++ it("bounds what it remembers: an id far enough back is forgotten rather than kept forever", async () => {+ await bindEnabled(SID);+ const fire = (messageId: string) =>+ fake.lastConnection().fire({+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId,+ messageType: "text",+ content: JSON.stringify({ text: messageId }),+ });+ // 65 distinct messages: one past the per-binding cap, so the first is evicted. The+ // cap is the point — a server that runs for months must not accumulate every id it+ // has ever seen — and forgetting the oldest is the price it buys.+ for (let i = 0; i < 65; i += 1) await fire(`om_bound_${i}`);+ await waitFor(() => runs.length === 65, 10_000);+ await fire("om_bound_0");+ await waitFor(() => runs.length === 66, 10_000);+ // The most recent ids are still remembered.+ await fire("om_bound_64");+ await settle(80);+ expect(runs).toHaveLength(66);+ });++ it("remembers across a connector restart, so a re-enable does not replay a message", async () => {+ await bindEnabled(SID);+ const evt = {+ chatId: "oc_chat_1",+ chatType: "p2p",+ messageId: "om_across_restart",+ messageType: "text",+ content: JSON.stringify({ text: "once only" }),+ };+ await fake.lastConnection().fire(evt);+ await waitFor(() => runs.length === 1);+ // Save-while-enabled restarts the connector with a fresh entry; the memory of what has+ // already been processed belongs to the binding, not to one connection.+ expect((await api.post(`${BASE(SID)}/state`, { enabled: false })).status).toBe(200);+ expect((await api.post(`${BASE(SID)}/state`, { enabled: true })).status).toBe(200);+ await fake.lastConnection().fire(evt);+ await settle(80);+ expect(runs).toHaveLength(1);+ });});++const settle = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));diff --git a/packages/web/src/features/messaging/messaging-binding-editor.tsx b/packages/web/src/features/messaging/messaging-binding-editor.tsxindex dc4fdb1a..4f6f6957 100644--- a/packages/web/src/features/messaging/messaging-binding-editor.tsx+++ b/packages/web/src/features/messaging/messaging-binding-editor.tsx@@ -500,28 +500,34 @@ export function MessagingBindingBody({ b }: { b: MessagingBindingEditorState }){/* The connection toggle + live status on one line: the Switch is the intent, thetone-colored text is what the connection actually is right now. At most onechannel is enabled per Session — the hint under the probes names what gates the- switch. The error state's `lastError` stays on this line by truncating inside its- own flex track, so a long message never grows the row and pushes the probes. */}- <div className="flex flex-wrap items-center gap-2 text-xs">- <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">- <Switch- checked={facts.enabled}- disabled={b.toggleBlocked}- onChange={(v) => void b.toggleEnabled(v)}- />- {S.messaging.enabled}- </label>- <span className="ml-2 text-gray-500 dark:text-gray-400">{S.messaging.statusLabel}</span>- <span- {...(facts.status.lastError !== undefined ? { title: facts.status.lastError } : {})}- className={`font-medium ${toneInk[STATUS_TONE[facts.status.state]]}`}- >- {S.messaging.status[facts.status.state]}- </span>+ switch. The error state's `lastError` gets its own line below rather than a track+ on this one: the connection failures worth reporting name what to do about them+ ("another program is already polling this bot …"), and a share of a row that+ already carries a switch, a label and a status word truncates that to a couple of+ words. Clamped to two lines so an error still cannot push the probes far, with+ the whole message on hover. */}+ <div className="space-y-1">+ <div className="flex flex-wrap items-center gap-2 text-xs">+ <label className="flex items-center gap-2 text-sm text-gray-700 dark:text-gray-300">+ <Switch+ checked={facts.enabled}+ disabled={b.toggleBlocked}+ onChange={(v) => void b.toggleEnabled(v)}+ />+ {S.messaging.enabled}+ </label>+ <span className="ml-2 text-gray-500 dark:text-gray-400">{S.messaging.statusLabel}</span>+ <span className={`font-medium ${toneInk[STATUS_TONE[facts.status.state]]}`}>+ {S.messaging.status[facts.status.state]}+ </span>+ </div>{facts.status.state === "error" && facts.status.lastError !== undefined && (- <span className="min-w-0 flex-1 truncate text-gray-400 dark:text-gray-500">+ <p+ title={facts.status.lastError}+ className="line-clamp-2 text-xs break-words text-gray-500 dark:text-gray-400"+ >{facts.status.lastError}- </span>+ </p>)}</div>{/* Entry-level probes — the MCP dialog idiom: standalone buttons, results as toasts. */}@@ -681,6 +687,7 @@ export function MessagingBindingHelp({ channel }: { channel: MessagingChannel })<ul className="list-disc space-y-1 pl-4"><li>{S.messaging.troubleNoChat}</li><li>{S.messaging.troubleConnError}</li>+ {channel === "telegram" && <li>{S.messaging.troubleOnePoller}</li>}</ul></HelpFold></div>diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex e9d734bc..8130a91d 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -1863,11 +1863,13 @@ Scenarios:faqSetupTitle: "Set up the bot",faqWhatTitle: "What binding does",faqTroubleTitle: "Troubleshooting",- /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials). */+ /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token). */troubleNoChat:"“Send test message” disabled? The bot must have received one message first, so it knows which chat to send to.",troubleConnError:"Connection status shows an error? Check the credentials; for Feishu also confirm the API domain and the long-connection event subscription.",+ troubleOnePoller:+ "Telegram reports that another program is polling? A Bot Token serves exactly one program at a time — close the other PenguinHarness server or bot script using it, or give this conversation a bot of its own.",},/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex a4e68bca..da5cfb7d 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -1824,10 +1824,12 @@ Benchmark:faqSetupTitle: "如何创建机器人",faqWhatTitle: "绑定后会发生什么",faqTroubleTitle: "常见问题",- /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials). */+ /** Troubleshooting entries (bot must be messaged once; connection errors point at credentials; one poller per Telegram token). */troubleNoChat: "「发送测试消息」不可用?机器人要先收到过一条消息,才知道要发到哪个会话。",troubleConnError:"连接状态显示错误?检查凭证是否正确;飞书还需确认 API 域名与事件订阅方式(长连接)。",+ troubleOnePoller:+ "Telegram 提示已有其他程序在轮询?一个 Bot Token 同一时刻只能被一个程序使用——关闭正在占用它的另一个 PenguinHarness 服务端或机器人脚本,或为该会话单独建一个机器人。",},/** Subagents side panel: call-graph of the latest Task + the selected child conversation. */diff --git a/packages/web/test/messaging-binding-editor.test.ts b/packages/web/test/messaging-binding-editor.test.tsindex cf5143bd..55c407a9 100644--- a/packages/web/test/messaging-binding-editor.test.ts+++ b/packages/web/test/messaging-binding-editor.test.ts@@ -1,11 +1,12 @@/*** The messaging binding editor's rendered shape (src/features/messaging/messaging-binding-editor.tsx).*- * Four rules this pins, all of which are invisible to a type checker: the form opens on its+ * Five rules this pins, all of which are invisible to a type checker: the form opens on its* FIELDS (the explanation lives in the collapsed FAQ under the save area, not above the first* input), each channel's developer-console link rides the credential field's corner, a stored- * secret is removed by the models-page clear checkbox rather than an unbind button — and that- * checkbox is gated, on screen, while the channel holds the connection.+ * secret is removed by the models-page clear checkbox rather than an unbind button — that+ * checkbox is gated, on screen, while the channel holds the connection — and a connection+ * error's detail reaches the reader whole rather than as a few words of a shared row.*/import { describe, expect, it } from "vitest";import { createElement } from "react";@@ -100,6 +101,33 @@ describe("MessagingBindingBody", () => {expect(live).toContain(S.messaging.disableBeforeClearHint);});+ it("gives a connection error its own line, whole, instead of a share of the status row", () => {+ // The connection failures worth reporting name the action in the sentence — a share of+ // a row that already carries a switch, a label and a status word cut this one to+ // "Conflict: ter", which tells the reader nothing they can act on.+ const lastError =+ "getUpdates failed: another program is already polling this bot — one bot token can serve only one PenguinHarness server at a time (code 409)";+ const html = render(+ stateOf("telegram", {+ telegram: {+ ...DARK,+ secretConfigured: true,+ enabled: true,+ status: { state: "error", lastError },+ },+ }),+ );+ // A paragraph of its own, carrying the message whole.+ expect(html).toContain(`>${lastError}</p>`);+ // Outside the toggle row: the row closes before the message begins.+ const rowAt = html.indexOf("flex flex-wrap items-center gap-2 text-xs");+ expect(rowAt).toBeGreaterThanOrEqual(0);+ expect(html.slice(rowAt, html.indexOf(lastError, rowAt))).toContain("</div>");+ // Bounded so an error still cannot push the probes far, with the whole text on hover.+ expect(html).toContain("line-clamp-2");+ expect(html).toContain(`title="${lastError}"`);+ });+it("shows the switch's gating reason when the other channel holds the connection", () => {const hint = S.messaging.otherEnabledHint(S.messaging.channelName.feishu);const html = render(