@womp/mcp-ui 0.1.21 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -280,7 +280,7 @@ Boolean requesting whether a visible border and background is provided by the ho
280
280
  - omitted: host decides border`)}),F({method:B(`ui/request-display-mode`),params:F({mode:Uh.describe(`The display mode being requested.`)})}),og=F({mode:Uh.describe(`The display mode that was actually set. May differ from requested if not supported.`)}).passthrough(),sg=L([B(`model`),B(`app`)]).describe(`Tool visibility scope - who can access the tool.`),F({resourceUri:A().optional(),visibility:P(sg).optional().describe(`Who can access this tool. Default: ["model", "app"]
281
281
  - "model": Tool visible to and callable by the agent
282
282
  - "app": Tool callable by the app from this server only`),csp:Hl().optional(),permissions:Hl().optional()}),F({mimeTypes:P(A()).optional().describe('Array of supported MIME types for UI resources.\nMust include `"text/html;profile=mcp-app"` for MCP Apps support.')}),F({method:B(`ui/download-file`),params:F({contents:P(L([kp,Ap])).describe(`Resource contents to download — embedded (inline data) or linked (host fetches). Uses standard MCP resource types.`)})}),F({method:B(`ui/message`),params:F({role:B(`user`).describe(`Message role, currently only "user" is supported.`),content:P(jp).describe(`Message content blocks (text, image, etc.).`)})}),F({method:B(`ui/notifications/sandbox-resource-ready`),params:F({html:A().describe(`HTML content to load into the inner iframe.`),sandbox:A().optional().describe(`Optional override for the inner iframe's sandbox attribute.`),csp:Yh.optional().describe(`CSP configuration from resource metadata.`),permissions:Xh.optional().describe(`Sandbox permissions from resource metadata.`)})}),cg=F({method:B(`ui/notifications/tool-result`),params:Bp.describe(`Standard MCP tool execution result.`)}),lg=F({toolInfo:F({id:rf.optional().describe(`JSON-RPC id of the tools/call request.`),tool:Lp.describe(`Tool definition including name, inputSchema, etc.`)}).optional().describe(`Metadata of the tool call that instantiated this App.`),theme:Hh.optional().describe(`Current color theme preference.`),styles:tg.optional().describe(`Style configuration for theming the app.`),displayMode:Uh.optional().describe(`How the UI is currently displayed.`),availableDisplayModes:P(Uh).optional().describe(`Display modes the host supports.`),containerDimensions:L([F({height:j().describe(`Fixed container height in pixels.`)}),F({maxHeight:L([j(),zl()]).optional().describe(`Maximum container height in pixels.`)})]).and(L([F({width:j().describe(`Fixed container width in pixels.`)}),F({maxWidth:L([j(),zl()]).optional().describe(`Maximum container width in pixels.`)})])).optional().describe(`Container dimensions. Represents the dimensions of the iframe or other
