@womp/mcp-ui 0.1.8 → 0.1.10
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.
- package/README.md +36 -3
- package/dist/index.js +8 -8
- package/dist/print/index.html +7 -7
- package/dist/upload/index.html +1 -10
- package/package.json +1 -1
- package/src/print/main.ts +47 -1
- package/src/shared/bridge.ts +23 -0
- package/src/upload/index.html +0 -9
- package/src/upload/main.ts +12 -13
package/dist/upload/index.html
CHANGED
|
@@ -193,12 +193,6 @@
|
|
|
193
193
|
color: var(--fg2);
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
-
.actions {
|
|
197
|
-
display: flex;
|
|
198
|
-
gap: 8px;
|
|
199
|
-
flex-wrap: wrap;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
196
|
/* Names the failing layer instead of going blank — there is no console
|
|
203
197
|
inside the sandboxed iframe. Empty collapses. */
|
|
204
198
|
.status {
|
|
@@ -286,7 +280,7 @@ Boolean requesting whether a visible border and background is provided by the ho
|
|
|
286
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"]
|
|
287
281
|
- "model": Tool visible to and callable by the agent
|
|
288
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
|
|
289
|
-
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>bg){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,yg))},o)},l=e=>{e&&(a(),i=e,t.onResult(e),e.status===`running`&&e.operationId!==void 0&&(r=Date.now(),c(e.operationId,vg)))};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}}function gg(e,t){return e.openLink({url:t})}async function _g(e,t,n){return e.request({method:`tools/call`,params:{name:t,arguments:n}},Bp)}var $,vg,yg,bg,xg=t((()=>{mg(),Fm(),$=e=>document.getElementById(e),vg=2e3,yg=1e4,bg=36e4}));n((()=>{xg();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,t=!1){$(`error-text`).textContent=e,$(`error-actions`).hidden=!t||!r.summary?.browserUploadUrl,$(`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 _g(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 inside the chat. The upload page does the same thing in a tab.`,!0),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)}),$(`open-page`).addEventListener(`click`,()=>{let e=r.summary?.browserUploadUrl;e&&gg(ae.app,e)})}))();</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(),{}),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>
|
|
290
284
|
</head>
|
|
291
285
|
<body>
|
|
292
286
|
<div class="card" id="card">
|
|
@@ -339,9 +333,6 @@ container holding the app. Specify either width or maxWidth, and either height o
|
|
|
339
333
|
</svg>
|
|
340
334
|
<div class="body">
|
|
341
335
|
<div id="error-text"></div>
|
|
342
|
-
<div class="actions" id="error-actions" hidden>
|
|
343
|
-
<button class="btn" id="open-page" type="button">Open the upload page instead</button>
|
|
344
|
-
</div>
|
|
345
336
|
</div>
|
|
346
337
|
</div>
|
|
347
338
|
|
package/package.json
CHANGED
package/src/print/main.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $, callTool, createCard, openLink, type GenerationResult } from "../shared/bridge";
|
|
1
|
+
import { $, callTool, createCard, openLink, pushModelContext, type GenerationResult } from "../shared/bridge";
|
|
2
2
|
import { expandHexInput, nearestPantone, normalizeHex, pantoneChips } from "./pantone";
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -96,6 +96,8 @@ const MAX_LONGEST_CM = 60;
|
|
|
96
96
|
const PANEL_DEFAULT_TINT = "#276ee2";
|
|
97
97
|
/** The panel's own re-price debounce. */
|
|
98
98
|
const REQUOTE_DEBOUNCE_MS = 500;
|
|
99
|
+
/** State push: faster than a re-quote (it prices nothing) but still one per gesture, not per keystroke. */
|
|
100
|
+
const SYNC_DEBOUNCE_MS = 300;
|
|
99
101
|
const AXES: Axis[] = ["width", "height", "depth"];
|
|
100
102
|
|
|
101
103
|
const state = {
|
|
@@ -129,6 +131,7 @@ const state = {
|
|
|
129
131
|
/** Monotonic guard: a slow older quote must never overwrite a newer one. */
|
|
130
132
|
let quoteSeq = 0;
|
|
131
133
|
let debounceTimer: number | undefined;
|
|
134
|
+
let syncTimer: number | undefined;
|
|
132
135
|
|
|
133
136
|
// --- helpers ---------------------------------------------------------------
|
|
134
137
|
|
|
@@ -169,6 +172,7 @@ function setQuoting(on: boolean) {
|
|
|
169
172
|
function markDirty() {
|
|
170
173
|
state.cartCheckoutUrl = "";
|
|
171
174
|
state.preparedUrl = "";
|
|
175
|
+
scheduleSync();
|
|
172
176
|
}
|
|
173
177
|
|
|
174
178
|
/**
|
|
@@ -668,6 +672,48 @@ function scheduleRequote() {
|
|
|
668
672
|
debounceTimer = window.setTimeout(() => void requote(), REQUOTE_DEBOUNCE_MS);
|
|
669
673
|
}
|
|
670
674
|
|
|
675
|
+
/** "Tinted clear (resin-clear-tinted) · matte · #276ee2 (Pantone 2386 C) · 10.2 cm · x2" */
|
|
676
|
+
function describeSelection(): string {
|
|
677
|
+
const m = selectedMaterial();
|
|
678
|
+
const snapped = snappedColor();
|
|
679
|
+
const bits = [`${materialLabel(m)} (${state.material})`];
|
|
680
|
+
if (state.finish && m?.finishes?.length) bits.push(state.finish);
|
|
681
|
+
if (snapped) bits.push(`${snapped.hex} (Pantone ${snapped.code})`);
|
|
682
|
+
if (state.longestSideCm) bits.push(`${fmtDim(state.longestSideCm, state.unit)} ${state.unit} longest side`);
|
|
683
|
+
bits.push(`x${state.quantity}`);
|
|
684
|
+
return bits.join(" · ");
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Publish what the card is showing — the whole point of the card being live.
|
|
689
|
+
*
|
|
690
|
+
* Its re-quotes are app-initiated calls whose results come back here and go
|
|
691
|
+
* nowhere else, so a configuration tuned for two minutes is invisible to the
|
|
692
|
+
* conversation: ask for it in chat and the model orders the settings it opened
|
|
693
|
+
* with. Two channels, deliberately: `sync_print_config` parks the selection on
|
|
694
|
+
* the server, which is what `add_to_cart` actually reads, and
|
|
695
|
+
* `updateModelContext` tells the model so it can talk about the right print
|
|
696
|
+
* (host-gated, and a no-op where it is unsupported).
|
|
697
|
+
*
|
|
698
|
+
* Failures are swallowed. A state push that does not land costs an out-of-date
|
|
699
|
+
* order note, not a broken card, and the user has the button right there.
|
|
700
|
+
*/
|
|
701
|
+
function syncConfig() {
|
|
702
|
+
if (!state.source || state.staticPrintUrl || !state.material) return;
|
|
703
|
+
void callTool(card.app, "sync_print_config", baseArgs()).catch(() => {});
|
|
704
|
+
void pushModelContext(
|
|
705
|
+
card.app,
|
|
706
|
+
`The 3D print card in this conversation now shows: ${describeSelection()}. ` +
|
|
707
|
+
"These are the user's own selections on the card, later than anything said in chat. " +
|
|
708
|
+
"If they ask to order or add it to the cart, call add_to_cart with only the mesh source.",
|
|
709
|
+
);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
function scheduleSync() {
|
|
713
|
+
if (syncTimer !== undefined) clearTimeout(syncTimer);
|
|
714
|
+
syncTimer = window.setTimeout(syncConfig, SYNC_DEBOUNCE_MS);
|
|
715
|
+
}
|
|
716
|
+
|
|
671
717
|
async function addToCart() {
|
|
672
718
|
const cta = $("cta") as HTMLButtonElement;
|
|
673
719
|
cta.disabled = true;
|
package/src/shared/bridge.ts
CHANGED
|
@@ -202,6 +202,29 @@ export async function callTool(app: App, name: string, args: Record<string, unkn
|
|
|
202
202
|
return app.request({ method: "tools/call", params: { name, arguments: args } }, CallToolResultSchema);
|
|
203
203
|
}
|
|
204
204
|
|
|
205
|
+
/**
|
|
206
|
+
* Push what the card is showing into the model's context for the next turn.
|
|
207
|
+
*
|
|
208
|
+
* A card's own tool calls are announced to nobody: the host proxies them and
|
|
209
|
+
* hands the result back to the iframe, so nothing the user changes here reaches
|
|
210
|
+
* the conversation. `ui/update-model-context` is the channel for that — the
|
|
211
|
+
* host holds the last update and gives it to the model on the next user
|
|
212
|
+
* message. It is host-gated, and Claude web was reported to drop the payload
|
|
213
|
+
* silently, so this is a bonus that makes the model DESCRIBE the right print,
|
|
214
|
+
* never the thing correctness rests on: the server holds the configuration too.
|
|
215
|
+
*
|
|
216
|
+
* No-ops (rather than throws) when the host does not advertise the capability.
|
|
217
|
+
*/
|
|
218
|
+
export async function pushModelContext(app: App, text: string) {
|
|
219
|
+
const supported = (app.getHostCapabilities() as { updateModelContext?: unknown } | undefined)?.updateModelContext;
|
|
220
|
+
if (!supported) return;
|
|
221
|
+
try {
|
|
222
|
+
await app.updateModelContext({ content: [{ type: "text", text }] });
|
|
223
|
+
} catch {
|
|
224
|
+
// A host that rejects the update is not a card the user can do nothing with.
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
|
|
205
228
|
/** Toggle fullscreen, trusting the host's answer over our request. */
|
|
206
229
|
export function toggleFullscreen(app: App) {
|
|
207
230
|
const isFull = document.documentElement.dataset.displayMode === "fullscreen";
|
package/src/upload/index.html
CHANGED
|
@@ -193,12 +193,6 @@
|
|
|
193
193
|
color: var(--fg2);
|
|
194
194
|
}
|
|
195
195
|
|
|
196
|
-
.actions {
|
|
197
|
-
display: flex;
|
|
198
|
-
gap: 8px;
|
|
199
|
-
flex-wrap: wrap;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
196
|
/* Names the failing layer instead of going blank — there is no console
|
|
203
197
|
inside the sandboxed iframe. Empty collapses. */
|
|
204
198
|
.status {
|
|
@@ -264,9 +258,6 @@
|
|
|
264
258
|
</svg>
|
|
265
259
|
<div class="body">
|
|
266
260
|
<div id="error-text"></div>
|
|
267
|
-
<div class="actions" id="error-actions" hidden>
|
|
268
|
-
<button class="btn" id="open-page" type="button">Open the upload page instead</button>
|
|
269
|
-
</div>
|
|
270
261
|
</div>
|
|
271
262
|
</div>
|
|
272
263
|
|
package/src/upload/main.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { $, callTool, createCard,
|
|
1
|
+
import { $, callTool, createCard, type GenerationResult } from "../shared/bridge";
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* The upload card — renders `create_upload` / `get_upload` and lets the user
|
|
@@ -16,8 +16,13 @@ import { $, callTool, createCard, openLink, type GenerationResult } from "../sha
|
|
|
16
16
|
* include the API origin (swan-backend adds its own origin at registration —
|
|
17
17
|
* the baked CSP cannot know which environment it will serve), and the backend
|
|
18
18
|
* answers the PUT with open CORS because the iframe origin is opaque. If either
|
|
19
|
-
* is missing the PUT fails as a network error
|
|
20
|
-
*
|
|
19
|
+
* is missing the PUT fails as a bare network error — there is no console in the
|
|
20
|
+
* sandbox, so the status line names that layer explicitly.
|
|
21
|
+
*
|
|
22
|
+
* There is no "open the upload page instead" exit any more: the swan-frontend
|
|
23
|
+
* page this card replaced was removed (2026-09-15, Anuj — one path, not two),
|
|
24
|
+
* so the recovery for a blocked PUT is the agent's own `curl -T`, which the
|
|
25
|
+
* tool text gives it.
|
|
21
26
|
*
|
|
22
27
|
* It also polls the app-callable `get_upload` while pending, so a file the
|
|
23
28
|
* AGENT pushed itself (an agent with a shell does that first) flips this card
|
|
@@ -33,7 +38,6 @@ interface UploadSummary {
|
|
|
33
38
|
maxMb: number;
|
|
34
39
|
expiresAt: string;
|
|
35
40
|
uploadUrl: string;
|
|
36
|
-
browserUploadUrl: string;
|
|
37
41
|
fileSize?: number;
|
|
38
42
|
url?: string;
|
|
39
43
|
lastError?: string;
|
|
@@ -86,9 +90,8 @@ function showOnly(id: "drop" | "progress" | "done" | "expired" | null) {
|
|
|
86
90
|
for (const key of ["drop", "progress", "done", "expired"] as const) $(key).hidden = key !== id;
|
|
87
91
|
}
|
|
88
92
|
|
|
89
|
-
function showError(text: string
|
|
93
|
+
function showError(text: string) {
|
|
90
94
|
$("error-text").textContent = text;
|
|
91
|
-
$("error-actions").hidden = !withPageFallback || !state.summary?.browserUploadUrl;
|
|
92
95
|
$("error").hidden = false;
|
|
93
96
|
}
|
|
94
97
|
|
|
@@ -282,10 +285,11 @@ function upload(file: File) {
|
|
|
282
285
|
};
|
|
283
286
|
const networkFailure = () => {
|
|
284
287
|
// No response at all: the host's sandbox refused the request (CSP or
|
|
285
|
-
// CORS), or the network dropped.
|
|
288
|
+
// CORS), or the network dropped. Retrying is worth one try; past that the
|
|
289
|
+
// assistant can send the file itself if it has a shell.
|
|
286
290
|
state.phase = "pending";
|
|
287
291
|
render();
|
|
288
|
-
showError("Could not send the file from
|
|
292
|
+
showError("Could not send the file from here. Try again — or ask your assistant to upload it for you.");
|
|
289
293
|
setStatus("PUT to the upload URL got no response — check connectDomains / CORS if this repeats.", true);
|
|
290
294
|
schedulePoll(POLL_START_MS);
|
|
291
295
|
};
|
|
@@ -344,8 +348,3 @@ drop.addEventListener("drop", (e) => {
|
|
|
344
348
|
const file = (e as DragEvent).dataTransfer?.files?.[0];
|
|
345
349
|
if (file) upload(file);
|
|
346
350
|
});
|
|
347
|
-
|
|
348
|
-
$("open-page").addEventListener("click", () => {
|
|
349
|
-
const url = state.summary?.browserUploadUrl;
|
|
350
|
-
if (url) void openLink(card.app, url);
|
|
351
|
-
});
|