diff --git a/CHANGELOG.md b/CHANGELOG.md index a551153a1..249a9906b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,26 @@ versioning aims for [SemVer](https://semver.org/). ## [Unreleased] +### 2026-11-19: WebMCP preview permissions ([#2746](https://github.com/groupthinking/EventRelay/pull/2746)) + +#### Fixed + +- Skip optional WebMCP tool registration when the browser's permissions policy + denies `tools`, and handle permission failures without unhandled rejections. +- Handle in-flight registration cancellation during Studio effect cleanup while + preserving diagnostics for unexpected failures. Security headers are unchanged. + +#### Regression SOP + +- Run `npm --workspace=apps/web run test -- src/lib/__tests__/webmcp-studio-tools.test.ts` + for changes to WebMCP initialization (16 tests cover registration, denied or + unavailable APIs, audits, and cancellation). +- Run the web app type check and ESLint on the changed TypeScript files. +- Check `/studio` normally and with `Permissions-Policy: tools=()` enforced by a + local verification proxy. Confirm the sidebar toggles after hydration and no + uncaught errors appear. Preserve restrictions rather than enabling tools in + embedded previews; forward development WebSocket traffic through the proxy. + ### 2026-11-13: Agent staff governance (docs) #### Added diff --git a/apps/web/src/components/OneLoopStudio.tsx b/apps/web/src/components/OneLoopStudio.tsx index 94026db09..b843e8621 100644 --- a/apps/web/src/components/OneLoopStudio.tsx +++ b/apps/web/src/components/OneLoopStudio.tsx @@ -81,13 +81,6 @@ function getYouTubeId(url: string) { return extractYouTubeId(url) || ''; } -function safeYouTubeWatchHref(rawId: string): string | null { - const match = /^[A-Za-z0-9_-]{6,20}$/.exec(rawId); - if (!match) return null; - const watchUrl = new URL('https://www.youtube.com/watch'); - watchUrl.searchParams.set('v', match[0]); - return watchUrl.toString(); -} function formatSavedVideoLabel(video: Video): string { const raw = video.title?.trim() ?? ''; @@ -479,7 +472,6 @@ export default function OneLoopStudio({ }, [transcriptWorking]); const videoId = useMemo(() => getYouTubeId(url || selected?.url || ''), [url, selected?.url]); - const watchHref = useMemo(() => safeYouTubeWatchHref(videoId), [videoId]); // Destructure at the hook call so render reads booleans + a callback ref, // not properties of an object that also carries refs (react-hooks/refs). const { containerRef, ready: playerReady, failed: playerFailed, seekTo } = @@ -792,7 +784,9 @@ export default function OneLoopStudio({ }, }, { signal: controller.signal }, - ); + ).catch((error: unknown) => { + console.error('WebMCP tool registration failed:', error); + }); return () => { controller.abort(); }; @@ -881,9 +875,6 @@ export default function OneLoopStudio({ Export -

- {statusText} -

{showTranscriptRetry && !transcriptWorking && selected?.status === 'failed' ? (
@@ -1008,72 +999,6 @@ export default function OneLoopStudio({
)} -
-
    - {( - [ - { id: 'pack', label: 'Pack' }, - { id: 'captions', label: 'Captions' }, - { id: 'transcript', label: 'Transcript' }, - { id: 'events', label: 'Events' }, - { id: 'ready', label: 'Ready' }, - ] as const - ).map((step, idx) => { - const activeIdx = - transcriptStage.id === 'ready' - ? 4 - : transcriptStage.id === 'events' - ? 3 - : transcriptStage.id === 'transcript' - ? 2 - : transcriptStage.id === 'captions' - ? 1 - : 0; - const isDone = - !transcriptWorking && - selected?.status !== 'failed' && - Boolean(selected?.videoPack || selected?.transcript?.trim()); - const isFailed = !transcriptWorking && selected?.status === 'failed'; - const stepState = isDone - ? 'done' - : isFailed - ? idx < activeIdx - ? 'done' - : idx === activeIdx - ? 'failed' - : 'idle' - : transcriptWorking - ? idx < activeIdx - ? 'done' - : idx === activeIdx - ? 'active' - : 'idle' - : 'idle'; - return ( -
  1. - {step.label} -
  2. - ); - })} -
- {watchHref ? ( - - YouTube ↗ - - ) : null} -
{selected?.videoPack ? (
diff --git a/apps/web/src/lib/__tests__/webmcp-studio-tools.test.ts b/apps/web/src/lib/__tests__/webmcp-studio-tools.test.ts index d77201530..76b240eb2 100644 --- a/apps/web/src/lib/__tests__/webmcp-studio-tools.test.ts +++ b/apps/web/src/lib/__tests__/webmcp-studio-tools.test.ts @@ -5,12 +5,147 @@ import { fileURLToPath } from 'node:url'; import { describe, expect, it, vi } from 'vitest'; import { auditDocumentAeoAndWebMcp, + getDocumentModelContext, registerStudioWebMcpTools, WEBFLOW_MCP_CURRICULUM_VIDEOS, + type StudioWebMcpHandlers, type WebMcpToolDefinition, } from '@/lib/webmcp-studio-tools'; describe('webmcp-studio-tools', () => { + const handlers: StudioWebMcpHandlers = { + getSnapshot: vi.fn(), + onLoadUrl: vi.fn(), + }; + + it.each(['permissionsPolicy', 'featurePolicy'])( + 'skips modelContext access and registration when %s denies tools', + async (policyProperty) => { + const allowsFeature = vi.fn(() => false); + const getModelContext = vi.fn(() => { + throw new DOMException('Tools are blocked by permissions policy.', 'NotAllowedError'); + }); + const doc = document.implementation.createHTMLDocument(); + Object.defineProperty(doc, policyProperty, { value: { allowsFeature } }); + Object.defineProperty(doc, 'modelContext', { get: getModelContext }); + + expect(getDocumentModelContext(doc)).toBeNull(); + expect(auditDocumentAeoAndWebMcp(doc).imperativeApiAvailable).toBe(false); + await expect(registerStudioWebMcpTools(handlers, { doc })).resolves.toEqual({ + registered: [], + supported: false, + }); + expect(allowsFeature).toHaveBeenCalledWith('tools'); + expect(getModelContext).not.toHaveBeenCalled(); + }, + ); + + it('prefers permissionsPolicy over the legacy featurePolicy API', () => { + const registerTool = vi.fn(); + const doc = { + permissionsPolicy: { allowsFeature: vi.fn(() => true) }, + featurePolicy: { allowsFeature: vi.fn(() => false) }, + modelContext: { registerTool }, + } as unknown as Document; + + expect(getDocumentModelContext(doc)).toEqual({ registerTool }); + }); + + it.each(['NotAllowedError', 'SecurityError'])( + 'treats a %s from the modelContext getter as unsupported', + async (name) => { + const doc = document.implementation.createHTMLDocument(); + Object.defineProperty(doc, 'modelContext', { + get: () => { + throw new DOMException('Tools access denied.', name); + }, + }); + + expect(getDocumentModelContext(doc)).toBeNull(); + expect(auditDocumentAeoAndWebMcp(doc).imperativeApiAvailable).toBe(false); + await expect(registerStudioWebMcpTools(handlers, { doc })).resolves.toEqual({ + registered: [], + supported: false, + }); + }, + ); + + it('returns unsupported without probing unknown policies when WebMCP is unavailable', async () => { + const doc = document.implementation.createHTMLDocument(); + const allowsFeature = vi.fn(); + Object.defineProperty(doc, 'featurePolicy', { value: { allowsFeature } }); + + await expect(registerStudioWebMcpTools(handlers, { doc })).resolves.toEqual({ + registered: [], + supported: false, + }); + expect(allowsFeature).not.toHaveBeenCalled(); + }); + + it.each(['throw', 'reject'])( + 'handles registration permission failures when registerTool uses %s', + async (failureMode) => { + const error = new DOMException('Tools access denied.', 'NotAllowedError'); + const registerTool = vi.fn(() => { + if (failureMode === 'throw') throw error; + return Promise.reject(error); + }); + const doc = { modelContext: { registerTool } } as unknown as Document; + + await expect(registerStudioWebMcpTools(handlers, { doc })).resolves.toEqual({ + registered: [], + supported: false, + }); + expect(registerTool).toHaveBeenCalledTimes(1); + }, + ); + + it('stops registration if permission is denied after a tool has registered', async () => { + const registerTool = vi.fn() + .mockResolvedValueOnce(undefined) + .mockRejectedValue(new DOMException('Tools access denied.', 'SecurityError')); + const doc = { modelContext: { registerTool } } as unknown as Document; + + await expect(registerStudioWebMcpTools(handlers, { doc })).resolves.toEqual({ + registered: ['get_active_video_pack'], + supported: false, + }); + expect(registerTool).toHaveBeenCalledTimes(2); + }); + + it('handles an in-flight registration aborted by effect cleanup', async () => { + const controller = new AbortController(); + const registerTool = vi.fn(() => { + controller.abort(); + return Promise.reject(controller.signal.reason); + }); + const doc = { modelContext: { registerTool } } as unknown as Document; + + await expect(registerStudioWebMcpTools(handlers, { doc, signal: controller.signal })) + .resolves.toEqual({ registered: [], supported: true }); + expect(registerTool).toHaveBeenCalledTimes(1); + }); + + it('does not register tools when the signal is already aborted', async () => { + const controller = new AbortController(); + controller.abort(); + const registerTool = vi.fn(); + const doc = { modelContext: { registerTool } } as unknown as Document; + + await expect(registerStudioWebMcpTools(handlers, { doc, signal: controller.signal })) + .resolves.toEqual({ registered: [], supported: true }); + expect(registerTool).not.toHaveBeenCalled(); + }); + + it('does not hide unexpected registration errors', async () => { + const error = new TypeError('Invalid tool definition'); + const doc = { + modelContext: { registerTool: vi.fn().mockRejectedValue(error) }, + } as unknown as Document; + + await expect(registerStudioWebMcpTools(handlers, { doc })).rejects.toBe(error); + }); + it('includes the Webflow MCP curriculum video entry for 6TrjBFW6EKg', () => { const webflow = WEBFLOW_MCP_CURRICULUM_VIDEOS.find((v) => v.videoId === '6TrjBFW6EKg'); expect(webflow).toBeDefined(); diff --git a/apps/web/src/lib/webmcp-studio-tools.ts b/apps/web/src/lib/webmcp-studio-tools.ts index e1c752f15..5d09f930b 100644 --- a/apps/web/src/lib/webmcp-studio-tools.ts +++ b/apps/web/src/lib/webmcp-studio-tools.ts @@ -89,18 +89,42 @@ export type AeoWebMcpAuditResult = { score: number; }; +type WebMcpPermissionsPolicy = { + allowsFeature: (feature: string) => boolean; +}; + type DocumentWithModelContext = Document & { modelContext?: WebMcpModelContext; + permissionsPolicy?: WebMcpPermissionsPolicy; + featurePolicy?: WebMcpPermissionsPolicy; }; +function hasErrorName(error: unknown, ...names: string[]): boolean { + // DOMExceptions can originate in a different iframe realm. + return ( + typeof error === 'object' && error !== null && 'name' in error + && typeof error.name === 'string' && names.includes(error.name) + ); +} + export function getDocumentModelContext(doc?: Document | null): WebMcpModelContext | null { const target = doc ?? (typeof document !== 'undefined' ? document : null); if (!target) return null; - const candidate = (target as DocumentWithModelContext).modelContext; - if (!candidate || typeof candidate.registerTool !== 'function') { - return null; + + try { + const contextDocument = target as DocumentWithModelContext; + if (!('modelContext' in contextDocument)) return null; + // An embedding preview can deny tools even when the browser exposes WebMCP. + const policy = contextDocument.permissionsPolicy ?? contextDocument.featurePolicy; + if (policy?.allowsFeature('tools') === false) return null; + + const candidate = contextDocument.modelContext; + if (!candidate || typeof candidate.registerTool !== 'function') return null; + return candidate; + } catch (error) { + if (hasErrorName(error, 'NotAllowedError', 'SecurityError')) return null; + throw error; } - return candidate; } /** @@ -274,8 +298,22 @@ export async function registerStudioWebMcpTools( const registered: string[] = []; for (const tool of tools) { - if (options?.signal?.aborted) break; - await modelContext.registerTool(tool, registerOptions); + if (options?.signal?.aborted) return { registered: [], supported: true }; + try { + await modelContext.registerTool(tool, registerOptions); + } catch (error) { + if ( + options?.signal?.aborted + && (error === options.signal.reason || hasErrorName(error, 'AbortError')) + ) { + return { registered: [], supported: true }; + } + if (hasErrorName(error, 'NotAllowedError', 'SecurityError')) { + return { registered, supported: false }; + } + throw error; + } + if (options?.signal?.aborted) return { registered: [], supported: true }; registered.push(tool.name); } diff --git a/apps/web/src/styles/studio-workbench.css b/apps/web/src/styles/studio-workbench.css index aa92afd78..b64f67fa5 100644 --- a/apps/web/src/styles/studio-workbench.css +++ b/apps/web/src/styles/studio-workbench.css @@ -630,6 +630,38 @@ /* ============================================================ <= 679px: single pane + sticky bottom dock tablist ============================================================ */ +/* Exact Studio refinement overrides. */ +.template-studio-bands { + display: inline; +} + +#studio-panel-output { + font-family: system-ui; + align-items: center; + justify-content: space-evenly; +} + +#studio-panel-output > .studio-pane-body:nth-of-type(2) > div.flex > div.flex.flex-nowrap:first-of-type { + align-items: stretch; +} + +#studio-ide-output-panel-tasks > div.flex.flex-col > section.flex.flex-col > div.uvai-card.p-6 { + font-family: inherit; +} + +#studio-panel-chat > .uvai-pane-header { + font-family: system-ui; +} + +#studio-panel-video > .uvai-pane-header, +#studio-panel-video .studio-steps-bar { + display: none; +} + +#studio-ide-output-panel-tasks { + font-size: 72px; +} + @media (max-width: 679px) { .uvai-cards.template-studio-shell { max-width: 100%;