283
- container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:A().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:A().optional().describe(`User's timezone in IANA format.`),userAgent:A().optional().describe(`Host application identifier.`),platform:L([B(`web`),B(`desktop`),B(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:F({touch:M().optional().describe(`Whether the device supports touch input.`),hover:M().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:F({top:j().describe(`Top safe area inset in pixels.`),right:j().describe(`Right safe area inset in pixels.`),bottom:j().describe(`Bottom safe area inset in pixels.`),left:j().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),ug=F({method:B(`ui/notifications/host-context-changed`),params:lg.describe(`Partial context update containing only changed fields.`)}),F({method:B(`ui/update-model-context`),params:F({content:P(jp).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:R(A(),N().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),F({method:B(`ui/initialize`),params:F({appInfo:bf.describe(`App identification (name and version).`),appCapabilities:ag.describe(`Features and capabilities this app provides.`),protocolVersion:A().describe(`Protocol version this app supports.`)})}),dg=F({protocolVersion:A().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:bf.describe(`Host application identification and version.`),hostCapabilities:ig.describe(`Features and capabilities provided by the host.`),hostContext:lg.describe(`Rich context about the host environment.`)}).passthrough(),fg={target:`draft-2020-12`},pg=class e extends zh{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Zh,toolinputpartial:Qh,toolresult:cg,toolcancelled:$h,hostcontextchanged:ug};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||o({jitless:!0}),this.setRequestHandler(jf,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=Dh(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Ih(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Ih(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Fh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Fh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(ng,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Hp,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Rp,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Bp,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},dp,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},ap,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?am:im;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Jh,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},mf,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Kh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},qh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},og,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new Vh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Bh}},dg,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}}}));function hg(e,t){let n,r=0,i,a=()=>{n!==void 0&&(clearTimeout(n),n=void 0)},o=new pg({name:e,version:`0.0.1`},{}),s=async e=>{let t=await o.request({method:`tools/call`,params:{name:`get_generation`,arguments:{operationId:e}}},Bp);if(!t.isError)return t.structuredContent},c=(e,o)=>{n=window.setTimeout(async()=>{if(Date.now()-r>yg){t.onTimeout?.();return}try{let n=await s(e);if(n?.status===`complete`){a(),i=n,t.onResult(n);return}}catch{}c(e,Math.min(o*1.5,vg))},o)},l=e=>{e&&(a(),i=e,t.onResult(e),e.status===`running`&&e.operationId!==void 0&&(r=Date.now(),c(e.operationId,_g)))};return o.ontoolinput=e=>{t.onInput?.(e?.arguments||{}),t.onResult({status:`running`})},o.ontoolresult=e=>l(e?.structuredContent),o.onhostcontextchanged=e=>{if(e?.theme&&Lh(e.theme),e?.styles?.variables&&Rh(e.styles.variables),e?.displayMode&&(document.documentElement.dataset.displayMode=e.displayMode),e?.safeAreaInsets){let{top:t=0,right:n=0,bottom:r=0,left:i=0}=e.safeAreaInsets;document.body.style.padding=`${t}px ${n}px ${r}px ${i}px`}},o.onteardown=async()=>(a(),{}),o.connect(new Vh(window.parent,window.parent)).catch(()=>{}),{app:o,current:()=>i}}async function gg(e,t,n){return e.request({method:`tools/call`,params:{name:t,arguments:n}},Bp)}var $,_g,vg,yg,bg=t((()=>{mg(),Fm(),$=e=>document.getElementById(e),_g=2e3,vg=1e4,yg=36e4}));n((()=>{bg();var e=1048576,t=5e3,n=15e3,r={phase:`connecting`},i,a=(e,t=!1)=>{let n=$(`status`);n.textContent=e,n.classList.toggle(`error`,t)},o=t=>{if(t<e)return`${Math.max(1,Math.round(t/1024))} KB`;let n=t/e;return`${n>=10?n.toFixed(0):n.toFixed(1)} MB`},s=e=>{let t=e.lastIndexOf(`.`);return t<0||t>=e.length-1?``:e.slice(t+1).toLowerCase()},c=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:`until ${t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`};function l(e){for(let t of[`drop`,`progress`,`done`,`expired`])$(t).hidden=t!==e}function u(e){$(`error-text`).textContent=e,$(`error`).hidden=!1}function d(){$(`error`).hidden=!0}function f(){let e=r.summary;if(!e){$(`title`).textContent=r.fileName?`Send ${r.fileName} to Womp`:`Send your 3D model to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,l(null);return}switch($(`title`).textContent=`Send ${e.fileName} to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,r.phase){case`pending`:{$(`drop-text`).textContent=`Drop ${e.fileName} here`;let t=c(e.expiresAt);$(`drop-hint`).textContent=`Only .${e.format} · up to ${e.maxMb} MB${t?` · link valid ${t}`:``}`,$(`file`).accept=`.${e.format}`,l(`drop`);break}case`uploading`:$(`progress-name`).textContent=`Uploading ${r.fileName||e.fileName}…`,l(`progress`);break;case`done`:{$(`done-name`).textContent=r.fileName||e.fileName;let t=r.fileSize??e.fileSize;$(`done-size`).textContent=t?` (${o(t)})`:``,$(`sub`).textContent=`ready to quote`,l(`done`);break}case`expired`:$(`expired-name`).textContent=e.fileName,$(`sub`).textContent=`upload link expired`,l(`expired`);break;default:l(null)}}function ee(e){let t=Math.min(99,Math.round(e*100));$(`fill`).style.width=`${t}%`,$(`progress-pct`).textContent=`${t}%`}function p(e){r.summary=e,e.status===`ready`?(r.phase=`done`,te()):e.status===`expired`?(r.phase=`expired`,te()):r.phase!==`uploading`&&(r.phase=`pending`),d(),e.status===`pending`&&e.lastError&&r.phase===`pending`&&u(`A previous attempt was refused: ${e.lastError}`),f(),a(``),r.phase===`pending`&&ne(t)}function te(){i!==void 0&&(clearTimeout(i),i=void 0)}function ne(e){te();let t=r.summary;if(!t||r.phase!==`pending`)return;let a=new Date(t.expiresAt).getTime();Number.isFinite(a)&&Date.now()>a+6e4||(i=window.setTimeout(async()=>{if(r.phase===`pending`){try{let e=await gg(ae.app,`get_upload`,{uploadId:t.uploadId});if(!e.isError&&e.structuredContent){let n=e.structuredContent;if(n.status!==`pending`||n.lastError!==t.lastError){p(n);return}}}catch{}ne(Math.min(e*1.5,n))}},e))}function re(e,t){let n=s(e.name);return n===t.format?e.size>t.maxBytes?`"${e.name}" is ${o(e.size)}; this account's limit is ${t.maxMb} MB per file.`:null:`This upload expects a .${t.format} file (${t.fileName}); "${e.name}" is a .${n||`?`}. Ask your assistant for a new upload if the format changed.`}function ie(e,t){try{let t=JSON.parse(e);if(t?.error?.message)return t.error.message}catch{}return t?`Upload failed (${t}). Try again.`:``}function m(e){let n=r.summary;if(!n||r.phase!==`pending`)return;d();let i=re(e,n);if(i){u(i);return}te(),r.phase=`uploading`,r.fileName=e.name,r.fileSize=e.size,ee(0),f(),a(``);let o=new XMLHttpRequest;o.open(`PUT`,n.uploadUrl),o.setRequestHeader(`Content-Type`,`application/octet-stream`),o.upload.onprogress=e=>{e.lengthComputable&&ee(e.loaded/e.total)},o.onload=()=>{if(o.status>=200&&o.status<300){let t;try{t=JSON.parse(o.responseText)}catch{}p(t??{...n,status:`ready`,fileSize:e.size});return}if(o.status===409){p({...n,status:`ready`});return}if(o.status===410){p({...n,status:`expired`});return}r.phase=`pending`,f(),u(ie(o.responseText,o.status)||`Upload failed (${o.status}). Try again.`),ne(t)};let s=()=>{r.phase=`pending`,f(),u(`Could not send the file from here. Try again — or ask your assistant to upload it for you.`),a(`PUT to the upload URL got no response — check connectDomains / CORS if this repeats.`,!0),ne(t)};o.onerror=s,o.onabort=s,o.send(e)}var ae=hg(`Womp upload`,{onInput:e=>{typeof e.fileName==`string`&&(r.fileName=e.fileName),f(),a(`Preparing upload…`)},onResult:e=>{let t=e;if(t.status===`running`){f(),a(`Preparing upload…`);return}if(typeof t.uploadId!=`number`||!t.uploadUrl){a(`The upload result is missing its URL — is swan-backend on a build with create_upload?`,!0);return}p(t)}}),oe=$(`drop`),h=$(`file`);$(`choose`).addEventListener(`click`,()=>h.click()),h.addEventListener(`change`,()=>{let e=h.files?.[0];h.value=``,e&&m(e)});for(let e of[`dragenter`,`dragover`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.add(`active`)});for(let e of[`dragleave`,`drop`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.remove(`active`)});oe.addEventListener(`drop`,e=>{let t=e.dataTransfer?.files?.[0];t&&m(t)})}))();</script>
283
+ container holding the app. Specify either width or maxWidth, and either height or maxHeight.`),locale:A().optional().describe(`User's language and region preference in BCP 47 format.`),timeZone:A().optional().describe(`User's timezone in IANA format.`),userAgent:A().optional().describe(`Host application identifier.`),platform:L([B(`web`),B(`desktop`),B(`mobile`)]).optional().describe(`Platform type for responsive design decisions.`),deviceCapabilities:F({touch:M().optional().describe(`Whether the device supports touch input.`),hover:M().optional().describe(`Whether the device supports hover interactions.`)}).optional().describe(`Device input capabilities.`),safeAreaInsets:F({top:j().describe(`Top safe area inset in pixels.`),right:j().describe(`Right safe area inset in pixels.`),bottom:j().describe(`Bottom safe area inset in pixels.`),left:j().describe(`Left safe area inset in pixels.`)}).optional().describe(`Mobile safe area boundaries in pixels.`)}).passthrough(),ug=F({method:B(`ui/notifications/host-context-changed`),params:lg.describe(`Partial context update containing only changed fields.`)}),F({method:B(`ui/update-model-context`),params:F({content:P(jp).optional().describe(`Context content blocks (text, image, etc.).`),structuredContent:R(A(),N().describe(`Structured content for machine-readable context data.`)).optional().describe(`Structured content for machine-readable context data.`)})}),F({method:B(`ui/initialize`),params:F({appInfo:bf.describe(`App identification (name and version).`),appCapabilities:ag.describe(`Features and capabilities this app provides.`),protocolVersion:A().describe(`Protocol version this app supports.`)})}),dg=F({protocolVersion:A().describe(`Negotiated protocol version string (e.g., "2025-11-21").`),hostInfo:bf.describe(`Host application identification and version.`),hostCapabilities:ig.describe(`Features and capabilities provided by the host.`),hostContext:lg.describe(`Rich context about the host environment.`)}).passthrough(),fg={target:`draft-2020-12`},pg=class e extends zh{_appInfo;_capabilities;options;_hostCapabilities;_hostInfo;_hostContext;_registeredTools={};_initializedSent=!1;_assertInitialized(e){if(this._initializedSent)return;let t=`[ext-apps] App.${e}() called before connect() completed the ui/initialize handshake. Await app.connect() before calling this method, or move data loading to an ontoolresult handler.`;if(this.options?.strict)throw Error(t);console.warn(`${t}. This will throw in a future release.`)}eventSchemas={toolinput:Zh,toolinputpartial:Qh,toolresult:cg,toolcancelled:$h,hostcontextchanged:ug};static ONE_SHOT_EVENTS=new Set([`toolinput`,`toolinputpartial`,`toolresult`,`toolcancelled`]);_everHadListener=new Set;_assertHandlerTiming(t){if(!e.ONE_SHOT_EVENTS.has(t)||this._everHadListener.has(t)||(this._everHadListener.add(t),!this._initializedSent))return;let n=`[ext-apps] "${String(t)}" handler registered after connect() completed the ui/initialize handshake. The host may have already sent this notification. Register handlers before calling app.connect().`;if(this.options?.strict)throw Error(n);console.warn(n)}setEventHandler(e,t){t&&this._assertHandlerTiming(e),super.setEventHandler(e,t)}addEventListener(e,t){this._assertHandlerTiming(e),super.addEventListener(e,t)}onEventDispatch(e,t){e===`hostcontextchanged`&&(this._hostContext={...this._hostContext,...t})}constructor(e,t={},n={autoResize:!0}){super(n),this._appInfo=e,this._capabilities=t,this.options=n,n.allowUnsafeEval||o({jitless:!0}),this.setRequestHandler(jf,e=>(console.log(`Received ping:`,e.params),{})),this.setEventHandler(`hostcontextchanged`,void 0)}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after transport is established`);this._capabilities=Dh(this._capabilities,e)}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let r=this,i=()=>{r._initializedSent&&r._capabilities.tools?.listChanged&&r.sendToolListChanged()},a=t.inputSchema!==void 0,o={title:t.title,description:t.description,inputSchema:t.inputSchema,outputSchema:t.outputSchema,annotations:t.annotations,_meta:t._meta,enabled:!0,enable(){this.enabled=!0,i()},disable(){this.enabled=!1,i()},update(e){Object.assign(this,e),i()},remove(){r._registeredTools[e]===o&&(delete r._registeredTools[e],i())},handler:async(t,r)=>{if(!o.enabled)throw Error(`Tool ${e} is disabled`);let i;if(a){let a=o.inputSchema;i=await n(a?await Ih(a,t??{},`Invalid input for tool ${e}: `):t??{},r)}else i=await n(r);return o.outputSchema&&!i.isError&&(i.structuredContent=await Ih(o.outputSchema,i.structuredContent,`Invalid output for tool ${e}: `)),i}};return this._registeredTools[e]=o,!this._capabilities.tools&&!this.transport&&this.registerCapabilities({tools:{listChanged:!0}}),this.ensureToolHandlersInitialized(),i(),o}_toolHandlersInitialized=!1;ensureToolHandlersInitialized(){this._toolHandlersInitialized||(this._toolHandlersInitialized=!0,this.oncalltool=async(e,t)=>{let n=this._registeredTools[e.name];if(!n)throw Error(`Tool ${e.name} not found`);return n.handler(e.arguments,t)},this.onlisttools=async(e,t)=>({tools:await Promise.all(Object.entries(this._registeredTools).filter(([e,t])=>t.enabled).map(async([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?await Fh(t.inputSchema,`input`):{type:`object`,properties:{}}};return t.outputSchema&&(n.outputSchema=await Fh(t.outputSchema,`output`)),t.annotations&&(n.annotations=t.annotations),t._meta&&(n._meta=t._meta),n}))}))}async sendToolListChanged(e={}){this._assertInitialized(`sendToolListChanged`),await this.notification({method:`notifications/tools/list_changed`,params:e})}getHostCapabilities(){return this._hostCapabilities}getHostVersion(){return this._hostInfo}getHostContext(){return this._hostContext}get ontoolinput(){return this.getEventHandler(`toolinput`)}set ontoolinput(e){this.setEventHandler(`toolinput`,e)}get ontoolinputpartial(){return this.getEventHandler(`toolinputpartial`)}set ontoolinputpartial(e){this.setEventHandler(`toolinputpartial`,e)}get ontoolresult(){return this.getEventHandler(`toolresult`)}set ontoolresult(e){this.setEventHandler(`toolresult`,e)}get ontoolcancelled(){return this.getEventHandler(`toolcancelled`)}set ontoolcancelled(e){this.setEventHandler(`toolcancelled`,e)}get onhostcontextchanged(){return this.getEventHandler(`hostcontextchanged`)}set onhostcontextchanged(e){this.setEventHandler(`hostcontextchanged`,e)}_onteardown;get onteardown(){return this._onteardown}set onteardown(e){this.warnIfRequestHandlerReplaced(`onteardown`,this._onteardown,e),this._onteardown=e,this.replaceRequestHandler(ng,(e,t)=>{if(!this._onteardown)throw Error(`No onteardown handler set`);return this._onteardown(e.params,t)})}_oncalltool;get oncalltool(){return this._oncalltool}set oncalltool(e){this.warnIfRequestHandlerReplaced(`oncalltool`,this._oncalltool,e),this._oncalltool=e,this.replaceRequestHandler(Hp,(e,t)=>{if(!this._oncalltool)throw Error(`No oncalltool handler set`);return this._oncalltool(e.params,t)})}_onlisttools;get onlisttools(){return this._onlisttools}set onlisttools(e){this.warnIfRequestHandlerReplaced(`onlisttools`,this._onlisttools,e),this._onlisttools=e,this.replaceRequestHandler(Rp,(e,t)=>{if(!this._onlisttools)throw Error(`No onlisttools handler set`);return this._onlisttools(e.params,t)})}assertCapabilityForMethod(e){if(e===`sampling/createMessage`&&!this._hostCapabilities?.sampling)throw Error(`Host does not support sampling (required for ${e})`)}assertRequestHandlerCapability(e){switch(e){case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Client does not support tool capability (required for ${e})`);return;case`ping`:case`ui/resource-teardown`:return;default:throw Error(`No handler for method ${e} registered`)}}assertNotificationCapability(e){}assertTaskCapability(e){throw Error(`Tasks are not supported in MCP Apps`)}assertTaskHandlerCapability(e){throw Error(`Task handlers are not supported in MCP Apps`)}async callServerTool(e,t){if(this._assertInitialized(`callServerTool`),typeof e==`string`)throw Error(`callServerTool() expects an object as its first argument, but received a string ("${e}"). Did you mean: callServerTool({ name: "${e}", arguments: { ... } })?`);return await this.request({method:`tools/call`,params:e},Bp,{onprogress:()=>{},resetTimeoutOnProgress:!0,...t})}async readServerResource(e,t){return this._assertInitialized(`readServerResource`),await this.request({method:`resources/read`,params:e},dp,t)}async listServerResources(e,t){return this._assertInitialized(`listServerResources`),await this.request({method:`resources/list`,params:e},ap,t)}async createSamplingMessage(e,t){this._assertInitialized(`createSamplingMessage`);let n=e.tools?am:im;return await this.request({method:`sampling/createMessage`,params:e},n,t)}sendMessage(e,t){return this._assertInitialized(`sendMessage`),this.request({method:`ui/message`,params:e},Jh,t)}sendLog(e){return this.notification({method:`notifications/message`,params:e})}updateModelContext(e,t){return this._assertInitialized(`updateModelContext`),this.request({method:`ui/update-model-context`,params:e},mf,t)}openLink(e,t){return this._assertInitialized(`openLink`),this.request({method:`ui/open-link`,params:e},Kh,t)}sendOpenLink=this.openLink;downloadFile(e,t){return this._assertInitialized(`downloadFile`),this.request({method:`ui/download-file`,params:e},qh,t)}requestTeardown(e={}){return this.notification({method:`ui/notifications/request-teardown`,params:e})}requestDisplayMode(e,t){return this._assertInitialized(`requestDisplayMode`),this.request({method:`ui/request-display-mode`,params:e},og,t)}sendSizeChanged(e){return this.notification({method:`ui/notifications/size-changed`,params:e})}setupSizeChangedNotifications(){let e=!1,t=0,n=0,r=()=>{e||(e=!0,requestAnimationFrame(()=>{e=!1;let r=document.documentElement,i=r.style.height;r.style.height=`max-content`;let a=Math.ceil(r.getBoundingClientRect().height);r.style.height=i;let o=Math.ceil(window.innerWidth);(o!==t||a!==n)&&(t=o,n=a,this.sendSizeChanged({width:o,height:a}))}))};r();let i=new ResizeObserver(r);return i.observe(document.documentElement),i.observe(document.body),()=>i.disconnect()}async connect(e=new Vh(window.parent,window.parent),t){if(this.transport)throw Error(`App is already connected. Call close() before connecting again.`);this._initializedSent=!1,await super.connect(e);try{let e=await this.request({method:`ui/initialize`,params:{appCapabilities:this._capabilities,appInfo:this._appInfo,protocolVersion:Bh}},dg,t);if(e===void 0)throw Error(`Server sent invalid initialize result: ${e}`);this._hostCapabilities=e.hostCapabilities,this._hostInfo=e.hostInfo,this._hostContext=e.hostContext,await this.notification({method:`ui/notifications/initialized`}),this._initializedSent=!0,this.options?.autoResize&&this.setupSizeChangedNotifications()}catch(e){throw this.close(),e}}}}));function hg(e,t){let n,r=0,i,a=()=>{n!==void 0&&(clearTimeout(n),n=void 0)},o=new pg({name:e,version:`0.0.1`},{}),s=async e=>{let t=await o.request({method:`tools/call`,params:{name:`get_generation`,arguments:{operationId:e}}},Bp);if(!t.isError)return t.structuredContent},c=(e,o)=>{n=window.setTimeout(async()=>{if(Date.now()-r>yg){t.onTimeout?.();return}try{let n=await s(e);if(n?.status===`complete`){a(),i=n,t.onResult(n);return}}catch{}c(e,Math.min(o*1.5,vg))},o)},l=e=>{e&&(a(),i=e,t.onResult(e),e.status===`running`&&e.operationId!==void 0&&(r=Date.now(),c(e.operationId,_g)))};return o.ontoolinput=e=>{t.onInput?.(e?.arguments||{}),t.onResult({status:`running`})},o.ontoolresult=e=>l(e?.structuredContent),o.onhostcontextchanged=e=>{if(e?.theme&&Lh(e.theme),e?.styles?.variables&&Rh(e.styles.variables),e?.displayMode&&(document.documentElement.dataset.displayMode=e.displayMode),e?.safeAreaInsets){let{top:t=0,right:n=0,bottom:r=0,left:i=0}=e.safeAreaInsets;document.body.style.padding=`${t}px ${n}px ${r}px ${i}px`}},o.onteardown=async()=>(a(),t.onTeardown?.(),{}),o.connect(new Vh(window.parent,window.parent)).catch(()=>{}),{app:o,current:()=>i}}async function gg(e,t,n){return e.request({method:`tools/call`,params:{name:t,arguments:n}},Bp)}var $,_g,vg,yg,bg=t((()=>{mg(),Fm(),$=e=>document.getElementById(e),_g=2e3,vg=1e4,yg=36e4}));n((()=>{bg();var e=1048576,t=5e3,n=15e3,r={phase:`connecting`},i,a=(e,t=!1)=>{let n=$(`status`);n.textContent=e,n.classList.toggle(`error`,t)},o=t=>{if(t<e)return`${Math.max(1,Math.round(t/1024))} KB`;let n=t/e;return`${n>=10?n.toFixed(0):n.toFixed(1)} MB`},s=e=>{let t=e.lastIndexOf(`.`);return t<0||t>=e.length-1?``:e.slice(t+1).toLowerCase()},c=e=>{let t=new Date(e);return Number.isNaN(t.getTime())?``:`until ${t.toLocaleTimeString([],{hour:`2-digit`,minute:`2-digit`})}`};function l(e){for(let t of[`drop`,`progress`,`done`,`expired`])$(t).hidden=t!==e}function u(e){$(`error-text`).textContent=e,$(`error`).hidden=!1}function d(){$(`error`).hidden=!0}function f(){let e=r.summary;if(!e){$(`title`).textContent=r.fileName?`Send ${r.fileName} to Womp`:`Send your 3D model to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,l(null);return}switch($(`title`).textContent=`Send ${e.fileName} to Womp`,$(`sub`).textContent=`so it can be quoted and printed`,r.phase){case`pending`:{$(`drop-text`).textContent=`Drop ${e.fileName} here`;let t=c(e.expiresAt);$(`drop-hint`).textContent=`Only .${e.format} · up to ${e.maxMb} MB${t?` · link valid ${t}`:``}`,$(`file`).accept=`.${e.format}`,l(`drop`);break}case`uploading`:$(`progress-name`).textContent=`Uploading ${r.fileName||e.fileName}…`,l(`progress`);break;case`done`:{$(`done-name`).textContent=r.fileName||e.fileName;let t=r.fileSize??e.fileSize;$(`done-size`).textContent=t?` (${o(t)})`:``,$(`sub`).textContent=`ready to quote`,l(`done`);break}case`expired`:$(`expired-name`).textContent=e.fileName,$(`sub`).textContent=`upload link expired`,l(`expired`);break;default:l(null)}}function ee(e){let t=Math.min(99,Math.round(e*100));$(`fill`).style.width=`${t}%`,$(`progress-pct`).textContent=`${t}%`}function p(e){r.summary=e,e.status===`ready`?(r.phase=`done`,te()):e.status===`expired`?(r.phase=`expired`,te()):r.phase!==`uploading`&&(r.phase=`pending`),d(),e.status===`pending`&&e.lastError&&r.phase===`pending`&&u(`A previous attempt was refused: ${e.lastError}`),f(),a(``),r.phase===`pending`&&ne(t)}function te(){i!==void 0&&(clearTimeout(i),i=void 0)}function ne(e){te();let t=r.summary;if(!t||r.phase!==`pending`)return;let a=new Date(t.expiresAt).getTime();Number.isFinite(a)&&Date.now()>a+6e4||(i=window.setTimeout(async()=>{if(r.phase===`pending`){try{let e=await gg(ae.app,`get_upload`,{uploadId:t.uploadId});if(!e.isError&&e.structuredContent){let n=e.structuredContent;if(n.status!==`pending`||n.lastError!==t.lastError){p(n);return}}}catch{}ne(Math.min(e*1.5,n))}},e))}function re(e,t){let n=s(e.name);return n===t.format?e.size>t.maxBytes?`"${e.name}" is ${o(e.size)}; this account's limit is ${t.maxMb} MB per file.`:null:`This upload expects a .${t.format} file (${t.fileName}); "${e.name}" is a .${n||`?`}. Ask your assistant for a new upload if the format changed.`}function ie(e,t){try{let t=JSON.parse(e);if(t?.error?.message)return t.error.message}catch{}return t?`Upload failed (${t}). Try again.`:``}function m(e){let n=r.summary;if(!n||r.phase!==`pending`)return;d();let i=re(e,n);if(i){u(i);return}te(),r.phase=`uploading`,r.fileName=e.name,r.fileSize=e.size,ee(0),f(),a(``);let o=new XMLHttpRequest;o.open(`PUT`,n.uploadUrl),o.setRequestHeader(`Content-Type`,`application/octet-stream`),o.upload.onprogress=e=>{e.lengthComputable&&ee(e.loaded/e.total)},o.onload=()=>{if(o.status>=200&&o.status<300){let t;try{t=JSON.parse(o.responseText)}catch{}p(t??{...n,status:`ready`,fileSize:e.size});return}if(o.status===409){p({...n,status:`ready`});return}if(o.status===410){p({...n,status:`expired`});return}r.phase=`pending`,f(),u(ie(o.responseText,o.status)||`Upload failed (${o.status}). Try again.`),ne(t)};let s=()=>{r.phase=`pending`,f(),u(`Could not send the file from here. Try again — or ask your assistant to upload it for you.`),a(`PUT to the upload URL got no response — check connectDomains / CORS if this repeats.`,!0),ne(t)};o.onerror=s,o.onabort=s,o.send(e)}var ae=hg(`Womp upload`,{onInput:e=>{typeof e.fileName==`string`&&(r.fileName=e.fileName),f(),a(`Preparing upload…`)},onResult:e=>{let t=e;if(t.status===`running`){f(),a(`Preparing upload…`);return}if(typeof t.uploadId!=`number`||!t.uploadUrl){a(`The upload result is missing its URL — is swan-backend on a build with create_upload?`,!0);return}p(t)}}),oe=$(`drop`),h=$(`file`);$(`choose`).addEventListener(`click`,()=>h.click()),h.addEventListener(`change`,()=>{let e=h.files?.[0];h.value=``,e&&m(e)});for(let e of[`dragenter`,`dragover`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.add(`active`)});for(let e of[`dragleave`,`drop`])oe.addEventListener(e,e=>{e.preventDefault(),oe.classList.remove(`active`)});oe.addEventListener(`drop`,e=>{let t=e.dataTransfer?.files?.[0];t&&m(t)})}))();</script>
284
284
  </head>
