Files
hapi/web/src/components/assistant-ui/markdown-a.test.tsx
T
f0ab4ba79d feat(cursor): detect inline model errors, surface, notify, and bridge (#878) (#987)
Cursor ACP sessions can fail mid-turn with a transient model error that the
agent reports inline rather than as an RPC rejection. HAPI treated those turns
as successful, so the session went quiet with no banner, no push, and no way to
resume without retyping the prompt.

This adds the full path:

- detect: classify inline/stderr model errors from the Cursor ACP stream,
  requiring strong signatures before typing a failure as a model error
- surface: persist `lastModelError` on session metadata; render a chat banner
  and a session-list indicator, with the prompt text kept out of list/SSE
  summaries so they never ship up to 32 KB of user prompt
- notify: deliver a push for an unacknowledged error, watermarked on the hub
  copy so a restart does not re-page the same eventId
- bridge & retry: offer a one-shot recovery prompt that replays the failed
  turn, bound to the originating eventId and gated so a real user turn always
  supersedes it. Auto-bridge is opt-in and defaults to OFF, persisted in hub
  settings and fanned out to live Cursor CLIs.

Re-cut onto current upstream/main. The branch had accumulated 108 iterative
hardening commits against a 289-commit-older base; replaying them individually
would have re-resolved the same conflicts ~100 times. The pre-re-cut tip was
2c28a1365 if the granular history is ever needed.

Absorbing upstream required adapting to three refactors that landed meanwhile:

- `MessageQueue2` grew an `internal?: boolean` control-message flag upstream
  while this branch added richer `internal` provenance. Unified on a tagged
  `QueueItemInternal` union (`control` | `model-error-bridge`) so one field
  carries one concept. `hasPendingNonBridgeTurn()` now treats *any* internal
  item as non-user: otherwise a queued `/auto-review` control slash would have
  counted as a user turn and wrongly superseded a live bridge.
- `AcpSdkBackend.prompt()` gained a `timing` callback upstream; merged it with
  this branch's `shouldSend` gate into a single options object.
- The hub settings route moved to a unified `updateSettings` transaction.
  `autoBridgeTransientModelErrors` is applied outside that transaction because
  SyncEngine owns its CLI fan-out and rollback under its own lock.

via [HAPI](https://hapi.run)

Co-authored-by: HAPI <noreply@hapi.run>
2026-11-13 18:50:09 +08:00

533 lines
24 KiB
TypeScript

/**
* Tests for the custom <A> anchor component and the inlined URL policy helpers
* in markdown-text.tsx.
*
* Covers:
* - classifyScheme: IANA / deny / custom, 6-axis security bypass
* - denyOnlyTransform: deny → "", IANA/custom → pass-through, relative paths
* - useAllowedSchemes (inlined): localStorage roundtrip, cross-tab storage event, tamper guard
* - <A> component click behaviour: deny, IANA, custom (dialog opened via context)
* - intra-tab cross-provider sync via module-level schemeListeners emitter
*/
import { describe, expect, it, vi, beforeEach } from 'vitest'
import { render, screen, fireEvent, cleanup, act, waitFor } from '@testing-library/react'
import React from 'react'
import { defaultComponents, classifyScheme, denyOnlyTransform, UriConfirmProvider } from '@/components/assistant-ui/markdown-text'
import { HappyChatProvider, type HappyChatContextValue } from '@/components/AssistantChat/context'
import { I18nProvider } from '@/lib/i18n-context'
import type { ApiClient } from '@/api/client'
const navigate = vi.fn()
vi.mock('@tanstack/react-router', async () => {
const actual = await vi.importActual<typeof import('@tanstack/react-router')>('@tanstack/react-router')
return {
...actual,
useNavigate: () => navigate,
}
})
// defaultComponents.a is the memoized A component.
const AnchorComponent = (defaultComponents as Record<string, unknown>).a as React.ComponentType<
React.ComponentPropsWithoutRef<'a'>
>
// Helper: wrap A in UriConfirmProvider so useContext(UriConfirmContext) is non-null.
// Previously <A> had a localHook fallback for bare renders, but that fallback
// added a storage listener per link (N links → N+1 listeners). The fallback is
// removed; tests must provide the context instead.
function renderA(props: React.ComponentPropsWithoutRef<'a'>, chat?: HappyChatContextValue) {
const tree = (
<I18nProvider>
<UriConfirmProvider>
<AnchorComponent {...props} />
</UriConfirmProvider>
</I18nProvider>
)
return render(
chat ? <HappyChatProvider value={chat}>{tree}</HappyChatProvider> : tree
)
}
function chatContext(overrides: Partial<HappyChatContextValue> = {}): HappyChatContextValue {
return {
api: {} as ApiClient,
sessionId: 'session-1',
metadata: { path: '/home/ada/coding/hapi', host: 'local' },
terminalToolDisplayMode: 'compact',
showSessionSummaryInChat: false,
disabled: false,
onRefresh: () => {},
hasMoreMessages: false,
isSyncingTail: false,
isLoadingMoreMessages: false,
loadOlderMessagesPreservingScroll: async () => 'loaded',
...overrides,
}
}
const STORAGE_KEY = 'hapi-allowed-schemes'
const OPEN_NEW_TAB_STORAGE_KEY = 'hapi-open-external-links-in-new-tab'
beforeEach(() => {
localStorage.clear()
cleanup()
vi.clearAllMocks()
})
// ── classifyScheme ────────────────────────────────────────────────────────────
describe('classifyScheme — IANA schemes', () => {
it.each(['https://example.com', 'http://example.com', 'mailto:user@x.com', 'irc://irc.libera.chat', 'ircs://irc.libera.chat', 'xmpp:user@x.com'])(
'classifies %s as iana',
(url) => expect(classifyScheme(url)).toBe('iana')
)
it('classifies HTTPS: (uppercase) as iana (case-insensitive)', () => {
expect(classifyScheme('HTTPS://example.com')).toBe('iana')
})
})
describe('classifyScheme — deny schemes', () => {
it.each(['javascript:alert(1)', 'data:text/html,<h1>xss</h1>', 'vbscript:msgbox(1)', 'file:///tmp/test.txt'])(
'classifies %s as deny',
(url) => expect(classifyScheme(url)).toBe('deny')
)
})
describe('classifyScheme — custom schemes', () => {
it.each(['obsidian://open?vault=V&file=F', 'vscode://file/path', 'slack://channel?team=T123'])(
'classifies %s as custom',
(url) => expect(classifyScheme(url)).toBe('custom')
)
})
describe('classifyScheme — security bypass axes', () => {
// (a) case bypass
it.each(['JavaScript:alert(1)', 'JAVASCRIPT:alert(1)'])('blocks %s (case) as deny', (url) =>
expect(classifyScheme(url)).toBe('deny')
)
// (b) whitespace prefix on entire URL
it.each(['\tjavascript:alert(1)', '\njavascript:alert(1)', ' javascript:alert(1)'])('blocks %s (whitespace prefix) as deny', (url) =>
expect(classifyScheme(url)).toBe('deny')
)
// (c) percent-encoding
it('%6Aavascript: (encoded j) → deny', () => expect(classifyScheme('%6Aavascript:alert(1)')).toBe('deny'))
it('jav%61script: (encoded a) → deny', () => expect(classifyScheme('jav%61script:alert(1)')).toBe('deny'))
// (d) double-encoding — 2-pass decode unwraps javascript%253A → javascript%3A → javascript:
// With 2-pass decode, the second pass resolves %3A → literal colon, so the scheme
// "javascript" is extracted and hits DENY_SCHEMES → 'deny' via scheme-match.
it('javascript%253A (double-encoded colon) → deny', () => expect(classifyScheme('javascript%253Aalert(1)')).toBe('deny'))
// `javascript%3Aalert(1)` — single-encoded colon. decodeURIComponent yields
// `javascript:alert(1)` with a literal colon, so classifyScheme extracts scheme
// "javascript" → hits DENY_SCHEMES → 'deny'. This is the real scheme-match path.
it('javascript%3A (single-encoded colon) → deny via scheme-match', () => expect(classifyScheme('javascript%3Aalert(1)')).toBe('deny'))
// (e) control characters spliced into scheme name
// Browsers strip \n, \t, \r from URL schemes during navigation; our normalizer
// must do the same before comparing against the deny list.
it('java\\nscript: (newline in scheme) → deny', () => expect(classifyScheme('java\nscript:alert(1)')).toBe('deny'))
it('java\\tscript: (tab in scheme) → deny', () => expect(classifyScheme('java\tscript:alert(1)')).toBe('deny'))
it('java\\rscript: (carriage return in scheme) → deny', () => expect(classifyScheme('java\rscript:alert(1)')).toBe('deny'))
it('java script: (space in scheme) → deny', () => expect(classifyScheme('java script:alert(1)')).toBe('deny'))
// percent-encoded control chars inside the scheme — decoded by pass 1 then stripped
it('java%0Ascript: (percent-encoded newline in scheme) → deny', () => expect(classifyScheme('java%0Ascript:alert(1)')).toBe('deny'))
// leading whitespace on the URL itself (already covered by trimStart, added for completeness)
it('\\tjavascript: (leading tab on URL) → deny', () => expect(classifyScheme('\tjavascript:alert(1)')).toBe('deny'))
// case sanity (also covered above but keep explicit)
it('JAVASCRIPT: → deny', () => expect(classifyScheme('JAVASCRIPT:alert(1)')).toBe('deny'))
it('JaVaScRipT: → deny', () => expect(classifyScheme('JaVaScRipT:')).toBe('deny'))
// edge
it('empty string → deny', () => expect(classifyScheme('')).toBe('deny'))
it('no-colon string → deny', () => expect(classifyScheme('not-a-url')).toBe('deny'))
})
// ── denyOnlyTransform ─────────────────────────────────────────────────────────
describe('denyOnlyTransform', () => {
it.each(['javascript:alert(1)', 'data:text/html,xss', 'vbscript:x', 'file:///tmp/f', 'JavaScript:alert(1)', 'jav%61script:alert(1)', '%6Aavascript:alert(1)'])(
'strips %s → ""',
(url) => expect(denyOnlyTransform(url)).toBe('')
)
it.each(['https://example.com', 'http://example.com', 'mailto:a@b.com'])(
'passes %s through unchanged',
(url) => expect(denyOnlyTransform(url)).toBe(url)
)
it.each(['obsidian://open?vault=V', 'vscode://file/path', 'slack://channel'])(
'passes custom scheme %s through unchanged',
(url) => expect(denyOnlyTransform(url)).toBe(url)
)
it('passes relative path through', () => {
expect(denyOnlyTransform('/relative/path')).toBe('/relative/path')
})
})
// ── useAllowedSchemes (inlined hook, tested via A component) ──────────────────
describe('localStorage roundtrip via A component', () => {
it('renders href="#" for unallowed custom scheme', () => {
renderA({ href: 'obsidian://open?vault=V&file=F', children: 'note' })
expect(document.querySelector('a')!.getAttribute('href')).toBe('#')
})
it('renders real href for pre-seeded allowed custom scheme', () => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(['obsidian']))
renderA({ href: 'obsidian://open?vault=V&file=F', children: 'note' })
expect(document.querySelector('a')!.getAttribute('href')).toBe('obsidian://open?vault=V&file=F')
})
it('isAllowed returns false for deny scheme even if tampered into localStorage', () => {
// Tamper: put javascript into allowed list
localStorage.setItem(STORAGE_KEY, JSON.stringify(['javascript']))
// The A component should still not treat javascript as allowed (it classifies to 'deny')
renderA({ href: 'javascript:alert(1)', children: 'evil' })
// href="" comes from denyOnlyTransform; onclick should preventDefault
const link = document.querySelector('a')!
const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true })
const preventSpy = vi.spyOn(clickEvent, 'preventDefault')
link.dispatchEvent(clickEvent)
expect(preventSpy).toHaveBeenCalled()
})
})
describe('cross-tab sync via storage event', () => {
it('updates after storage event fires (simulated other-tab write)', () => {
// Start with empty storage, render an unallowed custom link
renderA({ href: 'obsidian://open', children: 'note' })
expect(document.querySelector('a')!.getAttribute('href')).toBe('#')
// Simulate another tab writing the allowed schemes
act(() => {
localStorage.setItem(STORAGE_KEY, JSON.stringify(['obsidian']))
window.dispatchEvent(new StorageEvent('storage', {
key: STORAGE_KEY,
newValue: JSON.stringify(['obsidian']),
storageArea: localStorage,
}))
})
// After storage event the hook re-reads; re-render the component
cleanup()
renderA({ href: 'obsidian://open', children: 'note' })
expect(document.querySelector('a')!.getAttribute('href')).toBe('obsidian://open')
})
})
// ── <A> component — click handler ────────────────────────────────────────────
describe('markdown <A> component — click handler', () => {
it('prevents default when href is empty string (deny-scheme link)', () => {
renderA({ href: '', children: 'deny' })
const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true })
const preventSpy = vi.spyOn(clickEvent, 'preventDefault')
document.querySelector('a')!.dispatchEvent(clickEvent)
expect(preventSpy).toHaveBeenCalled()
})
it('prevents default when href is undefined', () => {
renderA({ children: 'no href' })
const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true })
const preventSpy = vi.spyOn(clickEvent, 'preventDefault')
document.querySelector('a')!.dispatchEvent(clickEvent)
expect(preventSpy).toHaveBeenCalled()
})
it('renders href="#" for an unallowed custom scheme (no middle-click bypass)', () => {
renderA({ href: 'obsidian://open?vault=V&file=F', children: 'note' })
expect(document.querySelector('a')!.getAttribute('href')).toBe('#')
})
it('renders the real href for an IANA scheme (https)', () => {
renderA({ href: 'https://example.com', children: 'link' })
expect(document.querySelector('a')!.getAttribute('href')).toBe('https://example.com')
})
it('does not navigate for a deny scheme (href="")', () => {
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
renderA({ href: '', children: 'evil' })
fireEvent.click(document.querySelector('a')!)
expect(openSpy).not.toHaveBeenCalled()
openSpy.mockRestore()
})
})
// ── relative / no-scheme hrefs — fail-closed (#1452) ─────────────────────────
//
// Finding 2 (historical): denyOnlyTransform passes relative hrefs through, but
// classifyScheme returned 'deny' for no-scheme inputs → preventDefault blocked
// internal links. Fixed by treating scheme-less as 'iana' when SPA-safe.
//
// #1452: scheme-less path-like hrefs that are NOT real app routes must not
// remain clickable SPA dead-ends. They become inert <span>s (or FilePathAnchor
// when they resolve to a workspace file).
describe('markdown <A> component — SPA-safe no-scheme hrefs still navigate', () => {
function clickAndCheckNotPrevented(href: string) {
renderA({ href, children: 'link' })
const clickEvent = new MouseEvent('click', { bubbles: true, cancelable: true })
const preventSpy = vi.spyOn(clickEvent, 'preventDefault')
document.querySelector('a')!.dispatchEvent(clickEvent)
expect(preventSpy).not.toHaveBeenCalled()
cleanup()
}
it('/settings → click not prevented (absolute-path relative link)', () => {
clickAndCheckNotPrevented('/settings')
})
it('#section → click not prevented (hash fragment link)', () => {
clickAndCheckNotPrevented('#section')
})
it('?q=1 → click not prevented (query-only link)', () => {
clickAndCheckNotPrevented('?q=1')
})
it('//example.com → click not prevented (protocol-relative URL, no colon)', () => {
clickAndCheckNotPrevented('//example.com/path')
})
it('https://example.com → click not prevented (regression: IANA still passes through)', () => {
clickAndCheckNotPrevented('https://example.com')
})
})
describe('markdown <A> component — fail-closed path-like hrefs (#1452)', () => {
it('renders ./foo as inert text (not a navigable <a>)', () => {
renderA({ href: './foo', children: 'dead' })
expect(document.querySelector('a')).toBeNull()
const inert = document.querySelector('.aui-md-a-inert')
expect(inert).not.toBeNull()
expect(inert!.getAttribute('title')).toBe('./foo')
expect(inert!.textContent).toBe('dead')
})
it('renders /home/... absolute file href as inert without chat context', () => {
renderA({ href: '/home/ada/proj/docs/a.md', children: 'abs' })
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('abs')
})
it('renders ~/... as inert without workspace metadata', () => {
renderA({ href: '~/proj/docs/a.md', children: 'tilde' })
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('tilde')
})
it('renders /path:colon as inert (path-like, not an app route)', () => {
renderA({ href: '/path:colon', children: 'weird' })
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')).not.toBeNull()
})
it('routes in-workspace absolute file href to FilePathAnchor when chat is present', () => {
renderA(
{ href: '/home/ada/coding/hapi/docs/a.md', children: 'abs' },
chatContext()
)
const link = document.querySelector('a')
expect(link).not.toBeNull()
expect(link!.getAttribute('href')).toContain('/sessions/session-1/file?')
expect(document.querySelector('.aui-md-a-inert')).toBeNull()
})
it('keeps outside-workspace absolute file href inert even with chat present', () => {
renderA(
{ href: '/etc/passwd.sh', children: 'etc' },
chatContext()
)
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('etc')
})
it('keeps outside-workspace Windows absolute href inert despite drive colon looking like a scheme', () => {
renderA(
{ href: 'D:/outside/secret.ts#L1', children: 'win' },
chatContext()
)
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('win')
})
it('routes hapi-file-candidate Windows href through containment to FilePathAnchor', () => {
const path = 'C:\\Users\\ada\\coding\\hapi\\docs\\a.md'
renderA(
{
href: 'hapi-file-candidate:' + encodeURIComponent(path),
children: 'win',
},
chatContext({
metadata: { path: 'C:\\Users\\ada\\coding\\hapi', host: 'local' },
})
)
const link = document.querySelector('a')
expect(link).not.toBeNull()
expect(link!.getAttribute('href')).toContain('/sessions/session-1/file?')
})
it('renders non-Windows hapi-file-candidate payloads as inert (no SPA navigate bypass)', () => {
renderA(
{
href: 'hapi-file-candidate:' + encodeURIComponent('/settings'),
children: 'spoof',
},
chatContext()
)
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('spoof')
})
it('renders empty hapi-file-candidate payload as inert (no custom-scheme confirm)', () => {
renderA({ href: 'hapi-file-candidate:', children: 'empty' }, chatContext())
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('empty')
})
it('renders uppercase hapi-file-candidate scheme as inert when payload is empty', () => {
renderA({ href: 'HAPI-FILE-CANDIDATE:', children: 'upper' }, chatContext())
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('upper')
})
it('renders percent-encoded hapi-file-candidate scheme as inert when payload is empty', () => {
renderA({ href: 'hapi%2Dfile%2Dcandidate:', children: 'enc' }, chatContext())
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('enc')
})
it('treats percent-encoded backslash Windows href as inert when outside workspace', () => {
renderA(
{ href: 'D:%5Coutside%5Csecret.ts', children: 'win' },
chatContext()
)
expect(document.querySelector('a')).toBeNull()
expect(document.querySelector('.aui-md-a-inert')?.textContent).toBe('win')
})
it('expands ~/ and routes to FilePathAnchor when workspace metadata is present', () => {
renderA(
{ href: '~/coding/hapi/docs/a.md', children: 'tilde' },
chatContext()
)
const link = document.querySelector('a')
expect(link).not.toBeNull()
expect(link!.getAttribute('href')).toContain('/sessions/session-1/file?')
})
it('keeps allowlisted relative file href as FilePathAnchor with chat', () => {
renderA({ href: 'docs/foo.md', children: 'rel' }, chatContext())
expect(document.querySelector('a')!.getAttribute('href')).toContain('/sessions/session-1/file?')
})
it('still renders /settings as a real navigable link with chat present', () => {
renderA({ href: '/settings', children: 'settings' }, chatContext())
expect(document.querySelector('a')!.getAttribute('href')).toBe('/settings')
expect(document.querySelector('.aui-md-a-inert')).toBeNull()
})
})
// ── "open external links in a new tab" setting (Settings > Display > Links) ──
describe('markdown <A> component — open external links in new tab setting', () => {
it('defaults to no explicit target on an external http(s) link', () => {
renderA({ href: 'https://example.com', children: 'link' })
expect(document.querySelector('a')!.getAttribute('target')).toBeNull()
})
it('forces target="_blank" + rel="noopener noreferrer" when the setting is enabled', () => {
localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true')
renderA({ href: 'https://example.com', children: 'link' })
const link = document.querySelector('a')!
expect(link.getAttribute('target')).toBe('_blank')
expect(link.getAttribute('rel')).toBe('noopener noreferrer')
})
it('does not force target on a relative/SPA href even when the setting is enabled', () => {
localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true')
renderA({ href: '/settings', children: 'settings' }, chatContext())
expect(document.querySelector('a')!.getAttribute('target')).toBeNull()
})
it('does not force target on a non-http(s) IANA scheme (mailto) even when enabled', () => {
localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true')
renderA({ href: 'mailto:a@b.com', children: 'mail' })
expect(document.querySelector('a')!.getAttribute('target')).toBeNull()
})
it('updates an already-rendered link when the setting changes via storage event (settings page in another tab, or Settings > Display in this one after context refactor)', () => {
renderA({ href: 'https://example.com', children: 'link' })
expect(document.querySelector('a')!.getAttribute('target')).toBeNull()
act(() => {
localStorage.setItem(OPEN_NEW_TAB_STORAGE_KEY, 'true')
window.dispatchEvent(new StorageEvent('storage', {
key: OPEN_NEW_TAB_STORAGE_KEY,
newValue: 'true',
storageArea: localStorage,
}))
})
expect(document.querySelector('a')!.getAttribute('target')).toBe('_blank')
})
})
// ── intra-tab cross-provider sync (schemeListeners emitter) ──────────────────
//
// P7e.1 added a module-level `schemeListeners: Set<SchemeListener>` so that
// when two sibling <UriConfirmProvider>s exist in the same window (e.g.
// MarkdownText + Reasoning in AssistantMessage), clicking "Always allow" in
// one provider's dialog immediately updates the other without waiting for a
// cross-tab storage event (which browsers only fire in OTHER tabs).
//
// This test asserts that path: mount two sibling providers, trigger allow()
// in one via the dialog flow, verify the other's link href updates.
describe('intra-tab cross-provider sync (schemeListeners emitter)', () => {
it('allowing a scheme in one UriConfirmProvider propagates to a sibling provider', async () => {
localStorage.clear()
// Suppress window.open — handleAlwaysAllow calls it after allow()
const openSpy = vi.spyOn(window, 'open').mockImplementation(() => null)
render(
<I18nProvider>
<UriConfirmProvider>
<AnchorComponent href="obsidian://open?a=1">link1</AnchorComponent>
</UriConfirmProvider>
<UriConfirmProvider>
<AnchorComponent href="obsidian://open?a=2">link2</AnchorComponent>
</UriConfirmProvider>
</I18nProvider>
)
const links = screen.getAllByRole('link')
const [a1, a2] = links
// Both links start blocked (href="#") because obsidian is not yet allowed.
expect(a1.getAttribute('href')).toBe('#')
expect(a2.getAttribute('href')).toBe('#')
// Click the first link → its provider opens the UriConfirmDialog.
await act(async () => {
fireEvent.click(a1)
})
// The "Always allow obsidian:" button is rendered by UriConfirmDialog
// via Radix Dialog portal into document.body.
const alwaysBtn = await waitFor(() =>
screen.getByRole('button', { name: /always allow obsidian/i })
)
await act(async () => {
fireEvent.click(alwaysBtn)
})
// After "Always allow", the schemeListeners emitter must have notified
// the sibling provider synchronously. Both links should now carry the
// live href (not '#').
await waitFor(() => {
expect(a1.getAttribute('href')).toBe('obsidian://open?a=1')
expect(a2.getAttribute('href')).toBe('obsidian://open?a=2')
})
openSpy.mockRestore()
})
})