The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): Telegram QR quick setup + persistent restart banner on Messaging
Teknium52dea2c7d9c5
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex ac9293c3236..b21be619de8 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -130,6 +130,7 @@"motion": "12.42.2","nanostores": "1.4.2","node-pty": "1.1.0",+ "qrcode": "1.5.4","radix-ui": "1.6.7","react": "19.2.7","react-arborist": "3.13.2",@@ -166,6 +167,7 @@"@types/d3-force": "3.0.10","@types/hast": "3.0.5","@types/node": "22.20.1",+ "@types/qrcode": "1.5.6","@types/react": "19.2.17","@types/react-dom": "19.2.3","@vitejs/plugin-react": "6.0.3",diff --git a/apps/desktop/src/api/messaging.ts b/apps/desktop/src/api/messaging.tsindex b49bdc93b82..21a5eabb09e 100644--- a/apps/desktop/src/api/messaging.ts+++ b/apps/desktop/src/api/messaging.ts@@ -4,6 +4,9 @@ import type {MessagingPlatformUpdate,PairingResponse,PairingUser,+ TelegramOnboardingApplyResponse,+ TelegramOnboardingStartResponse,+ TelegramOnboardingStatusResponse,WebhookCreatePayload,WebhookCreateResponse,WebhookEnableResponse,@@ -43,6 +46,54 @@ export function testMessagingPlatform(})}+// -- Telegram QR onboarding ---------------------------------------------------+// Pairing state lives in the memory of the backend process that started it, so+// every call in one flow carries the SAME profile scope — the Electron router+// picks the backend from it, and a mismatched apply would 404 the pairing.++export function startTelegramOnboarding(+ botName?: string,+ profile?: null | string+): Promise<TelegramOnboardingStartResponse> {+ return hermesApi<TelegramOnboardingStartResponse>({+ ...profileScoped(profile),+ path: '/api/messaging/telegram/onboarding/start',+ method: 'POST',+ body: botName ? { bot_name: botName } : {}+ })+}++export function getTelegramOnboardingStatus(+ pairingId: string,+ profile?: null | string+): Promise<TelegramOnboardingStatusResponse> {+ return hermesApi<TelegramOnboardingStatusResponse>({+ ...profileScoped(profile),+ path: `/api/messaging/telegram/onboarding/${encodeURIComponent(pairingId)}`+ })+}++export function applyTelegramOnboarding(+ pairingId: string,+ allowedUserIds: string[],+ profile?: null | string+): Promise<TelegramOnboardingApplyResponse> {+ return hermesApi<TelegramOnboardingApplyResponse>({+ ...profileScoped(profile),+ path: `/api/messaging/telegram/onboarding/${encodeURIComponent(pairingId)}/apply`,+ method: 'POST',+ body: { allowed_user_ids: allowedUserIds, ...profileScoped(profile) }+ })+}++export function cancelTelegramOnboarding(pairingId: string, profile?: null | string): Promise<{ ok: boolean }> {+ return hermesApi<{ ok: boolean }>({+ ...profileScoped(profile),+ path: `/api/messaging/telegram/onboarding/${encodeURIComponent(pairingId)}`,+ method: 'DELETE'+ })+}+// -- Pairing (who may DM the bot) --------------------------------------------// Unknown DMers get a one-time code and land in `pending` until an admin// approves them. Approval grants on the row's `request_id`, never on the code:diff --git a/apps/desktop/src/app/messaging/index.test.tsx b/apps/desktop/src/app/messaging/index.test.tsxindex 75bb9701e6f..ff67c14f0cd 100644--- a/apps/desktop/src/app/messaging/index.test.tsx+++ b/apps/desktop/src/app/messaging/index.test.tsx@@ -11,6 +11,11 @@ const getPairing = vi.fn()const approvePairing = vi.fn()const revokePairing = vi.fn()const openExternalLink = vi.fn()+const runGatewayRestart = vi.fn()+const watchGatewayRestartOutcome = vi.fn()+const startTelegramOnboarding = vi.fn()+const getTelegramOnboardingStatus = vi.fn()+const applyTelegramOnboarding = vi.fn()vi.mock('@/hermes', () => ({approvePairing: (platformId: string, requestId: string, profile?: null | string) =>@@ -21,10 +26,18 @@ vi.mock('@/hermes', () => ({revokePairing: (platformId: string, userId: string, profile?: null | string) =>revokePairing(platformId, userId, profile),setApiRequestProfile: vi.fn(),+ applyTelegramOnboarding: (pairingId: string, ids: string[], profile?: null | string) =>+ applyTelegramOnboarding(pairingId, ids, profile),+ cancelTelegramOnboarding: vi.fn(async () => ({ ok: true })),+ getTelegramOnboardingStatus: (pairingId: string, profile?: null | string) =>+ getTelegramOnboardingStatus(pairingId, profile),+ startTelegramOnboarding: (botName?: string, profile?: null | string) => startTelegramOnboarding(botName, profile),updateMessagingPlatform: (id: string, body: unknown, profile?: null | string) =>updateMessagingPlatform(id, body, profile)}))+vi.mock('qrcode', () => ({ toDataURL: vi.fn(async () => 'data:image/png;base64,QR') }))+// Keep store/profile's side-effecting imports inert (pulled in via the shared// settings scope store) — same seam as store/profile.test.ts.vi.mock('@/store/gateway', () => ({@@ -45,9 +58,15 @@ vi.mock('@/store/notifications', () => ({notifyError: vi.fn()}))-vi.mock('@/store/system-actions', () => ({- runGatewayRestart: vi.fn()-}))+vi.mock('@/store/system-actions', async () => {+ const { atom } = await import('nanostores')++ return {+ $gatewayRestarting: atom(false),+ runGatewayRestart: () => runGatewayRestart(),+ watchGatewayRestartOutcome: () => watchGatewayRestartOutcome()+ }+})function platform(patch: Partial<MessagingPlatformInfo> = {}): MessagingPlatformInfo {return {@@ -67,6 +86,8 @@ function platform(patch: Partial<MessagingPlatformInfo> = {}): MessagingPlatformbeforeEach(() => {updateMessagingPlatform.mockResolvedValue({ ok: true, platform: 'teams' })getPairing.mockResolvedValue({ approved: [], pending: [] })+ runGatewayRestart.mockResolvedValue(true)+ watchGatewayRestartOutcome.mockResolvedValue(true)})afterEach(() => {@@ -232,3 +253,101 @@ describe('MessagingView pairing', () => {expect(getPairing).not.toHaveBeenCalled()})})++describe('MessagingView restart banner', () => {+ const tokenField = {+ advanced: false,+ description: 'Bot token',+ is_password: true,+ is_set: false,+ key: 'TEAMS_TOKEN',+ prompt: 'Token',+ redacted_value: null,+ required: true,+ url: null+ }++ it('keeps a restart banner up after a save until the restart completes', async () => {+ // A toast vanishes; the credential still only loads on the next gateway+ // start. The page must keep saying so — and only stop once a restart+ // actually succeeded, not merely because one was requested.+ getMessagingPlatforms.mockResolvedValue({ platforms: [platform({ env_vars: [tokenField] })] })+ runGatewayRestart.mockResolvedValueOnce(false).mockResolvedValueOnce(true)++ await renderMessaging()++ fireEvent.change(await screen.findByLabelText('Token'), { target: { value: 'secret-1' } })+ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: /Save changes/ }))+ })++ await waitFor(() => expect(updateMessagingPlatform).toHaveBeenCalled())+ const restartNow = await screen.findByRole('button', { name: 'Restart now' })++ await act(async () => {+ fireEvent.click(restartNow)+ })+ // First attempt failed: banner stays.+ expect(await screen.findByRole('button', { name: 'Restart now' })).toBeTruthy()++ await act(async () => {+ fireEvent.click(screen.getByRole('button', { name: 'Restart now' }))+ })+ await waitFor(() => expect(screen.queryByRole('button', { name: 'Restart now' })).toBeNull())+ expect(runGatewayRestart).toHaveBeenCalledTimes(2)+ })+})++describe('MessagingView Telegram quick setup', () => {+ it('runs the QR pairing to apply on the page scope and watches the backend restart', async () => {+ // Every call of one pairing must hit the SAME backend (the pairing lives in+ // that process's memory), so start/status/apply all carry the page's scope+ // and apply names the profile the credentials land in.+ const { $settingsScopeOverride } = await import('@/store/settings-scope')+ $settingsScopeOverride.set('worker')+ getMessagingPlatforms.mockResolvedValue({+ platforms: [platform({ id: 'telegram', name: 'Telegram', state: 'not_configured' })]+ })+ startTelegramOnboarding.mockResolvedValue({+ deep_link: 'https://t.me/BotFather?start=abc',+ expires_at: new Date(Date.now() + 600_000).toISOString(),+ pairing_id: 'pair-1',+ qr_payload: 'tg://pair',+ suggested_username: 'hermes_bot'+ })+ getTelegramOnboardingStatus.mockResolvedValue({+ bot_username: 'hermes_bot',+ expires_at: new Date(Date.now() + 600_000).toISOString(),+ owner_user_id: '8792111505',+ status: 'ready'+ })+ applyTelegramOnboarding.mockResolvedValue({+ needs_restart: false,+ ok: true,+ platform: 'telegram',+ restart_started: true+ })++ try {+ await renderMessaging()++ await act(async () => {+ fireEvent.click(await screen.findByRole('button', { name: /Create with QR/ }))+ })+ await waitFor(() => expect(startTelegramOnboarding).toHaveBeenCalledWith(undefined, 'worker'))++ const save = await screen.findByRole('button', { name: /Save and restart/ }, { timeout: 4000 })+ expect(getTelegramOnboardingStatus).toHaveBeenCalledWith('pair-1', 'worker')+ expect(screen.getByText('8792111505')).toBeTruthy()++ await act(async () => {+ fireEvent.click(save)+ })++ await waitFor(() => expect(applyTelegramOnboarding).toHaveBeenCalledWith('pair-1', ['8792111505'], 'worker'))+ await waitFor(() => expect(watchGatewayRestartOutcome).toHaveBeenCalled())+ } finally {+ $settingsScopeOverride.set(null)+ }+ })+})diff --git a/apps/desktop/src/app/messaging/index.tsx b/apps/desktop/src/app/messaging/index.tsxindex 1611dcf3c20..30051383541 100644--- a/apps/desktop/src/app/messaging/index.tsx+++ b/apps/desktop/src/app/messaging/index.tsx@@ -4,6 +4,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { PageLoader } from '@/components/page-loader'import { StatusDot, type StatusTone } from '@/components/status-dot'+import { Alert, AlertDescription } from '@/components/ui/alert'import { Button } from '@/components/ui/button'import { ConfirmDialog } from '@/components/ui/confirm-dialog'import { DisclosureCaret } from '@/components/ui/disclosure-caret'@@ -19,17 +20,18 @@ import {type MessagingPlatformInfo,type PairingUser,revokePairing,+ type TelegramOnboardingApplyResponse,updateMessagingPlatform} from '@/hermes'import { type Translations, useI18n } from '@/i18n'import { openExternalLink } from '@/lib/external-link'-import { ExternalLink, Save, Trash2 } from '@/lib/icons'+import { AlertTriangle, ExternalLink, RefreshCw, Save, Trash2 } from '@/lib/icons'import { normalize } from '@/lib/text'import { cn } from '@/lib/utils'import { $changeEventsAvailable, $pairingChangeTick, $platformsChangeTick } from '@/store/live-sync'import { notify, notifyError } from '@/store/notifications'import { $settingsRequestProfile } from '@/store/settings-scope'-import { runGatewayRestart } from '@/store/system-actions'+import { $gatewayRestarting, runGatewayRestart, watchGatewayRestartOutcome } from '@/store/system-actions'import { useRefreshHotkey } from '../hooks/use-refresh-hotkey'import { useRouteEnumParam } from '../hooks/use-route-enum-param'@@ -41,6 +43,7 @@ import { SettingsProfileScope } from '../settings/profile-scope'import type { SetStatusbarItemGroup } from '../shell/statusbar-controls'import { PlatformAvatar } from './platform-icon'+import { TelegramQrSetup } from './telegram-qr-setup'interface MessagingViewProps extends React.ComponentProps<'section'> {setStatusbarItemGroup?: SetStatusbarItemGroup@@ -131,9 +134,12 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .// Shared settings "Applies to" scope, request-shaped (undefined → follow// the active profile; the API helpers treat null as "target primary").const scopeProfile = useStore($settingsRequestProfile)- // Both save/toggle toasts offer the same one-click restart.- const restartGatewayAction = { label: t.commandCenter.restartGateway, onClick: () => void runGatewayRestart() }const [platforms, setPlatforms] = useState<MessagingPlatformInfo[] | null>(null)+ // A saved credential/toggle only takes effect on the next gateway start, so a+ // vanishing toast is not enough: the page keeps a banner up until a restart+ // actually happens (dashboard parity). Cleared on a completed restart.+ const [restartNeeded, setRestartNeeded] = useState(false)+ const gatewayRestarting = useStore($gatewayRestarting)const [pairing, setPairing] = useState<{ approved: PairingUser[]; pending: PairingUser[] }>({approved: [],@@ -149,6 +155,19 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .const platformIds = useMemo(() => platforms?.map(p => p.id) ?? [], [platforms])const [selectedId, setSelectedId] = useRouteEnumParam('platform', platformIds, platformIds[0] ?? '')+ const restartGatewayNow = useCallback(async () => {+ // runGatewayRestart never rejects: it toasts the failure and settles the+ // statusbar indicator; the banner stays if the restart did not complete.+ const ok = await runGatewayRestart()++ if (ok) {+ setRestartNeeded(false)+ window.setTimeout(() => void refreshPlatformsRef.current(true), 4000)+ }+ }, [])++ const restartGatewayAction = { label: t.commandCenter.restartGateway, onClick: () => void restartGatewayNow() }+const refreshPlatforms = useCallback(async (silent = false) => {if (!silent) {@@ -171,6 +190,12 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .[m, scopeProfile])+ // Latest-callback ref: the deferred post-restart refresh must not capture a+ // stale scope closure from before a profile switch.+ const refreshPlatformsRef = useRef(refreshPlatforms)++ refreshPlatformsRef.current = refreshPlatforms+// Pairing has its own signal. platforms.changed tracks connect/disconnect// health via gateway_state.json, which a new pairing request never moves —// riding it would leave a pending row invisible until something unrelated@@ -310,6 +335,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .: row) ?? current)+ setRestartNeeded(true)notify({kind: 'success',title: enabled ? m.platformEnabled(platform.name) : m.platformDisabled(platform.name),@@ -336,6 +362,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .await updateMessagingPlatform(platform.id, { env }, scopeProfile)setEdits(current => ({ ...current, [platform.id]: {} }))await refreshPlatforms()+ setRestartNeeded(true)notify({kind: 'success',title: m.setupSaved(platform.name),@@ -362,6 +389,7 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .}}))await refreshPlatforms()+ setRestartNeeded(true)notify({ kind: 'success', title: m.keyCleared(key), message: m.setupUpdated(platform.name) })} catch (err) {notifyError(err, m.failedClear(key))@@ -370,6 +398,39 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .}}+ // QR onboarding wrote the token + allowlist and asked the backend to restart+ // the gateway. restart_started only means the child spawned; watch its exit+ // so a failed restart lands in the banner instead of a silent "stopped".+ async function handleTelegramApplied(result: TelegramOnboardingApplyResponse) {+ await refreshPlatforms(true)++ if (result.restart_started) {+ notify({ kind: 'success', title: m.setupSaved('Telegram'), message: m.telegramQr.savedRestarting })+ setRestartNeeded(false)+ const ok = await watchGatewayRestartOutcome()++ if (!ok) {+ setRestartNeeded(true)+ notifyError(new Error(m.restartFailedManual), m.restartFailedManual)+ }++ void refreshPlatforms(true)++ return+ }++ if (result.needs_restart) {+ // Backend could not spawn the restart (or is too old to try): fall back+ // to the app's own restart action, same as the manual-save path.+ await restartGatewayNow()++ if (result.restart_error) {+ notifyError(new Error(result.restart_error), m.telegramQr.savedRestartFailed(`: ${result.restart_error}`))+ setRestartNeeded(true)+ }+ }+ }+// Approve/revoke paint from a snapshot immediately, then let the// authoritative refresh have the last word. A failed write restores the// snapshot so the row never silently disappears on an error.@@ -437,6 +498,18 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .{/* Which profile's gateway this page configures (hidden forsingle-profile users). */}<SettingsProfileScope className="border-b border-(--ui-stroke-secondary) px-3 py-2" />+ {restartNeeded && (+ <Alert className="mx-3 mt-3 w-auto" variant="warning">+ <AlertTriangle />+ <AlertDescription className="flex flex-wrap items-center justify-between gap-2">+ <span>{m.restartNeeded}</span>+ <Button disabled={gatewayRestarting} onClick={() => void restartGatewayNow()} size="sm" variant="secondary">+ <RefreshCw className={gatewayRestarting ? 'animate-spin' : undefined} />+ {gatewayRestarting ? m.restarting : m.restartNow}+ </Button>+ </AlertDescription>+ </Alert>+ )}<div className="min-h-0 flex-1"><MasterDetail><ListColumn>@@ -484,9 +557,11 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .}))}onRevoke={setPendingRevoke}+ onTelegramApplied={result => void handleTelegramApplied(result)}pending={pendingByPlatform[selected.id] ?? []}platform={selected}saving={saving}+ scopeProfile={scopeProfile}/>)}</DetailColumn>@@ -564,9 +639,11 @@ function PlatformDetail({onClear,onEdit,onRevoke,+ onTelegramApplied,pending,platform,- saving+ saving,+ scopeProfile}: {approved: PairingUser[]approving: null | string@@ -575,9 +652,11 @@ function PlatformDetail({onClear: (key: string) => voidonEdit: (key: string, value: string) => voidonRevoke: (user: PairingUser) => void+ onTelegramApplied: (result: TelegramOnboardingApplyResponse) => voidpending: PairingUser[]platform: MessagingPlatformInfosaving: string | null+ scopeProfile: string | undefined}) {const { t } = useI18n()const m = t.messaging@@ -669,6 +748,15 @@ function PlatformDetail({</section>)}+ {platform.id === 'telegram' && (+ <section>+ <SectionTitle>{m.telegramQr.quickSetup}</SectionTitle>+ <div className="mt-3">+ <TelegramQrSetup onApplied={onTelegramApplied} platform={platform} scopeProfile={scopeProfile} />+ </div>+ </section>+ )}+<section><SectionTitle>{m.getCredentials}</SectionTitle><p className="mt-1 text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">diff --git a/apps/desktop/src/app/messaging/telegram-qr-setup.tsx b/apps/desktop/src/app/messaging/telegram-qr-setup.tsxnew file mode 100644index 00000000000..f0163bd6209--- /dev/null+++ b/apps/desktop/src/app/messaging/telegram-qr-setup.tsx@@ -0,0 +1,380 @@+import { useEffect, useMemo, useState } from 'react'++import { Badge } from '@/components/ui/badge'+import { Button } from '@/components/ui/button'+import { ErrorBanner } from '@/components/ui/error-state'+import { Input } from '@/components/ui/input'+import {+ applyTelegramOnboarding,+ cancelTelegramOnboarding,+ getTelegramOnboardingStatus,+ type MessagingPlatformInfo,+ startTelegramOnboarding,+ type TelegramOnboardingApplyResponse,+ type TelegramOnboardingStartResponse+} from '@/hermes'+import { useI18n } from '@/i18n'+import { openExternalLink } from '@/lib/external-link'+import { Check, ExternalLink, QrCode, Save, X } from '@/lib/icons'+import { cn } from '@/lib/utils'++import { CREDENTIAL_CONTROL_CLASS } from '../settings/credential-key-ui'++const TELEGRAM_USER_ID_RE = /^\d{3,20}$/++type Phase = 'applying' | 'idle' | 'ready' | 'starting' | 'waiting'++/** A 410 from the status endpoint means the pairing is gone for good (expired/claimed). */+export function isTerminalTelegramOnboardingError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error)++ return /\b410\b/.test(message) && /\b(expired|claimed|gone)\b/i.test(message)+}++export function formatExpiry(expiresAt: string, now = Date.now()): null | string {+ const ms = Date.parse(expiresAt) - now++ if (!Number.isFinite(ms) || ms <= 0) {+ return null+ }++ const seconds = Math.ceil(ms / 1000)++ return `${Math.floor(seconds / 60)}:${(seconds % 60).toString().padStart(2, '0')}`+}++async function renderQr(payload: string): Promise<string> {+ // Lazy: the QR encoder is only needed while a pairing is on screen.+ const QRCode = await import('qrcode')++ return QRCode.toDataURL(payload, { errorCorrectionLevel: 'M', margin: 1, width: 224 })+}++export interface TelegramQrSetupProps {+ /** Called after the backend wrote the token + allowlist; receives the restart outcome. */+ onApplied: (result: TelegramOnboardingApplyResponse) => void+ platform: MessagingPlatformInfo+ /** Request-shaped profile scope (undefined → active profile). */+ scopeProfile: string | undefined+}++/**+ * Telegram "Quick setup": the Nous pairing service mints a bot on the user's+ * behalf; we show its QR/deep link, poll until Telegram confirms, let the user+ * review the allowlist, and apply. Mirrors the dashboard's Channels flow so+ * the Desktop no longer sends users to @BotFather by hand.+ */+export function TelegramQrSetup({ onApplied, platform, scopeProfile }: TelegramQrSetupProps) {+ const { t } = useI18n()+ const q = t.messaging.telegramQr+ const [setup, setSetup] = useState<null | TelegramOnboardingStartResponse>(null)+ const [qrDataUrl, setQrDataUrl] = useState('')+ const [phase, setPhase] = useState<Phase>('idle')+ const [botUsername, setBotUsername] = useState<null | string>(null)+ const [allowedIds, setAllowedIds] = useState<string[]>([])+ const [detectedOwnerId, setDetectedOwnerId] = useState<null | string>(null)+ const [newAllowedId, setNewAllowedId] = useState('')+ const [error, setError] = useState('')+ const [tick, setTick] = useState(0)++ const reset = () => {+ setSetup(null)+ setQrDataUrl('')+ setPhase('idle')+ setBotUsername(null)+ setAllowedIds([])+ setDetectedOwnerId(null)+ setNewAllowedId('')+ setError('')+ }++ // Poll the pairing until Telegram confirms. A transient fetch error keeps+ // polling with a visible hint; a terminal 410 (or local expiry) resets.+ useEffect(() => {+ if (!setup || phase !== 'waiting') {+ return+ }++ let cancelled = false+ let timer: null | number = null++ const poll = async () => {+ try {+ const status = await getTelegramOnboardingStatus(setup.pairing_id, scopeProfile)++ if (cancelled) {+ return+ }++ if (status.status === 'ready') {+ setPhase('ready')+ setBotUsername(status.bot_username ?? null)+ setError('')++ if (status.owner_user_id && TELEGRAM_USER_ID_RE.test(status.owner_user_id)) {+ setDetectedOwnerId(status.owner_user_id)+ setAllowedIds([status.owner_user_id])+ }++ return+ }++ setError('')+ timer = window.setTimeout(() => void poll(), 2000)+ } catch (pollError) {+ if (cancelled) {+ return+ }++ const expiresAt = Date.parse(setup.expires_at)+ const expired = Number.isFinite(expiresAt) && Date.now() >= expiresAt++ if (isTerminalTelegramOnboardingError(pollError) || expired) {+ setSetup(null)+ setQrDataUrl('')+ setPhase('idle')+ setError(q.pairingExpired)++ return+ }++ setError(q.stillWaiting(String(pollError)))+ timer = window.setTimeout(() => void poll(), 2000)+ }+ }++ timer = window.setTimeout(() => void poll(), 1200)++ return () => {+ cancelled = true++ if (timer !== null) {+ window.clearTimeout(timer)+ }+ }+ }, [phase, q, scopeProfile, setup])++ // One-second tick keeps the expiry countdown honest while a pairing is shown.+ useEffect(() => {+ if (!setup) {+ return+ }++ const timer = window.setInterval(() => setTick(value => value + 1), 1000)++ return () => window.clearInterval(timer)+ }, [setup])++ const expiresIn = useMemo(+ () => (setup ? formatExpiry(setup.expires_at) : null),+ // tick refreshes the memo each second without recomputing on every render.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ [setup, tick]+ )++ const start = async () => {+ setPhase('starting')+ setError('')+ setBotUsername(null)+ setAllowedIds([])+ setDetectedOwnerId(null)+ setNewAllowedId('')++ try {+ const result = await startTelegramOnboarding(undefined, scopeProfile)+ const dataUrl = await renderQr(result.qr_payload)+ setSetup(result)+ setQrDataUrl(dataUrl)+ setPhase('waiting')+ } catch (startError) {+ setPhase('idle')+ setError(String(startError))+ }+ }++ const cancel = async () => {+ if (setup) {+ try {+ await cancelTelegramOnboarding(setup.pairing_id, scopeProfile)+ } catch {+ // Local cleanup still wins; the backend prunes expired pairings itself.+ }+ }++ reset()+ }++ const addAllowedId = () => {+ const trimmed = newAllowedId.trim()++ if (!TELEGRAM_USER_ID_RE.test(trimmed)) {+ setError(q.numericOnly)++ return+ }++ setError('')+ setAllowedIds(ids => (ids.includes(trimmed) ? ids : [...ids, trimmed]))+ setNewAllowedId('')+ }++ const apply = async () => {+ if (!setup) {+ return+ }++ if (allowedIds.length === 0) {+ setError(q.addAtLeastOne)++ return+ }++ setPhase('applying')+ setError('')++ try {+ const result = await applyTelegramOnboarding(setup.pairing_id, allowedIds, scopeProfile)+ reset()+ onApplied(result)+ } catch (applyError) {+ setPhase('ready')+ setError(String(applyError))+ }+ }++ return (+ <div className="rounded-xl border border-(--ui-stroke-secondary) bg-(--ui-surface-secondary,transparent) p-3">+ <div className="flex flex-wrap items-start justify-between gap-3">+ <div className="min-w-0">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[length:var(--conversation-text-font-size)] font-medium">{q.quickSetup}</span>+ <Badge variant="success">{q.recommended}</Badge>+ </div>+ <p className="mt-1 text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">+ {q.quickHelp}+ </p>+ </div>+ {phase === 'idle' && (+ <Button onClick={() => void start()} size="sm">+ <QrCode />+ {q.createWithQr}+ </Button>+ )}+ {phase === 'starting' && (+ <Button disabled size="sm">+ {q.starting}+ </Button>+ )}+ </div>++ {platform.configured && phase === 'idle' && (+ <p className="mt-2 text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-muted-foreground">+ {q.replaceWarning}+ </p>+ )}++ {error && <ErrorBanner className="mt-3">{error}</ErrorBanner>}++ {setup && qrDataUrl && (+ <div className="mt-3 grid gap-4 border-t border-(--ui-stroke-secondary) pt-3 lg:grid-cols-[minmax(0,1fr)_240px]">+ <div className="grid content-start gap-3">+ {phase === 'waiting' && (+ <div className="flex flex-wrap items-center gap-2">+ <Badge variant="warn">{q.waiting}</Badge>+ <span className="text-xs text-muted-foreground">{q.scanHint}</span>+ </div>+ )}++ {(phase === 'ready' || phase === 'applying') && (+ <>+ <div className="flex flex-wrap items-center gap-2">+ <Badge variant="success">{q.ready}</Badge>+ {botUsername && <span className="font-mono text-xs text-muted-foreground">@{botUsername}</span>}+ </div>++ <div className="grid gap-2">+ <div className="flex flex-wrap items-center gap-2">+ <span className="text-[0.7rem] font-semibold uppercase tracking-[0.14em] text-muted-foreground">+ {q.allowedUsers}+ </span>+ {detectedOwnerId && allowedIds.includes(detectedOwnerId) && (+ <Badge variant="success">{q.ownerDetected}</Badge>+ )}+ </div>+ <div className="flex flex-wrap gap-1.5">+ {allowedIds.map(id => (+ <button+ aria-label={`${t.common.remove} ${id}`}+ className={cn(+ 'inline-flex items-center gap-1 rounded-md border border-(--ui-stroke-secondary) px-2 py-1 font-mono text-xs',+ 'hover:border-destructive/50 hover:text-destructive'+ )}+ key={id}+ onClick={() => setAllowedIds(ids => ids.filter(existing => existing !== id))}+ type="button"+ >+ {id}+ <X className="size-3" />+ </button>+ ))}+ {allowedIds.length === 0 && <span className="text-xs text-muted-foreground">{q.addAtLeastOne}</span>}+ </div>+ <div className="flex items-center gap-2">+ <Input+ className={CREDENTIAL_CONTROL_CLASS}+ onChange={event => setNewAllowedId(event.target.value)}+ onKeyDown={event => {+ if (event.key === 'Enter') {+ event.preventDefault()+ addAllowedId()+ }+ }}+ placeholder={q.userIdPlaceholder}+ value={newAllowedId}+ />+ <Button onClick={addAllowedId} size="sm" variant="secondary">+ <Check />+ {q.add}+ </Button>+ </div>+ </div>++ <div className="flex flex-wrap gap-2">+ <Button disabled={phase === 'applying'} onClick={() => void apply()} size="sm">+ <Save />+ {phase === 'applying' ? q.applying : q.saveAndRestart}+ </Button>+ <Button disabled={phase === 'applying'} onClick={() => void cancel()} size="sm" variant="ghost">+ {t.common.cancel}+ </Button>+ </div>+ </>+ )}+ </div>++ <div className="flex flex-col items-center gap-2">+ <img alt="Telegram setup QR code" className="size-56 rounded-md bg-white p-2" src={qrDataUrl} />+ <Badge variant={expiresIn ? 'outline' : 'destructive'}>+ {expiresIn ? q.expiresIn(expiresIn) : q.expired}+ </Badge>+ <div className="flex flex-wrap justify-center gap-2">+ <Button+ onClick={() => openExternalLink(setup.deep_link)}+ size="sm"+ variant="secondary"+ >+ <ExternalLink />+ {q.openTelegram}+ </Button>+ {phase === 'waiting' && (+ <Button onClick={() => void cancel()} size="sm" variant="ghost">+ {t.common.cancel}+ </Button>+ )}+ </div>+ </div>+ </div>+ )}+ </div>+ )+}diff --git a/apps/desktop/src/app/webhooks/index.tsx b/apps/desktop/src/app/webhooks/index.tsxindex 4ebfe642aea..e63e30ec809 100644--- a/apps/desktop/src/app/webhooks/index.tsx+++ b/apps/desktop/src/app/webhooks/index.tsx@@ -147,19 +147,21 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {const restartGatewayNow = useCallback(async () => {setRestarting(true)- try {- await runGatewayRestart()+ // runGatewayRestart never rejects (it toasts its own failure); the boolean+ // is the only signal that the receiver actually came back.+ const ok = await runGatewayRestart()++ if (ok) {setRestartNeeded(false)setRestartError(null)// Give the receiver a moment to bind before re-reading state.window.setTimeout(() => void reload(true), 4000)- } catch (err) {+ } else {setRestartNeeded(true)- setRestartError(String(err))- notifyError(err, w.restartFailed(''))- } finally {- setRestarting(false)+ setRestartError(w.restartFailed(''))}++ setRestarting(false)}, [reload, w])const handleEnable = useCallback(async () => {diff --git a/apps/desktop/src/hermes.ts b/apps/desktop/src/hermes.tsindex 5042af6e47b..2beecf0583c 100644--- a/apps/desktop/src/hermes.ts+++ b/apps/desktop/src/hermes.ts@@ -121,6 +121,9 @@ export type {StaleAuxAssignment,StarmapGraph,StatusResponse,+ TelegramOnboardingApplyResponse,+ TelegramOnboardingStartResponse,+ TelegramOnboardingStatusResponse,ToolsetConfig,ToolsetInfo,ToolsetModel,diff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex 0ffa3fb3135..f7afe76382d 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -1289,6 +1289,38 @@ export const ar = defineLocale({unknown: 'غير معروف',hintPendingRestart: 'تحتاج إعادة تشغيل لتطبيق التغييرات.',hintGatewayStopped: 'البوابة متوقفة.',+ restartNeeded: 'تم الحفظ. أعد تشغيل بوابة المراسلة لتطبيق الإعدادات الجديدة.',+ restartNow: 'إعادة التشغيل الآن',+ restarting: 'جارٍ إعادة التشغيل…',+ restartFailedManual: 'فشلت إعادة تشغيل البوابة — أعد تشغيلها يدويًا وتحقق من سجلات البوابة.',+ telegramQr: {+ title: 'اختر طريقة ربط بوت Telegram',+ subtitle: 'كلا الخيارين يربط بوتًا تتحكم به ويحفظ بياناته في هذا التثبيت من Hermes فقط.',+ quickSetup: 'إعداد سريع',+ recommended: 'موصى به',+ quickHelp: 'امسح رمز QR وأكّد في Telegram. سينشئ Hermes البوت ويكتشف معرّف مستخدم Telegram الخاص بك تلقائيًا.',+ createWithQr: 'إنشاء عبر QR',+ starting: 'جارٍ البدء…',+ replaceWarning: 'بيانات Telegram مُعدّة بالفعل. سيحل إعداد QR الجديد أو رمز البوت محل البوت الحالي عند الحفظ.',+ scanHint: 'امسح بتطبيق Telegram على هاتفك، أو افتح الرابط على هذا الجهاز.',+ waiting: 'في انتظار Telegram…',+ expiresIn: remaining => `ينتهي خلال ${remaining}`,+ expired: 'منتهي',+ openTelegram: 'افتح Telegram',+ ready: 'تم إنشاء البوت',+ allowedUsers: 'المستخدمون المسموح لهم',+ ownerDetected: 'تم اكتشاف المالك',+ addAtLeastOne: 'أضف معرّف مستخدم Telegram واحدًا على الأقل.',+ userIdPlaceholder: 'معرّف مستخدم Telegram',+ add: 'إضافة',+ numericOnly: 'يجب أن تكون معرّفات مستخدمي Telegram أرقامًا.',+ saveAndRestart: 'حفظ وإعادة التشغيل',+ applying: 'جارٍ الحفظ…',+ pairingExpired: 'انتهت صلاحية اقتران Telegram. ابدأ إعداد QR جديدًا.',+ stillWaiting: detail => `ما زلنا ننتظر Telegram. إعادة المحاولة بعد: ${detail}`,+ savedRestarting: 'تم حفظ Telegram؛ تجري إعادة تشغيل البوابة…',+ savedRestartFailed: detail => `تم حفظ Telegram؛ فشلت إعادة تشغيل البوابة${detail}`+ },credentialsSet: 'بيانات الاعتماد مضبوطة',needsSetup: 'يحتاج إعدادا',gatewayStopped: 'البوابة متوقفة',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex a47f7b07e0e..a36819ce919 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -1909,6 +1909,38 @@ export const en: Translations = {failedRevoke: name => `Failed to revoke ${name}`,pairingLockedOut: 'Too many failed approvals — this platform is locked out. Try again later.',waitingSince: minutes => (minutes < 1 ? 'just now' : `${minutes}m ago`),+ restartNeeded: 'Saved. Restart the messaging gateway so the new settings take effect.',+ restartNow: 'Restart now',+ restarting: 'Restarting…',+ restartFailedManual: 'Gateway restart failed — restart it manually and check the gateway logs.',+ telegramQr: {+ title: 'Choose how to connect your Telegram bot',+ subtitle: 'Both options connect a bot you control and save its credentials only to this Hermes installation.',+ quickSetup: 'Quick setup',+ recommended: 'Recommended',+ quickHelp: 'Scan a QR code and confirm in Telegram. Hermes creates the bot and detects your Telegram user ID automatically.',+ createWithQr: 'Create with QR',+ starting: 'Starting…',+ replaceWarning: 'Telegram credentials are already configured. A new QR setup or bot token will replace the current bot when you save.',+ scanHint: 'Scan with the Telegram app on your phone, or open the link on this computer.',+ waiting: 'Waiting for Telegram…',+ expiresIn: remaining => `Expires in ${remaining}`,+ expired: 'Expired',+ openTelegram: 'Open Telegram',+ ready: 'Bot created',+ allowedUsers: 'Allowed users',+ ownerDetected: 'Owner detected',+ addAtLeastOne: 'Add at least one Telegram user ID.',+ userIdPlaceholder: 'Telegram user ID',+ add: 'Add',+ numericOnly: 'Allowed Telegram user IDs must be numeric.',+ saveAndRestart: 'Save and restart',+ applying: 'Saving…',+ pairingExpired: 'Telegram pairing expired. Start a new QR setup to try again.',+ stillWaiting: detail => `Still waiting for Telegram. Retrying after: ${detail}`,+ savedRestarting: 'Telegram saved; gateway restarting…',+ savedRestartFailed: detail => `Telegram saved; gateway restart failed${detail}`+ },fieldCopy: {TELEGRAM_BOT_TOKEN: {label: 'Bot token',diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 3d514ff4715..7a4689d69e2 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -1598,6 +1598,38 @@ export const ja = defineLocale({unknown: '不明',hintPendingRestart: 'この変更を適用するにはステータスバーからゲートウェイを再起動してください。',hintGatewayStopped: 'ステータスバーからゲートウェイを起動して接続してください。',+ restartNeeded: '保存しました。新しい設定を反映するにはメッセージングゲートウェイを再起動してください。',+ restartNow: '今すぐ再起動',+ restarting: '再起動中…',+ restartFailedManual: 'ゲートウェイの再起動に失敗しました。手動で再起動し、ゲートウェイのログを確認してください。',+ telegramQr: {+ title: 'Telegram ボットの接続方法を選択',+ subtitle: 'どちらの方法でも、あなたが管理するボットを接続し、資格情報はこの Hermes にのみ保存されます。',+ quickSetup: 'クイックセットアップ',+ recommended: '推奨',+ quickHelp: 'QR コードをスキャンして Telegram で確認します。Hermes がボットを作成し、あなたの Telegram ユーザー ID を自動検出します。',+ createWithQr: 'QR で作成',+ starting: '開始中…',+ replaceWarning: 'Telegram の資格情報はすでに設定されています。保存すると新しい QR セットアップまたはトークンが現在のボットを置き換えます。',+ scanHint: 'スマートフォンの Telegram アプリでスキャンするか、このコンピューターでリンクを開いてください。',+ waiting: 'Telegram を待機中…',+ expiresIn: remaining => `有効期限: ${remaining}`,+ expired: '期限切れ',+ openTelegram: 'Telegram を開く',+ ready: 'ボットを作成しました',+ allowedUsers: '許可ユーザー',+ ownerDetected: '所有者を検出',+ addAtLeastOne: 'Telegram ユーザー ID を 1 つ以上追加してください。',+ userIdPlaceholder: 'Telegram ユーザー ID',+ add: '追加',+ numericOnly: 'Telegram ユーザー ID は数字で入力してください。',+ saveAndRestart: '保存して再起動',+ applying: '保存中…',+ pairingExpired: 'Telegram のペアリングが期限切れです。新しい QR セットアップを開始してください。',+ stillWaiting: detail => `Telegram を待機中。エラー後に再試行: ${detail}`,+ savedRestarting: 'Telegram を保存しました。ゲートウェイを再起動中…',+ savedRestartFailed: detail => `Telegram を保存しましたが、ゲートウェイの再起動に失敗しました${detail}`+ },credentialsSet: '認証情報を設定しました',needsSetup: '設定が必要',gatewayStopped: 'メッセージングゲートウェイが停止中',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex db660107e92..587f0b53fc8 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -1940,6 +1940,38 @@ export const ru = defineLocale({failedRevoke: name => `Не удалось отозвать ${name}`,pairingLockedOut: 'Слишком много неудачных одобрений — эта платформа заблокирована. Попробуйте позже.',waitingSince: minutes => (minutes < 1 ? 'только что' : `${minutes}м назад`),+ restartNeeded: 'Сохранено. Перезапустите шлюз сообщений, чтобы применить новые настройки.',+ restartNow: 'Перезапустить',+ restarting: 'Перезапуск…',+ restartFailedManual: 'Не удалось перезапустить шлюз — перезапустите его вручную и проверьте журналы.',+ telegramQr: {+ title: 'Выберите способ подключения Telegram-бота',+ subtitle: 'Оба способа подключают бота под вашим контролем и сохраняют его данные только в этой установке Hermes.',+ quickSetup: 'Быстрая настройка',+ recommended: 'Рекомендуется',+ quickHelp: 'Отсканируйте QR-код и подтвердите в Telegram. Hermes создаст бота и определит ваш Telegram ID автоматически.',+ createWithQr: 'Создать по QR',+ starting: 'Запуск…',+ replaceWarning: 'Данные Telegram уже настроены. Новая QR-настройка или токен заменят текущего бота при сохранении.',+ scanHint: 'Отсканируйте в приложении Telegram на телефоне или откройте ссылку на этом компьютере.',+ waiting: 'Ожидание Telegram…',+ expiresIn: remaining => `Истекает через ${remaining}`,+ expired: 'Истёк',+ openTelegram: 'Открыть Telegram',+ ready: 'Бот создан',+ allowedUsers: 'Разрешённые пользователи',+ ownerDetected: 'Владелец определён',+ addAtLeastOne: 'Добавьте хотя бы один Telegram ID.',+ userIdPlaceholder: 'Telegram ID пользователя',+ add: 'Добавить',+ numericOnly: 'Telegram ID должны быть числовыми.',+ saveAndRestart: 'Сохранить и перезапустить',+ applying: 'Сохранение…',+ pairingExpired: 'Срок QR-настройки истёк. Начните новую.',+ stillWaiting: detail => `Всё ещё ждём Telegram. Повтор после: ${detail}`,+ savedRestarting: 'Telegram сохранён; шлюз перезапускается…',+ savedRestartFailed: detail => `Telegram сохранён; перезапуск шлюза не удался${detail}`+ },fieldCopy: {TELEGRAM_BOT_TOKEN: {label: 'Токен бота',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex f3d38de25b0..eb76fc419bd 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1687,6 +1687,38 @@ export interface Translations {failedRevoke: (name: string) => stringpairingLockedOut: stringwaitingSince: (minutes: number) => string+ restartNeeded: string+ restartNow: string+ restarting: string+ restartFailedManual: string+ telegramQr: {+ title: string+ subtitle: string+ quickSetup: string+ recommended: string+ quickHelp: string+ createWithQr: string+ starting: string+ replaceWarning: string+ scanHint: string+ waiting: string+ expiresIn: (remaining: string) => string+ expired: string+ openTelegram: string+ ready: string+ allowedUsers: string+ ownerDetected: string+ addAtLeastOne: string+ userIdPlaceholder: string+ add: string+ numericOnly: string+ saveAndRestart: string+ applying: string+ pairingExpired: string+ stillWaiting: (detail: string) => string+ savedRestarting: string+ savedRestartFailed: (detail: string) => string+ }fieldCopy: Record<string, { label?: string; help?: string; placeholder?: string }>platformIntro: Record<string, string>}diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex f4efd0f132b..0dc3060c688 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -1545,6 +1545,38 @@ export const zhHant = defineLocale({unknown: '未知',hintPendingRestart: '在狀態列重新啟動閘道以套用此變更。',hintGatewayStopped: '在狀態列啟動閘道以建立連線。',+ restartNeeded: '已儲存。請重新啟動訊息閘道以套用新設定。',+ restartNow: '立即重新啟動',+ restarting: '正在重新啟動…',+ restartFailedManual: '閘道重新啟動失敗 — 請手動重新啟動並檢查閘道日誌。',+ telegramQr: {+ title: '選擇連接 Telegram 機器人的方式',+ subtitle: '兩種方式都會連接由你控制的機器人,憑證僅儲存在此 Hermes 安裝中。',+ quickSetup: '快速設定',+ recommended: '推薦',+ quickHelp: '掃描 QR 碼並在 Telegram 中確認。Hermes 會自動建立機器人並偵測你的 Telegram 使用者 ID。',+ createWithQr: '以 QR 碼建立',+ starting: '正在啟動…',+ replaceWarning: 'Telegram 憑證已設定。儲存後,新的 QR 設定或機器人權杖將取代目前的機器人。',+ scanHint: '用手機上的 Telegram 應用程式掃描,或在這台電腦上開啟連結。',+ waiting: '等待 Telegram 確認…',+ expiresIn: remaining => `${remaining} 後到期`,+ expired: '已到期',+ openTelegram: '開啟 Telegram',+ ready: '機器人已建立',+ allowedUsers: '允許的使用者',+ ownerDetected: '已偵測擁有者',+ addAtLeastOne: '請至少新增一個 Telegram 使用者 ID。',+ userIdPlaceholder: 'Telegram 使用者 ID',+ add: '新增',+ numericOnly: '允許的 Telegram 使用者 ID 必須是數字。',+ saveAndRestart: '儲存並重新啟動',+ applying: '正在儲存…',+ pairingExpired: 'Telegram 配對已到期。請重新開始 QR 設定。',+ stillWaiting: detail => `仍在等待 Telegram。出錯後重試:${detail}`,+ savedRestarting: 'Telegram 已儲存;閘道正在重新啟動…',+ savedRestartFailed: detail => `Telegram 已儲存;閘道重新啟動失敗${detail}`+ },credentialsSet: '憑證已設定',needsSetup: '需要設定',gatewayStopped: '訊息閘道已停止',diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 89927db1178..0354377a07c 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -2076,6 +2076,38 @@ export const zh: Translations = {failedRevoke: name => `撤销 ${name} 失败`,pairingLockedOut: '批准失败次数过多,该平台已被暂时锁定,请稍后再试。',waitingSince: minutes => (minutes < 1 ? '刚刚' : `${minutes} 分钟前`),+ restartNeeded: '已保存。请重启消息网关以应用新设置。',+ restartNow: '立即重启',+ restarting: '正在重启…',+ restartFailedManual: '网关重启失败 — 请手动重启并检查网关日志。',+ telegramQr: {+ title: '选择连接 Telegram 机器人的方式',+ subtitle: '两种方式都会连接一个由你控制的机器人,凭据仅保存在此 Hermes 安装中。',+ quickSetup: '快速设置',+ recommended: '推荐',+ quickHelp: '扫描二维码并在 Telegram 中确认。Hermes 会自动创建机器人并识别你的 Telegram 用户 ID。',+ createWithQr: '通过二维码创建',+ starting: '正在启动…',+ replaceWarning: 'Telegram 凭据已配置。保存后,新的二维码设置或机器人令牌将替换当前机器人。',+ scanHint: '用手机上的 Telegram 应用扫描,或在这台电脑上打开链接。',+ waiting: '等待 Telegram 确认…',+ expiresIn: remaining => `${remaining} 后过期`,+ expired: '已过期',+ openTelegram: '打开 Telegram',+ ready: '机器人已创建',+ allowedUsers: '允许的用户',+ ownerDetected: '已识别所有者',+ addAtLeastOne: '请至少添加一个 Telegram 用户 ID。',+ userIdPlaceholder: 'Telegram 用户 ID',+ add: '添加',+ numericOnly: '允许的 Telegram 用户 ID 必须是数字。',+ saveAndRestart: '保存并重启',+ applying: '正在保存…',+ pairingExpired: 'Telegram 配对已过期。请重新开始二维码设置。',+ stillWaiting: detail => `仍在等待 Telegram。出错后重试:${detail}`,+ savedRestarting: 'Telegram 已保存;网关正在重启…',+ savedRestartFailed: detail => `Telegram 已保存;网关重启失败${detail}`+ },fieldCopy: {TELEGRAM_BOT_TOKEN: {label: 'Bot 令牌',diff --git a/apps/desktop/src/lib/icons.ts b/apps/desktop/src/lib/icons.tsindex 4c01becd7f4..3f63c54dd97 100644--- a/apps/desktop/src/lib/icons.ts+++ b/apps/desktop/src/lib/icons.ts@@ -97,6 +97,7 @@ import {IconPlayerPlay as Play,IconPlus as Plus,IconPower as Power,+ IconQrcode as QrCode,IconRefresh as RefreshCw,IconRefresh as RefreshCwIcon,IconDeviceFloppy as Save,@@ -228,6 +229,7 @@ export {Play,Plus,Power,+ QrCode,RefreshCw,RefreshCwIcon,Save,diff --git a/apps/desktop/src/store/system-actions.ts b/apps/desktop/src/store/system-actions.tsindex 43a8d9b770e..1867722785a 100644--- a/apps/desktop/src/store/system-actions.ts+++ b/apps/desktop/src/store/system-actions.ts@@ -8,6 +8,7 @@ import type { ActionResponse } from '@/types/hermes'const POLL_ATTEMPTS = 18const POLL_INTERVAL_MS = 1200const POLL_TIMEOUT_S = 180+const GATEWAY_RESTART_ACTION = 'gateway-restart'// True while a gateway restart is in flight — drives the statusbar gateway// indicator (glyph spinner) so the restart shows up where users already look,@@ -15,11 +16,13 @@ const POLL_TIMEOUT_S = 180export const $gatewayRestarting = atom(false)// Poll a backend action to completion (or a bounded window), throwing on a-// non-zero exit so the caller can surface the failure.-async function awaitAction(started: ActionResponse): Promise<void> {+// non-zero exit so the caller can surface the failure. In no-service installs+// the child becomes the foreground gateway and never exits, so "still running+// when the window closes" counts as success.+async function awaitAction(name: string): Promise<void> {for (let attempt = 0; attempt < POLL_ATTEMPTS; attempt += 1) {await new Promise(resolve => window.setTimeout(resolve, POLL_INTERVAL_MS))- const status = await getActionStatus(started.name, POLL_TIMEOUT_S)+ const status = await getActionStatus(name, POLL_TIMEOUT_S)if (!status.running) {if (status.exit_code != null && status.exit_code !== 0) {@@ -35,13 +38,37 @@ async function awaitAction(started: ActionResponse): Promise<void> {// indicator. Self-contained and never rejects, so every trigger — Cmd+K, the// messaging save/toggle toasts — gets identical feedback from a plain// `void runGatewayRestart()`, and a failure is the only thing that toasts.-export async function runGatewayRestart(): Promise<void> {+// Resolves `true` when the restart child completed cleanly (callers that keep+// a "restart needed" banner clear it on that signal only).+export async function runGatewayRestart(): Promise<boolean> {$gatewayRestarting.set(true)try {- await awaitAction(await restartGateway())+ const started: ActionResponse = await restartGateway()+ await awaitAction(started.name)++ return true} catch (err) {notifyError(err, translateNow('commandCenter.gatewayRestartFailed'))++ return false+ } finally {+ $gatewayRestarting.set(false)+ }+}++// Watch a restart the BACKEND spawned (e.g. after Telegram QR onboarding writes+// credentials) instead of one this app requested. Same indicator, same bounded+// poll; resolves `false` on a non-zero exit so the caller can re-arm its banner.+export async function watchGatewayRestartOutcome(): Promise<boolean> {+ $gatewayRestarting.set(true)++ try {+ await awaitAction(GATEWAY_RESTART_ACTION)++ return true+ } catch {+ return false} finally {$gatewayRestarting.set(false)}diff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex b4f178e24f3..4e5c140a57f 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -280,6 +280,35 @@ export interface MessagingPlatformTestResponse {state?: null | string}+// -- Telegram QR onboarding ---------------------------------------------------+// The Nous pairing service mints a bot on the user's behalf: the desktop shows+// a QR/deep link, Telegram confirms, the backend receives the token and writes+// it (plus the allowlist) into the target profile's .env, then restarts the+// gateway best-effort.++export interface TelegramOnboardingStartResponse {+ deep_link: string+ expires_at: string+ pairing_id: string+ qr_payload: string+ suggested_username: string+}++export type TelegramOnboardingStatusResponse =+ | { bot_username: null | string; expires_at: string; owner_user_id?: null | string; status: 'ready' }+ | { expires_at: string; status: 'waiting' }++export interface TelegramOnboardingApplyResponse {+ bot_username?: null | string+ needs_restart: boolean+ ok: boolean+ platform: 'telegram'+ restart_action?: string+ restart_error?: string+ restart_pid?: null | number+ restart_started?: boolean+}+// -- Webhooks (subscription CRUD) --------------------------------------------// Incoming HTTP event routes served by the webhook gateway platform. Backed by// the same JSON store the CLI/dashboard use; per-route HMAC secrets arediff --git a/package-lock.json b/package-lock.jsonindex 84d808002d0..eaf154d4507 100644--- a/package-lock.json+++ b/package-lock.json@@ -118,6 +118,7 @@"motion": "12.42.2","nanostores": "1.4.2","node-pty": "1.1.0",+ "qrcode": "1.5.4","radix-ui": "1.6.7","react": "19.2.7","react-arborist": "3.13.2",@@ -151,6 +152,7 @@"@types/d3-force": "3.0.10","@types/hast": "3.0.5","@types/node": "22.20.1",+ "@types/qrcode": "1.5.6","@types/react": "19.2.17","@types/react-dom": "19.2.3","@vitejs/plugin-react": "6.0.3",