285
285
  <body>
286
286
  <div class="card" id="card">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@womp/mcp-ui",
3
- "version": "0.1.21",
3
+ "version": "0.2.1",
4
4
  "description": "MCP Apps widgets for Womp's MCP server — interactive cards rendered inline in Claude and other MCP hosts.",
5
5
  "license": "MIT",
6
6
  "type": "commonjs",
@@ -39,6 +39,7 @@
39
39
  "@modelcontextprotocol/ext-apps": "^1.7.5",
40
40
  "@modelcontextprotocol/sdk": "^1.30.0",
41
41
  "@types/three": "^0.185.4",
42
+ "@womp/kakapo-web": "^0.1.0",
42
43
  "express": "^5.2.1",
43
44
  "three": "^0.185.1",
44
45
  "typescript": "^5.9.3",
@@ -72,14 +72,15 @@
72
72
  :root:not([data-display-mode="fullscreen"]) .full-only { display: none !important; }
73
73
  :root[data-display-mode="fullscreen"] .inline-only { display: none !important; }
74
74
 
75
+ /*
76
+ * No border or corner of its own: the server asks the host for its frame
77
+ * (`prefersBorder`), and ChatGPT draws it. A second one inside it read as
78
+ * a card in a card.
79
+ */
75
80
  .card {
76
81
  display: grid;
77
82
  grid-template-columns: minmax(0, 1fr);
78
- max-width: 760px;
79
- border-radius: var(--radius);
80
- overflow: hidden;
81
83
  background: var(--bg);
82
- border: 1px solid var(--line);
83
84
  box-sizing: border-box;
84
85
  }
