Self-improving AI Employees for everyone
Python ai-agentsai-employeeai-employeesassistantautonomous-agentsco-employeescompanygrok-botinstinctloop-agentsmuseown-your-datapersonalself-hosted
fix(telegram): three layers of owner-detection robustness
trohitgf746ddfac647
diff --git a/client/src/components/credentials/catalogueAdapter.ts b/client/src/components/credentials/catalogueAdapter.tsindex cb52cfd3..c9704588 100644--- a/client/src/components/credentials/catalogueAdapter.ts+++ b/client/src/components/credentials/catalogueAdapter.ts@@ -143,6 +143,7 @@ function buildFields(defs: ServerFieldDef[] | undefined): FieldDef[] | undefinedplaceholder: d.placeholder,default: d.default,required: d.required,+ help: d.help,}));}diff --git a/client/src/components/credentials/panels/ApiKeyPanel.tsx b/client/src/components/credentials/panels/ApiKeyPanel.tsxindex 6b69986f..c13b1853 100644--- a/client/src/components/credentials/panels/ApiKeyPanel.tsx+++ b/client/src/components/credentials/panels/ApiKeyPanel.tsx@@ -9,6 +9,9 @@ import { CheckCircle } from 'lucide-react';import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';import { Badge } from '@/components/ui/badge';import { Alert, AlertDescription } from '@/components/ui/alert';+import { Input } from '@/components/ui/input';+import { Label } from '@/components/ui/label';+import { ActionButton } from '@/components/ui/action-button';import ApiKeyInput from '../../ui/ApiKeyInput';import { useCredentialPanel } from '../useCredentialPanel';import { ProviderDefaultsSection, LlmUsageSection, ApiUsageSection } from '../sections';@@ -17,7 +20,12 @@ import type { ProviderConfig } from '../types';const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ config, visible }) => {const panel = useCredentialPanel(config, visible);+ // Primary credential field (validate / connect target — bot token,+ // api key, etc.). Secondary fields (telegram_owner_chat_id,+ // optional metadata) render below as plain text inputs with their+ // own save button — they don't go through validate.const field = config.fields?.[0];+ const secondaryFields = (config.fields ?? []).slice(1);// Single source of truth: panel.values (server-cached query data,// includes backend-served catalogue defaults like local-LLM Base URL).@@ -95,6 +103,26 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ c</Alert>)}+ {/* Secondary fields (e.g. telegram_owner_chat_id). Plain text ++ shadcn Input + Save ActionButton — bypasses the validate+ path because these are operator metadata, not credentials+ to probe upstream. Save writes via the same auth_service+ path the primary uses (panel.actions.save). */}+ {secondaryFields.map((sf) => (+ <SecondaryFieldRow+ key={sf.key}+ fieldKey={sf.key}+ label={sf.label}+ placeholder={sf.placeholder}+ help={sf.help}+ secret={sf.secret}+ value={panel.values[sf.key] ?? ''}+ onChange={(v) => panel.form.setFieldValue(sf.key, v)}+ onSave={() => panel.actions.save(sf.key, panel.values[sf.key] ?? '')}+ loading={panel.loading === 'save'}+ />+ ))}+{config.hasDefaults && <ProviderDefaultsSection providerId={config.id} />}{config.hasDefaults && <LlmUsageSection providerId={config.id} providerName={config.name} />}{config.usageService && <ApiUsageSection service={config.usageService} serviceName={config.name} />}@@ -102,4 +130,52 @@ const ApiKeyPanel: React.FC<{ config: ProviderConfig; visible: boolean }> = ({ c);};+interface SecondaryFieldRowProps {+ fieldKey: string;+ label: string;+ placeholder?: string;+ help?: string;+ secret?: boolean;+ value: string;+ onChange: (v: string) => void;+ onSave: () => void;+ loading: boolean;+}++/** Plain text/password field below the primary credential — for+ * operator metadata like telegram_owner_chat_id. shadcn Input + Label+ * + ActionButton; controlled by panel.values, saves via+ * panel.actions.save which writes through to the credentials DB. */+const SecondaryFieldRow: React.FC<SecondaryFieldRowProps> = ({+ fieldKey, label, placeholder, help, secret, value, onChange, onSave, loading,+}) => (+ <Card>+ <CardContent className="flex flex-col gap-2 pt-4">+ <Label htmlFor={`cred-${fieldKey}`} className="text-sm font-medium">+ {label}+ </Label>+ <div className="flex gap-2">+ <Input+ id={`cred-${fieldKey}`}+ type={secret ? 'password' : 'text'}+ value={value}+ onChange={(e) => onChange(e.target.value)}+ placeholder={placeholder}+ className="flex-1"+ />+ <ActionButton+ intent="save"+ onClick={onSave}+ disabled={loading}+ >+ Save+ </ActionButton>+ </div>+ {help && (+ <p className="text-xs text-muted-foreground">{help}</p>+ )}+ </CardContent>+ </Card>+);+export default ApiKeyPanel;diff --git a/client/src/components/credentials/types.ts b/client/src/components/credentials/types.tsindex cdde662a..fb195ea6 100644--- a/client/src/components/credentials/types.ts+++ b/client/src/components/credentials/types.ts@@ -25,6 +25,8 @@ export interface FieldDef {/** Pre-fill value when nothing stored. See ServerFieldDef.default. */default?: string;required?: boolean;+ /** Help text shown beneath the input (always visible). */+ help?: string;}// ============================================================================diff --git a/client/src/hooks/useCatalogueQuery.ts b/client/src/hooks/useCatalogueQuery.tsindex c94b8e59..56daf633 100644--- a/client/src/hooks/useCatalogueQuery.ts+++ b/client/src/hooks/useCatalogueQuery.ts@@ -52,6 +52,10 @@ export interface ServerFieldDef {without typing. */default?: string;required?: boolean;+ /** Multi-line description shown under the input (e.g. why this field+ exists, where to find the value). Different from `placeholder` —+ this is always visible. */+ help?: string;}/** Raw status-row descriptor — uses a string `ok_field` instead of a callable. */diff --git a/server/config/credential_providers.json b/server/config/credential_providers.jsonindex c017cb99..cb702369 100644--- a/server/config/credential_providers.json+++ b/server/config/credential_providers.json@@ -283,9 +283,18 @@"secret": true,"placeholder": "123456789:ABCdefGHIjklMNOpqrSTUvwxYZ","required": true+ },+ {+ "key": "telegram_owner_chat_id",+ "label": "Your Chat ID (optional)",+ "type": "text",+ "secret": false,+ "placeholder": "e.g. 123456789 — DM @userinfobot to get yours",+ "required": false,+ "help": "Set this to make telegramSend(recipient_type=self) route to your account immediately. If left blank, the bot auto-captures it from the first private DM you send after connecting."}],- "instructions": "Get a bot token from @BotFather on Telegram. After connecting, send any message to your bot to register as the owner."+ "instructions": "Get a bot token from @BotFather on Telegram. To use the 'Self' recipient on telegramSend, either fill in your Chat ID below or DM your bot once after connecting."},"gmail": {diff --git a/server/nodes/telegram/_service.py b/server/nodes/telegram/_service.pyindex 5996b4e3..e9d3bfc4 100644--- a/server/nodes/telegram/_service.py+++ b/server/nodes/telegram/_service.py@@ -257,12 +257,11 @@ class TelegramService(ServiceSingleton):}logger.info(f"[Telegram] Bot validated: @{me.username} (ID: {me.id})")- self._polling_task = asyncio.create_task(self._run_polling())- self._connected = True-- await self._broadcast_status()-- # Hydrate runtime owner_chat_id from stored credential.+ # Hydrate runtime owner_chat_id from stored credential+ # BEFORE polling starts so the pre-poll peek below can+ # short-circuit when we already know the owner. (Was+ # previously after polling -- race-prone with the+ # capture path in _on_message_received.)saved_owner = secrets.get("telegram_owner_chat_id")if saved_owner is None:try:@@ -277,6 +276,28 @@ class TelegramService(ServiceSingleton):except (TypeError, ValueError):pass+ # Pre-poll peek for historical owner capture.+ # Polling starts with drop_pending_updates=True+ # (correct hygiene for operational events -- we do+ # not want stale group spam replaying on every+ # restart) but that ALSO drops any DM the user sent+ # before the bot connected. Without this peek the+ # only path to owner capture is "DM the bot AFTER+ # polling has started", which is the surprising UX+ # that produces "Bot owner not detected" on every+ # fresh setup. get_updates() with no offset returns+ # the same pending queue without advancing it, so+ # the subsequent start_polling drop-pass is a no-op+ # for these messages -- they were going to be+ # dropped anyway, we just inspect them first.+ if self._owner_chat_id is None:+ await self._capture_owner_from_pending_updates()++ self._polling_task = asyncio.create_task(self._run_polling())+ self._connected = True++ await self._broadcast_status()+logger.info(f"[Telegram] Connected and polling started for @{me.username}")return {"success": True,@@ -355,36 +376,116 @@ class TelegramService(ServiceSingleton):self._connected = Falseawait self._broadcast_status()+ async def _capture_owner_from_pending_updates(self) -> None:+ """Inspect the bot's pending update queue (24h Telegram retention)+ for any private message and capture the owner if found. Called+ from connect() before polling starts -- after polling begins the+ ``drop_pending_updates=True`` flag throws these away unread.++ Uses the same atomic-write-through invariant as+ ``_on_message_received``: persist FIRST, set in-memory only on+ successful persist, so a restart can re-capture cleanly if the+ DB write fails.+ """+ try:+ # offset=None / 0 returns the queue without advancing the+ # confirmed offset. allowed_updates=["message"] skips+ # callback_query / poll / inline_query payloads we don't+ # care about for owner capture.+ pending = await self._bot.get_updates(+ timeout=0,+ allowed_updates=["message"],+ )+ except Exception as e:+ logger.warning(+ f"[Telegram] Pre-poll owner-capture peek failed "+ f"({type(e).__name__}): {e}. Owner capture will fall "+ f"back to live polling once the user DMs the bot.",+ )+ return++ for upd in pending:+ m = upd.message+ if not (m and m.chat and m.chat.type == "private" and m.from_user):+ continue+ captured_id = m.from_user.id+ try:+ from services.plugin.deps import get_auth_service+ await get_auth_service().store_api_key(+ "telegram_owner_chat_id",+ str(captured_id),+ models=[],+ )+ except Exception as persist_err:+ logger.error(+ f"[Telegram] FAILED to persist retroactively-captured "+ f"owner {captured_id}: {persist_err}. Workaround: "+ f"set TELEGRAM_OWNER_CHAT_ID={captured_id} in .env",+ exc_info=True,+ )+ return+ self._owner_chat_id = captured_id+ logger.info(+ f"[Telegram] Owner retroactively captured from pending "+ f"updates: @{m.from_user.username} (ID: {captured_id})"+ )+ return+async def _on_message_received(self, update: Update, context: ContextTypes.DEFAULT_TYPE):try:if not update.message:returnmsg = update.message- # Auto-capture bot owner from first private message+ # Auto-capture bot owner from first private message.+ # ATOMIC WRITE-THROUGH: persist to credentials DB FIRST, set+ # in-memory only on success. The previous order+ # (in-memory then await persist, with WARNING-level logging+ # of failures) had a silent failure mode: if the persist+ # raised, the rest of the process lifetime worked correctly,+ # then the next restart wiped in-memory and DB had nothing+ # -- subsequent telegramSend(recipient_type=self) failed+ # forever with "Bot owner not detected" and no trace of+ # what went wrong. The new order preserves the invariant+ # "in-memory has owner => DB has owner" so a restart can+ # always re-capture from the next inbound private message.if (self._owner_chat_id is Noneand msg.chat.type == "private"and msg.from_user):- self._owner_chat_id = msg.from_user.id- logger.info(- f"[Telegram] Owner detected: @{msg.from_user.username} "- f"(ID: {msg.from_user.id})"- )+ captured_id = msg.from_user.id+ persist_ok = Falsetry:from services.plugin.deps import get_auth_service- auth = get_auth_service()- await auth.store_api_key(+ await get_auth_service().store_api_key("telegram_owner_chat_id",- str(msg.from_user.id),+ str(captured_id),models=[],)+ persist_ok = Trueexcept Exception as persist_err:- logger.warning(- f"[Telegram] Failed to persist owner chat_id: {persist_err}"+ # ERROR-level so the failure surfaces in default+ # uvicorn output, not just DEBUG. Includes the+ # captured id so the user can manually set+ # TELEGRAM_OWNER_CHAT_ID in .env as an immediate+ # workaround. exc_info=True so the underlying+ # cause (encryption not initialised, DB locked,+ # disk full, ...) is visible.+ logger.error(+ f"[Telegram] FAILED to persist owner chat_id "+ f"{captured_id}: {persist_err}. The bot will not "+ f"recover this binding on restart. Workaround: "+ f"set TELEGRAM_OWNER_CHAT_ID={captured_id} in .env",+ exc_info=True,)- await self._broadcast_status()+ if persist_ok:+ self._owner_chat_id = captured_id+ logger.info(+ f"[Telegram] Owner detected and persisted: "+ f"@{msg.from_user.username} (ID: {captured_id})"+ )+ await self._broadcast_status()event_data = self._format_message(msg)logger.info(