Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
81 changes: 3 additions & 78 deletions apps/web/src/components/OneLoopStudio.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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() ?? '';
Expand Down Expand Up @@ -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 } =
Expand Down Expand Up @@ -792,7 +784,9 @@ export default function OneLoopStudio({
},
},
{ signal: controller.signal },
);
).catch((error: unknown) => {
console.error('WebMCP tool registration failed:', error);
});
return () => {
controller.abort();
};
Expand Down Expand Up @@ -881,9 +875,6 @@ export default function OneLoopStudio({
Export
</button>
</div>
<p className="w-full min-w-0 font-mono text-[11px] leading-snug text-[var(--uvai-ink-faint)]" role="status" data-testid="studio-ide-status">
{statusText}
</p>
{showTranscriptRetry && !transcriptWorking && selected?.status === 'failed' ? (
<div className="flex w-full flex-wrap items-center justify-between gap-2 rounded-lg border border-[var(--uvai-danger-border)] bg-[var(--uvai-danger-bg)] px-3 py-2 text-xs text-[var(--uvai-danger-ink)]">
<span className="min-w-0 flex-1 truncate">
Expand Down Expand Up @@ -1008,72 +999,6 @@ export default function OneLoopStudio({
</div>
)}
</div>
<div className="studio-steps-bar flex min-w-0 max-w-full flex-wrap items-center justify-between gap-2 px-3 py-1.5">
<ol
data-testid="studio-extraction-steps"
aria-label="Extraction progress"
className="studio-steps min-w-0 max-w-full flex-1 flex-wrap"
>
{(
[
{ 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 (
<li key={step.id} data-state={stepState} data-step={step.id}>
{step.label}
</li>
);
})}
</ol>
{watchHref ? (
<a
href={watchHref}
target="_blank"
rel="noreferrer"
aria-label="Trouble with this video? Watch it directly on YouTube"
title="Trouble with this video? Watch it directly on YouTube"
data-testid="studio-watch-on-youtube"
className="shrink-0 text-[11px] font-medium text-[var(--uvai-ink-soft)] underline-offset-2 hover:text-[var(--uvai-ink)] hover:underline"
>
YouTube ↗
</a>
) : null}
</div>
<div className="flex min-w-0 flex-col gap-3">
{selected?.videoPack ? (
<div className="uvai-card studio-pack-card min-w-0 max-w-full overflow-hidden p-3">
Expand Down
135 changes: 135 additions & 0 deletions apps/web/src/lib/__tests__/webmcp-studio-tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
50 changes: 44 additions & 6 deletions apps/web/src/lib/webmcp-studio-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/**
Expand Down Expand Up @@ -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);
}

Expand Down
Loading
Loading