85
86
  /* The chat column is wide enough on desktop: render left, choices right. */
@@ -131,12 +132,12 @@
131
132
  overflow: hidden;
132
133
  background: radial-gradient(120% 90% at 50% 35%, var(--stage-a), var(--stage-b));
133
134
  }
134
- .stage iframe {
135
+ .stage canvas {
135
136
  display: block;
136
137
  width: 100%;
137
138
  height: 100%;
138
- border: 0;
139
139
  }
140
+ .stage canvas[hidden] { display: none; }
140
141
  .preview {
141
142
  position: absolute;
142
143
  inset: 0;
@@ -483,7 +484,7 @@
483
484
  </div>
484
485
 
485
486
  <div class="stage">
486
- <iframe id="viewer" title="3D preview of your camera" allow="fullscreen" hidden></iframe>
487
+ <canvas id="canvas" aria-label="3D preview of your camera" hidden></canvas>
487
488
  <div class="preview" id="fallback" hidden></div>
488
489
  <div class="status" id="status" role="status">Connecting&hellip;</div>
489
490
  </div>
@@ -1,25 +1,25 @@
1
+ import { createViewer, type Script, type Viewer, type ViewerError } from "@womp/kakapo-web";
1
2
  import { $, callTool, createCard, openExternal, pushModelContext, toggleFullscreen } from "../shared/bridge";
2
3
 
3
4
  /**
4
5
  * The camera card — the OpenAI MCP's first project (swan-backend
5
6
  * docs/OPENAI_MCP.md). Brand-neutral: nothing here may say Womp.
6
7
  *
7
- * The 3D view is Carlos's hosted viewer (Kakapo on WebGPU) in a nested frame,
8
- * pointed at the scene the server renders for the design's current revision.
9
- * Two directions of change meet here:
8
+ * The 3D view is kakapo-web (Kakapo on WebGPU), bundled into the card: its
9
+ * viewer draws on the stage's canvas, from the scene the server renders for the
10
+ * design's current revision. The scene is all it fetches: its fonts and
11
+ * environment map are built in. Two directions of change meet here:
10
12
  *
11
- * - The user drags a slider in the viewer's Customize panel. The viewer only
12
- * answers `kakapo:getParams`, so the card asks every 1.5s, and a difference
13
- * is saved with `sync_camera_design` (app-only). The viewer already shows it;
14
- * no reload.
13
+ * - The user turns a shape knob in the card. The viewer shows it at once
14
+ * (`setParams`), and the change is saved with `sync_camera_design`
15
+ * (app-only).
15
16
  * - The model calls `update_camera_design`. That renders no card, so this card
16
17
  * polls `get_camera_design` and moves the viewer to the new revision when it
17
18
  * changed for any reason other than its own write.
18
19
  *
19
20
  * Colours are not viewer knobs (they live in the scene's materials), so a swatch
20
- * saves and moves the viewer to the new revision. A viewer that says it can
21
- * (`kakapo:setScene` in its ready message) swaps the revision in place, keeping
22
- * its camera and re-modelling only what changed; any other is reloaded. Each part
21
+ * saves and moves the viewer to the new revision: `setScene` swaps it in place,
22
+ * keeping its camera and re-modelling only what changed. Each part
23
23
  * is solid or a gradient of 2-3 colours, turned 45° at a time by the arrow; the
24
24
  * colours come from the palette, the native colour picker, or the eyedropper
25
25
  * where the browser has one.
@@ -27,9 +27,8 @@ import { $, callTool, createCard, openExternal, pushModelContext, toggleFullscre
27
27
  * Inline, the card is the render, the two colours, the price, Customize and
28
28
  * Order. Customize goes fullscreen, where the same card grows every control:
29
29
  * gradients, the picker, and the shape knobs under plain names. The card owns
30
- * those controls; the viewer is asked to hide its own panel and Print button
31
- * (`embed=1`). Until it takes `kakapo:setParams`, a knob turned here saves and
32
- * swaps in the new revision, the way a colour does.
30
+ * those controls; the viewer only draws. Without a viewer, a knob turned here
31
+ * saves and the drawing shows the new revision, the way a colour does.
33
32
  *
34
33
  * Order gets the quote from `checkout_camera` and opens its checkout link on
35
34
  * the web, all from here; paying happens there. In the chat, "order it" makes
@@ -56,8 +55,6 @@ interface DesignOption {
56
55
  interface Design {
57
56
  designId: string;
58
57
  rev: number;
59
- viewerUrl: string;
60
- viewerOrigin: string;
61
58
  sceneUrl: string;
62
59
  options: DesignOption[];
63
60
  /** Each part's colours: one is solid, more is a gradient. */
@@ -94,32 +91,20 @@ const EyeDropper = (window as Window & { EyeDropper?: EyeDropperCtor }).EyeDropp
94
91
  /** Marks this card's own writes, so its polling does not reload the viewer for them. */
95
92
  const writer = `card-${Math.random().toString(36).slice(2, 10)}`;
96
93
 
97
- const viewer = $("viewer") as HTMLIFrameElement;
94
+ const canvas = $("canvas") as HTMLCanvasElement;
98
95
  const fallback = $("fallback");
99
96
 
100
97
  let design: Design | undefined;
101
98
  /** Revision the viewer is showing. */
102
99
  let loadedRev = 0;
103
- let viewerReady = false;
104
- /** The design the viewer frame was loaded for. */
100
+ let viewer: Viewer | undefined;
101
+ /** The design the viewer was created for. */
105
102
  let viewerDesignId: string | undefined;
106
- /** Whether the viewer takes a new revision by message instead of a reload. */
107
- let viewerCanSwap = false;
108
- /** Whether the viewer takes knob values by message, so a knob needs no new scene. */
109
- let viewerCanSetParams = false;
110
- /** Where to post to the viewer: its origin, or "*" when it speaks as "null" (an opaque host). */
111
- let viewerTarget = "*";
112
- /** The scene URL a swap is waiting on, and the reload that stands in if it never lands. */
113
- let pendingSwap: string | undefined;
114
- let swapTimer: number | undefined;
115
- /** Waiting for the viewer's next params message. */
116
- const paramsWaiters: (() => void)[] = [];
117
- /** Last knob values read back from the viewer. */
103
+ /** Counts viewer starts, so a slow one that a newer start overtook is dropped. */
104
+ let viewerRequest = 0;
118
105
  let viewerParams: Record<string, number> | undefined;
119
106
  let webgpu: boolean | undefined;
120
- let syncTimer: number | undefined;
121
107
  let syncing: Promise<void> | undefined;
122
- let readyTimer: number | undefined;
123
108
  let pollTimer: number | undefined;
124
109
  let lastActivity = Date.now();
125
110
  let statusTimer: number | undefined;
@@ -142,6 +127,11 @@ const { app } = createCard("Camera", {
142
127
  if (typeof data.designId !== "string") return;
143
128
  adopt(data as Design);
144
129
  },
130
+ // The host is removing the card: release the GPU device and stop asking the server.
131
+ onTeardown: () => {
132
+ clearTimeout(pollTimer);
133
+ closeViewer();
134
+ },
145
135
  });
146
136
 
147
137
  /** A design arrived from the tool call that rendered this card. */
@@ -182,49 +172,78 @@ async function loadViewer(note?: string) {
182
172
  setStatus("");
183
173
  return;
184
174
  }
185
- if (viewerReady && viewerCanSwap && viewerDesignId === design.designId) swapScene(design.sceneUrl, note);
186
- else reloadViewer(note);
175
+ if (viewer && viewerDesignId === design.designId) await moveViewer(viewer, design.sceneUrl, note);
176
+ else await startViewer(note);
187
177
  }
