@beyondwork/wb-cli 0.1.38 → 0.1.40
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/CHANGELOG.md +15 -0
- package/out/cli.js +1799 -194
- package/out/extension.js +98 -98
- package/out/headless-host.js +71 -0
- package/package.json +1 -1
- package/wb-cli/skills/bw-workblock/SKILL.md +10 -8
- package/wb-cli/skills/bw-workblock/references/browser-validation.md +166 -78
- package/wb-cli/skills/bw-workblock/references/browser-run.sh +0 -104
- package/wb-cli/skills/bw-workblock/references/validate-ui.mjs +0 -279
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
(function(){var e=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function t(t){return typeof t==`string`&&e.test(t)}function n(e){return typeof e==`string`&&e.startsWith(`::bw:data:`)}function r(e){return t(e)?{task_id:e}:{task_name:e}}function i(e,t){return{...r(e.taskName),workblock_id:t.workblockId,module_id:t.moduleId,inputs:e.inputArgs,commit_ref:t.commitRef,data_environment_id:t.dataEnvironmentId}}function a(e,t){return{...r(e.taskName),run_id:t.runId,inputs:e.inputArgs,ui_task_run_id:t.uiTaskRunId}}async function o(e,t){let r={...e};return await Promise.all(Object.entries(r).map(async([e,i])=>{n(i)?r[e]=await t(i):typeof i==`string`&&i.startsWith(`$$$::bw:data:`)&&(r[e]=i.substring(3))})),r}function s(e){let t={};return e.forEach((e,n)=>{t[n]=e}),t}function c(){let e=null,t=0,n=[],r=null,i=null,a={},o={},s=new Map,c=new Map,l=new Map,u=new Map,d=0,f=`/`,p=null,m=null,h=[],g=new Map;function _(e){return(e??``).replace(/\s+/g,` `).trim()}function v(e,t){return _(e).toLowerCase().includes(_(t).toLowerCase())}function y(e){let t=globalThis.CSS;return t?.escape?t.escape(e):e.replace(/["\\]/g,`\\$&`)}function b(e){let t=[];return(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement||e instanceof HTMLSelectElement)&&t.push(...Array.from(e.labels??[]).map(e=>_(e.textContent))),e.id&&t.push(...Array.from(document.querySelectorAll(`label[for="${y(e.id)}"]`)).map(e=>_(e.textContent))),t.filter(Boolean)}function x(e){return e.split(/\s+/).map(e=>document.getElementById(e)?.textContent).map(_).filter(Boolean).join(` `)}function S(e){let t=e.tagName.toLowerCase();if(t===`button`)return`button`;if(t===`a`&&e.hasAttribute(`href`))return`link`;if(t===`textarea`)return`textbox`;if(t===`select`)return`combobox`;if(t===`form`)return`form`;if(t===`img`)return`img`;if(/^h[1-6]$/.test(t))return`heading`;if(t===`ul`||t===`ol`)return`list`;if(t===`li`)return`listitem`;if(t===`table`)return`table`;if(t===`tr`)return`row`;if(t===`td`||t===`th`)return`cell`;if(t!==`input`)return null;let n=(e.type||`text`).toLowerCase();return n===`checkbox`?`checkbox`:n===`radio`?`radio`:[`button`,`submit`,`reset`].includes(n)?`button`:n===`range`?`slider`:`textbox`}function C(e){return e.getAttribute(`role`)?.split(/\s+/)[0]||S(e)}function w(e){let t=e.getAttribute(`aria-label`);if(t)return _(t);let n=e.getAttribute(`aria-labelledby`);if(n)return x(n);let r=b(e);return r.length>0?r.join(` `):e instanceof HTMLInputElement&&[`button`,`submit`,`reset`].includes(e.type)?_(e.value):e instanceof HTMLImageElement?_(e.alt):(e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.placeholder?_(e.placeholder):_(e.getAttribute(`title`)||e.textContent)}function T(){return Array.from(document.body.querySelectorAll(`*`))}function E(e,t){let n=e.toLowerCase();return T().filter(e=>C(e)?.toLowerCase()===n?!t||v(w(e),t):!1)}function D(e){return T().filter(t=>b(t).some(t=>v(t,e))?!0:v(t.getAttribute(`aria-label`),e))}function O(e){return T().filter(t=>t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement?v(t.placeholder,e):!1)}function k(e){return T().filter(t=>v(t.textContent,e)?!Array.from(t.children).some(t=>v(t.textContent,e)):!1)}function A(e){return e.length===0?null:e.length===1?e[0]:e.find(e=>N(e))??e[0]}async function j(e){return e.selector?document.querySelector(e.selector):e.testid?A(Array.from(document.querySelectorAll(`[data-testid="${y(e.testid)}"]`))):e.role?A(E(e.role,e.name)):e.label?A(D(e.label)):e.placeholder?A(O(e.placeholder)):e.text?A(k(e.text)):null}function M(e){return e.selector?`selector "${e.selector}"`:e.testid?`testid "${e.testid}"`:e.role&&e.name?`role "${e.role}" with name "${e.name}"`:e.role?`role "${e.role}"`:e.label?`label "${e.label}"`:e.placeholder?`placeholder "${e.placeholder}"`:e.text?`text "${e.text}"`:`empty query`}function N(e){let t=window.getComputedStyle(e);if(t.display===`none`||t.visibility===`hidden`||t.opacity===`0`)return!1;let n=e.getBoundingClientRect();return n.width>0&&n.height>0}async function P(e){let t=await j(e);if(!t)return null;let n=t.getBoundingClientRect(),r={};for(let e of t.attributes)r[e.name]=e.value;return{exists:!0,visible:N(t),text:t.textContent?.trim()||``,value:t.value,attributes:r,rect:{x:n.x,y:n.y,width:n.width,height:n.height},tagName:t.tagName.toLowerCase()}}async function F(e){let t=await j(e);return t?t instanceof HTMLElement?(t.click(),{success:!0}):{success:!1,error:`Element is not clickable: ${M(e)}`}:{success:!1,error:`Element not found: ${M(e)}`}}function I(e,t){let n=e instanceof HTMLTextAreaElement?HTMLTextAreaElement.prototype:HTMLInputElement.prototype,r=Object.getOwnPropertyDescriptor(n,`value`)?.set;r?r.call(e,t):e.value=t}async function L(e,t,n,r){let i=await j(e);return i?i instanceof HTMLInputElement||i instanceof HTMLTextAreaElement?(i.focus(),I(i,n?t:i.value+t),i.dispatchEvent(new Event(`input`,{bubbles:!0})),i.dispatchEvent(new Event(`change`,{bubbles:!0})),r&&(i.dispatchEvent(new KeyboardEvent(`keydown`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keypress`,{key:`Enter`,code:`Enter`,bubbles:!0})),i.dispatchEvent(new KeyboardEvent(`keyup`,{key:`Enter`,code:`Enter`,bubbles:!0}))),{success:!0}):{success:!1,error:`Element is not an input: ${M(e)}`}:{success:!1,error:`Element not found: ${M(e)}`}}async function ee(e,t){let n=e?await j(e):document.activeElement;if(!(n instanceof HTMLElement))return{success:!1,error:e?`Element not found: ${M(e)}`:`No active element`};n.focus();for(let e of[`keydown`,`keypress`,`keyup`])n.dispatchEvent(new KeyboardEvent(e,{key:t,code:t,bubbles:!0,cancelable:!0}));return{success:!0}}async function te(e,t,n){let r=e?await j(e):document.scrollingElement;return r instanceof Element?(r.scrollBy({left:t,top:n,behavior:`auto`}),r.dispatchEvent(new Event(`scroll`,{bubbles:!0})),{success:!0}):{success:!1,error:e?`Element not found: ${M(e)}`:`No scrolling element`}}async function R(e,t,n=5e3){let r=Date.now(),i=async()=>{let n=await j(e);switch(t){case`attached`:return n!==null;case`detached`:return n===null;case`visible`:return n!==null&&N(n);case`hidden`:return n===null||!N(n)}};return new Promise(a=>{let o=async()=>{if(await i()){a({success:!0});return}if(Date.now()-r>=n){a({success:!1,error:`Timeout waiting for element ${M(e)} to be ${t}`});return}requestAnimationFrame(o)};o()})}let z=null,B=null;async function V(){return z||B||(B=new Promise((e,t)=>{let n=document.createElement(`script`);n.src=`https://unpkg.com/html-to-image@1.11.13/dist/html-to-image.js`,n.onload=()=>{z=window.htmlToImage,z?e(z):t(Error(`html-to-image not found on window`))},n.onerror=()=>t(Error(`Failed to load html-to-image`)),document.head.appendChild(n)}),B)}async function H(e){let t=document.body.style.width,n=document.documentElement.style.width,r=document.documentElement.style.overflow;e&&(document.documentElement.style.width=`${e}px`,document.body.style.width=`${e}px`,document.documentElement.style.overflow=`hidden`,document.body.offsetHeight,await new Promise(e=>requestAnimationFrame(e)));try{let e=await(await V()).toPng(document.body,{backgroundColor:`#ffffff`,pixelRatio:1});return e.startsWith(`data:image/png;base64,`)?e.split(`,`)[1]:e}catch(e){return console.error(`Error capturing screenshot:`,e),``}finally{e&&(document.body.style.width=t,document.documentElement.style.width=n,document.documentElement.style.overflow=r)}}function U(e){if(e.id)return`#${e.id}`;let t=e.getAttribute(`data-testid`);if(t)return`[data-testid="${t}"]`;let n=[e.tagName.toLowerCase()],r=e.getAttribute(`role`);r&&n.push(`[role="${r}"]`);let i=e.getAttribute(`type`);i&&n.push(`[type="${i}"]`);let a=e.getAttribute(`name`);a&&n.push(`[name="${a}"]`);let o=Array.from(e.classList).find(e=>!e.startsWith(`_`)&&e.length<30);o&&n.push(`.${o}`);let s=n.join(``);if(document.querySelectorAll(s).length===1)return s;let c=e.parentElement;return c?`${s}:nth-of-type(${Array.from(c.children).filter(t=>t.tagName===e.tagName).indexOf(e)+1})`:s}function W(){let e=[];document.querySelectorAll(`button, [role="button"], input[type="submit"], input[type="button"]`).forEach(t=>{let n=w(t)||t.value||``;e.push({text:n,selector:U(t),disabled:t.disabled||t.getAttribute(`aria-disabled`)===`true`})});let t=[];document.querySelectorAll(`input, textarea, select`).forEach(e=>{let n=e;t.push({selector:U(e),type:n.type||e.tagName.toLowerCase(),name:n.name||w(e)||void 0,value:n.value||void 0})});let n=[];document.querySelectorAll(`form`).forEach(e=>{n.push({id:e.id||void 0,name:e.name||void 0,inputCount:e.querySelectorAll(`input, textarea, select`).length})});let r=[];return document.querySelectorAll(`a[href]`).forEach(e=>{r.push({text:w(e)||``,href:e.href})}),{title:document.title,url:window.location.href,forms:n,buttons:e,inputs:t,links:r}}function ne(e){let t=e.data;`replyTo`in t?ie(t):re(t)}async function re(t){if(!e)throw Error(`Communication channel not initialized, but since we received a message, this should not happen`);switch(t.payload.type){case`GET_DATA`:{let n={status:`OK`};if($.onGetData)try{let e=await $.onGetData();if($._usingSetSubmitHandler)n={status:`OK`,data:e};else{if(!e||typeof e!=`object`||!(`status`in e))throw Error(`Unexpected result shape returned by bw.onGetData callback. Expected { status: "OK" | "ERROR", data?: any, error?: string }`);n=e}}catch(e){if($._usingSetSubmitHandler)n={status:`ERROR`,error:e instanceof Error?e.message:`Unknown error`};else throw e}let r={type:`GET_DATA_RESPONSE`,data:n};e.postMessage({replyTo:t.requestId,payload:r});break}case`ON_ACTION`:{let r=t.payload.key,i=n[parseInt(r,10)];if(typeof i.execute!=`string`)try{i.execute()}catch(e){console.error(`Error in action handler:`,e)}e.postMessage({replyTo:t.requestId,payload:{type:`ACK`}});break}case`ON_EVENT`:{let n=a[t.payload.event];if(n)try{n(t.payload.data)}catch(e){console.error(`Error in event handler:`,e)}e.postMessage({replyTo:t.requestId,payload:{type:`ACK`}});break}case`TEST_QUERY_ELEMENT`:{let n=await P(t.payload.query);e.postMessage({replyTo:t.requestId,payload:{type:`TEST_QUERY_ELEMENT_RESPONSE`,result:n}});break}case`TEST_CLICK_ELEMENT`:{let n=await F(t.payload.query);e.postMessage({replyTo:t.requestId,payload:{type:`TEST_CLICK_ELEMENT_RESPONSE`,...n}});break}case`TEST_TYPE_INTO_ELEMENT`:{let n=await L(t.payload.query,t.payload.text,t.payload.clear,t.payload.pressEnter);e.postMessage({replyTo:t.requestId,payload:{type:`TEST_TYPE_INTO_ELEMENT_RESPONSE`,...n}});break}case`TEST_PRESS_KEY`:{let n=await ee(t.payload.query,t.payload.key);e.postMessage({replyTo:t.requestId,payload:{type:`TEST_PRESS_KEY_RESPONSE`,...n}});break}case`TEST_SCROLL`:{let n=await te(t.payload.query,t.payload.deltaX??0,t.payload.deltaY??600);e.postMessage({replyTo:t.requestId,payload:{type:`TEST_SCROLL_RESPONSE`,...n}});break}case`TEST_WAIT_FOR_ELEMENT`:{let n=await R(t.payload.query,t.payload.state,t.payload.timeout);e.postMessage({replyTo:t.requestId,payload:{type:`TEST_WAIT_FOR_ELEMENT_RESPONSE`,...n}});break}case`TEST_GET_SCREENSHOT`:{let n=await H(t.payload.width);e.postMessage({replyTo:t.requestId,payload:{type:`TEST_SCREENSHOT_RESPONSE`,imageBase64:n}});break}case`TEST_GET_PAGE_STRUCTURE`:{let n=W();e.postMessage({replyTo:t.requestId,payload:{type:`TEST_PAGE_STRUCTURE_RESPONSE`,structure:n}});break}case`SET_ROUTE`:{let{url:n}=t.payload;n!==f&&(f=n,p&&p(f)),e.postMessage({replyTo:t.requestId,payload:{type:`SET_ROUTE_ACK`}});break}default:e.postMessage({type:`ERROR`,message:`Unknown request type`}),t.payload}}function ie(e){let t=g.get(e.replyTo);t&&(e.payload&&e.payload.type===`ERROR`?t.reject(Error(e.payload.message??`Unknown error`)):e.payload&&t.resolve(e.payload),g.delete(e.replyTo))}async function G(n){return new Promise((r,i)=>{let a=++t;g.set(a,{resolve:r,reject:i});let o={requestId:a,payload:n};e?e.postMessage(o):h.push(o)})}function K(){a.__yjs_event__||=e=>{let t=e,n=t.data_key;n&&s.get(n)?.forEach(e=>{e(t)})},a.__yjs_events_reset__||=e=>{let t=e;c.get(t.data_key)?.forEach(e=>{e()})}}function ae(){a.__graphlake_change__||=e=>{let{subscriptionId:t,...n}=e;u.get(t)?.onDelta(n)},a.__graphlake_ended__||=e=>{let t=e,n=u.get(t.subscriptionId);u.delete(t.subscriptionId),n?.onError?.(Error(t.error??`The GraphLake subscription ended: ${t.reason}`))}}function q(){return[...new Set([...l.values()].flat())]}function J(){G({type:`SET_SHORTCUTS`,shortcuts:q()}).catch(()=>{})}function oe(e){let t=e;q().includes(t.shortcut)&&document.body.dispatchEvent(new KeyboardEvent(`keydown`,{key:t.key,code:t.code,altKey:t.altKey,ctrlKey:t.ctrlKey,metaKey:t.metaKey,shiftKey:t.shiftKey,repeat:t.repeat,bubbles:!0,cancelable:!0,composed:!0}))}function Y(e){return(s.get(e)?.size??0)+(c.get(e)?.size??0)}function X(e){Y(e)===1&&G({type:`YJS_SUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to subscribe to YJS events:`,e)})}function Z(e){Y(e)===0&&G({type:`YJS_UNSUBSCRIBE_EVENTS`,dataKey:e}).catch(e=>{console.error(`Failed to unsubscribe from YJS events:`,e)})}function se(t){if(t.source!==window.parent)return;let n=t.ports?.[0];(t.data===`INIT_CHANNEL`||t.data&&typeof t.data==`object`&&t.data.type===`INIT_CHANNEL`)&&n&&(e=n,e.onmessage=ne,typeof t.data==`object`&&t.data.initialRoute&&t.data.initialRoute!==`/`&&(f=t.data.initialRoute,p&&p(f)),h.forEach(e=>{e.payload.type===`ROUTE_CHANGED`&&(e.payload.url=f),n.postMessage(e)}))}window.addEventListener(`message`,se);async function Q(e){n=e,await G({type:`SET_ACTIONS`,actions:e.map((e,t)=>{let n;return n=typeof e.execute==`string`?e.execute:t.toString(),{label:e.label,disabled:e.disabled,variant:e.variant,key:n}})})}let $={request:G,saveBlob:async e=>{let t=await G({type:`SAVE_BLOB`,blob:e});if(t.type===`SAVE_BLOB_RESPONSE`)return t.blobRef;throw Error(`Failed to save blob`)},fetchBlob:async e=>{if(typeof e!=`string`||!e.startsWith(`::bw:data:`))throw Error(`Unexpected argument to bw.fetchBlob. Argument is not a blob reference.`);let t=await G({type:`FETCH_BLOB`,blobRef:e});if(t.type===`FETCH_BLOB_RESPONSE`)return t.blob;throw Error(`Failed to fetch blob`)},getData:async()=>{let e=await G({type:`GET_UI_DATA`});if(e.type===`GET_UI_DATA_RESPONSE`)return e.data;throw Error(`Failed to get data`)},invokeTask:(async(e,t,n=30,r=void 0)=>{let i=await G({type:`INVOKE_TASK`,taskName:e,inputArgs:t,timeout:n});if(i.type===`INVOKE_RESPONSE`)return r?i.result[r]:{...i,status:`OK`};throw Error(`Failed to invoke task`)}),continue:async e=>{await G({type:`CONTINUE_UI`,inputArgs:e})},setActions:e=>{let t=n,i=r,a=Symbol(`actions`);return r=a,Q(e),()=>{r===a&&(r=i,Q(t))}},setEventHandler:(e,t)=>{let n=Symbol(`eventHandler`);return a[e]=t,o[e]=n,()=>{o[e]===n&&(delete a[e],delete o[e])}},registerShortcuts:e=>{let t=Symbol(`shortcuts`);return l.set(t,[...e]),a.__shortcut__=oe,J(),()=>{l.delete(t)&&J()}},setSubmitHandler:e=>{let t=Symbol(`submitHandler`);return $.onGetData=e,$._usingSetSubmitHandler=!0,i=t,G({type:`SET_SUBMIT_HANDLER`,present:!0}).catch(()=>{}),()=>{i===t&&(delete $.onGetData,$._usingSetSubmitHandler=!1,i=null,G({type:`SET_SUBMIT_HANDLER`,present:!1}).catch(()=>{}))}},setChildRunListener:e=>{a.__child_runs__=e,G({type:`SUBSCRIBE_CHILD_RUNS`}).then(t=>{t.type===`CHILD_RUNS_UPDATE`&&e(t.childRuns)}).catch(t=>{console.error(`Failed to subscribe to child runs:`,t),e([])})},navigate:e=>{e!==f&&(f=e,G({type:`ROUTE_CHANGED`,url:e}))},getRoute:()=>f,onRouteChange:e=>{p=e},connectRouter:e=>{let t=Symbol();m=t,G({type:`ROUTE_CHANGED`,url:f}),G({type:`ROUTES_CHANGED`,routes:e.routes??[]});let n=e.subscribe(e=>{m===t&&$.navigate(e)});return p=t=>{e.navigate(t)},e.navigate(f),()=>{n(),m===t&&(m=null,p=null,G({type:`ROUTES_CHANGED`,routes:[]}))}},navigateToStream:async e=>{await G({type:`NAVIGATE_TO_STREAM`,streamId:e})},openPlatformChat:async e=>{let t=await G({type:`OPEN_PLATFORM_CHAT`,emptyState:e?.emptyState,placeholder:e?.placeholder,id:e?.id,agent:e?.agent,args:e?.args,reset:e?.reset});if(t?.type===`OPEN_PLATFORM_CHAT_RESPONSE`)return{streamId:t.streamId,close:e=>$.closePlatformChat(e)};throw Error(`Unexpected response from openPlatformChat`)},closePlatformChat:async e=>{await G({type:`CLOSE_PLATFORM_CHAT`,closeStream:e?.closeStream})},emitYjsEvent:async(e,t,n)=>{let r=await G({type:`YJS_EMIT_EVENT`,dataKey:e,data:t,transient:n?.transient});if(r.type===`YJS_EMIT_EVENT_RESPONSE`)return r.event;throw Error(`Failed to emit YJS event`)},getYjsEvents:async e=>{let t=await G({type:`YJS_GET_EVENTS`,dataKey:e});if(t.type===`YJS_GET_EVENTS_RESPONSE`)return t.events;throw Error(`Failed to get YJS events`)},resetYjsEvents:async e=>{await G({type:`YJS_RESET_EVENTS`,dataKey:e})},subscribeYjsEvents:(e,t)=>{let n=s.get(e)??new Set;return n.add(t),s.set(e,n),K(),X(e),()=>{let n=s.get(e);n&&(n.delete(t),n.size===0&&s.delete(e),Z(e))}},onYjsEventsReset:(e,t)=>{let n=c.get(e)??new Set;return n.add(t),c.set(e,n),K(),X(e),()=>{let n=c.get(e);n&&(n.delete(t),n.size===0&&c.delete(e),Z(e))}},graphlake:{query:async(e,t)=>{let n=await G({type:`GRAPHLAKE_QUERY`,glq:e,params:t?.params,pageSize:t?.pageSize,pageToken:t?.pageToken});if(n.type===`GRAPHLAKE_QUERY_RESPONSE`)return n.page;throw Error(`Failed to query GraphLake`)},subscribe:(e,t,n)=>{d+=1;let r=`graphlake-${d}`;return u.set(r,{onDelta:n,onError:t?.onError}),ae(),G({type:`GRAPHLAKE_SUBSCRIBE`,subscriptionId:r,glq:e,params:t?.params}).catch(e=>{let t=u.get(r);u.delete(r);let n=e instanceof Error?e:Error(String(e));t?.onError?t.onError(n):t&&console.error(`Failed to subscribe to GraphLake:`,n)}),()=>{u.delete(r)&&G({type:`GRAPHLAKE_UNSUBSCRIBE`,subscriptionId:r}).catch(()=>{})}}},bindYjsDoc:(e,t,n)=>{let r=n?.doc??new t.Doc,i=n?.awareness?.module??null,a=n?.awareness?.instance??(i?new i.Awareness(r):null),o=!1,s=!1,c=32*1024,l=e=>{let t=``;for(let n=0;n<e.length;n+=c)t+=String.fromCharCode.apply(null,Array.from(e.subarray(n,n+c)));return btoa(t)},u=e=>{let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n},d=!1,f=[],p=e=>{s=!0,t.applyUpdate(r,e),s=!1},m=t=>{o||s||$.emitYjsEvent(e,l(t)).catch(e=>{console.error(`Failed to emit yjs doc update:`,e)})};r.on(`update`,m);let h=$.subscribeYjsEvents(e,e=>{if(o)return;let t=u(e.data);if(!d){f.push(t);return}p(t)});$.getYjsEvents(e).then(e=>{if(!o){for(let t of e)p(u(t.data));for(let e of f)p(e);f.length=0,d=!0}}).catch(e=>{console.error(`Failed to load yjs snapshot:`,e),d=!0;for(let e of f)p(e);f.length=0});let g=$.onYjsEventsReset(e,()=>{if(o)return;s=!0;let e=new t.Doc,n=t.encodeStateAsUpdate(e);t.applyUpdate(r,n),s=!1}),_=`${e}:awareness`,v=null;if(a&&i){v=({added:e,updated:t,removed:n})=>{if(o)return;let r=[...e,...t,...n],s=i.encodeAwarenessUpdate(a,r);$.emitYjsEvent(_,l(s),{transient:!0}).catch(e=>{console.error(`Failed to emit awareness update:`,e)})},a.on(`update`,v);let e={unsubscribeAwareness:$.subscribeYjsEvents(_,e=>{o||i.applyAwarenessUpdate(a,u(e.data),`remote`)})};return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g(),e.unsubscribeAwareness(),v&&a.off(`update`,v),i.removeAwarenessStates(a,[r.clientID],null)}}}return{doc:r,awareness:a,destroy:()=>{o=!0,r.off(`update`,m),h(),g()}}}};return $}var l=/^[a-zA-Z][a-zA-Z0-9-]*$/,u=/^[a-zA-Z0-9 \-_.+/=:*'@~%]*$/;function d(e){let t=new Map;for(let n of e.split(`;`)){let e=n.trim();if(!e)continue;let r=e.search(/\s/),i=(r===-1?e:e.slice(0,r)).toLowerCase(),a=r===-1?``:e.slice(r+1).trim().replace(/\s+/g,` `);if(!l.test(i))throw Error(`Invalid CSP directive name: ${JSON.stringify(i)}`);if(!u.test(a))throw Error(`Invalid CSP directive value for ${JSON.stringify(i)}`);t.set(i,a)}return t}function f(e,t){let n=d(e.join(`; `));if(t)for(let[e,r]of d(t))n.set(e,r);return Array.from(n,([e,t])=>t?`${e} ${t}`:e).join(`; `)}function p(e){let t=`default`,n=0,r=!1,i=new Map,a=e=>e===`granted`||e==="default"?e:`denied`,o=e=>{let t=e?.id;return typeof t==`string`?t:``},s=()=>{r||!e.bw||(r=!0,e.bw.setEventHandler(`__notification_click__`,e=>i.get(o(e))?.fire(`click`)),e.bw.setEventHandler(`__notification_close__`,e=>{let t=i.get(o(e));i.delete(o(e)),t?.fire(`close`)}))},c=async n=>{if(!e.bw)return t;s();try{let r=await e.bw.request({type:`NOTIFICATIONS_REQUEST_PERMISSION`,prompt:n});r.type===`NOTIFICATIONS_PERMISSION_RESPONSE`&&(t=a(r.permission))}catch{return t}return t};class l extends EventTarget{static get permission(){return t}static requestPermission(e){let t=c(!0);return e&&t.then(e),t}constructor(t,r){super(),n+=1,Object.assign(this,{title:String(t),body:typeof r?.body==`string`?r.body:``,tag:typeof r?.tag==`string`?r.tag:``,onclick:null,onclose:null,onerror:null,onshow:null,id:`notification-${n}`}),i.set(this.id,this);let a=()=>{i.delete(this.id),this.fire(`error`)};if(!e.bw){queueMicrotask(a);return}s(),e.bw.request({type:`NOTIFICATIONS_SHOW`,id:this.id,title:this.title,body:this.body||void 0,tag:this.tag||void 0}).then(e=>e.type===`NOTIFICATIONS_SHOW_RESPONSE`&&e.shown?this.fire(`show`):a()).catch(a)}close(){i.delete(this.id)&&(e.bw?.request({type:`NOTIFICATIONS_CLOSE`,id:this.id}).catch(()=>{}),this.fire(`close`))}fire(e){let t=new Event(e);({click:this.onclick,close:this.onclose,error:this.onerror,show:this.onshow})[e]?.call(this,t),this.dispatchEvent(t)}}e.Notification=l,c(!1)}function m(e){let t=new TextEncoder().encode(e),n=``,r=8192;for(let e=0;e<t.length;e+=r)n+=String.fromCharCode(...t.subarray(e,Math.min(e+r,t.length)));return btoa(n)}function h(e){let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return new TextDecoder().decode(r)}function g({content:e,runtime:t,csp:n,restrictEgress:r,inline:i,locale:a,reportBackground:o,blobUrl:l}){let u=[`default-src 'none'`,`connect-src blob: https://unpkg.com`,`worker-src blob:`,`form-action 'self'`,`img-src 'self' data: blob:`,`media-src blob:`,`script-src 'self' data: 'unsafe-inline' 'wasm-unsafe-eval' blob: https://unpkg.com ${`${window.location.origin}/pdf-viewer.js`}`,`style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net/npm/bulma@1.0.2/css/bulma.min.css`,`base-uri 'none'`],d=r?[`default-src 'none'`,`connect-src blob:`,`script-src 'unsafe-inline' 'wasm-unsafe-eval' blob: data:`,`style-src 'unsafe-inline'`,`img-src data: blob:`,`media-src blob:`,`worker-src blob:`,`form-action 'none'`,`base-uri 'none'`].join(`; `):f(u,n);function g(){let e={log:console.log,error:console.error,warn:console.warn,info:console.info,debug:console.debug};[`log`,`error`,`warn`,`info`,`debug`].forEach(t=>{console[t]=(...n)=>{e[t](...n),window.bw&&window.bw.request({type:`CONSOLE_LOG`,level:t,message:n.map(e=>{try{return typeof e==`string`?e:JSON.stringify(e)}catch{return String(e)}}).join(` `),timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send console log via sandbox API:`,t)})}}),window.addEventListener(`error`,t=>{(async()=>{let n=window;if(!n.bw)return;let r=t.error?`${t.error.message}${t.error.stack?`
|
|
2
|
+
|
|
3
|
+
Stack trace:
|
|
4
|
+
`+t.error.stack:``}`:t.message;try{t.error&&t.error.stack&&(r=await c(t.error?t.error.message:t.message,t.error.stack))}catch(t){e.log(`Failed to map and enhance stack trace: ${t}`)}e.error(`Javascript Error: `,t),n.bw.request({type:`CONSOLE_LOG`,level:`fatal`,message:`JavaScript Error: ${s(r,5e4)}`,timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send JavaScript error via sandbox API:`,t)})})()}),window.addEventListener(`unhandledrejection`,t=>{(async()=>{e.error(`Uncaught rejection error:`,t);let n=window;if(!n.bw)return;let r=t.reason,i=`Unhandled Promise Rejection`,a;if(r instanceof Error)i=r.message+(r.stack?`
|
|
5
|
+
|
|
6
|
+
Stack trace:
|
|
7
|
+
`+r.stack:``),a=r.stack;else if(typeof r==`string`)i=r;else try{i=JSON.stringify(r)}catch{i=String(r)}try{a&&(i=await c(r.message,a))}catch{}n.bw.request({type:`CONSOLE_LOG`,level:`fatal`,message:`Unhandled Promise Rejection: ${s(i,5e4)}`,timestamp:new Date().toISOString()}).catch(t=>{e.error(`Failed to send promise rejection via sandbox API:`,t)})})()});let t=null;function n(){return t||(t=new Promise(e=>{if(window.StackTrace&&window.StackTraceGPS&&e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}))return;let t=e=>new Promise(t=>{let n=document.createElement(`script`);n.src=e,n.async=!0,n.onload=()=>t(!0),n.onerror=()=>t(!1),document.head.appendChild(n)});Promise.all([t(`https://unpkg.com/stacktrace-js@2.0.2/dist/stacktrace.min.js`),t(`https://unpkg.com/stacktrace-gps@3.1.2/dist/stacktrace-gps.min.js`)]).then(()=>{window.StackTrace&&window.StackTraceGPS?e({StackTrace:window.StackTrace,StackTraceGPS:window.StackTraceGPS}):e(null)}),setTimeout(()=>{(!window.StackTrace||!window.StackTraceGPS)&&e(null)},5e3)}),t)}function r(e){if(!e)return null;let t=e.match(/[#@]\s*sourceMappingURL=data:application\/json;base64,([A-Za-z0-9+/=]+)/);if(!t)return null;try{return JSON.parse(atob(t[1]))}catch{return null}}let i=null;function a(){return i||(i=(async()=>{try{let e=r(window.__sandboxAppCode);if(e)return e;let t=window.__sandboxSourceMapRef;if(!t||!window.bw)return null;let n=await window.bw.fetchBlob(t);return n?JSON.parse(new TextDecoder().decode(n)):null}catch{return null}})(),i)}function o(e,t){if(!e)return null;if(!t)return new e({});let n=null;async function r(){if(n||!t)return n;let e=await new Promise(e=>{let t=document.createElement(`script`);t.src=`https://unpkg.com/source-map-js@1.2.1/source-map.js`,t.async=!0,t.onload=()=>e(window.sourceMap),t.onerror=()=>e(null),document.head.appendChild(t)});if(e&&e.SourceMapConsumer)try{n=new e.SourceMapConsumer(t)}catch{n=null}return n}let i=`/inline-app.js.map`,a=new e({sourceCache:window.__sandboxSourceMapRef?{[i]:t}:{},async ajax(e){if(e===`inline://app.js`){let e=window.__sandboxAppCode||``;return window.__sandboxSourceMapRef?`${e}\n//# sourceMappingURL=${i}`:e}return``}});return a._getMapping=async e=>{let t=await r();if(!t)return e;try{let n=t.originalPositionFor({line:e.lineNumber,column:e.columnNumber});if(n&&n.source)return{functionName:e.functionName,fileName:n.source,lineNumber:n.line||e.lineNumber,columnNumber:n.column||e.columnNumber}}catch{}return e},a}function s(e,t=6e4){return e&&e.length>t?e.slice(0,t)+`...<truncated>`:e}async function c(t,r){if(!r)return t;try{let i=await n();if(!i)return t;let{StackTrace:s,StackTraceGPS:c}=i,l=Error(t);try{l.stack=r}catch{}try{s.getSource&&=()=>Promise.resolve(``),s._getSource&&=()=>Promise.resolve(``)}catch{}let u=await s.fromError(l,{offline:!0}).catch(()=>[]);if(!Array.isArray(u)||!u.length)return t;let d=o(c,await a()),f=[];for(let t of u){let n=t;if(d)try{if(n=await d.pinpoint(t).catch(()=>t),n.functionName===`react_stack_bottom_frame`)break}catch(r){e.log(`Stack trace mapping failed`,r),n=t}let r=n.functionName||t.functionName||`<anonymous>`,i=n.fileName||n.source||t.fileName||`<unknown>`,a=n.lineNumber||t.lineNumber||0,o=n.columnNumber||t.columnNumber||0;f.push(` at ${r} (${i}:${a}:${o})`)}return f.length?t+`
|
|
8
|
+
|
|
9
|
+
Parsed & Mapped Stack:
|
|
10
|
+
`+f.join(`
|
|
11
|
+
`):t}catch(n){return e.log(`Stack parsing/mapping failed`,n),t}}}function _(){let e=document.getElementById(`root`);if(!e||!window.bw)return;let t=()=>{window.bw?.request({type:`REPORT_HEIGHT`,height:Math.ceil(e.getBoundingClientRect().height)}).catch(()=>{})};try{new ResizeObserver(t).observe(e)}catch{}window.addEventListener(`load`,t)}function v(){let e=()=>{for(let e of[document.documentElement,document.body]){if(!e)continue;let t=getComputedStyle(e).backgroundColor;if(t&&t!==`transparent`&&t!==`rgba(0, 0, 0, 0)`)return t}return null},t,n=()=>{let n=e();n!==t&&(t=n,window.bw?.request({type:`REPORT_BACKGROUND`,color:n}).catch(()=>{}))},r=()=>{let e=new MutationObserver(n);e.observe(document.documentElement,{attributes:!0}),document.body&&e.observe(document.body,{attributes:!0}),n()};document.readyState===`loading`?document.addEventListener(`DOMContentLoaded`,r,{once:!0}):r(),window.addEventListener(`load`,n)}let y=o?`<script type="module">(${v.toString()})();<\/script>`:``,b=`<script type="module">(${p.toString()})(window);<\/script>`,x=[`<script type="module">(${g.toString()})();<\/script>`,`<script type="module">window.bw = ${c.toString()}();<\/script>`,`<script type="module">window.data = ${s.toString()};<\/script>`,`<script type="module">window.bw.formDataToObject = window.data;<\/script>`,`<script type="module">window.bw.base64ToStr = ${h.toString()};<\/script>`,`<script type="module">window.bw.locale = ${JSON.stringify(a??`en`)};<\/script>`,b,y,...i?[`<script type="module">(${_.toString()})();<\/script>`]:[]].join(`
|
|
12
|
+
`),S=i?`height: auto;`:`height: 100%;`;if(t===`react@18`||t===`react@19`){let t,n,r;typeof e==`object`?(t=m(e.js),n=e.css,r=e.sourcemap):t=m(e);let i=r&&l?`\\n//# sourceMappingURL=${l(r)}`:``;return`
|
|
13
|
+
<!DOCTYPE html>
|
|
14
|
+
<html lang="${a??`en`}" style="${S}">
|
|
15
|
+
<head>
|
|
16
|
+
<meta http-equiv="Content-Security-Policy" content="${d}">
|
|
17
|
+
<meta charset="utf-8">
|
|
18
|
+
${x}
|
|
19
|
+
<script type="module">
|
|
20
|
+
window.__sandboxSourceMapRef = ${JSON.stringify(r??null)};
|
|
21
|
+
const __appCode = window.bw.base64ToStr('${t}');
|
|
22
|
+
window.__sandboxAppCode = __appCode;
|
|
23
|
+
const codeWithName = __appCode + "\\n//# sourceURL=inline://app.js${i}";
|
|
24
|
+
const mod = await import(URL.createObjectURL(new Blob([codeWithName], { type: 'application/javascript' })));
|
|
25
|
+
mod.default('root', window.bw);
|
|
26
|
+
<\/script>
|
|
27
|
+
${n?`<style>${n}</style>`:``}
|
|
28
|
+
</head>
|
|
29
|
+
<body style="${S} margin: 0;">
|
|
30
|
+
<div id="root" style="${S}"></div>
|
|
31
|
+
</body>
|
|
32
|
+
</html>
|
|
33
|
+
`}let C,w=``;if(typeof e==`string`)w=e,C=m(e);else throw Error(`Invalid bodyContent type. Expected string or object, got ${typeof e}`);return`
|
|
34
|
+
<!DOCTYPE html>
|
|
35
|
+
<html lang="${a??`en`}" style="height: 100%;">
|
|
36
|
+
<head>
|
|
37
|
+
<meta http-equiv="Content-Security-Policy" content="${d}">
|
|
38
|
+
<meta charset="utf-8">
|
|
39
|
+
<script type="module">(${g.toString()})();<\/script>
|
|
40
|
+
${b}
|
|
41
|
+
<script type="module">
|
|
42
|
+
const __appCode = window.bw.base64ToStr('${C}');
|
|
43
|
+
window.__sandboxAppCode = __appCode;
|
|
44
|
+
const codeWithName = __appCode + "\\n//# sourceURL=inline://app.js";
|
|
45
|
+
const mod = await import(URL.createObjectURL(new Blob([codeWithName], { type: 'application/javascript' })));
|
|
46
|
+
mod.default('root', window.bw);
|
|
47
|
+
<\/script>
|
|
48
|
+
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@1.0.2/css/bulma.min.css" />
|
|
49
|
+
<link rel="stylesheet" href="/styles/sandbox.css" />
|
|
50
|
+
|
|
51
|
+
<script>
|
|
52
|
+
window.bw = ${c.toString()}();
|
|
53
|
+
window.data = ${s.toString()};
|
|
54
|
+
window.bw.formDataToObject = window.data; // Expose formDataToObject as part of the \`bw\` api.
|
|
55
|
+
window.bw.base64ToStr = ${h.toString()};
|
|
56
|
+
window.bw.locale = ${JSON.stringify(a??`en`)};
|
|
57
|
+
<\/script>
|
|
58
|
+
${y}
|
|
59
|
+
</head>
|
|
60
|
+
<body style="height: 100%; margin: 0;">
|
|
61
|
+
${w}
|
|
62
|
+
</body>
|
|
63
|
+
</html>
|
|
64
|
+
`}var _=class extends MessageChannel{#e;#t;#n;#r;#i=0;#a=new Map;constructor(e){super(),this.#e=e.sandboxIframe,this.#t=e.onRequest,this.#n=e.onError,this.#r=e.getInitialRoute,this.port1.onmessage=this.#c,this.port2.onmessageerror=e=>{this.#n(Error(e.data))},this.#e.contentDocument?.readyState===`complete`&&this.#o()?queueMicrotask(this.#s):this.#e.addEventListener(`load`,this.#s,{once:!0})}request=(e,t={})=>new Promise((n,r)=>{let i=++this.#i,a=t.timeoutMs&&t.timeoutMs>0?setTimeout(()=>{this.#a.delete(i),r(Error(`Sandbox request timed out after ${t.timeoutMs}ms (${e.type})`))},t.timeoutMs):void 0;this.#a.set(i,{resolve:n,reject:r,timeoutId:a});let o={requestId:i,payload:e};this.port1.postMessage(o)});close(){this.#e.removeEventListener(`load`,this.#s);for(let[e,t]of this.#a)t.timeoutId&&clearTimeout(t.timeoutId),t.reject(Error(`Sandbox message channel closed`)),this.#a.delete(e);this.port1.close(),this.port2.close()}#o=()=>{try{let e=this.#e.contentWindow?.location.href;return!!e&&e!==`about:blank`}catch{return!1}};#s=()=>{this.#e.contentWindow?this.#e.contentWindow.postMessage({type:`INIT_CHANNEL`,initialRoute:this.#r?.()??`/`},`*`,[this.port2]):this.#n(Error(`Missing contentWindow on iframe`))};#c=async e=>{`replyTo`in e.data?this.#l(e.data):this.#u(e.data)};#l=async e=>{let t=this.#a.get(e.replyTo);t?.timeoutId&&clearTimeout(t.timeoutId),t?.resolve(e.payload),this.#a.delete(e.replyTo)};#u=async e=>{let{requestId:t,payload:n}=e;if(n.type===`ERROR`)return this.#n(Error(n.message));let r;try{let e=await this.#t(n);r={replyTo:t,payload:e?.type===`GET_UI_DATA_RESPONSE`?JSON.parse(JSON.stringify(e)):e}}catch(e){r={replyTo:t,payload:{type:`ERROR`,message:e.message}}}this.port1.postMessage(r)}},v=500,y=2e3,b=`bw-ui`,x=new Set([`error`,`fatal`]),S=new Set([`continue`,`continue_next`]);function C(e){let t=``;for(let n=0;n<e.length;n+=32768)t+=String.fromCharCode(...e.subarray(n,n+32768));return btoa(t)}function w(e){let t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}function T(e){let t=new TextDecoder().decode(w(e.base64));try{return JSON.parse(t)}catch{return t}}function E(e){return{ready:!1,mode:e,log:[],submits:[]}}function D(e,t){e.ready||(e.ready=!0,O(e,t,{kind:`ready`}))}function O(e,t,n){e.log.push(n),e.log.length>v&&e.log.shift(),n.kind===`submit`&&e.submits.push(n);let r=n.kind!==`console`||x.has(n.level.toLowerCase());n.kind!==`chrome`&&r&&t.call(`host_event`,n).catch(()=>{})}function k(e){let{init:t,transport:r,state:s,controls:c}=e,l=e=>O(s,r,e),u=e=>{if(t.mode===`detached`)throw Error(`${e} is not available in a UI-only module`)},d=()=>{if(!t.runId||!t.taskRunId)throw Error(`A headless host in run mode needs the run and the task run`);return{runId:t.runId,uiTaskRunId:t.taskRunId}},f=async(e,t)=>{try{let n=await r.call(e,t);return l({kind:`bridge`,method:e,ok:!0}),n}catch(t){throw l({kind:`bridge`,method:e,ok:!1,error:t.message}),t}},p=async e=>T(await f(`blob_get`,{key:e}));return async e=>{switch(e.type){case`INVOKE_TASK`:{let{outputs:n}=t.mode===`run`?await f(`invoke_run_task`,{...a(e,d()),timeout_seconds:e.timeout}):await f(`invoke_workblock_task`,{...i(e,t),timeout_seconds:e.timeout});return{type:`INVOKE_RESPONSE`,result:await o(n,p)}}case`SAVE_BLOB`:{let t=e.blob instanceof Blob?e.blob:new Blob([new Uint8Array(e.blob)]),{blob_ref:n}=await f(`blob_put`,{content_type:t.type||`application/octet-stream`,base64:C(new Uint8Array(await t.arrayBuffer()))});return{type:`SAVE_BLOB_RESPONSE`,blobRef:n}}case`FETCH_BLOB`:return{type:`FETCH_BLOB_RESPONSE`,blob:w((await f(`blob_get`,{key:e.blobRef})).base64)};case`GET_UI_DATA`:{let e=n(t.data)?await p(t.data):t.data;return D(s,r),e==null?{type:`GET_UI_DATA_RESPONSE`}:{type:`GET_UI_DATA_RESPONSE`,data:e}}case`SET_ACTIONS`:e.actions.length>0&&u(`Actions are`),c.setActions(e.actions);return;case`SET_SUBMIT_HANDLER`:e.present&&u(`A submit handler is`),c.setSubmitVisible(e.present);return;case`CONTINUE_UI`:if(u(`Continue is`),t.mode===`run`){l({kind:`chrome`,type:e.type});return}l({kind:`submit`,via:`continue`,data:e.inputArgs});return;case`CONSOLE_LOG`:l({kind:`console`,level:e.level,message:e.message});return;case`ERROR`:throw l({kind:`page_error`,message:e.message}),Error(`Received error from sandbox ${e.message}`);case`SUBSCRIBE_CHILD_RUNS`:if(t.mode!==`run`)throw Error(`Child runs are not available without a run`);return{type:`CHILD_RUNS_UPDATE`,childRuns:t.childRuns??[]};case`YJS_EMIT_EVENT`:return{type:`YJS_EMIT_EVENT_RESPONSE`,event:await f(`yjs_emit_event`,{data_key:e.dataKey,data:e.data,transient:e.transient})};case`YJS_GET_EVENTS`:return{type:`YJS_GET_EVENTS_RESPONSE`,events:await f(`yjs_get_events`,{data_key:e.dataKey})};case`YJS_SUBSCRIBE_EVENTS`:await f(`yjs_subscribe_events`,{data_key:e.dataKey});return;case`YJS_UNSUBSCRIBE_EVENTS`:await f(`yjs_unsubscribe_events`,{data_key:e.dataKey});return;case`YJS_RESET_EVENTS`:throw Error(`A headless host does not reset collaborative history`);case`GRAPHLAKE_QUERY`:case`GRAPHLAKE_SUBSCRIBE`:case`GRAPHLAKE_UNSUBSCRIBE`:throw Error(`GraphLake data is not available in a headless host`);case`OPEN_PLATFORM_CHAT`:case`CLOSE_PLATFORM_CHAT`:throw l({kind:`chrome`,type:e.type}),Error(`The platform chat is not available in a headless host`);case`NOTIFICATIONS_REQUEST_PERMISSION`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_PERMISSION_RESPONSE`,permission:`unsupported`};case`NOTIFICATIONS_SHOW`:return l({kind:`chrome`,type:e.type}),{type:`NOTIFICATIONS_SHOW_RESPONSE`,shown:!1};case`NOTIFICATIONS_CLOSE`:case`SET_SHORTCUTS`:case`REPORT_HEIGHT`:case`REPORT_BACKGROUND`:case`NAVIGATE_TO_STREAM`:case`ROUTE_CHANGED`:case`ROUTES_CHANGED`:l({kind:`chrome`,type:e.type});return;default:return e}}}async function A(e){let{init:t,transport:n,state:r,action:i}=e,a=e=>O(r,n,e),o;try{let t=await e.request({type:`GET_DATA`});if(t.type!==`GET_DATA_RESPONSE`){a({kind:`submit`,via:`submit`,action:i,error:`Unexpected response ${t.type}`});return}if(t.data.status===`ERROR`){a({kind:`submit`,via:`submit`,action:i,error:t.data.error??`Submission rejected`});return}o=t.data.data}catch(e){a({kind:`submit`,via:`submit`,action:i,error:e.message});return}if(t.mode!==`run`){a({kind:`submit`,via:`submit`,action:i,data:o});return}try{await n.call(`continue_ui`,{task_id:t.taskRunId,data:o}),a({kind:`submit`,via:`submit`,action:i,data:o,sent:!0})}catch(e){a({kind:`submit`,via:`submit`,action:i,data:o,sent:!1,error:e.message})}}var j=`
|
|
65
|
+
html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; }
|
|
66
|
+
#bw-frame { height: 100%; }
|
|
67
|
+
#bw-frame.with-controls { height: calc(100% - 52px); }
|
|
68
|
+
#bw-frame iframe { border: 0; width: 100%; height: 100%; display: block; }
|
|
69
|
+
#bw-controls { height: 52px; box-sizing: border-box; display: flex; gap: 8px; align-items: center; padding: 0 12px; border-top: 1px solid #e5e5e5; }
|
|
70
|
+
#bw-controls[hidden] { display: none; }
|
|
71
|
+
`;function M(e,t){let n=E(e.mode),r=document,i=r.createElement(`style`);i.textContent=j,r.head.appendChild(i);let a=r.createElement(`div`);a.id=`bw-frame`;let o=r.createElement(`div`);o.id=`bw-controls`,o.hidden=!0;let s=r.createElement(`button`);s.type=`button`,s.textContent=`Submit`,s.hidden=!0,o.appendChild(s),r.body.append(a,o);let c=r.createElement(`iframe`);c.name=b,c.title=`Task UI`,c.setAttribute(`sandbox`,`allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-top-navigation-by-user-activation`),c.srcdoc=g({content:e.bundle,runtime:e.runtime,csp:e.csp,locale:e.locale??`en`}),c.addEventListener(`load`,()=>setTimeout(()=>D(n,t),y),{once:!0}),a.appendChild(c);let l=[],u=()=>{let e=!s.hidden||l.length>0;o.hidden=!e,a.classList.toggle(`with-controls`,e)},d=e=>O(n,t,e),f=new _({sandboxIframe:c,onRequest:k({init:e,transport:t,state:n,controls:{setSubmitVisible:e=>{s.hidden=!e,u()},setActions:e=>{l.forEach(e=>e.remove()),l=e.map(e=>{let t=r.createElement(`button`);return t.type=`button`,t.textContent=e.label,t.disabled=e.disabled??!1,t.onclick=()=>{if(S.has(e.key)){p(e.key);return}f.request({type:`ON_ACTION`,key:e.key}).catch(e=>{d({kind:`page_error`,message:e.message})})},o.appendChild(t),t}),u()}}}),onError:e=>d({kind:`page_error`,message:e.message})}),p=r=>A({init:e,transport:t,state:n,action:r,request:e=>f.request(e,{timeoutMs:3e4})});return s.onclick=()=>void p(),t.subscribe(e=>{let t=e.type===`yjs_event`?`__yjs_event__`:`__yjs_events_reset__`;f.request({type:`ON_EVENT`,event:t,data:e.data}).catch(()=>{})}),n}function N(e){return{call:(t,n)=>e(t,n),subscribe:()=>{}}}function P(e,t){return{call:async(t,n)=>{let r=await fetch(e,{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({method:t,body:n})}),i={};try{i=await r.json()}catch{throw Error(`Bridge call ${t} failed with HTTP status ${r.status}`)}if(!r.ok||!i.ok)throw Error(i.error??`Bridge call ${t} failed with HTTP status ${r.status}`);return i.result},subscribe:e=>{if(!t)return;let n=new EventSource(t);n.onmessage=t=>{e(JSON.parse(t.data))}}}}var F=document.currentScript?.dataset??{};function I(){if(typeof window.bwTransport==`function`)return N(window.bwTransport);if(F.bridgeUrl)return P(F.bridgeUrl,F.eventsUrl);throw Error(`The headless host has no transport: define window.bwTransport or data-bridge-url`)}var L={start(e){if(L.state)throw Error(`The headless host already started`);return L.state=M(e,I()),L.state}};window.bwHeadlessHost=L,F.initUrl&&fetch(F.initUrl).then(e=>{if(!e.ok)throw Error(`Loading ${F.initUrl} failed with HTTP status ${e.status}`);return e.json()}).then(e=>L.start(e)).catch(e=>{document.body.textContent=e.message,console.error(e)})})();
|
package/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publisher": "beyondwork",
|
|
4
4
|
"displayName": "Beyond Work",
|
|
5
5
|
"description": "Tool for interacting with Beyond Work workblocks from VS Code and CLI.",
|
|
6
|
-
"version": "0.1.
|
|
6
|
+
"version": "0.1.40",
|
|
7
7
|
"vsce": {
|
|
8
8
|
"baseContentUrl": "https://github.com/bwllaming/code/blob/HEAD/src/vscode/beyondwork",
|
|
9
9
|
"baseImagesUrl": "https://github.com/bwllaming/code/raw/HEAD/src/vscode/beyondwork"
|
|
@@ -43,14 +43,16 @@ done from Studio.
|
|
|
43
43
|
7. **Prove it.** Run `wb-cli test [<module>]` when the module has tests, then `wb-cli run
|
|
44
44
|
<module>`, or `wb-cli run <module>/<task> --inputs '{...}'`, for what you changed. Since wb-cli
|
|
45
45
|
0.1.36, `wb-cli run <module>/<task>` calls an invokable task without a run. It returns no run id
|
|
46
|
-
and no logs, and the active run stays unchanged. A run
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
46
|
+
and no logs, and the active run stays unchanged. A run stops at a task UI. Check each task UI
|
|
47
|
+
that you changed with `wb-cli ui <module>/<task>`, which shows it in a headless browser with
|
|
48
|
+
Playwright and needs no browser of the user. Look at its screenshots. To go through a run, open
|
|
49
|
+
each waiting UI with `wb-cli ui <module>/<task> --in-run` and press Submit.
|
|
50
|
+
`references/browser-validation.md` next to this file describes both. Studio's Start and its
|
|
51
|
+
"Configure & Run module" form need a browser tool in the user's signed-in browser. What you did
|
|
52
|
+
not see run, report as not checked.
|
|
53
|
+
8. **Report** the Studio workspace URL, the version, the files changed, the validate, test and run
|
|
54
|
+
results, the UIs you checked with the screenshots you looked at, or why there were none, and
|
|
55
|
+
what is left for the user in Studio.
|
|
54
56
|
|
|
55
57
|
## Credentials
|
|
56
58
|
|
|
@@ -1,87 +1,175 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Check task UIs with `wb-cli ui`
|
|
2
2
|
|
|
3
|
-
`wb-cli run` proves Python tasks by their outputs
|
|
4
|
-
|
|
5
|
-
|
|
3
|
+
`wb-cli run` proves Python tasks by their outputs, but a run stops at a task UI. `wb-cli ui` shows a
|
|
4
|
+
task UI in a headless browser on this machine. You can see the UI and use it. `wb-cli ui` needs
|
|
5
|
+
Playwright, not the user's browser.
|
|
6
6
|
|
|
7
|
-
|
|
8
|
-
signed in to the tenant, such as Claude in Chrome in Claude Code or the ChatGPT browser extension
|
|
9
|
-
in the Codex desktop app. It works on any tenant.
|
|
10
|
-
- **The Playwright script** next to this file, from a monorepo checkout on a tenant on the dev-eu1
|
|
11
|
-
cluster whose namespace secrets you can read. It mints its own session cookie with `testcookies`.
|
|
7
|
+
## When
|
|
12
8
|
|
|
13
|
-
|
|
9
|
+
Check the UI in these cases:
|
|
14
10
|
|
|
15
|
-
|
|
11
|
+
- A new workblock or module that a person starts.
|
|
12
|
+
- A change to a task UI: the component, its `render_ui` call, the data it shows, or the outputs it
|
|
13
|
+
returns.
|
|
14
|
+
- A run of the module that you changed reports `waiting`.
|
|
15
|
+
|
|
16
|
+
"Should work" from the code or the type check is a guess. Say what you saw and what you did not.
|
|
17
|
+
|
|
18
|
+
## What `wb-cli ui` shows
|
|
19
|
+
|
|
20
|
+
| Target | Mode | The page shows | Data |
|
|
21
|
+
| --- | --- | --- | --- |
|
|
22
|
+
| `<module>/<task>` | `preview` | The task's UI, with Submit and the UI's action buttons below it. | The JSON file of `--data <file>`. Without `--data`: the data that the task showed in the workspace's latest run. |
|
|
23
|
+
| `<module>` | `detached` | The UI of a UI-only module, as a Space shows it. | The data that the module gives its UI. |
|
|
24
|
+
| `<module>/<task> --in-run`, or `<module> --in-run` | `run` | The task UI that waits in the workspace's run, as Studio shows it, with Submit and the UI's action buttons below it. | The data of that run. |
|
|
25
|
+
|
|
26
|
+
- The tenant builds the UI from the workspace's last commit, not from your files. Push first. A
|
|
27
|
+
`note` line tells you when the workspace and your files differ.
|
|
28
|
+
- In a preview, Submit and continue record the data and send nothing. In a UI-only module, Submit,
|
|
29
|
+
actions and continue fail, because the module has no run.
|
|
30
|
+
- In a run, Submit and the actions `continue` and `continue_next` send the data to the run, as
|
|
31
|
+
Studio does. `bw.continue` does nothing, as in a Studio task panel. The UI's task calls run in
|
|
32
|
+
the run, and the UI sees the child runs that the task had when the page opened.
|
|
33
|
+
- `--in-run` shows the UI that the run built, not your files. After a push, start a new run first.
|
|
34
|
+
- The UI's task calls (`invokeTask`) and its collaborative documents run on the tenant, on the
|
|
35
|
+
workspace, as your user. File uploads fail: `wb-cli ui` cannot upload files yet.
|
|
36
|
+
- A module that is not UI-only has no UI of its own. Name one of its tasks instead.
|
|
37
|
+
- A task call from the UI waits at most 300 s.
|
|
38
|
+
- For a preview, the tenant builds the task's `react_component:`. When the task's `render_ui` call
|
|
39
|
+
names another asset, pass `--asset <name>`. wb-cli takes the runtime and the CSP of the task's UI
|
|
40
|
+
from the latest run. Without one, the runtime is `react@19` and the CSP is the default. Then pass
|
|
41
|
+
`--runtime react@18` or `--csp '<directives>'` when `render_ui` sets them.
|
|
42
|
+
|
|
43
|
+
## Install Playwright once
|
|
44
|
+
|
|
45
|
+
`--exec` and `--screenshot` load Playwright from your environment. wb-cli looks in the current
|
|
46
|
+
directory and its parents, then in the global packages. Install it in the directory that holds your
|
|
47
|
+
checkouts, not in a checkout. wb-cli reports every file in a checkout that the workblock does not
|
|
48
|
+
claim.
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
cd <directory-that-holds-the-checkout>
|
|
52
|
+
npm i -D playwright && npx playwright install chromium
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
When Chromium does not start on Linux, `npx playwright install-deps chromium` installs the system
|
|
56
|
+
libraries that it needs.
|
|
57
|
+
|
|
58
|
+
## Drive the UI
|
|
59
|
+
|
|
60
|
+
Run each command from inside the checkout. `wb-cli ui` prints one JSON object per line.
|
|
61
|
+
|
|
62
|
+
| Route | Command | It ends |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| A screenshot | `wb-cli ui <target> --screenshot ../shots/review.png` | After the PNG is written. |
|
|
65
|
+
| A Playwright script | `wb-cli ui <target> --exec ../drive.mjs` | After the script returns. Exit 1 when it throws. |
|
|
66
|
+
| Playwright MCP, or your own browser tool | `wb-cli ui <target>` in the background, then open the URL of the `ready` line. | On Ctrl-C (SIGINT) or SIGTERM. Exit 1 when the tenant closes the connection. |
|
|
67
|
+
|
|
68
|
+
`--exec` and `--screenshot` can go together: the script runs first. The screenshot shows the whole
|
|
69
|
+
UI, up to 8000 px high.
|
|
70
|
+
|
|
71
|
+
Your own browser tool must run on this machine, because the server listens on 127.0.0.1 only. The
|
|
72
|
+
URL acts as your user on the tenant. Do not put it in a report.
|
|
73
|
+
|
|
74
|
+
A script's default export gets these values. Keep the script next to the checkout, not in it.
|
|
75
|
+
|
|
76
|
+
| Name | What it is |
|
|
77
|
+
| --- | --- |
|
|
78
|
+
| `page` | The Playwright page. Submit and the UI's action buttons are on it, below the UI. |
|
|
79
|
+
| `ui` | `page.frameLocator('iframe[name="bw-ui"]')`: locators inside the task UI. |
|
|
80
|
+
| `frame` | The task UI's `Frame`. |
|
|
81
|
+
| `host.state()` | What the page recorded: `{ ready, mode, log, submits }`. |
|
|
82
|
+
| `url` | The URL of the page. |
|
|
83
|
+
|
|
84
|
+
```js
|
|
85
|
+
// ../drive.mjs
|
|
86
|
+
export default async ({ page, ui, host }) => {
|
|
87
|
+
await ui.getByLabel("Owner").fill("Anna");
|
|
88
|
+
await page.screenshot({ path: "../shots/filled.png" });
|
|
89
|
+
await page.getByRole("button", { name: "Submit" }).click();
|
|
90
|
+
// The page records the submit after the UI answers it.
|
|
91
|
+
await page.waitForFunction(() => window.bwHeadlessHost.state.submits.length > 0);
|
|
92
|
+
const { submits } = await host.state();
|
|
93
|
+
return submits.at(-1);
|
|
94
|
+
};
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
The script runs after the UI asked for its data. Wait for what the UI renders with locators, not
|
|
98
|
+
with fixed delays.
|
|
99
|
+
|
|
100
|
+
## Read the output
|
|
101
|
+
|
|
102
|
+
| `event` | Fields | Meaning |
|
|
103
|
+
| --- | --- | --- |
|
|
104
|
+
| `note` | `message` | The page does not show your files: the workspace and your files differ, or the workspace holds content that is not at a commit. |
|
|
105
|
+
| `ready` | `url`, `frame`, `mode`, `module_id`, `task_id`, `commit_ref`, `data_from`, `run_id`, `task_run_id` | The page is served. `data_from` is `file` or `run`. In a preview, `task_run_id` is the task run whose data the preview shows. In a run, `run_id` and `task_run_id` name the run and the task run that waits. |
|
|
106
|
+
| `host_event` | `kind`, and the fields of the kind | The page reports `ready`, `submit` (with `data`, or `error` when the component rejected it; in a run also `sent`, which is true when the run received the data), `console` (error lines of the UI), `page_error`, and `bridge` (each platform request of the UI, with `ok` and `error`). |
|
|
107
|
+
| `result` | `value` | What the `--exec` script returned. |
|
|
108
|
+
| `error` | `message` | The `--exec` script threw. |
|
|
109
|
+
| `screenshot` | `path` | The PNG that `--screenshot` wrote. |
|
|
110
|
+
|
|
111
|
+
Look at every screenshot. A red-on-red label or a hidden button is in the picture and nowhere else.
|
|
112
|
+
Compare each `submit` with the outputs that the request asks for.
|
|
113
|
+
|
|
114
|
+
## Finish a waiting run
|
|
115
|
+
|
|
116
|
+
`wb-cli ui` without `--in-run` never continues a run. To finish a run that waits at a task UI:
|
|
117
|
+
|
|
118
|
+
1. Start the run with `wb-cli run <module>`. It reports `waiting` when a task UI waits.
|
|
119
|
+
2. Open that UI in the run and press Submit, as a person would:
|
|
120
|
+
`wb-cli ui <module>/<task> --in-run --exec ../submit.mjs`. The script fills the UI and clicks
|
|
121
|
+
`page.getByRole("button", { name: "Submit" })`. The `submit` event shows `sent: true` when the run
|
|
122
|
+
received the data.
|
|
123
|
+
3. Run `wb-cli run --wait-for latest`. It prints the state and the outputs of every task. Compare the
|
|
124
|
+
outputs with the request. When the next task waits at a UI, repeat step 2 for it.
|
|
125
|
+
|
|
126
|
+
To send data that you checked in a preview without the UI, use
|
|
127
|
+
`wb-cli api continue_ui '{"task_id": "<task-run-id>", "data": {...}}'`. The task run id is the
|
|
128
|
+
`task_run_id` of the `ready` line, or of the task in state `wait_ui` in
|
|
129
|
+
`wb-cli run --wait-for latest --json`. When the checkout has no workspace in `.bw/workblock.json`,
|
|
130
|
+
add `--stream <workspace-id>`, the last part of the workspace URL that `wb-cli status` prints.
|
|
131
|
+
|
|
132
|
+
When no task UI shows the result, a person sees the outputs only as raw data behind the module's
|
|
133
|
+
output node in Studio, and not at all in a Space (`.skills/workblock-architecture`).
|
|
134
|
+
|
|
135
|
+
## The full Studio flow, from Start to the result
|
|
136
|
+
|
|
137
|
+
`wb-cli ui` shows one UI at a time. It does not press Studio's Start, and it does not show Studio's
|
|
138
|
+
"Configure & Run module" form. To check what a person sees from Start through each UI to the result,
|
|
139
|
+
use a browser tool that acts in the user's own browser, where the user is signed in to the tenant.
|
|
140
|
+
Examples are Claude in Chrome in Claude Code and the ChatGPT browser extension in the Codex desktop
|
|
141
|
+
app. Without one, report that flow as not checked and give the workspace URL that `wb-cli status`
|
|
142
|
+
prints.
|
|
143
|
+
|
|
144
|
+
That browser acts as the user with all of the user's rights, not only the token's scopes:
|
|
145
|
+
|
|
146
|
+
- Open only this checkout's workspace, the URL that `wb-cli status` prints.
|
|
147
|
+
- Press only Start, the controls of the task UIs, Submit and the details of a toast.
|
|
148
|
+
- Never press Deploy. Never change sharing, permissions or settings. Never delete anything.
|
|
149
|
+
- On a login page, stop and ask the user to sign in in that browser. Never type credentials.
|
|
150
|
+
|
|
151
|
+
Do these steps:
|
|
16
152
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
Studio shows Stop instead of Start. Then open the workspace. The task UI runs in a sandboxed
|
|
33
|
-
iframe in a process of its own. While the tab is hidden, the clicks and keys that you send into
|
|
34
|
-
it are lost without an error, and screenshots still look right. So check that
|
|
35
|
-
`document.visibilityState` is `visible`, and when it is not, or a click into a task UI has no
|
|
36
|
-
effect, ask the user to bring the browser window to the front and keep it visible until you
|
|
37
|
-
finish.
|
|
38
|
-
2. Press `Start <module>` or `Try changes` in the toolbar, or pick the module under `Start specific
|
|
39
|
-
module`. When Start opens the "Configure & Run module" form instead of a task UI, stop: the
|
|
40
|
-
module has inputs, which is a finding against step 3 of the skill, not a form to fill in.
|
|
41
|
-
3. Use each task UI as a person would. Page reading (the accessibility tree, element search, form
|
|
42
|
-
input) may see nothing inside the iframe. Then take a screenshot, click by coordinates, type, and
|
|
43
|
-
zoom in to confirm that the text arrived. Submit and the other run controls are outside the
|
|
44
|
-
iframe, below it.
|
|
45
|
-
4. A rejected Submit shows a "Submission rejected" toast for a few seconds. Its "View error details"
|
|
46
|
-
button opens the data that the component rejected, with the reason it threw.
|
|
47
|
-
5. Look at a screenshot of every screen: a red-on-red label or a hidden button is in the picture and
|
|
48
|
-
nowhere else.
|
|
49
|
-
6. When the run ends, `wb-cli run --wait-for latest` from the checkout prints the state and the
|
|
50
|
-
outputs of every task. Compare the outputs with what the request asked for. When no task UI
|
|
51
|
-
shows the result, a person sees the outputs only as raw data behind the module's output node in
|
|
52
|
-
Studio, and not at all in a Space (`.skills/workblock-architecture`).
|
|
53
|
-
|
|
54
|
-
## With the Playwright script
|
|
55
|
-
|
|
56
|
-
When the script stops for the tenant or the access, report the UI as not checked and hand over the
|
|
57
|
-
workspace URL. Do not probe the access with `kubectl` yourself: a call against another context says
|
|
58
|
-
`Forbidden` for reasons of its own.
|
|
59
|
-
|
|
60
|
-
`browser-run.sh` next to this file does every step in one shell; `validate-ui.mjs` is the Playwright
|
|
61
|
-
script it runs. Copy both next to your checkout (not into it: the checkout lists files it does not
|
|
62
|
-
claim).
|
|
63
|
-
|
|
64
|
-
1. Edit `useTheUi()` in your copy: fill the fields, press the buttons and wait for the texts the
|
|
65
|
-
request describes, with `shot(page, "<name>")` at each step.
|
|
66
|
-
2. Push, then run from inside the checkout:
|
|
67
|
-
```bash
|
|
68
|
-
REPO=<monorepo> MODULE=<module> SCRIPT=<dir>/validate-ui.mjs SHOTS_DIR=<dir>/shots \
|
|
69
|
-
bash <dir>/browser-run.sh
|
|
70
|
-
```
|
|
71
|
-
It mints the session cookie into a private file, presses the module's Start button as a person
|
|
72
|
-
does, drives each UI the run shows and submits it (a UI with its own actions has no Submit:
|
|
73
|
-
press the one that continues the run in `useTheUi`, or it is left open), and prints the run's
|
|
74
|
-
final states and outputs.
|
|
75
|
-
Every stop prints what to do.
|
|
76
|
-
3. Look at every screenshot in `SHOTS_DIR`: a red-on-red label or a hidden button is in the picture
|
|
77
|
-
and nowhere else. The `result-*` screenshots show the end of the run in Studio, where module
|
|
78
|
-
outputs are raw data; a Space does not show them at all (`.skills/workblock-architecture`).
|
|
79
|
-
Compare the outputs with what the request asked for.
|
|
153
|
+
1. Push, then run `wb-cli cancel`. While a run waits at a task UI, Studio shows Stop instead of
|
|
154
|
+
Start. Then open the workspace.
|
|
155
|
+
2. Check that `document.visibilityState` is `visible`. A task UI runs in a sandboxed iframe in a
|
|
156
|
+
process of its own. While the tab is hidden, the clicks and keys that you send into it are lost
|
|
157
|
+
without an error, and screenshots still look right. If the tab is hidden, or a click into a task
|
|
158
|
+
UI has no effect, ask the user to bring the browser window to the front and keep it visible.
|
|
159
|
+
3. Press `Start <module>` or `Try changes` in the toolbar, or pick the module under `Start specific
|
|
160
|
+
module`. If Start opens the "Configure & Run module" form instead of a task UI, stop. The module
|
|
161
|
+
has inputs, which is a finding against step 3 of the skill, not a form to fill in.
|
|
162
|
+
4. Use each task UI as a person would. Page reading may see nothing inside the iframe. Then take a
|
|
163
|
+
screenshot, click by coordinates, type, and zoom in to confirm that the text arrived. Submit and
|
|
164
|
+
the other run controls are outside the iframe, below it.
|
|
165
|
+
5. A rejected Submit shows a "Submission rejected" toast for a few seconds. Its "View error details"
|
|
166
|
+
button opens the data that the component rejected, with the reason.
|
|
167
|
+
6. When the run ends, run `wb-cli run --wait-for latest` and compare the outputs with the request.
|
|
80
168
|
|
|
81
169
|
## Fix and report
|
|
82
170
|
|
|
83
|
-
When something is wrong, fix it in the checkout, push, and
|
|
84
|
-
|
|
171
|
+
When something is wrong, fix it in the checkout, push, and check again. After three rounds on the
|
|
172
|
+
same problem, stop and report what still fails and what you tried.
|
|
85
173
|
|
|
86
|
-
Report
|
|
87
|
-
request, and
|
|
174
|
+
Report the UIs you checked and how, the screenshots you looked at, the submits and outputs set
|
|
175
|
+
against the request, and what you could not check and why.
|
|
@@ -1,104 +0,0 @@
|
|
|
1
|
-
#!/usr/bin/env bash
|
|
2
|
-
# The browser-validation recipe as one script, run from inside the workblock checkout:
|
|
3
|
-
# REPO=<monorepo> MODULE=<module> SCRIPT=<path>/validate-ui.mjs SHOTS_DIR=<dir> bash browser-run.sh
|
|
4
|
-
# START=studio (the default) presses the module's Start button in the browser, the way a person
|
|
5
|
-
# does. START=cli starts the run with `wb-cli run <module>` instead, for a module that people never
|
|
6
|
-
# start from Studio (a trigger, a schedule or another workblock starts it).
|
|
7
|
-
# Every step is one shell, so the session cookie never lives in an exported variable.
|
|
8
|
-
# Exit codes: 0 submitted and outputs printed; 1 setup or run problem (the message says which);
|
|
9
|
-
# 3 the run failed or still waits at a UI nobody drove; validate-ui.mjs's own 2 (login or page),
|
|
10
|
-
# 3 (submit rejected, or Start opened the generic input form) and 4 (no task UI) pass through, and
|
|
11
|
-
# its 5 (a UI with its own actions, left open) ends the recipe with the run waiting there, exit 0.
|
|
12
|
-
set -euo pipefail
|
|
13
|
-
: "${REPO:?the monorepo checkout}" "${MODULE:?the module to run}" "${SCRIPT:?validate-ui.mjs}" "${SHOTS_DIR:?screenshot directory}"
|
|
14
|
-
START=${START:-studio}
|
|
15
|
-
case "$START" in studio | cli) ;; *) echo "START is studio or cli, not $START" >&2; exit 1 ;; esac
|
|
16
|
-
W="$REPO/bin/wb-cli"
|
|
17
|
-
|
|
18
|
-
# 1. The tenant host and the workspace URL of this checkout.
|
|
19
|
-
STATUS=$("$W" status --json)
|
|
20
|
-
HOST=$(jq -r .marker.host <<<"$STATUS")
|
|
21
|
-
WORKSPACE_URL="https://$HOST/w/studio/s/$(jq -r .marker.streamId <<<"$STATUS")"
|
|
22
|
-
|
|
23
|
-
# 2. testcookies inputs. -t is the host's first label (testcookies builds the cookie domain
|
|
24
|
-
# <t>.dev-eu1.bworker.ai from it, so the tenant must be on dev-eu1). -n is the Kubernetes
|
|
25
|
-
# namespace of the tenant's ingress. -e is the user the wb-cli token belongs to. kubectl
|
|
26
|
-
# runs with the monorepo's environment, which holds the kubeconfig.
|
|
27
|
-
TENANT=${HOST%%.*}
|
|
28
|
-
NS=$(cd "$REPO" && eval "$(DIRENV_LOG_FORMAT= direnv export bash 2>/dev/null)" && kubectl --context dev-eu1 get ingress -A \
|
|
29
|
-
-o jsonpath='{range .items[*]}{.metadata.namespace}{" "}{.spec.rules[*].host}{"\n"}{end}' 2>/dev/null |
|
|
30
|
-
awk -v h="$HOST" '{for (i = 2; i <= NF; i++) if ($i == h) { print $1; exit }}') || true
|
|
31
|
-
[ -n "$NS" ] || { echo "No ingress on dev-eu1 serves $HOST: the tenant is not on dev-eu1, or kubectl has no access. Report the UI as not checked in a browser." >&2; exit 1; }
|
|
32
|
-
EMAIL=$("$W" tenants "$HOST" --json | jq -r '.tenants[0].user // empty') || true
|
|
33
|
-
[ -n "$EMAIL" ] || { echo "wb-cli has no working sign-in for $HOST; run wb-cli tenants $HOST to see why." >&2; exit 1; }
|
|
34
|
-
echo "host=$HOST tenant=$TENANT namespace=$NS email=$EMAIL workspace=$WORKSPACE_URL"
|
|
35
|
-
|
|
36
|
-
# 3. Mint the cookie into a private file. Never print it. A Forbidden here means the tenant's
|
|
37
|
-
# secret is not readable with your credentials: that is the stop to report.
|
|
38
|
-
COOKIE_FILE=$(umask 077 && mktemp)
|
|
39
|
-
trap 'rm -f "$COOKIE_FILE"' EXIT
|
|
40
|
-
COOKIE_ERR=$(mktemp)
|
|
41
|
-
if ! (cd "$REPO" && bin/bazel run //src/beyondwork.ai/tools/testcookies:testcookies -- \
|
|
42
|
-
-n "$NS" -t "$TENANT" -e "$EMAIL" >"$COOKIE_FILE" 2>"$COOKIE_ERR"); then
|
|
43
|
-
grep -i -m 3 'forbidden\|denied\|error' "$COOKIE_ERR" >&2 || tail -n 3 "$COOKIE_ERR" >&2
|
|
44
|
-
rm -f "$COOKIE_ERR"
|
|
45
|
-
echo "testcookies failed; the UI cannot be checked in a browser with these credentials. Report that." >&2
|
|
46
|
-
exit 1
|
|
47
|
-
fi
|
|
48
|
-
rm -f "$COOKIE_ERR"
|
|
49
|
-
[ -s "$COOKIE_FILE" ] || { echo "testcookies wrote no cookie" >&2; exit 1; }
|
|
50
|
-
|
|
51
|
-
# 4. With START=studio the browser starts the run. A run that still waits would show its UI before
|
|
52
|
-
# Start is pressed, so stop it first, as `run` does. With START=cli the run starts here and must
|
|
53
|
-
# report "waiting"; anything else is a task problem to fix first.
|
|
54
|
-
if [ "$START" = studio ]; then
|
|
55
|
-
"$W" cancel
|
|
56
|
-
RUN_ID=latest
|
|
57
|
-
START_MODULE=$MODULE
|
|
58
|
-
else
|
|
59
|
-
RUN=$("$W" run "$MODULE" --json) || true
|
|
60
|
-
[ "$(jq -r .status <<<"$RUN")" = waiting ] || { echo "run did not reach the UI:" >&2; echo "$RUN" >&2; exit 1; }
|
|
61
|
-
RUN_ID=$(jq -r .run_id <<<"$RUN")
|
|
62
|
-
START_MODULE=
|
|
63
|
-
echo "run $RUN_ID is waiting at $(jq -r '.tasks[] | select(.task_id == "'"$(jq -r .waiting_task_id <<<"$RUN")"'") | .task_name' <<<"$RUN")"
|
|
64
|
-
fi
|
|
65
|
-
|
|
66
|
-
# 5. Drive each UI the run shows, one validate-ui.mjs call per UI, until the run stops waiting.
|
|
67
|
-
# Right after a submit the run can still report the submitted UI as waiting; when no further
|
|
68
|
-
# UI appears (exit 4 after the first), the run has gone past it. bin/node needs WORKSPACE_ROOT
|
|
69
|
-
# when the current directory is outside the monorepo.
|
|
70
|
-
STEP=1
|
|
71
|
-
OPEN=
|
|
72
|
-
while :; do
|
|
73
|
-
CODE=0
|
|
74
|
-
WB_WORKSPACE_URL="$WORKSPACE_URL" BW_SAML_COOKIE_FILE="$COOKIE_FILE" SHOTS_DIR="$SHOTS_DIR" BW_REPO="$REPO" \
|
|
75
|
-
WB_START_MODULE="$START_MODULE" WB_UI_STEP="$STEP" WORKSPACE_ROOT="$REPO" "$REPO/bin/node" "$SCRIPT" || CODE=$?
|
|
76
|
-
if [ "$CODE" -eq 5 ]; then
|
|
77
|
-
OPEN=1
|
|
78
|
-
break
|
|
79
|
-
fi
|
|
80
|
-
if [ "$CODE" -ne 0 ]; then
|
|
81
|
-
{ [ "$CODE" -eq 4 ] && [ "$STEP" -gt 1 ]; } || exit "$CODE"
|
|
82
|
-
break
|
|
83
|
-
fi
|
|
84
|
-
[ "$("$W" run --wait-for "$RUN_ID" --json | jq -r .status)" = waiting ] || break
|
|
85
|
-
STEP=$((STEP + 1))
|
|
86
|
-
START_MODULE=
|
|
87
|
-
[ "$STEP" -le 10 ] || { echo "The run still waits after 10 UIs; stopping." >&2; exit 1; }
|
|
88
|
-
done
|
|
89
|
-
|
|
90
|
-
# 6. The outputs are the proof. A run that waits at a UI nobody drove has not reached its result;
|
|
91
|
-
# one that waits at the UI left open is an app doing its job.
|
|
92
|
-
"$W" run --wait-for "$RUN_ID"
|
|
93
|
-
if [ -z "$OPEN" ] && [ "$("$W" run --wait-for "$RUN_ID" --json | jq -r .status)" = waiting ]; then
|
|
94
|
-
echo "The run still waits for a person that no UI step drove: the recipe did not reach the result." >&2
|
|
95
|
-
exit 3
|
|
96
|
-
fi
|
|
97
|
-
|
|
98
|
-
# 7. The end of the run as Studio shows it: the graph, and the module's outputs behind its output
|
|
99
|
-
# node. A failure here leaves the proof of step 6 standing, so it does not fail the recipe.
|
|
100
|
-
if [ -z "$OPEN" ]; then
|
|
101
|
-
WB_WORKSPACE_URL="$WORKSPACE_URL" BW_SAML_COOKIE_FILE="$COOKIE_FILE" SHOTS_DIR="$SHOTS_DIR" BW_REPO="$REPO" \
|
|
102
|
-
WB_RESULT="$MODULE" WORKSPACE_ROOT="$REPO" "$REPO/bin/node" "$SCRIPT" ||
|
|
103
|
-
echo "No screenshot of the end of the run. Report the result view as not checked." >&2
|
|
104
|
-
fi
|