Skip to content

The agent that grows with you

fix(desktop): key Webhooks state and REST to the active backend profile

Austin Pickett96c64b452646
diff --git a/apps/desktop/src/api/messaging.ts b/apps/desktop/src/api/messaging.ts
index bca8d7e68f2..65da1c89510 100644
--- a/apps/desktop/src/api/messaging.ts
+++ b/apps/desktop/src/api/messaging.ts
@@ -151,33 +151,39 @@ export function revokePairing(platform: string, userId: string, profile?: null |
// shared JSON store the CLI/dashboard also drive. Enable mutates config and
// best-effort restarts the gateway; subscription changes hot-reload.
-export function getWebhooks(): Promise<WebhooksResponse> {
+/** `profile` = the backend owner this view captured at mount; omitted → the
+ * ambient request scope. Keyed explicitly so a view that survives an active
+ * profile switch keeps talking to the profile it belongs to (#71352). */
+export function getWebhooks(profile?: null | string): Promise<WebhooksResponse> {
return hermesApi<WebhooksResponse>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: '/api/webhooks'
})
}
-export function enableWebhooks(): Promise<WebhookEnableResponse> {
+export function enableWebhooks(profile?: null | string): Promise<WebhookEnableResponse> {
return hermesApi<WebhookEnableResponse>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: '/api/webhooks/enable',
method: 'POST'
})
}
-export function createWebhook(body: WebhookCreatePayload): Promise<WebhookCreateResponse> {
+export function createWebhook(
+ body: WebhookCreatePayload,
+ profile?: null | string
+): Promise<WebhookCreateResponse> {
return hermesApi<WebhookCreateResponse>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: '/api/webhooks',
method: 'POST',
body
})
}
-export function deleteWebhook(name: string): Promise<{ ok: boolean }> {
+export function deleteWebhook(name: string, profile?: null | string): Promise<{ ok: boolean }> {
return hermesApi<{ ok: boolean }>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: `/api/webhooks/${encodeURIComponent(name)}`,
method: 'DELETE'
})
@@ -185,10 +191,11 @@ export function deleteWebhook(name: string): Promise<{ ok: boolean }> {
export function setWebhookEnabled(
name: string,
- enabled: boolean
+ enabled: boolean,
+ profile?: null | string
): Promise<{ enabled: boolean; name: string; ok: boolean }> {
return hermesApi<{ enabled: boolean; name: string; ok: boolean }>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: `/api/webhooks/${encodeURIComponent(name)}/enabled`,
method: 'PUT',
body: { enabled }
diff --git a/apps/desktop/src/api/system.ts b/apps/desktop/src/api/system.ts
index 6b729c57ba5..8492857aae8 100644
--- a/apps/desktop/src/api/system.ts
+++ b/apps/desktop/src/api/system.ts
@@ -145,9 +145,9 @@ export function runCurator(): Promise<ActionResponse> {
})
}
-export function restartGateway(): Promise<ActionResponse> {
+export function restartGateway(profile?: null | string): Promise<ActionResponse> {
return hermesApi<ActionResponse>({
- ...profileScoped(),
+ ...profileScoped(profile),
path: '/api/gateway/restart',
method: 'POST'
})
@@ -171,7 +171,11 @@ export function checkHermesUpdate(force = false): Promise<BackendUpdateCheckResp
})
}
-export function getActionStatus(name: string, lines = 200, profile?: ProfileScope): Promise<ActionStatusResponse> {
+export function getActionStatus(
+ name: string,
+ lines = 200,
+ profile?: ProfileScope
+): Promise<ActionStatusResponse> {
return window.hermesDesktop.api<ActionStatusResponse>({
...capabilityScoped(profile),
path: `/api/actions/${encodeURIComponent(name)}/status?lines=${Math.max(1, lines)}`
diff --git a/apps/desktop/src/app/webhooks/index.tsx b/apps/desktop/src/app/webhooks/index.tsx
index e63e30ec809..c3cefabcb49 100644
--- a/apps/desktop/src/app/webhooks/index.tsx
+++ b/apps/desktop/src/app/webhooks/index.tsx
@@ -1,6 +1,6 @@
import { useStore } from '@nanostores/react'
import { useQuery, useQueryClient } from '@tanstack/react-query'
-import { useCallback, useEffect, useMemo, useState } from 'react'
+import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import { PageLoader } from '@/components/page-loader'
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'
@@ -33,7 +33,7 @@ import { useI18n } from '@/i18n'
import { AlertTriangle, Globe, Plus, RefreshCw } from '@/lib/icons'
import { cn } from '@/lib/utils'
import { notify, notifyError } from '@/store/notifications'
-import { $profileScope } from '@/store/profile'
+import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'
import { runGatewayRestart } from '@/store/system-actions'
import { useRefreshHotkey } from '../hooks/use-refresh-hotkey'
@@ -77,13 +77,40 @@ interface WebhooksViewProps {
onClose: () => void
}
+interface ProfileOwnedWebhooksViewProps extends WebhooksViewProps {
+ backendProfile: string
+}
+
export function WebhooksView({ onClose }: WebhooksViewProps) {
+ const backendProfile = normalizeProfileKey(useStore($activeGatewayProfile))
+
+ // Profile-owned draft/dialog/secret state must disappear at the same
+ // boundary as its backend owner: the key unmounts the old operation scope
+ // synchronously on switch, including while the profile rail stays in All
+ // profiles mode (#71352). AGENTS.md: a live profile swap is a re-home —
+ // the previous context must not leak into the next one.
+ return <ProfileOwnedWebhooksView backendProfile={backendProfile} key={backendProfile} onClose={onClose} />
+}
+
+function ProfileOwnedWebhooksView({ backendProfile, onClose }: ProfileOwnedWebhooksViewProps) {
const { t } = useI18n()
const w = t.webhooks
- // Re-load when the active profile changes so REST routes to the right backend.
- const profileScope = useStore($profileScope)
const queryClient = useQueryClient()
- const queryKey = useMemo(() => ['webhooks', profileScope] as const, [profileScope])
+ const queryKey = useMemo(() => ['webhooks', backendProfile] as const, [backendProfile])
+ const ownerActive = useRef(true)
+
+ // StrictMode rehearses this effect as mount → cleanup → mount; setting the
+ // flag in setup (not only clearing it in cleanup) keeps ordinary completions
+ // working after the rehearsal. The guard drops late completions from an
+ // already-unmounted profile owner.
+ // eslint-disable-next-line no-restricted-syntax -- lifecycle ownership flag, not an atom mirror
+ useEffect(() => {
+ ownerActive.current = true
+
+ return () => {
+ ownerActive.current = false
+ }
+ }, [])
const [query, setQuery] = useState('')
const [enabling, setEnabling] = useState(false)
@@ -113,7 +140,7 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
refetch
} = useQuery({
queryKey,
- queryFn: getWebhooks
+ queryFn: () => getWebhooks(backendProfile)
})
// React Query v5 dropped useQuery onError; surface a load failure toast once
@@ -134,7 +161,7 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
try {
await queryClient.invalidateQueries({ queryKey })
} catch (err) {
- if (!silent) {
+ if (!silent && ownerActive.current) {
notifyError(err, w.loadFailed)
}
}
@@ -149,20 +176,28 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
// runGatewayRestart never rejects (it toasts its own failure); the boolean
// is the only signal that the receiver actually came back.
- const ok = await runGatewayRestart()
+ const ok = await runGatewayRestart(backendProfile)
+
+ if (!ownerActive.current) {
+ return
+ }
if (ok) {
setRestartNeeded(false)
setRestartError(null)
// Give the receiver a moment to bind before re-reading state.
- window.setTimeout(() => void reload(true), 4000)
+ window.setTimeout(() => {
+ if (ownerActive.current) {
+ void reload(true)
+ }
+ }, 4000)
} else {
setRestartNeeded(true)
setRestartError(w.restartFailed(''))
}
setRestarting(false)
- }, [reload, w])
+ }, [backendProfile, reload, w])
const handleEnable = useCallback(async () => {
setEnabling(true)
@@ -170,12 +205,20 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
setRestartError(null)
try {
- const result = await enableWebhooks()
+ const result = await enableWebhooks(backendProfile)
await reload(true)
+ if (!ownerActive.current) {
+ return
+ }
+
if (result.restart_started) {
notify({ kind: 'success', message: w.enabledRestarting })
- window.setTimeout(() => void reload(true), 4000)
+ window.setTimeout(() => {
+ if (ownerActive.current) {
+ void reload(true)
+ }
+ }, 4000)
} else {
const detail = result.restart_error ? `: ${result.restart_error}` : '.'
setRestartNeeded(true)
@@ -183,11 +226,15 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
notify({ kind: 'error', message: w.restartFailed(detail) })
}
} catch (err) {
- notifyError(err, w.restartFailed(''))
+ if (ownerActive.current) {
+ notifyError(err, w.restartFailed(''))
+ }
} finally {
- setEnabling(false)
+ if (ownerActive.current) {
+ setEnabling(false)
+ }
}
- }, [reload, w])
+ }, [backendProfile, reload, w])
const resetForm = useCallback(() => {
setName('')
@@ -228,26 +275,37 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
.map(s => s.trim())
.filter(Boolean)
- const res = await createWebhook({
- deliver,
- deliver_only: deliverOnly,
- description: description.trim() || undefined,
- events: eventsList.length ? eventsList : undefined,
- name: name.trim(),
- prompt: prompt.trim() || undefined,
- skills: skillsList.length ? skillsList : undefined
- })
+ const res = await createWebhook(
+ {
+ deliver,
+ deliver_only: deliverOnly,
+ description: description.trim() || undefined,
+ events: eventsList.length ? eventsList : undefined,
+ name: name.trim(),
+ prompt: prompt.trim() || undefined,
+ skills: skillsList.length ? skillsList : undefined
+ },
+ backendProfile
+ )
+
+ if (!ownerActive.current) {
+ return
+ }
notify({ kind: 'success', message: w.created })
setCreated({ secret: res.secret, url: res.url })
resetForm()
void reload(true)
} catch (err) {
- notifyError(err, w.createFailed(''))
+ if (ownerActive.current) {
+ notifyError(err, w.createFailed(''))
+ }
} finally {
- setCreating(false)
+ if (ownerActive.current) {
+ setCreating(false)
+ }
}
- }, [deliver, deliverOnly, description, events, name, prompt, reload, resetForm, skills, w])
+ }, [backendProfile, deliver, deliverOnly, description, events, name, prompt, reload, resetForm, skills, w])
const handleToggle = useCallback(
async (subName: string, nextEnabled: boolean) => {
@@ -262,15 +320,24 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
)
try {
- await setWebhookEnabled(subName, nextEnabled)
+ await setWebhookEnabled(subName, nextEnabled, backendProfile)
+
+ if (!ownerActive.current) {
+ return
+ }
+
notify({ kind: 'success', message: nextEnabled ? w.enabled(subName) : w.disabled(subName) })
void reload(true)
} catch (err) {
+ if (!ownerActive.current) {
+ return
+ }
+
await reload(true)
notifyError(err, w.toggleFailed(subName, nextEnabled))
}
},
- [queryClient, queryKey, reload, w]
+ [backendProfile, queryClient, queryKey, reload, w]
)
// ConfirmDialog owns the pending→done→close beat; throw to surface its inline
@@ -282,14 +349,23 @@ export function WebhooksView({ onClose }: WebhooksViewProps) {
}
try {
- await deleteWebhook(pendingDelete)
+ await deleteWebhook(pendingDelete, backendProfile)
+
+ if (!ownerActive.current) {
+ return
+ }
+
notify({ kind: 'success', title: w.deleted, message: pendingDelete })
void reload(true)
} catch (err) {
+ if (!ownerActive.current) {
+ return
+ }
+
notifyError(err, w.deleteFailed(pendingDelete))
throw err
}
- }, [pendingDelete, reload, w])
+ }, [backendProfile, pendingDelete, reload, w])
const visible = useMemo(() => {
const q = query.trim().toLowerCase()
diff --git a/apps/desktop/src/store/system-actions.ts b/apps/desktop/src/store/system-actions.ts
index 2a0e80f5634..b26c169f4bb 100644
--- a/apps/desktop/src/store/system-actions.ts
+++ b/apps/desktop/src/store/system-actions.ts
@@ -31,7 +31,7 @@ export const $gatewayRestarting = atom(false)
// a window refused end to end is a failure, not a silent success: resolving it
// would erase the caller's "restart needed" banner while the gateway stays
// down.
-async function awaitAction(name: string): Promise<void> {
+async function awaitAction(name: string, profile?: string): Promise<void> {
let sawAnsweredPoll = false
let lastPollError: unknown = null
@@ -41,7 +41,7 @@ async function awaitAction(name: string): Promise<void> {
let status: Awaited<ReturnType<typeof getActionStatus>>
try {
- status = await getActionStatus(name)
+ status = await getActionStatus(name, 200, profile)
} catch (err) {
// The backend accepted the restart POST a moment ago and is now
// refusing — the expected shape of the restart window itself.
@@ -110,8 +110,10 @@ export async function confirmSharedGatewayRestart(): Promise<false | null | stri
// messaging save/toggle toasts — gets identical feedback from a plain
// `void runGatewayRestart()`, and a failure is the only thing that toasts.
// 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> {
+// a "restart needed" banner clear it on that signal only). Pass `profile` to
+// pin both the restart request and its status polls to one backend owner; the
+// ambient scope serves callers without an owner (#71352).
+export async function runGatewayRestart(profile?: string): Promise<boolean> {
const shared = await confirmSharedGatewayRestart()
if (shared === false) {
@@ -121,8 +123,8 @@ export async function runGatewayRestart(): Promise<boolean> {
$gatewayRestarting.set(true)
try {
- const started: ActionResponse = await restartGateway()
- await awaitAction(started.name)
+ const started: ActionResponse = await restartGateway(profile)
+ await awaitAction(started.name, profile)
if (shared) {
notify({ kind: 'success', message: translateNow('commandCenter.sharedGatewayRestarted', shared.length) })
diff --git a/apps/desktop/src/webhooks-rest.test.ts b/apps/desktop/src/webhooks-rest.test.ts
index ee277a3a897..d90fce565f3 100644
--- a/apps/desktop/src/webhooks-rest.test.ts
+++ b/apps/desktop/src/webhooks-rest.test.ts
@@ -23,4 +23,12 @@ describe('Webhook REST parity helpers', () => {
expect(api).toHaveBeenCalledWith(expect.objectContaining({ method: 'DELETE', path: '/api/webhooks/my%20hook' }))
})
+
+ it('routes an explicitly owned delete to that profile, not the ambient scope', async () => {
+ await deleteWebhook('my hook', 'coder')
+
+ expect(api).toHaveBeenCalledWith(
+ expect.objectContaining({ method: 'DELETE', path: '/api/webhooks/my%20hook', profile: 'coder' })
+ )
+ })
})