188
178
 
189
- /** Hand the viewer another revision of the design on screen. */
190
- function swapScene(url: string, note?: string) {
191
- pendingSwap = url;
179
+ async function moveViewer(current: Viewer, url: string, note?: string) {
192
180
  setStatus(note ?? "Updating the 3D view…");
193
- viewer.contentWindow?.postMessage({ type: "kakapo:setScene", url }, viewerTarget);
194
- clearTimeout(swapTimer);
195
- swapTimer = window.setTimeout(() => {
196
- if (pendingSwap === url) reloadViewer(note);
197
- }, 15_000);
181
+ try {
182
+ if (!(await current.setScene(url)) || current !== viewer) return;
183
+ viewerParams = flatten(current.getScripts());
184
+ setStatus("");
185
+ } catch {
186
+ if (current === viewer) await startViewer(note);
187
+ }
198
188
  }
199
189
 
200
- function reloadViewer(note?: string) {
190
+ async function startViewer(note?: string) {
201
191
  if (!design) return;
202
- viewerReady = false;
203
- viewerCanSwap = false;
204
- viewerCanSetParams = false;
205
- viewerParams = undefined;
206
- viewerDesignId = design.designId;
207
- pendingSwap = undefined;
208
- clearTimeout(swapTimer);
209
- viewer.hidden = false;
210
- // The drawing stands in until the viewer says it is ready.
192
+ const d = design;
193
+ const request = ++viewerRequest;
194
+ closeViewer();
195
+ canvas.hidden = false;
211
196
  drawPreview(false);
212
- // The card owns the controls: ask the viewer to drop its own panel and Print button.
213
- const src = new URL(design.viewerUrl);
214
- src.searchParams.set("embed", "1");
215
- viewer.src = src.toString();
216
197
  setStatus(note ?? "Loading the 3D viewer…");
217
- clearTimeout(readyTimer);
218
- readyTimer = window.setTimeout(() => {
219
- if (viewerReady) return;
220
- setStatus("The 3D viewer hasn't loaded — this app may not allow it here.");
221
- report("viewer-timeout");
222
- }, 25_000);
198
+ let modelled = false;
199
+ try {
200
+ const next = await createViewer(canvas, {
201
+ sceneUrl: d.sceneUrl,
202
+ onProgress: ({ built, total }) => {
203
+ if (modelled || request !== viewerRequest) return;
204
+ modelled = built === total;
205
+ if (modelled) {
206
+ fallback.hidden = true;
207
+ setStatus("");
208
+ }
209
+ },
210
+ onError: (e) => {
211
+ if (e.code === "device-lost") {
212
+ showFallback();
213
+ setStatus("The 3D view stopped. Reopen the card to restart it.");
214
+ }
215
+ report(`viewer-${e.code}`, e.message);
216
+ },
217
+ });
218
+ if (request !== viewerRequest) {
219
+ next.destroy();
220
+ return;
221
+ }
222
+ viewer = next;
223
+ viewerDesignId = d.designId;
224
+ viewerParams = flatten(next.getScripts());
225
+ report("viewer-ready");
226
+ } catch (e) {
227
+ if (request !== viewerRequest) return;
228
+ const err = e as ViewerError;
229
+ closeViewer();
230
+ if (err.code === "no-webgpu") webgpu = false;
231
+ showFallback();
232
+ setStatus(err.code === "no-webgpu" ? "" : "The 3D view couldn't load. You can still change the design and order it.");
233
+ report(`viewer-${err.code ?? "failed"}`, String(err.message ?? err));
234
+ }
235
+ }
236
+
237
+ function closeViewer() {
238
+ viewer?.destroy();
239
+ viewer = undefined;
240
+ viewerDesignId = undefined;
241
+ viewerParams = undefined;
223
242
  }
224
243
 
225
244
  function showFallback() {
226
245
  if (!design) return;
227
- viewer.hidden = true;
246
+ canvas.hidden = true;
228
247
  drawPreview(true);
229
248
  }
230
249
 
@@ -279,96 +298,16 @@ function cameraSvg(d: Design) {
279
298
  );
280
299
  }
281
300
 
282
- /** The viewer reports `scripts: [{ nodeId, name, params: { knob: value } }]`; knob names are unique across them. */
283
- function flatten(scripts: unknown): Record<string, number> {
301
+ function flatten(scripts: Script[]): Record<string, number> {
284
302
  const out: Record<string, number> = {};
285
- if (!Array.isArray(scripts)) return out;
286
303
  for (const script of scripts) {
287
- const params = (script as { params?: Record<string, unknown> })?.params ?? {};
288
- for (const [name, value] of Object.entries(params)) {
289
- if (typeof value === "number" && Number.isFinite(value)) out[name] = value;
304
+ for (const p of script.params) {
305
+ if (typeof p.value === "number" && Number.isFinite(p.value)) out[p.name] = p.value;
290
306
  }
291
307
  }
292
308
  return out;
293
309
  }
294
310
 
295
- /**
296
- * Where the viewer's messages come from. A host that frames the card on an
297
- * opaque origin (a sandbox without allow-same-origin) passes that sandbox down
298
- * to the viewer's frame, which then speaks as "null" — still our frame, as
299
- * `event.source` proves.
300
- */
301
- const fromViewer = (event: MessageEvent, d: Design) =>
302
- event.source === viewer.contentWindow && (event.origin === d.viewerOrigin || event.origin === "null");
303
-
304
- window.addEventListener("message", (event) => {
305
- if (!design || !fromViewer(event, design)) return;
306
- const msg = event.data as { type?: string; scripts?: unknown; messages?: unknown; url?: string; error?: string };
307
- if (msg?.type === "kakapo:ready") {
308
- viewerReady = true;
309
- viewerTarget = event.origin === "null" ? "*" : event.origin;
310
- viewerCanSwap = Array.isArray(msg.messages) && msg.messages.includes("kakapo:setScene");
311
- viewerCanSetParams = Array.isArray(msg.messages) && msg.messages.includes("kakapo:setParams");
312
- fallback.hidden = true;
313
- clearTimeout(readyTimer);
314
- viewerParams = flatten(msg.scripts);
315
- setStatus("");
316
- report("viewer-ready");
317
- } else if (msg?.type === "kakapo:sceneSet") {
318
- if (msg.url !== pendingSwap) return; // an earlier swap, answering late
319
- pendingSwap = undefined;
320
- clearTimeout(swapTimer);
321
- if (msg.error) {
322
- reloadViewer();
323
- return;
324
- }
325
- // The revision's knob values are the viewer's now: the baseline for spotting the user's next change.
326
- viewerParams = flatten(msg.scripts);
327
- setStatus("");
328
- } else if (msg?.type === "kakapo:params") {
329
- onViewerParams(flatten(msg.scripts));
330
- for (const done of paramsWaiters.splice(0)) done();
331
- } else if (msg?.type === "kakapo:print") {
332
- // A viewer that ignores embed=1 still shows Print: treat it as Order.
333
- onViewerParams(flatten(msg.scripts));
334
- void order();
335
- }
336
- });
337
-
338
- // The viewer has no change event, so read its knobs on an interval while visible.
339
- window.setInterval(() => {
340
- if (!design || !viewerReady || document.visibilityState !== "visible") return;
341
- viewer.contentWindow?.postMessage({ type: "kakapo:getParams" }, viewerTarget);
342
- }, 1_500);
343
-
344
- /**
345
- * The viewer's knobs as they are now rather than at the last poll, for a save
346
- * the user just asked for: one made with values up to 1.5s old would put back
347
- * a slider they had just moved.
348
- */
349
- function freshViewerParams(): Promise<void> {
350
- if (!viewerReady) return Promise.resolve();
351
- return new Promise((resolve) => {
352
- paramsWaiters.push(resolve);
353
- viewer.contentWindow?.postMessage({ type: "kakapo:getParams" }, viewerTarget);
354
- window.setTimeout(resolve, 500);
355
- });
356
- }
357
-
358
- function onViewerParams(params: Record<string, number>) {
359
- if (!viewerParams) {
360
- viewerParams = params;
361
- return;
362
- }
363
- const before = viewerParams;
364
- if (!Object.keys(params).some((k) => params[k] !== before[k])) return;
365
- viewerParams = params;
366
- lastActivity = Date.now();
367
- setStatus("Saving…");
368
- clearTimeout(syncTimer);
369
- syncTimer = window.setTimeout(() => void flushSync(), 700);
370
- }
371
-
372
311
  // ---- saving -------------------------------------------------------------------
373
312
 
374
313
  /** What the card changes besides the viewer's knobs. */
@@ -382,8 +321,6 @@ interface Finish {
382
321
  * changed). Serialised, so two quick changes cannot race each other's baseRev.
383
322
  */
384
323
  async function flushSync(finish?: Finish) {
385
- clearTimeout(syncTimer);
386
- syncTimer = undefined;
387
324
  while (syncing) await syncing;
388
325
  if (!design) return;
389
326
  const baseRev = design.rev;
@@ -452,15 +389,9 @@ async function poll() {
452
389
  const next = res.structuredContent as Design | undefined;
453
390
  if (!res.isError && next && next.rev > design.rev) {
454
391
  lastActivity = Date.now();
455
- if (syncTimer !== undefined) {
456
- // A slider move is waiting to be saved: save it first, so the reload
457
- // below shows the chat's change AND the user's.
458
- await flushSync();
459
- } else {
460
- design = next;
461
- render();
462
- if (next.rev > loadedRev) void loadViewer("Updated from the chat…");
463
- }
392
+ design = next;
393
+ render();
394
+ if (next.rev > loadedRev) void loadViewer("Updated from the chat…");
464
395
  }
465
396
  }
466
397
  } catch {
@@ -552,7 +483,7 @@ function render() {
552
483
 
553
484
  $("price").textContent = design.price.label;
554
485
  $("price-inline").textContent = design.price.label;
555
- if (!fallback.hidden) drawPreview(viewer.hidden);
486
+ if (!fallback.hidden) drawPreview(canvas.hidden);
556
487
  }
557
488
 
558
489
  /** An eyedropper (Lucide `pipette`, ISC). */
@@ -677,11 +608,10 @@ async function setKnob(name: string, value: number) {
677
608
  design = { ...design, options: design.options.map((o) => (o.name === name ? { ...o, value } : o)) };
678
609
  render();
679
610
  setStatus("Saving…");
680
- await freshViewerParams();
681
611
  viewerParams = { ...(viewerParams ?? {}), [name]: value };
682
- if (viewerCanSetParams) {
612
+ if (viewer) {
683
613
  // The viewer shows it at once; the save only records it.
684
- viewer.contentWindow?.postMessage({ type: "kakapo:setParams", params: { [name]: value } }, viewerTarget);
614
+ viewer.setParams({ [name]: value });
685
615
  await flushSync();
686
616
  } else {
687
617
  // An empty finish still means "the viewer is behind": swap in the saved revision.
@@ -769,7 +699,6 @@ async function setPaint(slot: Slot, paint: string[]) {
769
699
  design = { ...design, colors: { ...design.colors, [slot]: paint } };
770
700
  render();
771
701
  setStatus("Saving…");
772
- await freshViewerParams();
773
702
  await flushSync({ colors: { [slot]: paint } });
774
703
  }
775
704
 
@@ -779,7 +708,6 @@ async function setAngle(slot: Slot, angle: number) {
779
708
  design = { ...design, gradientAngles: { ...design.gradientAngles, [slot]: angle } };
780
709
  render();
781
710
  setStatus("Saving…");
782
- await freshViewerParams();
783
711
  await flushSync({ gradientAngles: { [slot]: angle } });
784
712
  }
785
713
 
@@ -827,8 +755,7 @@ async function order() {
827
755
  button.disabled = true;
828
756
  setStatus("Opening checkout…");
829
757
  try {
830
- await freshViewerParams();
831
- if (syncTimer !== undefined || syncing) await flushSync();
758
+ await syncing;
832
759
  const res = await callTool(app, "checkout_camera", { designId: design.designId });
833
760
  const quote = res.structuredContent as Quote | undefined;
834
761
  if (res.isError || typeof quote?.checkoutUrl !== "string") {
@@ -76,6 +76,8 @@ export interface CardHooks {
76
76
  * the controls before the first quote lands.
77
77
  */
78
78
  onInput?: (args: Record<string, unknown>) => void;
79
+ /** Called when the host is about to remove the card: release what outlives the DOM (a GPU device). */
80
+ onTeardown?: () => void;
79
81
  }
80
82
 
81
83
  export interface Card {
@@ -175,6 +177,7 @@ export function createCard(name: string, hooks: CardHooks): Card {
175
177
  // hidden iframe.
176
178
  app.onteardown = async () => {
177
179
  stopPolling();
180
+ hooks.onTeardown?.();
178
181
  return {};
179
182
  };
180
183